text stringlengths 2 1.04M | meta dict |
|---|---|
package org.apache.accumulo.core.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.hadoop.io.Text;
import org.junit.jupiter.api.Test;
/**
* Test the TextUtil class.
*/
public class TextUtilTest {
@Test
public void testGetBytes() {
String longMessage = "This is some text";
Text longMessageText = new Text(longMessage);
String smallerMessage = "a";
Text smallerMessageText = new Text(smallerMessage);
Text someText = new Text(longMessage);
assertEquals(someText, longMessageText);
someText.set(smallerMessageText);
assertTrue(someText.getLength() != someText.getBytes().length);
assertEquals(TextUtil.getBytes(someText).length, smallerMessage.length());
assertEquals((new Text(TextUtil.getBytes(someText))), smallerMessageText);
}
}
| {
"content_hash": "c17120c62427081d4446862cad19041c",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 78,
"avg_line_length": 30.344827586206897,
"alnum_prop": 0.7454545454545455,
"repo_name": "mjwall/accumulo",
"id": "d2d223a408684a82f569b583fd045fb484374075",
"size": "1687",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "core/src/test/java/org/apache/accumulo/core/util/TextUtilTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2437"
},
{
"name": "C++",
"bytes": "37312"
},
{
"name": "CSS",
"bytes": "6564"
},
{
"name": "FreeMarker",
"bytes": "65275"
},
{
"name": "HTML",
"bytes": "5504"
},
{
"name": "Java",
"bytes": "20894419"
},
{
"name": "JavaScript",
"bytes": "85381"
},
{
"name": "Makefile",
"bytes": "2872"
},
{
"name": "Python",
"bytes": "7344"
},
{
"name": "Shell",
"bytes": "77849"
},
{
"name": "Thrift",
"bytes": "46767"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Can. J. Bot. 77(1): 89 (1999)
#### Original name
Ascotaiwania hughesii Fallah, J.L. Crane & Shearer, 1999
### Remarks
null | {
"content_hash": "033ca4c5cf4da6536b42d754ce37fdb3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 56,
"avg_line_length": 16.23076923076923,
"alnum_prop": 0.6872037914691943,
"repo_name": "mdoering/backbone",
"id": "b932fb5ca5544e144cf401b6f1f0b3c0960ee63c",
"size": "291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Sordariomycetes/Sordariales/Ascotaiwania/Ascotaiwania hughesii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package test.sdncontroller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Vector;
import it.unibo.deis.lia.ramp.RampEntryPoint;
import it.unibo.deis.lia.ramp.core.e2e.BoundReceiveSocket;
import it.unibo.deis.lia.ramp.core.e2e.E2EComm;
import it.unibo.deis.lia.ramp.core.e2e.GenericPacket;
import it.unibo.deis.lia.ramp.core.e2e.UnicastPacket;
import it.unibo.deis.lia.ramp.core.internode.sdn.applicationRequirements.ApplicationRequirements;
import it.unibo.deis.lia.ramp.core.internode.sdn.applicationRequirements.TrafficType;
import it.unibo.deis.lia.ramp.core.internode.sdn.controllerClient.ControllerClient;
import it.unibo.deis.lia.ramp.core.internode.Dispatcher;
import it.unibo.deis.lia.ramp.service.management.ServiceDiscovery;
import it.unibo.deis.lia.ramp.service.management.ServiceResponse;
import it.unibo.deis.lia.ramp.util.GeneralUtils;
import oshi.SystemInfo;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;
/**
* @author Alessandro Dolci
* @author Dmitrij David Padalino Montenero
* <p>
* This test must be executed on the node that is responsible to
* start a new communication by selecting the preferred static method
* to be called in the main placed in the bottom.
*/
public class ControllerClientTestSender {
private static ControllerClient controllerClient;
private static RampEntryPoint ramp;
/**
* Test method for Best Path policy (send two consecutive strings)
*/
private static void sendTwoMessages() {
String message = "Hello, world!";
System.out.println("ControllerClientTestSender: waiting 40 seconds");
try {
Thread.sleep(40 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSend", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse serviceResponse = null;
if (serviceResponses.size() > 0)
serviceResponse = serviceResponses.get(0);
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.VIDEO_STREAM, ApplicationRequirements.UNUSED_FIELD, ApplicationRequirements.UNUSED_FIELD, 0, 20);
int[] destNodeIds = new int[]{serviceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
System.out.println("ControllerClientTestSender: sending message \""
+ message + "\" to the receiver (nodeId: " + serviceResponse.getServerNodeId() + "), flowId: " + flowId);
try {
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
serviceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
E2EComm.serialize(message)
);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: message sent to the receiver");
System.out.println("ControllerClientTestSender: waiting 5 seconds");
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
message = "Second message.";
applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, ApplicationRequirements.UNUSED_FIELD, ApplicationRequirements.UNUSED_FIELD, 0, 20);
flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
System.out.println("ControllerClientTestSender: sending message \""
+ message + "\" to the receiver (nodeId: " + serviceResponse.getServerNodeId() + "), flowId: " + flowId);
try {
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
serviceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
E2EComm.serialize(message)
);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: message sent to the receiver");
System.out.println("ControllerClientTestSender: waiting 20 seconds");
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Test method for no SDN policy (send a single file, selected through the fileName variable)
*/
private static void sendAFile() {
System.out.println("ControllerClientTestSender: waiting 10 seconds");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSend", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse serviceResponse = null;
if (serviceResponses.size() > 0)
serviceResponse = serviceResponses.get(0);
BoundReceiveSocket responseSocket = null;
try {
responseSocket = E2EComm.bindPreReceive(serviceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
String fileName = "./ramp_controllerclienttest.jar";
String message = fileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending file name to the receiver (nodeId: " + serviceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(serviceResponse.getServerDest(), serviceResponse.getServerPort(), serviceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: file name sent to the receiver");
String response = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
if (response.equals("ok")) {
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
// ApplicationRequirements applicationRequirements = new ApplicationRequirements(ApplicationRequirements.ApplicationType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
// int[] destNodeIds = new int[] {serviceResponse.getServerNodeId()};
// int[] destPorts = new int[0];
// int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
int flowId = GenericPacket.UNUSED_FIELD;
// File file = new File("./ramp_controllerclienttest.jar");
File file = new File(fileName);
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: sending the file to the receiver (nodeId: "
+ serviceResponse.getServerNodeId() + "), flowId: " + flowId);
try {
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
serviceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
fileInputStream);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: file sent to the receiver");
String finalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
finalMessage = (String) payload;
}
if (finalMessage.equals("file_received"))
System.out.println("ControllerClientTestSender: final message received from the receiver, file transfer completed");
else
System.out.println("ControllerClientTestSender: wrong final message received from the receiver");
}
}
/**
* Test method for traffic engineering policies (send two files addressing different RAMP services)
* This is ideal to test the SinglePriorityForwarder
* <p>
* Tips:
* use a file called testFile.txt and place it in the project root directory.
* to create a file of a preferred size use the following command in linux
* truncate -s xM testFile.txt
* where x is the dimension in megabyte of the size.
* For a file of 55MB the command is
* truncate -s 55M testFile.txt
* <p>
* In this method are needed two files called
* - testFile.txt for the first receiver
* - testFile2.txt for the second receiver
*/
private static void sendTwoFilesToDifferentReceivers() {
/*
* Initialize the output file to keep track when each packet of the flow
* is sent in order to get the total flow latency and the average packet
* latency.
*/
File outputFile = new File("flow_latencies_sender.csv");
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert printWriter != null;
printWriter.println("timestamp,fileName");
/*
* PrintWriter to be passed to sender threads
*/
final PrintWriter finalPrintWriter = printWriter;
System.out.println("ControllerClientTestSender: waiting 10 seconds");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*
* Discover the first receiver and get its information.
*/
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendFirst", 60 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse serviceResponse = null;
assert serviceResponses != null;
if (serviceResponses.size() > 0)
serviceResponse = serviceResponses.get(0);
BoundReceiveSocket responseSocket = null;
try {
assert serviceResponse != null;
responseSocket = E2EComm.bindPreReceive(serviceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
assert responseSocket != null;
int responseSocketPort = responseSocket.getLocalPort();
/*
* Discover the second receiver and get its information.
*/
Vector<ServiceResponse> secondServiceResponses = null;
try {
secondServiceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendSecond", 60 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse secondServiceResponse = null;
assert secondServiceResponses != null;
if (secondServiceResponses.size() > 0)
secondServiceResponse = secondServiceResponses.get(0);
/*
* Send the name of the file to be sent to the first receiver and wait for an ack.
*/
String firstFileName = "./testFile.txt";
String message = firstFileName + ";" + responseSocketPort;
System.out.println("ControllerClientTestSender: sending first file name to the receiver (nodeId: " + serviceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(serviceResponse.getServerDest(), serviceResponse.getServerPort(), serviceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: first file name sent to the receiver");
String response = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
/*
* As soon as we get the ack from the first receiver
* we can start to send the file.
*/
assert response != null;
if (response.equals("ok")) {
/*
* Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
*/
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
int[] destNodeIds = new int[]{serviceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
File firstFile = new File(firstFileName);
FileInputStream firstFileInputStream = null;
try {
firstFileInputStream = new FileInputStream(firstFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: sending the first file to the receiver (nodeId: "
+ serviceResponse.getServerNodeId() + "), flowId: " + flowId);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
finalPrintWriter.println(timestamp + "," + firstFileName);
try {
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
serviceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
firstFileInputStream);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: first file sent to the receiver");
}
/*
* Wait 5 seconds before making the second thread start.
*/
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
/*
* Send the name of the file to be sent to the second receiver and wait for an ack.
*/
String secondFileName = "./testFile2.txt";
message = secondFileName + ";" + responseSocketPort;
assert secondServiceResponse != null;
System.out.println("ControllerClientTestSender: sending second file name to the receiver (nodeId: " + secondServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(secondServiceResponse.getServerDest(), secondServiceResponse.getServerPort(), secondServiceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: second file name sent to the receiver");
response = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
/*
* As soon as we get the ack from the second receiver
* we can start to send the file.
*/
assert response != null;
if (response.equals("ok")) {
/*
* Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
*/
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
int[] destNodeIds = new int[]{secondServiceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
File secondFile = new File(secondFileName);
FileInputStream secondFileInputStream = null;
try {
secondFileInputStream = new FileInputStream(secondFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: sending the second file to the receiver (nodeId: "
+ secondServiceResponse.getServerNodeId() + "), flowId: " + flowId);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
finalPrintWriter.println(timestamp + "," + secondFileName);
try {
E2EComm.sendUnicast(
secondServiceResponse.getServerDest(),
secondServiceResponse.getServerNodeId(),
secondServiceResponse.getServerPort(),
secondServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
secondFileInputStream);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: second file sent to the receiver");
}
/*
* Get the final message for the first file.
*/
String firstFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
firstFinalMessage = (String) payload;
}
/*
* Get the final message for the second file.
*/
String secondFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
secondFinalMessage = (String) payload;
}
assert firstFinalMessage != null;
assert secondFinalMessage != null;
if (firstFinalMessage.equals("file_received") && secondFinalMessage.equals("file_received"))
System.out.println("ControllerClientTestSender: final messages received from the receivers, file transfer completed");
else
System.out.println("ControllerClientTestSender: wrong final messages received from the receivers");
finalPrintWriter.close();
printWriter.close();
}
/**
* Test method for traffic engineering policies (send three files addressing different RAMP services)
* This is ideal to test the MultipleFlowsSinglePriorityForwarder
* <p>
* Tips:
* use a file called testFile.txt and place it in the project root directory.
* to create a file of a preferred size use the following command in linux
* truncate -s xM testFile.txt
* where x is the dimension in megabyte of the size.
* For a file of 55MB the command is
* truncate -s 55M testFile.txt
* <p>
* In this method are needed two files called
* - testFile.txt for the first receiver
* - testFile2.txt for the second receiver
* - testFile3.txt for the third receiver
*/
private static void sendThreeFilesToDifferentReceivers() {
/*
* Initialize the output file to keep track when each packet of the flow
* is sent in order to get the total flow latency and the average packet
* latency.
*/
File outputFile = new File("flow_latencies_sender.csv");
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert printWriter != null;
printWriter.println("timestamp,fileName");
/*
* PrintWriter to be passed to sender threads
*/
final PrintWriter finalPrintWriter = printWriter;
System.out.println("ControllerClientTestSender: waiting 10 seconds");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*
* Discover the first receiver and get its information.
*/
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(20, "SDNControllerTestSendFirst", 120 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse serviceResponse = null;
assert serviceResponses != null;
if (serviceResponses.size() > 0)
serviceResponse = serviceResponses.get(0);
BoundReceiveSocket responseSocket = null;
try {
assert serviceResponse != null;
responseSocket = E2EComm.bindPreReceive(serviceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
/*
* Discover the second receiver and get its information.
*/
Vector<ServiceResponse> secondServiceResponses = null;
try {
secondServiceResponses = ServiceDiscovery.findServices(20, "SDNControllerTestSendSecond", 120 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse secondServiceResponse = null;
assert secondServiceResponses != null;
if (secondServiceResponses.size() > 0)
secondServiceResponse = secondServiceResponses.get(0);
/*
* Discover the third receiver and get its information.
*/
Vector<ServiceResponse> thirdServiceResponses = null;
try {
thirdServiceResponses = ServiceDiscovery.findServices(20, "SDNControllerTestSendThird", 120 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse thirdServiceResponse = null;
assert thirdServiceResponses != null;
if (thirdServiceResponses.size() > 0)
thirdServiceResponse = thirdServiceResponses.get(0);
/*
* Send the name of the file to be sent to the first receiver and wait for an ack.
*/
String firstFileName = "./testFile.txt";
assert responseSocket != null;
String message = firstFileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending first file name to the receiver (nodeId: " + serviceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(serviceResponse.getServerDest(), serviceResponse.getServerPort(), serviceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: first file name sent to the receiver");
String response = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
/*
* As soon as we get the ack from the first receiver
* we can start to send the file.
*/
assert response != null;
if (response.equals("ok")) {
/*
* Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
*/
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
int[] destNodeIds = new int[]{serviceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
File firstFile = new File(firstFileName);
FileInputStream firstFileInputStream = null;
try {
firstFileInputStream = new FileInputStream(firstFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: sending the first file to the receiver (nodeId: "
+ serviceResponse.getServerNodeId() + "), flowId: " + flowId);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
finalPrintWriter.println(timestamp + "," + firstFileName);
try {
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
serviceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
firstFileInputStream);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: first file sent to the receiver");
}
/*
* Wait 3 seconds before making the second thread start.
*/
try {
Thread.sleep(3000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
/*
* Send the name of the file to be sent to the second receiver and wait for an ack.
*/
String secondFileName = "./testFile2.txt";
message = secondFileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending second file name to the receiver (nodeId: " + secondServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(secondServiceResponse.getServerDest(), secondServiceResponse.getServerPort(), secondServiceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: second file name sent to the receiver");
response = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
/*
* As soon as we get the ack from the second receiver
* we can start to send the file.
*/
assert response != null;
if (response.equals("ok")) {
/*
* Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
*/
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
int[] destNodeIds = new int[]{secondServiceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
File secondFile = new File(secondFileName);
FileInputStream secondFileInputStream = null;
try {
secondFileInputStream = new FileInputStream(secondFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: sending the second file to the receiver (nodeId: "
+ secondServiceResponse.getServerNodeId() + "), flowId: " + flowId);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
finalPrintWriter.println(timestamp + "," + secondFileName);
try {
E2EComm.sendUnicast(
secondServiceResponse.getServerDest(),
secondServiceResponse.getServerNodeId(),
secondServiceResponse.getServerPort(),
secondServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
secondFileInputStream);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: second file sent to the receiver");
}
/*
* Wait 3 seconds before making the second thread start.
*/
try {
Thread.sleep(3000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
/*
* Send the name of the file to be sent to the third receiver and wait for an ack.
*/
String thirdFileName = "./testFile3.txt";
message = thirdFileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending third file name to the receiver (nodeId: " + thirdServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(thirdServiceResponse.getServerDest(), thirdServiceResponse.getServerPort(), thirdServiceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: third file name sent to the receiver");
response = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
/*
* As soon as we get the ack from the third receiver
* we can start to send the file.
*/
assert response != null;
if (response.equals("ok")) {
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
int[] destNodeIds = new int[]{thirdServiceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
File thirdFile = new File(thirdFileName);
FileInputStream thirdFileInputStream = null;
try {
thirdFileInputStream = new FileInputStream(thirdFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: sending the third file to the receiver (nodeId: "
+ thirdServiceResponse.getServerNodeId() + "), flowId: " + flowId);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
finalPrintWriter.println(timestamp + "," + thirdFileName);
try {
E2EComm.sendUnicast(
thirdServiceResponse.getServerDest(),
thirdServiceResponse.getServerNodeId(),
thirdServiceResponse.getServerPort(),
thirdServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
thirdFileInputStream);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: third file sent to the receiver");
}
/*
* Get the final message for the first file.
*/
String firstFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
firstFinalMessage = (String) payload;
}
/*
* Get the final message for the second file.
*/
String secondFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
secondFinalMessage = (String) payload;
}
/*
* Get the final message for the third file.
*/
String thirdFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
thirdFinalMessage = (String) payload;
}
assert firstFinalMessage != null;
assert secondFinalMessage != null;
assert thirdFinalMessage != null;
if (firstFinalMessage.equals("file_received") && secondFinalMessage.equals("file_received") && thirdFinalMessage.equals("file_received"))
System.out.println("ControllerClientTestSender: final messages received from the receivers, file transfer completed");
else
System.out.println("ControllerClientTestSender: wrong final messages received from the receivers");
finalPrintWriter.close();
printWriter.close();
}
/**
* Test method for rerouting policy (send one series of consecutive packets addressing one RAMP service)
* This is ideal to test the BestPathForwarder
*
* @param protocol Protocol to be used for the series transfer.
* @param packetPayloadInByte Payload of each packet.
* @param packetFrequency Interval in milliseconds between each packet sending.
* @param totalTransferTime Total time in seconds of the series transfer.
* The total number of packets is given by the following formula:
* int numberOfPacketsPerSeries = (1000 * totalTime) / packetFrequency;
*/
public static void sendOneSeriesOfPacketsToOneReceiver(int protocol, int packetPayloadInByte, int packetFrequency, int totalTransferTime) {
/*
* Initialize the output file to keep track when each packet of the flow
* is sent in order to get the total flow latency and the average packet
* latency.
*/
File outputFile = new File("flow_latencies_sender.csv");
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert printWriter != null;
printWriter.println("timestamp,flowId,seqNumber");
/*
* PrintWriter to be passed to sender threads
*/
final PrintWriter finalPrintWriter = printWriter;
System.out.println("ControllerClientTestSender: waiting 30 seconds");
try {
Thread.sleep(30 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*
* Discover the first receiver get its information.
*/
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(20, "SDNControllerTestSendFirst", 60 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse serviceResponse = null;
assert serviceResponses != null;
if(serviceResponses.size() > 0) {
serviceResponse = serviceResponses.get(0);
}
BoundReceiveSocket responseSocket = null;
try {
assert serviceResponse != null;
responseSocket = E2EComm.bindPreReceive(serviceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
assert responseSocket != null;
int responseSocketPort = responseSocket.getLocalPort();
String fileName = "first_series";
String message = fileName + ";" + responseSocketPort;
System.out.println("ControllerClientTestSender: sending first series of packets name to the receiver (nodeId: " + serviceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(serviceResponse.getServerDest(), serviceResponse.getServerPort(), serviceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: first series of packets name sent to the receiver");
String response = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
if (response != null && response.equals("ok")) {
/*
* Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features.
*
* The first series a packet is at low priority.
*/
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 36000);
int[] destNodeIds = new int[]{serviceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
System.out.println("ControllerClientTestSender: sending the first series of packets to the receiver (nodeId: "
+ serviceResponse.getServerNodeId() + "), flowId: " + flowId);
byte[] payload = new byte[packetPayloadInByte];
ControllerMessageTest packet = new ControllerMessageTest();
packet.setPayload(payload);
long preFor = System.currentTimeMillis();
int numberOfPacketsPerSeries = (1000 * totalTransferTime) / packetFrequency;
for (int i = 0; i < numberOfPacketsPerSeries; i++) {
try {
int seqNumber = i + 1;
packet.setSeqNumber(seqNumber);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
System.out.println("First thread " + seqNumber);
finalPrintWriter.println(timestamp + "," + flowId + "," + seqNumber);
finalPrintWriter.flush();
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
protocol,
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
E2EComm.serialize(packet));
long sleep = (packetFrequency * seqNumber) - (System.currentTimeMillis() - preFor);
if (sleep > 0) {
Thread.sleep(sleep);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("ControllerClientTestSender: first series of packets sent to the receiver");
}
String firstFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
firstFinalMessage = (String) payload;
}
assert firstFinalMessage != null;
if (firstFinalMessage.equals("series_received")) {
System.out.println("ControllerClientTestSender: final messages received from the receiver, series transfer completed");
} else {
System.out.println("ControllerClientTestSender: wrong final messages received from the receiver");
}
finalPrintWriter.close();
printWriter.close();
}
/**
* Test method for traffic engineering policies (send two series of consecutive packets addressing different RAMP services)
* This is ideal to test the SinglePriorityForwarder
*/
public static void sendTwoSeriesOfPacketsToDifferentReceivers(int protocol, int packetPayloadInByte, int numberOfPacketsPerSeries) {
/*
* Initialize the output file to keep track when each packet of the flow
* is sent in order to get the total flow latency and the average packet
* latency.
*/
File outputFile = new File("flow_latencies_sender.csv");
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert printWriter != null;
printWriter.println("timestamp,flowId,seqNumber");
/*
* PrintWriter to be passed to sender threads
*/
final PrintWriter finalPrintWriter = printWriter;
System.out.println("ControllerClientTestSender: waiting 10 seconds");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendFirst", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
assert serviceResponses != null;
final ServiceResponse serviceResponse = serviceResponses.get(0);
BoundReceiveSocket responseSocket = null;
try {
responseSocket = E2EComm.bindPreReceive(serviceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Vector<ServiceResponse> secondServiceResponses = null;
try {
secondServiceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendSecond", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
assert secondServiceResponses != null;
final ServiceResponse secondServiceResponse = secondServiceResponses.get(0);
BoundReceiveSocket secondResponseSocket = null;
try {
secondResponseSocket = E2EComm.bindPreReceive(secondServiceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
assert secondResponseSocket != null;
System.out.println("" + secondServiceResponse.getServerPort() + secondResponseSocket.getLocalPort());
String fileName = "first_series";
assert responseSocket != null;
String message = fileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending first series of packets name to the receiver (nodeId: " + serviceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(serviceResponse.getServerDest(), serviceResponse.getServerPort(), serviceResponse.getProtocol(), E2EComm.serialize(message));
System.out.println("//////////////// PRIMA RICHIESTA INVIATA ///////////////////");
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: first series of packets name sent to the receiver");
String response = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
Thread firstThread = null;
System.out.println("//////////////// PRIMO ACK RICEVUTO ///////////////////");
if (response != null && response.equals("ok")) {
/*
* Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features.
*
* The first series a packet is at low priority.
*/
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 36000);
int[] destNodeIds = new int[]{serviceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
System.out.println("ControllerClientTestSender: sending the first series of packets to the receiver (nodeId: "
+ serviceResponse.getServerNodeId() + "), flowId: " + flowId);
byte[] payload = new byte[packetPayloadInByte];
/*
* This is the thread that send the first series of packet.
*/
firstThread = new Thread(() -> {
ControllerMessageTest packet = new ControllerMessageTest();
packet.setPayload(payload);
long now = System.currentTimeMillis();
for (int i = 0; i < numberOfPacketsPerSeries; i++) {
try {
packet.setSeqNumber(i + 1);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
System.out.println("First thread " + timestamp);
//finalPrintWriter.println(timestamp + "," + flowId + "," + (i + 1));
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
protocol,
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
E2EComm.serialize(packet));
long sleep = 20 - (System.currentTimeMillis() - now);
if (sleep > 0)
Thread.sleep(sleep);
now = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
});
firstThread.start();
System.out.println("ControllerClientTestSender: first series of packets sent to the receiver");
}
System.out.println("//////////////// QUI ////////////////");
/*
* Delay the second series of packet
*/
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
fileName = "second_series";
message = fileName + ";" + secondResponseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending second series of packets name to the receiver (nodeId: " + secondServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(secondServiceResponse.getServerDest(), secondServiceResponse.getServerPort(), secondServiceResponse.getProtocol(), E2EComm.serialize(message));
System.out.println("//////////////// SECONDA RICHIESTA INVIATA ///////////////////");
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: second series of packets name sent to the receiver");
response = null;
gp = null;
try {
gp = E2EComm.receive(secondResponseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
System.out.println("//////////////// SECONDO ACK RICEVUTO ///////////////////");
Thread secondThread = null;
if (response != null && response.equals("ok")) {
/*
* Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
*
* The second series a packet is at high priority.
*/
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.VIDEO_STREAM, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 36000);
int[] destNodeIds = new int[]{secondServiceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
System.out.println("ControllerClientTestSender: sending the second series of packets to the receiver (nodeId: "
+ secondServiceResponse.getServerNodeId() + "), flowId: " + flowId);
byte[] payload = new byte[packetPayloadInByte];
/*
* This is the thread that send the second series of packet.
*/
secondThread = new Thread(() -> {
ControllerMessageTest packet = new ControllerMessageTest();
packet.setPayload(payload);
long now = System.currentTimeMillis();
for (int i = 0; i < numberOfPacketsPerSeries; i++) {
try {
packet.setSeqNumber(i + 1);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
System.out.println("Second thread " + timestamp);
//finalPrintWriter.println(timestamp + "," + flowId + "," + (i + 1));
E2EComm.sendUnicast(
secondServiceResponse.getServerDest(),
secondServiceResponse.getServerNodeId(),
secondServiceResponse.getServerPort(),
protocol,
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
E2EComm.serialize(packet));
long sleep = 20 - (System.currentTimeMillis() - now);
Thread.sleep(sleep);
now = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
});
secondThread.start();
System.out.println("ControllerClientTestSender: second series of packets sent to the receiver");
}
String firstFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
firstFinalMessage = (String) payload;
}
String secondFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(secondResponseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
secondFinalMessage = (String) payload;
}
if (firstFinalMessage.equals("series_received") && secondFinalMessage.equals("series_received")) {
firstThread.interrupt();
secondThread.interrupt();
System.out.println("ControllerClientTestSender: final messages received from the receivers, series transfer completed");
} else {
System.out.println("ControllerClientTestSender: wrong final messages received from the receivers");
}
finalPrintWriter.close();
printWriter.close();
}
/**
* Test method for traffic engineering policies (send two series of consecutive packets addressing different RAMP services)
* This is ideal to test the SinglePriorityForwarder
*/
public static void sendTwoSeriesOfPacketsToDifferentReceiversNew(int protocol, int packetPayloadInByte, int numberOfPacketsPerSeries) {
/*
* Initialize the output file to keep track when each packet of the flow
* is sent in order to get the total flow latency and the average packet
* latency.
*/
File outputFile = new File("flow_latencies_sender.csv");
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert printWriter != null;
printWriter.println("timestamp,flowId,seqNumber");
/*
* PrintWriter to be passed to sender threads
*/
final PrintWriter finalPrintWriter = printWriter;
System.out.println("ControllerClientTestSender: waiting 10 seconds");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendFirst", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
assert serviceResponses != null;
final ServiceResponse serviceResponse = serviceResponses.get(0);
BoundReceiveSocket responseSocket = null;
try {
responseSocket = E2EComm.bindPreReceive(serviceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Vector<ServiceResponse> secondServiceResponses = null;
try {
secondServiceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendSecond", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
assert secondServiceResponses != null;
final ServiceResponse secondServiceResponse = secondServiceResponses.get(0);
BoundReceiveSocket secondResponseSocket = null;
try {
secondResponseSocket = E2EComm.bindPreReceive(secondServiceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
assert secondResponseSocket != null;
System.out.println("" + secondServiceResponse.getServerPort() + secondResponseSocket.getLocalPort());
String fileName = "first_series";
assert responseSocket != null;
String message = fileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending first series of packets name to the receiver (nodeId: " + serviceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(serviceResponse.getServerDest(), serviceResponse.getServerPort(), serviceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: first series of packets name sent to the receiver");
/*
* Get the first flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features.
*
* The first series a packet is at low priority.
*/
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 36000);
int[] destNodeIds = new int[]{serviceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
/*
* Get the second flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
*
* The second series a packet is at high priority.
*/
ApplicationRequirements secondApplicationRequirements = new ApplicationRequirements(TrafficType.VIDEO_STREAM, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 36000);
int[] secondDestNodeIds = new int[]{secondServiceResponse.getServerNodeId()};
int[] secondDestPorts = new int[0];
int secondFlowId = controllerClient.getFlowId(secondApplicationRequirements, secondDestNodeIds, secondDestPorts);
System.out.println("ControllerClientTestSender: sending the first series of packets to the receiver (nodeId: "
+ serviceResponse.getServerNodeId() + "), flowId: " + flowId);
byte[] payload = new byte[packetPayloadInByte];
/*
* This is the thread that send the first series of packet.
*/
Thread firstThread = new Thread(() -> {
ControllerMessageTest packet = new ControllerMessageTest();
packet.setPayload(payload);
packet.setPriority(3);
long now = System.currentTimeMillis();
for (int i = 0; i < numberOfPacketsPerSeries; i++) {
try {
packet.setSeqNumber(i + 1);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
System.out.println("First thread " + timestamp);
finalPrintWriter.println(timestamp + "," + flowId + "," + (i + 1));
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
protocol,
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
E2EComm.serialize(packet));
long sleep = 20 - (System.currentTimeMillis() - now);
if (sleep > 0)
Thread.sleep(sleep);
now = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("ControllerClientTestSender: first series of packets sent to the receiver");
});
firstThread.start();
/*
* Delay the second series of packet
*/
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
fileName = "second_series";
message = fileName + ";" + secondResponseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending second series of packets name to the receiver (nodeId: " + secondServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(secondServiceResponse.getServerDest(), secondServiceResponse.getServerPort(), secondServiceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: second series of packets name sent to the receiver");
System.out.println("ControllerClientTestSender: sending the second series of packets to the receiver (nodeId: "
+ secondServiceResponse.getServerNodeId() + "), flowId: " + secondFlowId);
byte[] secondPayload = new byte[packetPayloadInByte];
/*
* This is the thread that send the second series of packet.
*/
Thread secondThread = new Thread(() -> {
ControllerMessageTest packet = new ControllerMessageTest();
packet.setPayload(secondPayload);
packet.setPriority(1);
long now = System.currentTimeMillis();
for (int i = 0; i < numberOfPacketsPerSeries; i++) {
try {
packet.setSeqNumber(i + 1);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
System.out.println("Second thread " + timestamp);
finalPrintWriter.println(timestamp + "," + flowId + "," + (i + 1));
E2EComm.sendUnicast(
secondServiceResponse.getServerDest(),
secondServiceResponse.getServerNodeId(),
secondServiceResponse.getServerPort(),
protocol,
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
secondFlowId,
E2EComm.serialize(packet));
long sleep = 20 - (System.currentTimeMillis() - now);
Thread.sleep(sleep);
now = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("ControllerClientTestSender: second series of packets sent to the receiver");
});
secondThread.start();
GenericPacket gp = null;
/*
* Get the final message for the first series of packet.
*/
String firstFinalMessage = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object packetPayload = null;
try {
packetPayload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (packetPayload instanceof String)
firstFinalMessage = (String) packetPayload;
}
/*
* Get the final message for the second series of packet.
*/
String secondFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(secondResponseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object packetPayload = null;
try {
packetPayload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (packetPayload instanceof String)
secondFinalMessage = (String) packetPayload;
}
assert firstFinalMessage != null;
assert secondFinalMessage != null;
if (firstFinalMessage.equals("series_received") && secondFinalMessage.equals("series_received")) {
firstThread.interrupt();
secondThread.interrupt();
System.out.println("ControllerClientTestSender: final messages received from the receivers, series transfer completed");
} else {
System.out.println("ControllerClientTestSender: wrong final messages received from the receivers");
}
finalPrintWriter.close();
printWriter.close();
}
/**
* Test method for traffic engineering policies using UDP protocol (send three series of consecutive packets addressing different RAMP services)
*/
private static void sendThreeSeriesOfPacketsToDifferentReceivers() {
System.out.println("ControllerClientTestSender: waiting 10 seconds");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendFirst", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse serviceResponse = serviceResponses.get(0);
BoundReceiveSocket responseSocket = null;
try {
responseSocket = E2EComm.bindPreReceive(serviceResponse.getProtocol());
} catch (Exception e3) {
e3.printStackTrace();
}
String fileName = "first_series";
String message = fileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending first series of packets name to the receiver (nodeId: " + serviceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(serviceResponse.getServerDest(), serviceResponse.getServerPort(), serviceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: first series of packets name sent to the receiver");
String response = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
if (response != null && response.equals("ok")) {
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.AUDIO_STREAM, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
int[] destNodeIds = new int[]{serviceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
System.out.println("ControllerClientTestSender: sending the first series of packets to the receiver (nodeId: "
+ serviceResponse.getServerNodeId() + "), flowId: " + flowId);
byte[] payload = new byte[10000];
new Thread() {
public void run() {
try {
for (int i = 0; i < 5000; i++) {
E2EComm.sendUnicast(
serviceResponse.getServerDest(),
serviceResponse.getServerNodeId(),
serviceResponse.getServerPort(),
serviceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
payload);
Thread.sleep(1, 600000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
System.out.println("ControllerClientTestSender: first series of packets sent to the receiver");
}
try {
Thread.sleep(3000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
Vector<ServiceResponse> secondServiceResponses = null;
try {
secondServiceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendSecond", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse secondServiceResponse = secondServiceResponses.get(0);
fileName = "second_series";
message = fileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending second series of packets name to the receiver (nodeId: " + secondServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(secondServiceResponse.getServerDest(), secondServiceResponse.getServerPort(), secondServiceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: second series of packets name sent to the receiver");
response = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
if (response.equals("ok")) {
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.AUDIO_STREAM, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
int[] destNodeIds = new int[]{secondServiceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
System.out.println("ControllerClientTestSender: sending the second series of packets to the receiver (nodeId: "
+ secondServiceResponse.getServerNodeId() + "), flowId: " + flowId);
byte[] payload = new byte[10000];
new Thread() {
public void run() {
try {
E2EComm.sendUnicast(
secondServiceResponse.getServerDest(),
secondServiceResponse.getServerNodeId(),
secondServiceResponse.getServerPort(),
secondServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
payload);
Thread.sleep(1, 600000);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
System.out.println("ControllerClientTestSender: second file sent to the receiver");
}
try {
Thread.sleep(3000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
Vector<ServiceResponse> thirdServiceResponses = null;
try {
thirdServiceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSendThird", 5 * 1000, 1, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse thirdServiceResponse = thirdServiceResponses.get(0);
fileName = "third_series";
message = fileName + ";" + responseSocket.getLocalPort();
System.out.println("ControllerClientTestSender: sending third series of packets name to the receiver (nodeId: " + thirdServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(thirdServiceResponse.getServerDest(), thirdServiceResponse.getServerPort(), thirdServiceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: third series of packets name sent to the receiver");
response = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
if (response.equals("ok")) {
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.VIDEO_STREAM, GenericPacket.UNUSED_FIELD, GenericPacket.UNUSED_FIELD, 0, 400);
int[] destNodeIds = new int[]{thirdServiceResponse.getServerNodeId()};
int[] destPorts = new int[0];
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
// int flowId = GenericPacket.UNUSED_FIELD;
System.out.println("ControllerClientTestSender: sending the third series of packets to the receiver (nodeId: "
+ thirdServiceResponse.getServerNodeId() + "), flowId: " + flowId);
byte[] payload = new byte[10000];
new Thread() {
public void run() {
try {
E2EComm.sendUnicast(
thirdServiceResponse.getServerDest(),
thirdServiceResponse.getServerNodeId(),
thirdServiceResponse.getServerPort(),
thirdServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
payload);
Thread.sleep(1, 600000);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
System.out.println("ControllerClientTestSender: third series of packets sent to the receiver");
}
String firstFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
firstFinalMessage = (String) payload;
}
String secondFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
secondFinalMessage = (String) payload;
}
String thirdFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(responseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
thirdFinalMessage = (String) payload;
}
if (firstFinalMessage.equals("series_received") && secondFinalMessage.equals("series_received") && thirdFinalMessage.equals("series_received"))
System.out.println("ControllerClientTestSender: final messages received from the receivers, file transfer completed");
else
System.out.println("ControllerClientTestSender: wrong final messages received from the receivers");
}
/**
* Test method for Tree-based Multicast policy (send a string to multiple receivers)
*/
private static void sendMessageToMultipleReceivers() {
String message = "Hello, world!";
System.out.println("ControllerClientTestSender: waiting 10 seconds");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSend", 5 * 1000, 2, null);
} catch (Exception e) {
e.printStackTrace();
}
ServiceResponse firstServiceResponse = null;
ServiceResponse secondServiceResponse = null;
if (serviceResponses.size() == 2) {
firstServiceResponse = serviceResponses.get(0);
secondServiceResponse = serviceResponses.get(1);
}
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, ApplicationRequirements.UNUSED_FIELD, ApplicationRequirements.UNUSED_FIELD, 0, 20);
int[] destNodeIds = new int[]{firstServiceResponse.getServerNodeId(), secondServiceResponse.getServerNodeId()};
int[] destPorts = new int[]{firstServiceResponse.getServerPort(), secondServiceResponse.getServerPort()};
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
System.out.println("ControllerClientTestSender: sending message \""
+ message + "\" to the receivers (first nodeId: " + firstServiceResponse.getServerNodeId() + ", second nodeId: " + secondServiceResponse.getServerNodeId() + "), flowId: " + flowId);
try {
E2EComm.sendUnicast(
new String[]{GeneralUtils.getLocalHost()},
Dispatcher.getLocalRampId(),
40000,
firstServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
E2EComm.serialize(message)
);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: message sent to the receiver");
System.out.println("ControllerClientTestSender: waiting 5 seconds");
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
/**
* Test method for Tree-based Multicast policy (send two payloads to multiple receivers
* using separate communication and then repeat adopting the Tree-based Multicast policy)
*
* @throws Exception
*/
private static void sendMultipleMessagesToMultipleReceivers() throws Exception {
System.out.println("ControllerClientTestSender: waiting 10 seconds");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Vector<ServiceResponse> serviceResponses = null;
try {
serviceResponses = ServiceDiscovery.findServices(5, "SDNControllerTestSend", 5 * 1000, 2, null);
} catch (Exception e) {
e.printStackTrace();
}
final ServiceResponse firstServiceResponse = serviceResponses.get(0);
final ServiceResponse secondServiceResponse = serviceResponses.get(1);
final BoundReceiveSocket firstResponseSocket = E2EComm.bindPreReceive(firstServiceResponse.getProtocol());
final BoundReceiveSocket secondResponseSocket = E2EComm.bindPreReceive(secondServiceResponse.getProtocol());
new Thread() {
public void run() {
String message = Integer.toString(firstResponseSocket.getLocalPort());
System.out.println("ControllerClientTestSender: sending first message port to the first receiver (nodeId: " + firstServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(firstServiceResponse.getServerDest(), firstServiceResponse.getServerPort(), firstServiceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: first message port sent to the first receiver");
String response = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(firstResponseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
if (response.equals("ok")) {
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, ApplicationRequirements.UNUSED_FIELD, ApplicationRequirements.UNUSED_FIELD, 0, 200);
int[] destNodeIds = new int[]{firstServiceResponse.getServerNodeId()};
int[] destPorts = new int[]{firstServiceResponse.getServerPort()};
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
byte[] messagePayload = new byte[20000000];
System.out.println("ControllerClientTestSender: sending the first message to the first receiver (nodeId: "
+ firstServiceResponse.getServerNodeId() + "), flowId: " + flowId);
try {
E2EComm.sendUnicast(
firstServiceResponse.getServerDest(),
firstServiceResponse.getServerNodeId(),
firstServiceResponse.getServerPort(),
firstServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
messagePayload);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: first message sent to the first receiver");
}
}
}.start();
new Thread() {
public void run() {
String message = Integer.toString(secondResponseSocket.getLocalPort());
System.out.println("ControllerClientTestSender: sending first message port to the second receiver (nodeId: " + secondServiceResponse.getServerNodeId() + ")");
try {
E2EComm.sendUnicast(secondServiceResponse.getServerDest(), secondServiceResponse.getServerPort(), secondServiceResponse.getProtocol(), E2EComm.serialize(message));
} catch (Exception e3) {
e3.printStackTrace();
}
System.out.println("ControllerClientTestSender: first message port sent to the second receiver");
String response = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(secondResponseSocket);
} catch (Exception e3) {
e3.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String) {
response = (String) payload;
}
}
if (response.equals("ok")) {
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, ApplicationRequirements.UNUSED_FIELD, ApplicationRequirements.UNUSED_FIELD, 0, 200);
int[] destNodeIds = new int[]{secondServiceResponse.getServerNodeId()};
int[] destPorts = new int[]{secondServiceResponse.getServerPort()};
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
byte[] messagePayload = new byte[20000000];
System.out.println("ControllerClientTestSender: sending the first message to the second receiver (nodeId: "
+ secondServiceResponse.getServerNodeId() + "), flowId: " + flowId);
try {
E2EComm.sendUnicast(
secondServiceResponse.getServerDest(),
secondServiceResponse.getServerNodeId(),
secondServiceResponse.getServerPort(),
secondServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
messagePayload);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: first message sent to the second receiver");
}
}
}.start();
// String firstFinalMessage = null;
// GenericPacket gp = null;
// try {
// gp = E2EComm.receive(firstResponseSocket);
// } catch (Exception e) {
// e.printStackTrace();
// }
// if (gp instanceof UnicastPacket) {
// UnicastPacket up = (UnicastPacket) gp;
// Object payload = null;
// try {
// payload = E2EComm.deserialize(up.getBytePayload());
// } catch (Exception e) {
// e.printStackTrace();
// }
// if (payload instanceof String)
// firstFinalMessage = (String) payload;
// }
// String secondFinalMessage = null;
// gp = null;
// try {
// gp = E2EComm.receive(secondResponseSocket);
// } catch (Exception e) {
// e.printStackTrace();
// }
// if (gp instanceof UnicastPacket) {
// UnicastPacket up = (UnicastPacket) gp;
// Object payload = null;
// try {
// payload = E2EComm.deserialize(up.getBytePayload());
// } catch (Exception e) {
// e.printStackTrace();
// }
// if (payload instanceof String)
// secondFinalMessage = (String) payload;
// }
// if (firstFinalMessage.equals("message_received") && secondFinalMessage.equals("message_received"))
// System.out.println("ControllerClientTestSender: first two messages sent, waiting 5 seconds and sending the third message");
System.out.println("ControllerClientTestSender: waiting 20 seconds and sending the third message");
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
// Set a new flowId, or use the GenericPacket.UNUSED_FIELD value to avoid RAMP-SDN features
ApplicationRequirements applicationRequirements = new ApplicationRequirements(TrafficType.FILE_TRANSFER, ApplicationRequirements.UNUSED_FIELD, ApplicationRequirements.UNUSED_FIELD, 0, 20);
int[] destNodeIds = new int[]{firstServiceResponse.getServerNodeId(), secondServiceResponse.getServerNodeId()};
int[] destPorts = new int[]{firstServiceResponse.getServerPort(), secondServiceResponse.getServerPort()};
int flowId = controllerClient.getFlowId(applicationRequirements, destNodeIds, destPorts);
byte[] messagePayload = new byte[20000000];
System.out.println("ControllerClientTestSender: sending the third message to the receivers (first nodeId: "
+ firstServiceResponse.getServerNodeId() + ", second nodeId: " + secondServiceResponse.getServerNodeId() + "), flowId: " + flowId);
try {
E2EComm.sendUnicast(
new String[]{GeneralUtils.getLocalHost()},
Dispatcher.getLocalRampId(),
40000,
firstServiceResponse.getProtocol(),
false,
GenericPacket.UNUSED_FIELD,
E2EComm.DEFAULT_BUFFERSIZE,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
GenericPacket.UNUSED_FIELD,
flowId,
messagePayload
);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ControllerClientTestSender: message sent to the receiver");
String firstFinalMessage = null;
GenericPacket gp = null;
try {
gp = E2EComm.receive(firstResponseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
firstFinalMessage = (String) payload;
}
String secondFinalMessage = null;
gp = null;
try {
gp = E2EComm.receive(secondResponseSocket);
} catch (Exception e) {
e.printStackTrace();
}
if (gp instanceof UnicastPacket) {
UnicastPacket up = (UnicastPacket) gp;
Object payload = null;
try {
payload = E2EComm.deserialize(up.getBytePayload());
} catch (Exception e) {
e.printStackTrace();
}
if (payload instanceof String)
secondFinalMessage = (String) payload;
}
if (firstFinalMessage.equals("message_received") && secondFinalMessage.equals("message_received"))
System.out.println("ControllerClientTestSender: final messages received from the receivers, message transfer completed");
else
System.out.println("ControllerClientTestSender: wrong final messages received from the receivers");
}
/**
* As first and only argument insert the name of the network interface that will be monitored
* by the StatsPrinter thread. It should be specified the one used by the ControllerClient.
* <p>
* In order to know the name of the network interface you can run the command:
* - On Linux: ifconfig
* - On Windows: ipconfig
*
* @param args name of the monitored interface
*/
public static void main(String[] args) {
String monitoredInterface = args[0];
ramp = RampEntryPoint.getInstance(true, null);
/*
* Wait a few second to allow the node to discover neighbors, otherwise the service cannot be found
*/
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
/*
* Force neighbors update to make sure to know them
*/
ramp.forceNeighborsUpdate();
System.out.println("ControllerClientTestSender: registering shutdown hook");
/*
* Setup signal handling in order to always stop RAMP gracefully
*/
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
try {
if (ramp != null && controllerClient != null) {
System.out.println("ShutdownHook is being executed: gracefully stopping RAMP...");
controllerClient.stopClient();
ramp.stopRamp();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}));
controllerClient = ControllerClient.getInstance();
StatsPrinter statsPrinter = new StatsPrinter("output_external.csv", monitoredInterface);
statsPrinter.start();
try {
/*
* Test method to run, match it with the one in ControllerClientTestReceiver
*/
sendOneSeriesOfPacketsToOneReceiver(E2EComm.TCP, 1024, 50, 15);
} catch (Exception e) {
e.printStackTrace();
}
statsPrinter.stopStatsPrinter();
controllerClient.stopClient();
ramp.stopRamp();
}
/**
* Utility to log all network traffic on a specific network interface
*/
public static class StatsPrinter extends Thread {
private static final int TIME_INTERVAL = 500;
private String outputFileName;
private String monitoredInterface;
private boolean active;
public StatsPrinter(String outputFileName, String monitoredInterface) {
this.outputFileName = outputFileName;
this.monitoredInterface = monitoredInterface;
this.active = true;
}
public void stopStatsPrinter() {
this.active = false;
}
public void run() {
File outputFile = new File(outputFileName);
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert printWriter != null;
printWriter.println("timestamp,throughput");
SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
NetworkIF[] networkIFs = hardwareAbstractionLayer.getNetworkIFs();
NetworkIF transmissionInterface = null;
/*
* Select the network interface to monitor
*/
for (NetworkIF networkIF : networkIFs) {
String test = networkIF.getName();
if (networkIF.getName().equals(monitoredInterface)) {
transmissionInterface = networkIF;
}
}
long startTransmittedBytes = 0;
assert transmissionInterface != null;
transmissionInterface.updateNetworkStats();
startTransmittedBytes = startTransmittedBytes + transmissionInterface.getBytesSent();
while (this.active) {
try {
Thread.sleep(TIME_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
long transmittedBytes = 0;
transmissionInterface.updateNetworkStats();
transmittedBytes = transmittedBytes + transmissionInterface.getBytesSent();
System.out.println("bytes sent: " + transmissionInterface.getBytesSent());
long periodTransmittedBytes = transmittedBytes - startTransmittedBytes;
startTransmittedBytes = transmittedBytes;
double throughput = periodTransmittedBytes / ((double) TIME_INTERVAL / 1000);
LocalDateTime localDateTime = LocalDateTime.now();
String timestamp = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
printWriter.println(timestamp + "," + throughput);
}
printWriter.close();
}
}
}
| {
"content_hash": "47c4acf115c7fa79e2670652ee121019",
"timestamp": "",
"source": "github",
"line_count": 2569,
"max_line_length": 212,
"avg_line_length": 44.11599844297392,
"alnum_prop": 0.5567437838600949,
"repo_name": "DSG-UniFE/ramp",
"id": "1e97557bdc8bbd4e16fb7a96dbffcf76da9d4ccd",
"size": "113334",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/sdncontroller/ControllerClientTestSender.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2166"
},
{
"name": "Java",
"bytes": "2167539"
}
],
"symlink_target": ""
} |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.github.johnpersano.supertoasts"
android:versionCode="14"
android:versionName="1.3.1" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application/>
</manifest> | {
"content_hash": "e0728175e5ef254406343c156a63275f",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 68,
"avg_line_length": 25.25,
"alnum_prop": 0.6765676567656765,
"repo_name": "daimajia/SuperToasts",
"id": "7d988e271f092fdca6a0954fecc8ea05bd88d508",
"size": "303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "supertoasts/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "2304"
},
{
"name": "Java",
"bytes": "184287"
}
],
"symlink_target": ""
} |
<?php
namespace AppBundle\Entity;
interface EntityHavingPhoneNumbersInterface
{
/**
* Get phone Numbers
*/
public function getPhoneNumbers();
/**
* Add phoneNumber
*
* @param PhoneNumber $phoneNumber
*/
public function addPhoneNumber(PhoneNumber $phoneNumber);
/**
* Remove phoneNumber
*
* @param PhoneNumber $phoneNumber
*/
public function removePhoneNumber(PhoneNumber $phoneNumber);
} | {
"content_hash": "d46a91429c645235b7caf5eaaf686cb3",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 64,
"avg_line_length": 17.142857142857142,
"alnum_prop": 0.6270833333333333,
"repo_name": "theoboldt/juvem",
"id": "8e6e66c100437ee86f7786bc75bb563cf27417e0",
"size": "705",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/AppBundle/Entity/EntityHavingPhoneNumbersInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10048"
},
{
"name": "HTML",
"bytes": "8494"
},
{
"name": "JavaScript",
"bytes": "246390"
},
{
"name": "PHP",
"bytes": "2484612"
},
{
"name": "SCSS",
"bytes": "42083"
},
{
"name": "Twig",
"bytes": "845089"
}
],
"symlink_target": ""
} |
/**
* If you are developing a project that makes use of Dijit widgets, you will probably want to include the two files
* below; otherwise, you can remove them. When building for release, Dojo will automatically combine all of your
* @imported CSS files into a single file.
*
* It is highly, highly recommended that you develop your CSS using LESS: http://lesscss.org.
*/
@import '../../dojo/resources/dojo.css';
@import '../../dijit/themes/claro/claro.css';
@import '../../dijit/themes/claro/claro.css';
@import "../../dojox/grid/resources/claroGrid.css";
@import 'style.css';
| {
"content_hash": "9374ba6f430525ddb5b5d15b6b08ba71",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 115,
"avg_line_length": 44.92307692307692,
"alnum_prop": 0.7157534246575342,
"repo_name": "znerol/node-delta",
"id": "4a8ffa2305315cb6294eed06a647f5bf84aab9b8",
"size": "584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/vizmerge/app/resources/app.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1358"
},
{
"name": "HTML",
"bytes": "379"
},
{
"name": "JavaScript",
"bytes": "333059"
},
{
"name": "Makefile",
"bytes": "1768"
},
{
"name": "Shell",
"bytes": "70"
}
],
"symlink_target": ""
} |
# A0140887W
###### \java\seedu\doist\commons\core\Config.java
``` java
/**
* Config values used by the app
*/
public class Config {
public static final String DEFAULT_CONFIG_FILE = "config.json";
public static String lastUsedFile = "";
// Config values customizable through config file
private String appTitle = "Doist";
private Level logLevel = Level.INFO;
private String absoluteStoragePath = "";
private String userPrefsFilePath = "preferences.json";
private String todoListFilePath = "data" + File.separator + "todolist.xml";
private String aliasListMapFilePath = "data" + File.separator + "aliaslistmap.xml";
private String todoListName = "MyTodoList";
public Config() {
// Gets current working directory of Doist (in operating system platform-specific style)
absoluteStoragePath = Paths.get(".").toAbsolutePath().normalize().toString();
}
public String getAppTitle() {
return appTitle;
}
public void setAppTitle(String appTitle) {
this.appTitle = appTitle;
}
public Level getLogLevel() {
return logLevel;
}
public void setLogLevel(Level logLevel) {
this.logLevel = logLevel;
}
public String getAbsoluteStoragePath() {
return absoluteStoragePath;
}
/** Model should call this to save the absolute storage path */
public void setAbsoluteStoragePath(String absoluteStoragePath) {
this.absoluteStoragePath = absoluteStoragePath;
}
public String getUserPrefsFilePath() {
return userPrefsFilePath;
}
public String getAbsoluteUserPrefsFilePath() {
return absoluteStoragePath + File.separator + userPrefsFilePath;
}
public void setUserPrefsFilePath(String userPrefsFilePath) {
this.userPrefsFilePath = userPrefsFilePath;
}
public String getTodoListFilePath() {
return todoListFilePath;
}
public String getAbsoluteTodoListFilePath() {
return absoluteStoragePath + File.separator + todoListFilePath;
}
public void setTodoListFilePath(String todoListFilePath) {
this.todoListFilePath = todoListFilePath;
}
public String getAliasListMapFilePath() {
return aliasListMapFilePath;
}
public String getAbsoluteAliasListMapFilePath() {
return absoluteStoragePath + File.separator + aliasListMapFilePath;
}
public void setAliasListMapFilePath(String aliasListMapFilePath) {
this.aliasListMapFilePath = aliasListMapFilePath;
}
public String getTodoListName() {
return todoListName;
}
public void setTodoListName(String todoListName) {
this.todoListName = todoListName;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Config)) { //this handles null as well.
return false;
}
Config o = (Config) other;
return Objects.equals(appTitle, o.appTitle)
&& Objects.equals(logLevel, o.logLevel)
&& Objects.equals(absoluteStoragePath, o.absoluteStoragePath)
&& Objects.equals(userPrefsFilePath, o.userPrefsFilePath)
&& Objects.equals(aliasListMapFilePath, o.aliasListMapFilePath)
&& Objects.equals(todoListFilePath, o.todoListFilePath)
&& Objects.equals(todoListName, o.todoListName);
}
@Override
public int hashCode() {
return Objects.hash(appTitle, logLevel, absoluteStoragePath, userPrefsFilePath,
aliasListMapFilePath, todoListFilePath, todoListName);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("App title : " + appTitle);
sb.append("\nCurrent log level : " + logLevel);
sb.append("\nAbsolute Storage Path : " + absoluteStoragePath);
sb.append("\nPreference file Location : " + userPrefsFilePath);
sb.append("\nAlias List Map file location : " + aliasListMapFilePath);
sb.append("\nLocal data file location : " + todoListFilePath);
sb.append("\nTodoList name : " + todoListName);
return sb.toString();
}
}
```
###### \java\seedu\doist\commons\events\config\AbsoluteStoragePathChangedEvent.java
``` java
/** Indicates the absolute storage path in config has changed*/
public class AbsoluteStoragePathChangedEvent extends BaseEvent {
public final String todoListPath;
public final String aliasListMapPath;
public final String userPrefsPath;
public AbsoluteStoragePathChangedEvent(String todoListPath, String aliasListMapPath, String userPrefsPath) {
this.todoListPath = todoListPath;
this.aliasListMapPath = aliasListMapPath;
this.userPrefsPath = userPrefsPath;
}
@Override
public String toString() {
return "Paths Changed: " + todoListPath + ", " + aliasListMapPath + ", " + userPrefsPath;
}
}
```
###### \java\seedu\doist\commons\events\model\AliasListMapChangedEvent.java
``` java
/** Indicates the AliasListMap in the model has changed*/
public class AliasListMapChangedEvent extends BaseEvent {
public final ReadOnlyAliasListMap data;
public AliasListMapChangedEvent(ReadOnlyAliasListMap data) {
this.data = data;
}
@Override
public String toString() {
return data.toString();
}
}
```
###### \java\seedu\doist\commons\util\ConfigUtil.java
``` java
public static String getConfigPath() throws IOException {
if (!Config.lastUsedFile.isEmpty()) {
return Config.lastUsedFile;
} else {
return Config.DEFAULT_CONFIG_FILE;
}
}
}
```
###### \java\seedu\doist\commons\util\FileUtil.java
``` java
/**
* Writes given string to a file.
* Will create the file if it does not exist yet.
*/
public static void writeToFile(File file, String content) throws IOException {
// Make sure that dirs is made first before writing
File newFile = new File(file.getAbsolutePath());
newFile.getParentFile().mkdirs();
// Write the file now
Files.write(file.toPath(), content.getBytes(CHARSET));
}
```
###### \java\seedu\doist\logic\commands\Command.java
``` java
/**
* Constructs a feedback message to summarise an operation that sorted a listing of tasks.
*
* @param sortType used in the command
* @return summary message for tasks sorted
*/
public static String getMessageForTaskListSortedSummary(List<SortType> sortTypes) {
return String.format(Messages.MESSAGE_TASKS_SORTED_OVERVIEW, sortTypes.toString());
}
```
###### \java\seedu\doist\logic\commands\Command.java
``` java
/**
* Provides any needed dependencies to the command.
* Commands making use of any of these should override this method to gain
* access to the dependencies.
*/
public void setData(Model model, AliasListMapModel aliasModel, ConfigModel configModel) {
this.model = model;
this.aliasModel = aliasModel;
this.configModel = configModel;
}
```
###### \java\seedu\doist\logic\commands\EditCommand.java
``` java
public Optional<FinishedStatus> getFinishStatus() {
return finishStatus;
}
```
###### \java\seedu\doist\logic\commands\FinishCommand.java
``` java
/**
* Marks the task as 'finished' identified using it's last displayed index from the to-do list.
*/
public class FinishCommand extends Command {
public static final String DEFAULT_COMMAND_WORD = "finish";
public static final String MESSAGE_USAGE = DEFAULT_COMMAND_WORD
+ ": Marks the tasks as 'finished' identified by the index numbers used in the last task listing.\n"
+ "Parameters: INDEX [INDEX...] (must be a positive integer)\n"
+ "Example: " + DEFAULT_COMMAND_WORD + " 1 8";
public static final String MESSAGE_FINISH_TASK_SUCCESS = "Finished Tasks: %1$s";
public static final String MESSAGE_TASK_ALREADY_FINISHED = "Tasks already finished: %1$s";
public final int[] targetIndices;
public FinishCommand(int[] targetIndices) {
this.targetIndices = targetIndices;
}
@Override
public CommandResult execute() throws CommandException {
assert model != null;
String outputMessage = "";
ArrayList<ReadOnlyTask> tasksToFinish = getMultipleTasksFromIndices(targetIndices);
ArrayList<ReadOnlyTask> tasksFinished = new ArrayList<ReadOnlyTask>();
ArrayList<ReadOnlyTask> tasksAlreadyFinished = new ArrayList<ReadOnlyTask>();
for (ReadOnlyTask task : tasksToFinish) {
try {
int index = model.finishTask(task);
if (index >= 0) {
EventsCenter.getInstance().post(new JumpToListRequestEvent(index));
}
tasksFinished.add(task);
} catch (TaskNotFoundException tnfe) {
assert false : "The target task cannot be missing";
} catch (TaskAlreadyFinishedException e) {
tasksAlreadyFinished.add(task);
}
}
if (!tasksAlreadyFinished.isEmpty()) {
outputMessage += String.format(MESSAGE_TASK_ALREADY_FINISHED, tasksAlreadyFinished + "\n");
}
if (!tasksFinished.isEmpty()) {
outputMessage += String.format(MESSAGE_FINISH_TASK_SUCCESS, tasksFinished);
}
return new CommandResult(outputMessage, true);
}
}
```
###### \java\seedu\doist\logic\commands\ListCommand.java
``` java
public static final String DEFAULT_COMMAND_WORD = "list";
public static final String MESSAGE_USAGE = DEFAULT_COMMAND_WORD
+ ": List tasks as specified by the parameters\n"
+ "TYPE could be pending, overdue or finished. If no TYPE is specified, all tasks will be listed.\n"
+ "Parameters: [TYPE] [\\from START_TIME] [\\to END_TIME] [\\as PRIORITY] [\\under TAG...]\n"
+ "Example: " + DEFAULT_COMMAND_WORD + " pending \\under school ";
//public static final String MESSAGE_INVALID_PREAMBLE = "Invalid list type! Type should be pending,"
// + " overdue or finished";
public static final String MESSAGE_SUCCESS = "Listed %1$s tasks";
public static final String MESSAGE_PENDING = String.format(MESSAGE_SUCCESS, "pending");
public static final String MESSAGE_FINISHED = String.format(MESSAGE_SUCCESS, "finished");
public static final String MESSAGE_OVERDUE = String.format(MESSAGE_SUCCESS, "overdue");
public static final String MESSAGE_ALL = String.format(MESSAGE_SUCCESS, "all");
private UniqueTagList tagList = new UniqueTagList();
private TaskType type = null;
private TaskDate dates = null;
```
###### \java\seedu\doist\logic\commands\ListCommand.java
``` java
/** Trims trailing whitespace, removes leading whitespace, replaces in-between whitespaces with one underscore
* and converts to uppercase letters. This is so that it can be converted to the TaskType enum.
*
* @param preamble the pre-processed preamble of the list command
* @return the processed preamble
* */
private String processListPreamble(String preamble) {
// remove all trailing spaces, new line characters etc
String processedPreamble = preamble.trim();
// remove all leading spaces, new line characters etc
processedPreamble = processedPreamble.replaceAll("^\\s+", "");
// replace in-between spaces, new line characters etc with _
processedPreamble = processedPreamble.replaceAll("\\s+", "_");
// change to uppercase
processedPreamble = processedPreamble.toUpperCase();
return processedPreamble;
}
/** Default list type if there is no preamble */
private void listDefault() {
type = TaskType.ALL;
}
@Override
public CommandResult execute() {
assert model != null;
model.updateFilteredTaskList(type, tagList, dates);
model.sortTasksByDefault();
String message = "";
if (type != null) {
if (type.equals(TaskType.PENDING)) {
message = MESSAGE_PENDING;
} else if (type.equals(TaskType.FINISHED)) {
message = MESSAGE_FINISHED;
} else if (type.equals(TaskType.ALL)) {
message = MESSAGE_ALL;
} else if (type.equals(TaskType.OVERDUE)) {
message = MESSAGE_OVERDUE;
} else {
message = "";
}
} else {
assert false : "type should not be null!";
}
CommandResult commandResult = tagList.isEmpty() ?
new CommandResult(message) :
new CommandResult(getSuccessMessageListUnder(message, tagList));
return commandResult;
}
```
###### \java\seedu\doist\logic\commands\LoadCommand.java
``` java
/**
* Load a todoList xml file into Doist, replacing current data
*/
public class LoadCommand extends Command {
public String path;
public static final String DEFAULT_COMMAND_WORD = "load";
public static final String MESSAGE_USAGE = DEFAULT_COMMAND_WORD
+ ":\n" + "Loads an external XML data file into Doist and overrides existing tasks." + "\n"
+ "You can use both absolute and relative file paths to a data file. Use // to seperate directories.\n\t"
+ "Parameters: filePath " + "\n\t"
+ "Example: " + DEFAULT_COMMAND_WORD
+ " C:/Users/todolist.xml";
public static final String MESSAGE_SUCCESS = "New data from %1$s loaded! Tasks will be replaced.";
public static final String MESSAGE_UNABLE_TO_READ = "Unable to read file!";
public static final String MESSAGE_INVALID_FILE = "Invalid data file! Unable to load.";
public static final String MESSAGE_NOT_FILE = "This is not a file. Unable to load.";
public static final String MESSAGE_NOT_EXIST = "File does not exist. Unable to load.";
public static final String MESSAGE_INVALID_PATH = "Invalid file path entered! \n%1$s";
public LoadCommand(String path) {
this.path = path;
}
@Override
public CommandResult execute() throws CommandException {
assert model != null;
try {
File file = new File(path);
if (!file.isFile()) {
throw new CommandException(MESSAGE_NOT_FILE);
}
Optional<ReadOnlyTodoList> todoList = new XmlTodoListStorage(file.getCanonicalPath()).readTodoList();
if (todoList.isPresent()) {
model.resetData(todoList.get());
} else {
throw new CommandException(MESSAGE_NOT_EXIST);
}
} catch (DataConversionException e) {
throw new CommandException(MESSAGE_INVALID_FILE);
} catch (IOException e) {
throw new CommandException(MESSAGE_UNABLE_TO_READ);
} catch (SecurityException e) {
throw new CommandException(MESSAGE_UNABLE_TO_READ);
}
return new CommandResult(String.format(MESSAGE_SUCCESS, path), true);
}
}
```
###### \java\seedu\doist\logic\commands\SaveAtCommand.java
``` java
/**
* Changes the absolute storage path by changing config
*/
public class SaveAtCommand extends Command {
public File file;
public static final String DEFAULT_COMMAND_WORD = "save_at";
public static final String MESSAGE_USAGE = DEFAULT_COMMAND_WORD
+ ":\n" + "Changes the storage folder of Doist." + "\n"
+ "You can use both absolute and relative file paths to a folder. Use // to seperate directories.\n\t"
+ "Parameters: path " + "\n\t"
+ "Example: " + DEFAULT_COMMAND_WORD
+ " C:/Users";
public static final String MESSAGE_SUCCESS = "New Storage Path is: %1$s";
public static final String MESSAGE_FILE_EXISTS = "A file already exists with the same name."
+ " Do give a path to a folder!";
public static final String MESSAGE_INVALID_PATH = "Invalid folder path entered! \n%1$s";
public SaveAtCommand(File file) {
this.file = file;
}
@Override
public CommandResult execute() throws CommandException {
assert configModel != null;
if (file.exists() && !file.isDirectory()) {
throw new CommandException(MESSAGE_FILE_EXISTS);
}
// This would trigger an event that will change storage
configModel.changeConfigAbsolutePath(file.toPath().toAbsolutePath());
return new CommandResult(String.format(MESSAGE_SUCCESS, file));
}
}
```
###### \java\seedu\doist\logic\commands\SortCommand.java
``` java
/**
* Sorts all tasks in the to-do list by the specified parameter and shows it to the user.
*/
public class SortCommand extends Command {
public enum SortType {
PRIORITY,
TIME,
ALPHA
}
public List<SortType> sortTypes = new ArrayList<SortType>();
public static final String DEFAULT_COMMAND_WORD = "sort";
public static final String MESSAGE_USAGE = DEFAULT_COMMAND_WORD
+ ":\n" + "Sorts previously listed tasks." + "\n"
+ "You can sort by priority, alphabetical order or by time\n\t"
+ "SORT_TYPE can be PRIORITY, TIME, or ALPHA\n"
+ "Parameters: SORT_TYPE " + "\n\t"
+ "Example: " + DEFAULT_COMMAND_WORD
+ "alpha";
public static final String MESSAGE_SORT_CONSTRAINTS =
"You can only " + DEFAULT_COMMAND_WORD + "\n"
+ SortType.PRIORITY.toString() + " "
+ SortType.ALPHA.toString() + " "
+ SortType.TIME.toString();
public SortCommand(List<SortType> list) {
this.sortTypes = list;
}
@Override
public CommandResult execute() {
assert model != null;
model.sortTasks(sortTypes);
return new CommandResult(getMessageForTaskListSortedSummary(sortTypes));
}
}
```
###### \java\seedu\doist\logic\commands\UnfinishCommand.java
``` java
/**
* Marks the task as 'unfinished' identified using it's last displayed index from the to-do list.
*/
public class UnfinishCommand extends Command {
public static final String DEFAULT_COMMAND_WORD = "unfinish";
public static final String MESSAGE_USAGE = DEFAULT_COMMAND_WORD
+ ": Marks the tasks as not 'finished' identified by the index numbers used in the last task listing.\n"
+ "Parameters: INDEX [INDEX...] (must be a positive integer)\n"
+ "Example: " + DEFAULT_COMMAND_WORD + " 1 8";
public static final String MESSAGE_UNFINISH_TASK_SUCCESS = "Unfinished Tasks: %1$s";
public static final String MESSAGE_TASK_ALREADY_NOT_FINISHED = "Tasks already not finished: %1$s";
public final int[] targetIndices;
public UnfinishCommand(int[] targetIndices) {
this.targetIndices = targetIndices;
}
@Override
public CommandResult execute() throws CommandException {
assert model != null;
String outputMessage = "";
ArrayList<ReadOnlyTask> tasksToUnfinish = getMultipleTasksFromIndices(targetIndices);
ArrayList<ReadOnlyTask> tasksUnfinished = new ArrayList<ReadOnlyTask>();
ArrayList<ReadOnlyTask> tasksAlreadyNotFinished = new ArrayList<ReadOnlyTask>();
for (ReadOnlyTask task : tasksToUnfinish) {
try {
int index = model.unfinishTask(task);
if (index >= 0) {
System.out.println(index);
EventsCenter.getInstance().post(new JumpToListRequestEvent(index));
}
tasksUnfinished.add(task);
} catch (TaskNotFoundException pnfe) {
assert false : "The target task cannot be missing";
} catch (TaskAlreadyUnfinishedException e) {
tasksAlreadyNotFinished.add(task);
}
}
if (!tasksAlreadyNotFinished.isEmpty()) {
outputMessage += String.format(MESSAGE_TASK_ALREADY_NOT_FINISHED, tasksAlreadyNotFinished + "\n");
}
if (!tasksUnfinished.isEmpty()) {
outputMessage += String.format(MESSAGE_UNFINISH_TASK_SUCCESS, tasksUnfinished);
}
return new CommandResult(outputMessage, true);
}
}
```
###### \java\seedu\doist\logic\LogicManager.java
``` java
public LogicManager(Model model, AliasListMapModel aliasModel, ConfigModel configModel) {
this.model = model;
this.aliasModel = aliasModel;
this.configModel = configModel;
this.parser = new Parser(aliasModel);
}
```
###### \java\seedu\doist\logic\parser\DeleteCommandParser.java
``` java
/**
* Parses input arguments and creates a new DeleteCommand object
*/
public class DeleteCommandParser {
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns an DeleteCommand object for execution.
*/
public Command parse(String args) {
int[] indices = ParserUtil.parseStringToIntArray(args);
if (indices == null) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(indices);
}
}
```
###### \java\seedu\doist\logic\parser\LoadCommandParser.java
``` java
/**
* Parses input arguments and creates a new LoadCommand object
*/
public class LoadCommandParser {
public Command parse(String argument) {
// Remove trailing whitespace
String processedArgument = argument.trim();
// remove all leading spaces, new line characters etc
processedArgument = processedArgument.replaceAll("^\\s+", "");
// cannot be empty path
if (processedArgument.isEmpty()) {
return new IncorrectCommand(String.format(LoadCommand.MESSAGE_INVALID_PATH, LoadCommand.MESSAGE_USAGE));
}
return new LoadCommand(processedArgument);
}
}
```
###### \java\seedu\doist\logic\parser\SaveAtCommandParser.java
``` java
/**
* Parses input arguments and creates a new SaveAtCommand object
*/
public class SaveAtCommandParser {
public Command parse(String argument) {
// Remove trailing whitespace
String processedArgument = argument.trim();
// remove all leading spaces, new line characters etc
processedArgument = processedArgument.replaceAll("^\\s+", "");
// cannot be empty path
if (processedArgument.isEmpty()) {
return new IncorrectCommand(String.format(SaveAtCommand.MESSAGE_INVALID_PATH, SaveAtCommand.MESSAGE_USAGE));
}
File file = new File(processedArgument);
try {
String path = file.getCanonicalPath();
return new SaveAtCommand(new File(path));
} catch (IOException e) {
return new IncorrectCommand(String.format(SaveAtCommand.MESSAGE_INVALID_PATH, SaveAtCommand.MESSAGE_USAGE));
} catch (SecurityException e) {
return new IncorrectCommand(String.format(SaveAtCommand.MESSAGE_INVALID_PATH, SaveAtCommand.MESSAGE_USAGE));
}
}
}
```
###### \java\seedu\doist\logic\parser\SortCommandParser.java
``` java
public class SortCommandParser {
public Command parse(String argument) {
// Remove trailing whitespace
String processedArgument = argument.trim();
// remove all leading spaces, new line characters etc
processedArgument = processedArgument.replaceAll("^\\s+", "");
// remove extra spaces in between, change to single space
processedArgument = processedArgument.replaceAll("\\s+", " ");
processedArgument = processedArgument.toUpperCase();
String[] arguments = processedArgument.split(" ");
if (!areValidSortArguments(arguments)) {
return new IncorrectCommand(String.format(SortCommand.MESSAGE_SORT_CONSTRAINTS, SortCommand.MESSAGE_USAGE));
}
return new SortCommand(stringArrayToSortTypeList(arguments));
}
/**
* Returns true if a given string array has a valid sort arguments
*/
public static boolean areValidSortArguments(String[] arguments) {
for (String argument : arguments) {
if (!checkIfValidSortType(argument)) {
return false;
}
}
return true;
}
private static boolean checkIfValidSortType(String argument) {
return argument.equals(SortType.PRIORITY.toString()) ||
argument.equals(SortType.ALPHA.toString()) ||
argument.equals(SortType.TIME.toString());
}
private static List<SortType> stringArrayToSortTypeList(String[] arguments) {
List<SortType> list = new ArrayList<SortType>();
try {
for (String argument : arguments) {
list.add(SortType.valueOf(argument));
}
} catch (IllegalArgumentException e) {
assert false : "Should check that arguments are valid sort type before converting to list";
}
return list;
}
}
```
###### \java\seedu\doist\MainApp.java
``` java
@Override
public void init() throws Exception {
LOGGER.info("=========================[ Initializing " + APPLICATION_NAME + " ]=======================");
super.init();
config = initConfig(getApplicationParameter("config"));
configModel = new ConfigManager(config);
storage = new StorageManager(config.getAbsoluteTodoListFilePath(), config.getAbsoluteAliasListMapFilePath(),
config.getAbsoluteUserPrefsFilePath());
userPrefs = initPrefs(config);
initLogging(config);
model = initModelManager(storage, userPrefs);
aliasModel = initAliasListMapManager(storage);
logic = new LogicManager(model, aliasModel, configModel);
ui = new UiManager(logic, config, userPrefs);
initEventsCenter();
}
```
###### \java\seedu\doist\MainApp.java
``` java
private AliasListMapModel initAliasListMapManager(Storage storage) {
ReadOnlyAliasListMap initialAliasData = initAliasListMapData(storage);
return new AliasListMapManager(initialAliasData);
}
```
###### \java\seedu\doist\model\AliasListMap.java
``` java
/**
* Stores a HashMap of ArrayLists representing the alias list
*/
public class AliasListMap implements ReadOnlyAliasListMap {
private HashMap<String, ArrayList<String>> commandAliases;
```
###### \java\seedu\doist\model\AliasListMap.java
``` java
public AliasListMap() {
setDefaultAliasListMapping();
}
public AliasListMap(ReadOnlyAliasListMap src) {
commandAliases = new HashMap<String, ArrayList<String>>(src.getAliasListMapping());
if (commandAliases.size() < getDefaultAliasListMapping().size()) {
setDefaultAliasListMapping();
}
}
// utility methods
@Override
public String toString() {
return commandAliases.toString();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof AliasListMap // instanceof handles nulls
&& this.getAliasListMapping().equals((((AliasListMap) other).getAliasListMapping())));
}
@Override
public int hashCode() {
return commandAliases.hashCode();
}
}
```
###### \java\seedu\doist\model\AliasListMapManager.java
``` java
/**
* Represents the in-memory model of the aliasListMap
* All changes to any model should be synchronized.
*/
public class AliasListMapManager extends ComponentManager implements AliasListMapModel {
private static final Logger logger = LogsCenter.getLogger(ConfigManager.class);
private final AliasListMap aliasListMap;
/**
* Initializes a AliasListMapManager with the given aliasListMap object
*/
public AliasListMapManager(ReadOnlyAliasListMap aliasListMap) {
super();
assert !CollectionUtil.isAnyNull(aliasListMap);
logger.fine("Initializing AliasListMapManager with aliasListMap: " + aliasListMap);
this.aliasListMap = new AliasListMap(aliasListMap);
}
public AliasListMapManager() {
this(new AliasListMap());
}
@Override
public ReadOnlyAliasListMap getAliasListMap() {
return aliasListMap;
}
@Override
public void setAlias(String alias, String commandWord) {
aliasListMap.setAlias(alias, commandWord);
indicateAliasListMapChanged();
}
/** Returns a list of aliases for the specified command word */
@Override
public List<String> getAliasList(String defaultCommandWord) {
return aliasListMap.getAliasList(defaultCommandWord);
}
@Override
public void removeAlias(String alias) {
aliasListMap.removeAlias(alias);
indicateAliasListMapChanged();
}
```
###### \java\seedu\doist\model\AliasListMapModel.java
``` java
/**
* The API of the AliasListMapModel component.
*/
public interface AliasListMapModel {
/** Returns the AliasListMap */
ReadOnlyAliasListMap getAliasListMap();
/** Sets an alias in the AliasListMap */
void setAlias(String alias, String commandWord);
/** Get the alias list of a defaultCommandWord */
List<String> getAliasList(String defaultCommandWord);
/** Get the valid command list of a defaultCommandWord */
List<String> getValidCommandList(String defaultCommandWord);
/** Get the set of default command words */
Set<String> getDefaultCommandWordSet();
/** Resets alias list to default */
void resetToDefaultCommandWords();
/** Remove the alias if it exists, otherwise nothing happens */
void removeAlias(String alias);
}
```
###### \java\seedu\doist\model\ConfigManager.java
``` java
/**
* Represents the in-memory model of the config data
* All changes to any model should be synchronized.
*/
public class ConfigManager extends ComponentManager implements ConfigModel {
private static final Logger logger = LogsCenter.getLogger(ConfigManager.class);
private final Config config;
/**
* Initializes a ConfigManager with the given config object
*/
public ConfigManager(Config config) {
super();
assert !CollectionUtil.isAnyNull(config);
logger.fine("Initializing ConfigManager with config: " + config);
this.config = config;
}
public ConfigManager() {
this(new Config());
}
//========== change absolute storage path =================================================
@Override
public void changeConfigAbsolutePath(Path path) {
config.setAbsoluteStoragePath(path.toString());
try {
ConfigUtil.saveConfig(config, ConfigUtil.getConfigPath());
indicateAbsoluteStoragePathChanged();
} catch (IOException e) {
logger.warning("Failed to save config file : " + StringUtil.getDetails(e));
}
}
/** Raises an event to indicate the absolute storage path has changed */
private void indicateAbsoluteStoragePathChanged() {
raise(new AbsoluteStoragePathChangedEvent(config.getAbsoluteTodoListFilePath(),
config.getAbsoluteAliasListMapFilePath(), config.getAbsoluteUserPrefsFilePath()));
}
}
```
###### \java\seedu\doist\model\ConfigModel.java
``` java
/**
* The API of the ConfigModel component.
*/
public interface ConfigModel {
/** Change absolute path in config */
void changeConfigAbsolutePath(Path path);
}
```
###### \java\seedu\doist\model\ModelManager.java
``` java
/**
* Initializes a ModelManager with the given to-do list and userPrefs.
*/
public ModelManager(ReadOnlyTodoList todoList, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(todoList, userPrefs);
logger.fine("Initializing with To-do List: " + todoList + " and user prefs " + userPrefs);
this.todoList = new TodoList(todoList);
filteredTasks = new FilteredList<>(this.todoList.getTaskList());
updateFilteredListToShowDefault();
sortTasksByDefault();
saveCurrentToHistory();
}
public ModelManager() {
this(new TodoList(), new UserPrefs());
}
//=========== TodoList =============================================================
@Override
public void resetData(ReadOnlyTodoList newData) {
todoList.resetData(newData);
sortTasksByDefault();
indicateTodoListChanged();
}
@Override
public ReadOnlyTodoList getTodoList() {
return todoList;
}
/** Raises an event to indicate the model has changed */
private void indicateTodoListChanged() {
raise(new TodoListChangedEvent(todoList));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
todoList.removeTask(target);
indicateTodoListChanged();
}
```
###### \java\seedu\doist\model\ModelManager.java
``` java
@Override
public int finishTask(ReadOnlyTask target) throws TaskNotFoundException,
TaskAlreadyFinishedException {
assert target != null;
try {
todoList.changeTaskFinishStatus(target, true);
} catch (TaskAlreadyUnfinishedException e) {
assert false : "finishTask should not try to unfinish tasks!";
}
sortTasksByDefault();
indicateTodoListChanged();
return getFilteredTaskList().indexOf(target);
}
@Override
public int unfinishTask(ReadOnlyTask target) throws TaskNotFoundException,
TaskAlreadyUnfinishedException {
assert target != null;
try {
todoList.changeTaskFinishStatus(target, false);
} catch (TaskAlreadyFinishedException e) {
assert false : "unfinishTask should not try to finish tasks!";
}
sortTasksByDefault();
indicateTodoListChanged();
return getFilteredTaskList().indexOf(target);
}
@Override
public synchronized int addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
todoList.addTask(task);
sortTasksByDefault();
indicateTodoListChanged();
return getFilteredTaskList().indexOf(task);
}
@Override
public int updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask)
throws UniqueTaskList.DuplicateTaskException {
assert editedTask != null;
int todoListIndex = filteredTasks.getSourceIndex(filteredTaskListIndex);
todoList.updateTask(todoListIndex, editedTask);
sortTasksByDefault();
indicateTodoListChanged();
return getFilteredTaskList().indexOf(editedTask);
}
@Override
public void sortTasksByDefault() {
sortTasks(getDefaultSorting());
}
/** Returns the list of SortTypes that is the default sorting.
* Tasks are sorted by time, then priority then by alphabetical order
*/
@Override
public List<SortType> getDefaultSorting() {
List<SortType> sortTypes = new ArrayList<SortType>();
sortTypes.add(SortType.TIME);
sortTypes.add(SortType.PRIORITY);
sortTypes.add(SortType.ALPHA);
return sortTypes;
}
@Override
public void sortTasks(List<SortType> sortTypes) {
todoList.sortTasks(parseSortTypesToComparator(sortTypes));
}
/**
* Parses a list of sort types into a combined comparator that can be used by ReadOnlyTask
* to sort tasks
*
* @param sortTypes a list of SortTypes
* @return the combined comparator
*/
@Override
public void sortTasks(Comparator<ReadOnlyTask> comparator) {
todoList.sortTasks(comparator);
}
@Override
public ReadOnlyTaskCombinedComparator parseSortTypesToComparator(List<SortType> sortTypes) {
List<Comparator<ReadOnlyTask>> comparatorList = new ArrayList<Comparator<ReadOnlyTask>>();
// Finished tasks are always put at the bottom
comparatorList.add(new ReadOnlyTaskFinishedStatusComparator());
for (SortType type : sortTypes) {
if (type.equals(SortType.PRIORITY)) {
comparatorList.add(new ReadOnlyTaskPriorityComparator());
} else if (type.equals(SortType.TIME)) {
comparatorList.add(new ReadOnlyTaskTimingComparator());
} else if (type.equals(SortType.ALPHA)) {
comparatorList.add(new ReadOnlyTaskAlphabetComparator());
}
}
return new ReadOnlyTaskCombinedComparator(comparatorList);
}
```
###### \java\seedu\doist\model\ReadOnlyAliasListMap.java
``` java
/**
* Unmodifiable map of an alias list mapping
*/
public interface ReadOnlyAliasListMap {
/**
* Returns an unmodifiable map of an alias list mapping.
*/
Map<String, ArrayList<String>> getAliasListMapping();
}
```
###### \java\seedu\doist\model\task\FinishedStatus.java
``` java
/**
* Represents the finished status of a task in the to-do list
* Default value is "not finished".
* Will only be "finished" if user "finish" a task with the finish command
*/
public class FinishedStatus {
private boolean isFinished;
public FinishedStatus() {
this(false);
}
public FinishedStatus(boolean status) {
this.isFinished = status;
}
public boolean getIsFinished() {
return this.isFinished;
}
public void setIsFinished(boolean isFinished) {
this.isFinished = isFinished;
}
@Override
public String toString() {
return Boolean.toString(isFinished);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof FinishedStatus // instanceof handles nulls
&& this.isFinished == (((FinishedStatus) other).getIsFinished())); // state check
}
@Override
public int hashCode() {
return Boolean.hashCode(isFinished);
}
}
```
###### \java\seedu\doist\model\task\Priority.java
``` java
/**
* Represents a task's priority in the to-do list
* Guarantees: immutable; is valid as declared in {@link #isValidPriority(String)}
* Default value is NORMAL if not set by user.
*/
public class Priority {
public static final String EXAMPLE = "HIGH";
public static final String MESSAGE_PRIORITY_CONSTRAINTS = "Task priority should be 'NORMAL', "
+ "'IMPORTANT' or 'VERY IMPORTANT'";
public static final PriorityLevel DEFAULT_PRIORITY = PriorityLevel.NORMAL;
public enum PriorityLevel {
NORMAL("Normal"), IMPORTANT("Important"), VERY_IMPORTANT("Very Important");
private String strValue;
PriorityLevel(String value) {
this.strValue = value;
}
@Override
public String toString() {
return this.strValue;
}
}
private final PriorityLevel priority;
/**
* If no parameters are given, it is set to default priority
*/
public Priority() {
this.priority = DEFAULT_PRIORITY;
}
/**
* Validates given string priority.
*
* @throws IllegalValueException if given priority string is invalid.
*/
public Priority(String priority) throws IllegalValueException {
final String processedPriority = processPriorityString(priority);
if (!isValidPriority(processedPriority)) {
throw new IllegalValueException(MESSAGE_PRIORITY_CONSTRAINTS);
}
this.priority = PriorityLevel.valueOf(processedPriority);
}
public PriorityLevel getPriorityLevel() {
return priority;
}
/**
* Returns true if a given string is a valid priority
*/
public static boolean isValidPriority(String priority) {
return priority.equals(PriorityLevel.VERY_IMPORTANT.name())
|| priority.equals(PriorityLevel.IMPORTANT.name())
|| priority.equals(PriorityLevel.NORMAL.name());
}
/**
* Process string to process all whitespace, spaces and new line and
* change all characters to upper case so that it will be a
* valid priority string
* @returns string of the processed priority string
*/
public static String processPriorityString(String priority) {
// remove all trailing spaces, new line characters etc
String processedPriority = priority.trim();
// remove all leading spaces, new line characters etc
processedPriority = processedPriority.replaceAll("^\\s+", "");
// replace in-between spaces, new line characters etc with _
processedPriority = processedPriority.replaceAll("\\s+", "_");
processedPriority = processedPriority.toUpperCase();
return processedPriority;
}
@Override
public String toString() {
return priority.toString();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Priority // instanceof handles nulls
&& this.priority.equals((((Priority) other).priority))); // state check
}
@Override
public int hashCode() {
return priority.toString().hashCode();
}
}
```
###### \java\seedu\doist\model\task\ReadOnlyTask.java
``` java
/**
* Compare the priority of two tasks
* @return: -1 if task2 has a lower priority than task1
*/
public class ReadOnlyTaskPriorityComparator implements Comparator<ReadOnlyTask> {
@Override
public int compare(ReadOnlyTask task1, ReadOnlyTask task2) {
// Highest priority to lowest priority
PriorityLevel task1Priority = task1.getPriority().getPriorityLevel();
PriorityLevel task2Priority = task2.getPriority().getPriorityLevel();
return task2Priority.compareTo(task1Priority);
}
}
/**
* Compare the timing of two tasks
* @return: -1 if task1 is earlier than task2
*/
public class ReadOnlyTaskTimingComparator implements Comparator<ReadOnlyTask> {
@Override
public int compare(ReadOnlyTask task1, ReadOnlyTask task2) {
// Earliest to latest timing
Date date1 = task1.getDates().getStartDate();
Date date2 = task2.getDates().getStartDate();
// Floating tasks are put behind
if (date1 == null && date2 == null) {
return 0;
} else if (date1 == null) {
return 1;
} else if (date2 == null) {
return -1;
}
return date1.compareTo(date2);
}
}
/**
* Compare the tasks by alphabetical order of their description
* @return: -1 if task1 is less than task2 (alphabetical order)
*/
public class ReadOnlyTaskAlphabetComparator implements Comparator<ReadOnlyTask> {
@Override
public int compare(ReadOnlyTask task1, ReadOnlyTask task2) {
// A to Z
String desc1 = task1.getDescription().desc;
String desc2 = task2.getDescription().desc;
return desc1.compareTo(desc2);
}
}
/**
* Compare the finished status of two tasks
* @return: -1 if task1 is not finished but task2 is finished
*/
public class ReadOnlyTaskFinishedStatusComparator implements Comparator<ReadOnlyTask> {
@Override
public int compare(ReadOnlyTask task1, ReadOnlyTask task2) {
FinishedStatus status1 = task1.getFinishedStatus();
FinishedStatus status2 = task2.getFinishedStatus();
// finished tasks are put behind
if (status1.getIsFinished() == status2.getIsFinished()) {
return 0;
} else if (!status1.getIsFinished() && status2.getIsFinished()) {
return -1;
} else {
return 1;
}
}
}
```
###### \java\seedu\doist\model\task\TaskDate.java
``` java
// Workaround has been done because equals method does not work for type Date
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof TaskDate)) {
return false;
}
TaskDate otherDate = (TaskDate) other;
if (this.startDate == otherDate.startDate && this.endDate == otherDate.endDate) {
return true;
} else if (this.startDate == null || otherDate.startDate == null
|| this.endDate == null || otherDate.endDate == null) {
return false;
} else {
return (this.startDate.toString().equals(otherDate.startDate.toString())
&& this.endDate.toString().equals(otherDate.endDate.toString()));
}
}
```
###### \java\seedu\doist\model\task\UniqueTaskList.java
``` java
/**
* Sorts the internal list with comparator
*/
public void sort(Comparator<ReadOnlyTask> comparator) {
assert comparator != null;
internalList.sort(comparator);
}
```
###### \java\seedu\doist\model\task\UniqueTaskList.java
``` java
/**
* Changes the finish status of the equivalent task from the list.
*
* @throws TaskNotFoundException if no such task could be found in the list.
* @throws TaskAlreadyFinishedException if task is already finished but trying to finish it
* @throws TaskAlreadyUnfinishedException if task is already not finished but trying to unfinish it
* @returns true if finish status of task is successfully changed
*/
public boolean changeFinishStatus(ReadOnlyTask toChangeFinish, boolean isToFinish) throws TaskNotFoundException,
TaskAlreadyFinishedException, TaskAlreadyUnfinishedException {
assert toChangeFinish != null;
// Find task in internal list
final int taskIndex = internalList.indexOf(toChangeFinish);
boolean taskExists = taskIndex < 0 ? false : true;
if (!taskExists) {
throw new TaskNotFoundException();
} else {
Task taskToUpdate = internalList.get(taskIndex);
if (isToFinish) {
finishTask(taskToUpdate);
} else {
unfinishTask(taskToUpdate);
}
// Update the observable list so that UI can be updated too
internalList.set(taskIndex, taskToUpdate);
}
return taskExists;
}
private void finishTask(Task toFinish) throws TaskAlreadyFinishedException {
if (toFinish.getFinishedStatus().getIsFinished()) {
logger.info("Attemping to finish task already finished, task details:\n" + toFinish.getAsText());
throw new TaskAlreadyFinishedException();
} else {
toFinish.setFinishedStatus(new FinishedStatus(true));
}
}
private void unfinishTask(Task toUnfinish) throws TaskAlreadyUnfinishedException {
if (!toUnfinish.getFinishedStatus().getIsFinished()) {
logger.info("Attemping to unfinish task that is already not finished, task details:\n"
+ toUnfinish.getAsText());
throw new TaskAlreadyUnfinishedException();
} else {
toUnfinish.setFinishedStatus(new FinishedStatus(false));
}
}
```
###### \java\seedu\doist\model\task\UniqueTaskList.java
``` java
/**
* Signals that a task is already finished and you are trying to finish it again
*/
public static class TaskAlreadyFinishedException extends Exception {}
/**
* Signals that a task is already not finished and you are trying to unfinish it
*/
public static class TaskAlreadyUnfinishedException extends Exception {}
}
```
###### \java\seedu\doist\model\TodoList.java
``` java
public void sortTasks(Comparator<ReadOnlyTask> comparator) {
this.tasks.sort(comparator);
}
```
###### \java\seedu\doist\model\TodoList.java
``` java
/**
* Changes finish status of a task
* @param readOnlyTask task to have its finish status to be changed
* @param isToFinish true if task is to be finished, else task will be unfinished
*/
public boolean changeTaskFinishStatus(ReadOnlyTask readOnlyTask, boolean isToFinish)
throws TaskNotFoundException, TaskAlreadyFinishedException, TaskAlreadyUnfinishedException {
assert readOnlyTask != null;
Task taskToFinish = new Task(readOnlyTask);
return tasks.changeFinishStatus(taskToFinish, isToFinish);
}
```
###### \java\seedu\doist\storage\JsonUserPrefsStorage.java
``` java
@Override
public void setUserPrefsFilePath(String path) {
this.filePath = path;
}
@Override
public String getUserPrefsFilePath() {
return filePath;
}
}
```
###### \java\seedu\doist\storage\Storage.java
``` java
@Override
String getAliasListMapFilePath();
@Override
Optional<ReadOnlyAliasListMap> readAliasListMap() throws DataConversionException, IOException;
@Override
void saveAliasListMap(ReadOnlyAliasListMap aliasListMap) throws IOException;
/**
* Saves the current version of the Aliaslist Map to the hard disk.
* Creates the data file if it is missing.
* Raises {@link DataSavingExceptionEvent} if there was an error during saving.
*/
void handleAliasListMapChangedEvent(AliasListMapChangedEvent almce);
/**
* Edits the storage path for todolistStorage, userPrefsStorage, aliasMapStorage
*/
void handleAbsoluteStoragePathChangedEvent(AbsoluteStoragePathChangedEvent aspce);
}
```
###### \java\seedu\doist\storage\StorageManager.java
``` java
@Override
public void setUserPrefsFilePath(String path) {
userPrefsStorage.setUserPrefsFilePath(path);
}
@Override
public String getUserPrefsFilePath() {
return userPrefsStorage.getUserPrefsFilePath();
}
```
###### \java\seedu\doist\storage\StorageManager.java
``` java
@Override
public void setTodoListFilePath(String path) {
todoListStorage.setTodoListFilePath(path);
}
// ================ ArrayListMap methods ==============================
@Override
public String getAliasListMapFilePath() {
return aliasListMapStorage.getAliasListMapFilePath();
}
@Override
public Optional<ReadOnlyAliasListMap> readAliasListMap() throws DataConversionException, IOException {
return readAliasListMap(aliasListMapStorage.getAliasListMapFilePath());
}
@Override
public Optional<ReadOnlyAliasListMap> readAliasListMap(String filePath) throws DataConversionException,
IOException {
logger.fine("Attempting to read data from aliaslistmap file: " + filePath);
return aliasListMapStorage.readAliasListMap(filePath);
}
@Override
public void saveAliasListMap(ReadOnlyAliasListMap aliasListMap) throws IOException {
saveAliasListMap(aliasListMap, aliasListMapStorage.getAliasListMapFilePath());
}
@Override
public void saveAliasListMap(ReadOnlyAliasListMap aliasListMap, String filePath) throws IOException {
logger.fine("Attempting to write to aliaslistmap data file: " + filePath);
aliasListMapStorage.saveAliasListMap(aliasListMap, filePath);
}
@Override
public void setAliasListMapFilePath(String path) {
aliasListMapStorage.setAliasListMapFilePath(path);
}
```
###### \java\seedu\doist\storage\StorageManager.java
``` java
@Override
@Subscribe
public void handleAliasListMapChangedEvent(AliasListMapChangedEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event, "Local data aliaslistmap changed, saving to file"));
try {
saveAliasListMap(event.data);
} catch (IOException e) {
raise(new DataSavingExceptionEvent(e));
}
}
private void moveFileToNewLocation(String oldPath, String newPath) {
try {
File oldFile = new File(oldPath);
if (oldFile.exists() && !oldFile.isDirectory()) {
File newFile = new File(newPath);
// Ensure that the new directory exists before moving if not there will be an I/O exception
newFile.getParentFile().mkdirs();
Files.move(oldFile.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
logger.info("Tried to move any existing files but failed" + StringUtil.getDetails(e));
}
}
@Override
@Subscribe
public void handleAbsoluteStoragePathChangedEvent(AbsoluteStoragePathChangedEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event, "Absolute storage path changed,"
+ "changing for all storages"));
// Move to the new locations
moveFileToNewLocation(aliasListMapStorage.getAliasListMapFilePath(), event.aliasListMapPath);
moveFileToNewLocation(todoListStorage.getTodoListFilePath(), event.todoListPath);
moveFileToNewLocation(userPrefsStorage.getUserPrefsFilePath(), event.userPrefsPath);
// Change the paths
todoListStorage.setTodoListFilePath(event.todoListPath);
userPrefsStorage.setUserPrefsFilePath(event.userPrefsPath);
aliasListMapStorage.setAliasListMapFilePath(event.aliasListMapPath);
}
}
```
###### \java\seedu\doist\storage\util\XMLHashMapAdapter.java
``` java
/**
* A class to serve as an XML adapter to convert between Java HashMap to
* XML Serializable Key Values
* @see XMLSerializableKeysValues
*/
public class XMLHashMapAdapter extends XmlAdapter<XMLSerializableKeysValues,
Map<String, List<String>>> {
/**
* Converts from XML to Map (HashMap)
*/
@Override
public Map<String, List<String>> unmarshal(XMLSerializableKeysValues in) throws Exception {
HashMap<String, List<String>> hashMap = new HashMap<>();
for (XMLSerializableKeyValueElement entry : in.entries()) {
hashMap.put(entry.key(), entry.value());
}
return hashMap;
}
/**
* Converts from Map (HashMap) to XML
*/
@Override
public XMLSerializableKeysValues marshal(Map<String, List<String>> map) throws Exception {
XMLSerializableKeysValues props = new XMLSerializableKeysValues();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
props.addElement(new XMLSerializableKeyValueElement(entry.getKey(), entry.getValue()));
}
return props;
}
}
```
###### \java\seedu\doist\storage\util\XMLSerializableKeysValues.java
``` java
/**
* A class to contain a list of XML Serializable Key Value Element
* @see XMLSerializableKeyValueElement
*/
public class XMLSerializableKeysValues {
@XmlElement(name = "elements")
private List<XMLSerializableKeyValueElement> entries = new ArrayList<>();
List<XMLSerializableKeyValueElement> entries() {
return Collections.unmodifiableList(entries);
}
void addElement(XMLSerializableKeyValueElement element) {
entries.add(element);
}
}
```
###### \java\seedu\doist\storage\util\XMLSerializableKeyValueElement.java
``` java
/**
* An Immutable class with key and value that is serializable to XML format
*/
public class XMLSerializableKeyValueElement {
@XmlElement(name = "key")
private String key;
@XmlElement(name = "value")
private List<String> value;
XMLSerializableKeyValueElement() {
}
XMLSerializableKeyValueElement(String name, List<String> value) {
this.key = name;
this.value = value;
}
public List<String> value() {
return value;
}
public String key() {
return key;
}
}
```
###### \java\seedu\doist\storage\XmlAdaptedTask.java
``` java
/**
* JAXB-friendly version of the Task.
*/
public class XmlAdaptedTask {
private static final String NULL_STRING = "null";
@XmlElement(required = true)
private String desc;
@XmlElement(required = true)
private String priority;
@XmlElement(required = true)
private String finishedStatus;
@XmlElement(required = true)
private String startDate;
@XmlElement(required = true)
private String endDate;
@XmlElement
private List<XmlAdaptedTag> tagged = new ArrayList<>();
/**
* Constructs an XmlAdaptedTask.
* This is the no-arg constructor that is required by JAXB.
*/
public XmlAdaptedTask() {}
/**
* Converts a given Task into this class for JAXB use.
*
* @param source future changes to this will not affect the created XmlAdaptedTask
*/
public XmlAdaptedTask(ReadOnlyTask source) {
desc = source.getDescription().desc;
priority = source.getPriority().getPriorityLevel().toString();
finishedStatus = Boolean.toString(source.getFinishedStatus().getIsFinished());
startDate = getDateString(source.getDates().getStartDate());
endDate = getDateString(source.getDates().getEndDate());
tagged = new ArrayList<>();
for (Tag tag : source.getTags()) {
tagged.add(new XmlAdaptedTag(tag));
}
}
private String getDateString(Date date) {
if (date != null) {
return date.toString();
} else {
return NULL_STRING;
}
}
/**
* Converts this jaxb-friendly adapted task object into the model's Task object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted task
*/
public Task toModelType() throws IllegalValueException {
// instead of throwing illegal value exception,
// can consider just removing the invalid data
final List<Tag> taskTags = new ArrayList<>();
for (XmlAdaptedTag tag : tagged) {
taskTags.add(tag.toModelType());
}
final Description name = new Description(this.desc);
final Priority priority = new Priority(this.priority);
final FinishedStatus finishedStatus = new FinishedStatus(Boolean.parseBoolean(this.finishedStatus));
final Date startDate = getDate(this.startDate);
final Date endDate = getDate(this.endDate);
final UniqueTagList tags = new UniqueTagList(taskTags);
return new Task(name, priority, finishedStatus, new TaskDate(startDate, endDate), tags);
}
private Date getDate(String dateString) {
if (dateString.equals(NULL_STRING)) {
return null;
} else {
return TaskDate.parseDate(dateString);
}
}
}
```
###### \java\seedu\doist\storage\XmlSerializableAliasListMap.java
``` java
/**
* An Immutable AliasListMap that is serializable to XML format
*/
@XmlRootElement(name = "aliaslistMap")
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlSerializableAliasListMap implements ReadOnlyAliasListMap {
@XmlElement(name = "aliasListMap")
@XmlJavaTypeAdapter(XMLHashMapAdapter.class)
Map<String, List<String>> aliasListMap;
/**
* Creates an empty XmlSerializableAliasListMap.
* This empty constructor is required for marshalling to XML format.
*/
public XmlSerializableAliasListMap() {
aliasListMap = new HashMap<String, List<String>>();
}
/**
* Conversion from model to storage
*/
public XmlSerializableAliasListMap(ReadOnlyAliasListMap src) {
this();
Map<String, ArrayList<String>> map = src.getAliasListMapping();
for (Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
aliasListMap.put(entry.getKey(), list);
}
}
/**
* Conversion from storage to model
*/
@Override
public Map<String, ArrayList<String>> getAliasListMapping() {
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for (Map.Entry<String, List<String>> entry : aliasListMap.entrySet()) {
ArrayList<String> list = null;
if (entry.getValue() != null) {
list = new ArrayList<String>(entry.getValue());
} else {
list = new ArrayList<String>();
}
map.put(entry.getKey(), list);
}
return map;
}
}
```
###### \java\seedu\doist\storage\XmlTodoListStorage.java
``` java
@Override
public void setTodoListFilePath(String path) {
this.filePath = path;
}
}
```
###### \java\seedu\doist\ui\CommandBox.java
``` java
/**
* Sets the command box style to indicate a successful command.
*/
private void setStyleToIndicateCommandSuccess() {
commandTextField.getStyleClass().remove(ERROR_STYLE_CLASS);
// Only add success style if don't already have
if (!commandTextField.getStyleClass().contains(SUCCESS_STYLE_CLASS)) {
commandTextField.getStyleClass().add(SUCCESS_STYLE_CLASS);
}
}
/**
* Sets the command box style to indicate a failed command.
*/
private void setStyleToIndicateCommandFailure() {
commandTextField.getStyleClass().remove(SUCCESS_STYLE_CLASS);
// Only add error style if don't already have
if (!commandTextField.getStyleClass().contains(ERROR_STYLE_CLASS)) {
commandTextField.getStyleClass().add(ERROR_STYLE_CLASS);
}
}
}
```
###### \java\seedu\doist\ui\HelpWindow.java
``` java
/**
* Controller for a window that loads the cheatsheet image
*/
public class HelpWindow extends UiPart<Region> {
private static final Logger logger = LogsCenter.getLogger(HelpWindow.class);
private static final String ICON = "/images/help_icon.png";
private static final String FXML = "HelpWindow.fxml";
private static final String TITLE = "Help";
private static final double MAX_WIDTH = 1040;
private static final double START_HEIGHT = 800;
@FXML
private ImageView helpImage;
@FXML
private ScrollPane scrollPane;
@FXML
private AnchorPane helpWindowRoot;
private final Stage dialogStage;
public HelpWindow() {
super(FXML);
Scene scene = new Scene(getRoot());
//Null passed as the parent stage to make it non-modal.
dialogStage = createDialogStage(TITLE, null, scene);
dialogStage.setHeight(START_HEIGHT);
dialogStage.setWidth(MAX_WIDTH);
dialogStage.setMaxWidth(MAX_WIDTH);
FxViewUtil.setStageIcon(dialogStage, ICON);
FxViewUtil.applyAnchorBoundaryParameters(scrollPane, 0.0, 0.0, 0.0, 0.0);
}
public void show() {
logger.fine("Showing help page about the application.");
dialogStage.showAndWait();
}
}
```
###### \java\seedu\doist\ui\MainWindow.java
``` java
@FXML
private void handleDarkTheme() {
changeToTheme(darkThemeUrl);
}
@FXML
private void handleLightTheme() {
changeToTheme(lightThemeUrl);
}
private void changeToTheme(String themeUrl) {
Scene scene = primaryStage.getScene();
// Remove all existing stylesheets
scene.getStylesheets().removeAll(themeUrls);
// Add the new stylesheet
if (!scene.getStylesheets().contains(themeUrl)) {
scene.getStylesheets().add(themeUrl);
}
}
```
###### \java\seedu\doist\ui\StatusBarFooter.java
``` java
@Subscribe
public void handleStoragePathChangedEvent(AbsoluteStoragePathChangedEvent aspce) {
logger.info(LogsCenter.getEventHandlingLogMessage(aspce, "Setting storage path display to "
+ aspce.todoListPath));
setSaveLocation(aspce.todoListPath);
}
}
```
###### \java\seedu\doist\ui\TaskCard.java
``` java
public class TaskCard extends UiPart<Region> {
private static final String FXML = "TaskListCard.fxml";
private static final String START_TIME_TEXT = "Start: ";
private static final String END_TIME_TEXT = "End: ";
private static final String BY_TIME_TEXT = "By: ";
public static final String NORMAL_STYLE_CLASS = "normal";
public static final String OVERDUE_STYLE_CLASS = "overdue";
public static final String FINISHED_STYLE_CLASS = "finished";
@FXML
private BorderPane cardPane;
@FXML
private GridPane grid;
@FXML
private VBox sideBox;
@FXML
private VBox taskBox;
@FXML
CheckBox checkbox;
@FXML
private Label desc;
@FXML
private Label id;
@FXML
private Label priority;
@FXML
private Label startTime;
@FXML
private Label endTime;
@FXML
private FlowPane tags;
@FXML
private ImageView star1;
@FXML
private ImageView star2;
public TaskCard(ReadOnlyTask task, int displayedIndex) {
super(FXML);
setStyleToNormal();
desc.setText(task.getDescription().desc);
id.setText(displayedIndex + ". ");
initTime(task);
initCheckbox(task);
initPriority(task);
initTags(task);
}
/**
* Initialise time appearance on task card
*/
private void initTime(ReadOnlyTask task) {
if (task.getDates().isDeadline()) {
startTime.setText(BY_TIME_TEXT + prettyDate(task.getDates().getStartDate()));
endTime.setText("");
} else if (task.getDates().isEvent()) {
startTime.setText(START_TIME_TEXT + prettyDate(task.getDates().getStartDate()));
endTime.setText(END_TIME_TEXT + prettyDate(task.getDates().getEndDate()));
} else {
// floating task
startTime.setText("");
endTime.setText("");
}
if (task.getDates().isPast()) {
setStyleToOverdue();
}
}
/**
* Initialise checkbox to be marked or unmarked
*/
private void initCheckbox(ReadOnlyTask task) {
// Don't allow user to mark or unmark checkbox
checkbox.setDisable(true);
// Disabled but opacity is force set to 1
checkbox.setStyle("-fx-opacity: 1");
if (task.getFinishedStatus().getIsFinished()) {
checkbox.setSelected(true);
setStyleToFinished();
} else {
checkbox.setSelected(false);
}
}
/**
* Initialise priority to show text and the stars
*/
private void initPriority(ReadOnlyTask task) {
priority.setText(task.getPriority().toString());
if (task.getPriority().getPriorityLevel().equals(Priority.PriorityLevel.NORMAL)) {
// Disable both stars
star1.setImage(null);
star2.setImage(null);
} else if (task.getPriority().getPriorityLevel().equals(Priority.PriorityLevel.IMPORTANT)) {
// Disable one star
star2.setImage(null);
}
}
private void initTags(ReadOnlyTask task) {
task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
/**
* Sets the card pane style to the style of a normal task
*/
private void setStyleToNormal() {
cardPane.getStyleClass().remove(OVERDUE_STYLE_CLASS);
cardPane.getStyleClass().remove(FINISHED_STYLE_CLASS);
// Only add style if don't already have
if (!cardPane.getStyleClass().contains(NORMAL_STYLE_CLASS)) {
cardPane.getStyleClass().add(NORMAL_STYLE_CLASS);
}
}
/**
* Sets the card pane style to the style of an overdue task
*/
private void setStyleToOverdue() {
cardPane.getStyleClass().remove(NORMAL_STYLE_CLASS);
cardPane.getStyleClass().remove(FINISHED_STYLE_CLASS);
// Only add style if don't already have
if (!cardPane.getStyleClass().contains(OVERDUE_STYLE_CLASS)) {
cardPane.getStyleClass().add(OVERDUE_STYLE_CLASS);
}
}
/**
* Sets the card pane style to the style of a normal task
*/
private void setStyleToFinished() {
cardPane.getStyleClass().remove(OVERDUE_STYLE_CLASS);
cardPane.getStyleClass().remove(NORMAL_STYLE_CLASS);
// Only add style if don't already have
if (!cardPane.getStyleClass().contains(FINISHED_STYLE_CLASS)) {
cardPane.getStyleClass().add(FINISHED_STYLE_CLASS);
}
}
```
###### \resources\view\DarkTheme.css
``` css
@import url("CommandBoxCss.css");
@import url("Extensions.css");
.background {
-fx-background-color: #000000;
}
.check-box>.box {
-fx-background-insets: 0;
-fx-background-radius: 0;
-fx-background-color: #777777;
}
.check-box:selected>.box>.mark {
-fx-background-color: white;
}
.label {
-fx-font-size: 11pt;
-fx-font-family: "Segoe UI Semibold";
-fx-text-fill: #555555;
-fx-opacity: 0.9;
}
.label-bright {
-fx-font-size: 11pt;
-fx-font-family: "Segoe UI Semibold";
-fx-text-fill: white;
-fx-opacity: 1;
}
.label-header {
-fx-font-size: 32pt;
-fx-font-family: "Segoe UI Light";
-fx-text-fill: white;
-fx-opacity: 1;
}
.tab-pane {
-fx-padding: 0 0 0 1;
}
.tab-pane .tab-header-area {
-fx-padding: 0 0 0 0;
-fx-min-height: 0;
-fx-max-height: 0;
}
.list-view {
-fx-selection-bar:#555555;
-fx-selection-bar-non-focused: #555555;
-fx-background-insets: 0;
-fx-padding: -2px;
}
.list-view .list-cell:even {
-fx-control-inner-background: #424242;
}
.list-view .list-cell:odd {
-fx-control-inner-background: #303030;
}
.list-cell {
-fx-label-padding: 0 0 0 0;
-fx-graphic-text-gap : 0;
-fx-padding: 0 0 0 0;
-fx-border-color: transparent;
}
.list-cell .label {
-fx-text-fill: white;
}
.cell_big_label {
-fx-font-size: 16px;
-fx-text-fill: #010504;
}
.cell_small_label {
-fx-font-size: 11px;
-fx-text-fill: #010504;
}
.anchor-pane {
-fx-background-color:#303030;
-fx-text-fill: #010504;
}
.anchor-pane-with-border {
-fx-background-color: #303030;
-fx-border-color: #303030;
-fx-border-top-width: 1px;
}
.status-bar {
-fx-background-color: #000000;
}
.result-display {
-fx-background-color: #000000;
}
.result-display .label {
-fx-text-fill: black !important;
}
.status-bar .label {
-fx-text-fill: white;
}
.status-bar-with-border {
-fx-background-color: #303030;
-fx-border-color: transparent;
-fx-border-width: 0px;
}
.status-bar-with-border .label {
-fx-text-fill: white;
}
.grid-pane {
-fx-background-color: transparent;
-fx-border-color: #303030;
-fx-border-width: 1px;
}
.grid-pane .anchor-pane {
-fx-background-color: #303030;
}
.context-menu {
-fx-background-color: #303030;
}
.context-menu .label {
-fx-text-fill: white;
}
.menu-bar {
-fx-background-color:#303030;
}
.menu-item:focused {
-fx-background-color:#212121;
}
.menu-bar .label {
-fx-font-size: 14pt;
-fx-font-family: "Segoe UI Light";
-fx-text-fill: white;
-fx-opacity: 0.9;
}
.menu .left-container {
-fx-background-color: black;
}
.menu:showing {
-fx-background-color: #303030;
}
.menu:hover {
-fx-background-color: #303030;
}
/*
* Metro style Push Button
* Author: Pedro Duque Vieira
* http://pixelduke.wordpress.com/2012/10/23/jmetro-windows-8-controls-on-java/
*/
.button {
-fx-padding: 5 22 5 22;
-fx-border-color: #e2e2e2;
-fx-border-width: 2;
-fx-background-radius: 0;
-fx-background-color: #1d1d1d;
-fx-font-family: "Segoe UI", Helvetica, Arial, sans-serif;
-fx-font-size: 11pt;
-fx-text-fill: #d8d8d8;
-fx-background-insets: 0 0 0 0, 0, 1, 2;
}
.button:hover {
-fx-background-color: #3a3a3a;
}
.button:pressed, .button:default:hover:pressed {
-fx-background-color: white;
-fx-text-fill: #1d1d1d;
}
.button:focused {
-fx-border-color: white, white;
-fx-border-width: 1, 1;
-fx-border-style: solid, segments(1, 1);
-fx-border-radius: 0, 0;
-fx-border-insets: 1 1 1 1, 0;
}
.button:disabled, .button:default:disabled {
-fx-opacity: 0.4;
-fx-background-color: #1d1d1d;
-fx-text-fill: white;
}
.button:default {
-fx-background-color: -fx-focus-color;
-fx-text-fill: #ffffff;
}
.button:default:hover {
-fx-background-color: derive(-fx-focus-color, 30%);
}
.dialog-pane {
-fx-background-color: #1d1d1d;
}
.dialog-pane > *.button-bar > *.container {
-fx-background-color: #1d1d1d;
}
.dialog-pane > *.label.content {
-fx-font-size: 14px;
-fx-font-weight: bold;
-fx-text-fill: white;
}
.dialog-pane:header *.header-panel {
-fx-background-color: derive(#1d1d1d, 25%);
}
.dialog-pane:header *.header-panel *.label {
-fx-font-size: 18px;
-fx-font-style: italic;
-fx-fill: white;
-fx-text-fill: white;
}
.scroll-bar .track-background {
-fx-background-color: #212121;
}
.scroll-bar .thumb {
-fx-background-color: #555555;
-fx-background-insets: 3;
}
.scroll-bar .increment-button, .scroll-bar .decrement-button {
-fx-background-color: transparent;
-fx-padding: 0 0 0 0;
}
.scroll-bar .increment-arrow, .scroll-bar .decrement-arrow {
-fx-shape: " ";
}
.scroll-bar:vertical .increment-arrow, .scroll-bar:vertical .decrement-arrow {
-fx-padding: 1 8 1 8;
}
.scroll-bar:horizontal .increment-arrow, .scroll-bar:horizontal .decrement-arrow {
-fx-padding: 8 1 8 1;
}
.list-view .scroll-bar:horizontal {
-fx-opacity: 1;
}
#cardPane {
-fx-background-color: transparent;
-fx-border-width: 0 0 0 4;
}
/* for normal tasks in cardPane */
.normal {
-fx-border-color: #76d7ea;
}
/* for overdue tasks in cardPane */
.overdue {
-fx-border-color: #fc80a5;
}
/* for finished tasks in cardPane */
.finished {
-fx-border-color: #99ff99;
}
#commandTypeLabel {
-fx-font-size: 11px;
-fx-text-fill: #F70D1A;
}
#sideBox {
-fx-border-color: transparent;
}
.text-area {
-fx-background-insets: 0;
-fx-text-fill: white;
-fx-padding: -2px;
}
.text-area .content {
-fx-background-color: #212121;
-fx-border-color: #212121;
}
.text-area:focused .content {
-fx-background-color: #212121;
}
.text-area:focused {
-fx-highlight-fill: white;
}
#taskBox {
-fx-border-color: #212121;
-fx-border-width: 0 0 0 0;
}
#filterField, #taskListPanel, #taskWebpage {
-fx-effect: innershadow(gaussian, black, 10, 0, 0, 0);
}
#tags {
-fx-hgap: 7;
-fx-vgap: 3;
}
#tags .label {
-fx-text-fill: white;
-fx-background-color: #888888;
-fx-padding: 1 3 1 3;
-fx-border-radius: 2;
-fx-background-radius: 2;
-fx-font-size: 11;
}
.error {
-fx-background-color: #ffb3b3;
}
.white {
-fx-background-color: #a9a9a9 , #e3e3e4, #e3e3e4;
}
```
###### \resources\view\HelpWindow.fxml
``` fxml
<AnchorPane fx:id="helpWindowRoot" prefHeight="500.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
<children>
<ScrollPane fx:id="scrollPane" prefWidth="1020.0">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0">
<children>
<ImageView fx:id="helpImage" fitWidth="1000.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="@../images/cheatsheet.png" />
</image>
</ImageView>
</children>
</AnchorPane>
</content>
</ScrollPane>
</children>
</AnchorPane>
```
###### \resources\view\LightTheme.css
``` css
@import url("CommandBoxCss.css");
@import url("Extensions.css");
.background {
-fx-background-color: #000000;
}
.check-box>.box {
-fx-background-insets: 0;
-fx-background-radius: 0;
-fx-background-color: #DFEFF0;
}
.label {
-fx-font-size: 11pt;
-fx-font-family: "Segoe UI Semibold";
-fx-text-fill: #555555;
-fx-opacity: 0.9;
}
.label-bright {
-fx-font-size: 11pt;
-fx-font-family: "Segoe UI Semibold";
-fx-text-fill: white;
-fx-opacity: 1;
}
.label-header {
-fx-font-size: 32pt;
-fx-font-family: "Segoe UI Light";
-fx-text-fill: white;
-fx-opacity: 1;
}
.tab-pane {
-fx-padding: 0 0 0 1;
}
.tab-pane .tab-header-area {
-fx-padding: 0 0 0 0;
-fx-min-height: 0;
-fx-max-height: 0;
}
.list-view {
-fx-selection-bar:#A0C6DD;
-fx-selection-bar-non-focused: #A0C6DD;
-fx-background-insets: 0;
}
.list-view .list-cell:even {
-fx-control-inner-background: #F5FAFA;
-fx-text-fill: black;
}
.list-view .list-cell:odd {
-fx-control-inner-background: transparent;
-fx-text-fill: black;
}
.list-cell {
-fx-label-padding: 0 0 0 0;
-fx-graphic-text-gap : 0;
-fx-padding: 0 0 0 0;
-fx-border-color: transparent;
}
.list-cell .label {
-fx-text-fill: #010504;
}
.cell_big_label {
-fx-font-size: 16px;
-fx-text-fill: #010504;
}
.cell_small_label {
-fx-font-size: 11px;
-fx-text-fill: #010504;
}
.anchor-pane {
-fx-background-color:#FFFFFF;
-fx-text-fill: #010504;
}
.anchor-pane-with-border {
-fx-background-color: #FFFFFF;
-fx-border-color: #FFFFFF;
-fx-border-top-width: 1px;
}
.status-bar {
-fx-background-color: #000000;
}
.result-display {
-fx-background-color: #000000;
}
.result-display .label {
-fx-text-fill: black !important;
}
.status-bar .label {
-fx-text-fill: black;
}
.status-bar-with-border {
-fx-background-color: #FFFFFF;
-fx-border-color: transparent;
-fx-border-width: 0px;
}
.status-bar-with-border .label {
-fx-text-fill: black;
}
.grid-pane {
-fx-background-color: transparent;
-fx-border-color: transparent;
-fx-border-width: 1px;
}
.grid-pane .anchor-pane {
-fx-background-color: #FFFFFF;
}
.context-menu {
-fx-background-color: #FFFFFF;
}
.context-menu .label {
-fx-text-fill: black;
}
.menu-bar {
-fx-background-color:#FFFFFF;
}
.menu-item:focused {
-fx-background-color:#F5FAFA;
}
.menu-bar .label {
-fx-font-size: 14pt;
-fx-font-family: "Segoe UI Light";
-fx-text-fill: black;
-fx-opacity: 0.9;
}
.menu .left-container {
-fx-background-color: black;
}
.menu:showing {
-fx-background-color: #F5FAFA;
}
.menu:hover {
-fx-background-color: #F5FAFA;
}
/*
* Metro style Push Button
* Author: Pedro Duque Vieira
* http://pixelduke.wordpress.com/2012/10/23/jmetro-windows-8-controls-on-java/
*/
.button {
-fx-padding: 5 22 5 22;
-fx-border-color: #e2e2e2;
-fx-border-width: 2;
-fx-background-radius: 0;
-fx-background-color: #1d1d1d;
-fx-font-family: "Segoe UI", Helvetica, Arial, sans-serif;
-fx-font-size: 11pt;
-fx-text-fill: #d8d8d8;
-fx-background-insets: 0 0 0 0, 0, 1, 2;
}
.button:hover {
-fx-background-color: #3a3a3a;
}
.button:pressed, .button:default:hover:pressed {
-fx-background-color: white;
-fx-text-fill: #1d1d1d;
}
.button:focused {
-fx-border-color: white, white;
-fx-border-width: 1, 1;
-fx-border-style: solid, segments(1, 1);
-fx-border-radius: 0, 0;
-fx-border-insets: 1 1 1 1, 0;
}
.button:disabled, .button:default:disabled {
-fx-opacity: 0.4;
-fx-background-color: #1d1d1d;
-fx-text-fill: white;
}
.button:default {
-fx-background-color: -fx-focus-color;
-fx-text-fill: #ffffff;
}
.button:default:hover {
-fx-background-color: derive(-fx-focus-color, 30%);
}
.dialog-pane {
-fx-background-color: #1d1d1d;
}
.dialog-pane > *.button-bar > *.container {
-fx-background-color: #1d1d1d;
}
.dialog-pane > *.label.content {
-fx-font-size: 14px;
-fx-font-weight: bold;
-fx-text-fill: white;
}
.dialog-pane:header *.header-panel {
-fx-background-color: derive(#1d1d1d, 25%);
}
.dialog-pane:header *.header-panel *.label {
-fx-font-size: 18px;
-fx-font-style: italic;
-fx-fill: white;
-fx-text-fill: white;
}
.scroll-bar .track-background {
-fx-background-color: #F5FAFA;
}
.scroll-bar .thumb {
-fx-background-color: #6D929B;
-fx-background-insets: 3;
}
.scroll-bar .increment-button, .scroll-bar .decrement-button {
-fx-background-color: transparent;
-fx-padding: 0 0 0 0;
}
.scroll-bar .increment-arrow, .scroll-bar .decrement-arrow {
-fx-shape: " ";
}
.scroll-bar:vertical .increment-arrow, .scroll-bar:vertical .decrement-arrow {
-fx-padding: 1 8 1 8;
}
.scroll-bar:horizontal .increment-arrow, .scroll-bar:horizontal .decrement-arrow {
-fx-padding: 8 1 8 1;
}
.list-view .scroll-bar:horizontal {
-fx-opacity: 1;
-fx-padding:-2;
}
#cardPane {
-fx-background-color: transparent;
-fx-border-width: 0 0 0 4;
}
/* for normal tasks in cardPane */
.normal {
-fx-border-color: #76d7ea;
}
/* for overdue tasks in cardPane */
.overdue {
-fx-border-color: #fc80a5;
}
/* for finished tasks in cardPane */
.finished {
-fx-border-color: #99ff99;
}
#commandTypeLabel {
-fx-font-size: 11px;
-fx-text-fill: #F70D1A;
}
#sideBox {
-fx-border-color: transparent;
}
.text-area {
-fx-background-insets: 0;
-fx-background-color: #F5FAFA;
-fx-text-fill: #005B9A;
}
.text-area .content {
-fx-background-color: #F5FAFA;
}
.text-area:focused .content {
-fx-background-color: #F5FAFA;
}
.text-area:focused {
-fx-highlight-fill: #7ecfff;
}
#taskBox {
-fx-border-color: #89CFF0;
-fx-border-width: 0 0 0 0;
}
#filterField, #taskListPanel, #taskWebpage {
-fx-effect: innershadow(gaussian, black, 10, 0, 0, 0);
}
#tags {
-fx-hgap: 7;
-fx-vgap: 3;
}
#tags .label {
-fx-text-fill: white;
-fx-background-color: #383838;
-fx-padding: 1 3 1 3;
-fx-border-radius: 2;
-fx-background-radius: 2;
-fx-font-size: 11;
}
.error {
-fx-background-color: #ffb3b3;
}
.white {
-fx-background-color: #a9a9a9 , white , white;
}
```
###### \resources\view\MainWindow.fxml
``` fxml
<VBox maxHeight="Infinity" maxWidth="Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
<children>
<MenuBar VBox.vgrow="NEVER">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleExit" text="Exit" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem fx:id="helpMenuItem" mnemonicParsing="false" onAction="#handleHelp" text="Help" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Theme">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleLightTheme" text="LightTheme" />
<MenuItem mnemonicParsing="false" onAction="#handleDarkTheme" text="DarkTheme" />
</items>
</Menu>
</menus>
</MenuBar>
<AnchorPane fx:id="commandBoxPlaceholder" styleClass="anchor-pane-with-border" VBox.vgrow="NEVER">
<padding>
<Insets bottom="5.0" left="10.0" right="10.0" top="5.0" />
</padding>
</AnchorPane>
<AnchorPane fx:id="resultDisplayPlaceholder" maxHeight="100" minHeight="100" prefHeight="100" styleClass="anchor-pane-with-border" VBox.vgrow="NEVER">
<padding>
<Insets bottom="5.0" left="10.0" right="10.0" top="5.0" />
</padding>
</AnchorPane>
<AnchorPane fx:id="taskListPanelPlaceholder" maxHeight="Infinity" styleClass="anchor-pane" VBox.vgrow="ALWAYS">
<VBox.margin>
<Insets />
</VBox.margin></AnchorPane>
<AnchorPane fx:id="statusbarPlaceholder" VBox.vgrow="NEVER" />
</children>
</VBox>
```
###### \resources\view\TaskListCard.fxml
``` fxml
<BorderPane id="cardPane" fx:id="cardPane" maxWidth="Infinity" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
<center>
<GridPane fx:id="grid" maxWidth="Infinity" BorderPane.alignment="CENTER">
<columnConstraints>
<ColumnConstraints hgrow="ALWAYS" maxWidth="40.0" />
<ColumnConstraints hgrow="ALWAYS" maxWidth="Infinity" minWidth="150.0" />
</columnConstraints>
<children>
<VBox fx:id="sideBox" maxWidth="10.0" prefHeight="100.0" prefWidth="10.0">
<children>
<CheckBox fx:id="checkbox" mnemonicParsing="false">
<padding>
<Insets bottom="10.0" left="5.0" />
</padding>
</CheckBox>
<ImageView fx:id="star1" fitHeight="25.0" fitWidth="25.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="@../images/star.png" />
</image>
<VBox.margin>
<Insets left="5.0" />
</VBox.margin>
</ImageView>
<ImageView fx:id="star2" fitHeight="25.0" fitWidth="25.0" layoutX="10.0" layoutY="41.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="@../images/star.png" />
</image>
<VBox.margin>
<Insets left="5.0" top="5.0" />
</VBox.margin>
</ImageView>
</children>
</VBox>
<VBox fx:id="taskBox" maxWidth="Infinity" prefHeight="100.0" GridPane.columnIndex="1" GridPane.hgrow="ALWAYS" GridPane.vgrow="ALWAYS">
<children>
<FlowPane maxWidth="Infinity" rowValignment="TOP">
<children>
<HBox>
<children>
<Label fx:id="id" styleClass="cell_big_label" text="asdasdadasdasdasdasdasdasdadasdasdasdasdasdasdadasdasdasdasdasdasdadasdasdasdasdasdasdadasdasdasdasd" />
<Label fx:id="desc" maxWidth="Infinity" styleClass="cell_big_label" text="\$first" />
</children>
</HBox>
</children>
</FlowPane>
<FlowPane fx:id="tags" alignment="CENTER_LEFT" />
<Label fx:id="priority" styleClass="cell_small_label" text="\$priority" />
<Label fx:id="startTime" styleClass="cell_small_label" text="\$startTime" />
<Label fx:id="endTime" styleClass="cell_small_label" text="\$endTime" />
</children>
</VBox>
</children>
<rowConstraints>
<RowConstraints vgrow="ALWAYS" />
</rowConstraints>
</GridPane>
</center>
</BorderPane>
```
| {
"content_hash": "58dd42e478f7e6f7e4eef2e606b27cc4",
"timestamp": "",
"source": "github",
"line_count": 2838,
"max_line_length": 191,
"avg_line_length": 30.736081747709655,
"alnum_prop": 0.6346627841658165,
"repo_name": "CS2103JAN2017-W13-B4/main",
"id": "d878c67d212b7d8bde5960f15404955a5b55767b",
"size": "87229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "collated/main/A0140887W.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "259"
},
{
"name": "CSS",
"bytes": "13226"
},
{
"name": "Java",
"bytes": "540424"
},
{
"name": "Shell",
"bytes": "1525"
}
],
"symlink_target": ""
} |
package org.onosproject.incubator.net.virtual.cli;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Completion;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.api.action.Option;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.incubator.net.virtual.NetworkId;
import org.onosproject.incubator.net.virtual.VirtualNetworkAdminService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
/**
* Creates a new virtual link.
*/
@Service
@Command(scope = "onos", name = "vnet-create-link",
description = "Creates a new virtual link in a network.")
public class VirtualLinkCreateCommand extends AbstractShellCommand {
@Argument(index = 0, name = "networkId", description = "Network ID",
required = true, multiValued = false)
@Completion(VirtualNetworkCompleter.class)
Long networkId = null;
@Argument(index = 1, name = "srcDeviceId", description = "Source device ID",
required = true, multiValued = false)
@Completion(VirtualDeviceCompleter.class)
String srcDeviceId = null;
@Argument(index = 2, name = "srcPortNum", description = "Source port number",
required = true, multiValued = false)
@Completion(VirtualPortCompleter.class)
Integer srcPortNum = null;
@Argument(index = 3, name = "dstDeviceId", description = "Destination device ID",
required = true, multiValued = false)
@Completion(VirtualDeviceCompleter.class)
String dstDeviceId = null;
@Argument(index = 4, name = "dstPortNum", description = "Destination port number",
required = true, multiValued = false)
@Completion(VirtualPortCompleter.class)
Integer dstPortNum = null;
@Option(name = "-b", aliases = "--bidirectional",
description = "If this argument is passed in then the virtual link created will be bidirectional, " +
"otherwise the link will be unidirectional.",
required = false, multiValued = false)
boolean bidirectional = false;
@Override
protected void doExecute() {
VirtualNetworkAdminService service = get(VirtualNetworkAdminService.class);
ConnectPoint src = new ConnectPoint(DeviceId.deviceId(srcDeviceId), PortNumber.portNumber(srcPortNum));
ConnectPoint dst = new ConnectPoint(DeviceId.deviceId(dstDeviceId), PortNumber.portNumber(dstPortNum));
service.createVirtualLink(NetworkId.networkId(networkId), src, dst);
if (bidirectional) {
service.createVirtualLink(NetworkId.networkId(networkId), dst, src);
}
print("Virtual link successfully created.");
}
}
| {
"content_hash": "c97bd9a8343ca14b53e880fe7ced6fb6",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 113,
"avg_line_length": 41.55882352941177,
"alnum_prop": 0.7133757961783439,
"repo_name": "oplinkoms/onos",
"id": "4bc6ea5b84ab6b9f52b3ea56171c18a8742be07d",
"size": "3443",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "apps/virtual/app/src/main/java/org/onosproject/incubator/net/virtual/cli/VirtualLinkCreateCommand.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "364443"
},
{
"name": "Dockerfile",
"bytes": "2443"
},
{
"name": "HTML",
"bytes": "319812"
},
{
"name": "Java",
"bytes": "46767333"
},
{
"name": "JavaScript",
"bytes": "4022973"
},
{
"name": "Makefile",
"bytes": "1658"
},
{
"name": "P4",
"bytes": "171319"
},
{
"name": "Python",
"bytes": "977954"
},
{
"name": "Ruby",
"bytes": "8615"
},
{
"name": "Shell",
"bytes": "336303"
},
{
"name": "TypeScript",
"bytes": "894995"
}
],
"symlink_target": ""
} |
package org.jasig.cas.web.support;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.webflow.execution.RequestContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/**
* Abstract implementation of the handler that has all of the logic. Encapsulates the logic in case we get it wrong!
*
* @author Scott Battaglia
* @since 3.3.5
*/
public abstract class AbstractThrottledSubmissionHandlerInterceptorAdapter extends HandlerInterceptorAdapter implements InitializingBean {
private static final int DEFAULT_FAILURE_THRESHOLD = 100;
private static final int DEFAULT_FAILURE_RANGE_IN_SECONDS = 60;
private static final String DEFAULT_USERNAME_PARAMETER = "username";
private static final String SUCCESSFUL_AUTHENTICATION_EVENT = "success";
/** Logger object. **/
protected final Logger logger = LoggerFactory.getLogger(getClass());
@Min(0)
private int failureThreshold = DEFAULT_FAILURE_THRESHOLD;
@Min(0)
private int failureRangeInSeconds = DEFAULT_FAILURE_RANGE_IN_SECONDS;
@NotNull
private String usernameParameter = DEFAULT_USERNAME_PARAMETER;
private double thresholdRate;
@Override
public void afterPropertiesSet() throws Exception {
this.thresholdRate = (double) failureThreshold / (double) failureRangeInSeconds;
}
@Override
public final boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object o) throws Exception {
// we only care about post because that's the only instance where we can get anything useful besides IP address.
if (!"POST".equals(request.getMethod())) {
return true;
}
if (exceedsThreshold(request)) {
recordThrottle(request);
response.sendError(HttpStatus.SC_FORBIDDEN,
"Access Denied for user [" + request.getParameter(usernameParameter)
+ " from IP Address [" + request.getRemoteAddr() + "]");
return false;
}
return true;
}
@Override
public final void postHandle(final HttpServletRequest request, final HttpServletResponse response,
final Object o, final ModelAndView modelAndView) throws Exception {
if (!"POST".equals(request.getMethod())) {
return;
}
final RequestContext context = (RequestContext) request.getAttribute("flowRequestContext");
if (context == null || context.getCurrentEvent() == null) {
return;
}
// User successfully authenticated
if (SUCCESSFUL_AUTHENTICATION_EVENT.equals(context.getCurrentEvent().getId())) {
return;
}
// User submitted invalid credentials, so we update the invalid login count
recordSubmissionFailure(request);
}
public final void setFailureThreshold(final int failureThreshold) {
this.failureThreshold = failureThreshold;
}
public final void setFailureRangeInSeconds(final int failureRangeInSeconds) {
this.failureRangeInSeconds = failureRangeInSeconds;
}
public final void setUsernameParameter(final String usernameParameter) {
this.usernameParameter = usernameParameter;
}
protected double getThresholdRate() {
return this.thresholdRate;
}
protected int getFailureThreshold() {
return this.failureThreshold;
}
protected int getFailureRangeInSeconds() {
return this.failureRangeInSeconds;
}
protected String getUsernameParameter() {
return this.usernameParameter;
}
/**
* Record throttling event.
*
* @param request the request
*/
protected void recordThrottle(final HttpServletRequest request) {
logger.warn("Throttling submission from {}. More than {} failed login attempts within {} seconds.",
request.getRemoteAddr(), failureThreshold, failureRangeInSeconds);
}
/**
* Record submission failure.
*
* @param request the request
*/
protected abstract void recordSubmissionFailure(HttpServletRequest request);
/**
* Determine whether threshold has been exceeded.
*
* @param request the request
* @return true, if successful
*/
protected abstract boolean exceedsThreshold(HttpServletRequest request);
}
| {
"content_hash": "d728a9370422bb4f9464294b61052885",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 139,
"avg_line_length": 32.554794520547944,
"alnum_prop": 0.6968230591205554,
"repo_name": "mabes/cas",
"id": "71ef94f14863771c7121247260cd6ae4485558d5",
"size": "5551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cas-server-webapp-support/src/main/java/org/jasig/cas/web/support/AbstractThrottledSubmissionHandlerInterceptorAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "959"
},
{
"name": "CSS",
"bytes": "24673"
},
{
"name": "HTML",
"bytes": "31487"
},
{
"name": "Java",
"bytes": "2585471"
},
{
"name": "JavaScript",
"bytes": "1021749"
},
{
"name": "Shell",
"bytes": "8253"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.citruspay.sample">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="com.citruspay.sample.BaseApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
tools:replace="android:allowBackup">
<activity
android:name="com.citruspay.sample.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="io.fabric.ApiKey"
android:value="fabaabc4273e4e67d52a5410e9b2fa7a59088976" />
</application>
</manifest>
| {
"content_hash": "5d732b1630a56ad32ba12819c1ee67a9",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 76,
"avg_line_length": 37.03333333333333,
"alnum_prop": 0.6336633663366337,
"repo_name": "citruspay/plug-play-sdk-android",
"id": "daec1c6522e6189769b61892972ad87eac200456",
"size": "1111",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "28392"
}
],
"symlink_target": ""
} |
<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
<class name="ru.job4j.todo.Item" table="items">
<id name="id" column="id">
<generator class="identity"/>
</id>
<property name="description" type="string" column="description"></property>
<property name="created" type="timestamp" column="created"></property>
<property name="done" type="boolean" column="done"></property>
</class>
</hibernate-mapping> | {
"content_hash": "eda30cac795734159fa4caa9cc44a5a6",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 83,
"avg_line_length": 48.5,
"alnum_prop": 0.6391752577319587,
"repo_name": "dbelokursky/dbelokursky",
"id": "9bf78dafaec3792b3edc25aec042af605b04f667",
"size": "485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_009/01/src/main/resources/ru/job4j/todo/Item.hbm.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18542"
},
{
"name": "HTML",
"bytes": "25852"
},
{
"name": "Java",
"bytes": "519057"
},
{
"name": "JavaScript",
"bytes": "2314"
},
{
"name": "TSQL",
"bytes": "487479"
},
{
"name": "XSLT",
"bytes": "494"
}
],
"symlink_target": ""
} |
package org.drools.verifier.core.index.model;
import java.util.ArrayList;
import org.drools.verifier.core.configuration.AnalyzerConfiguration;
import org.drools.verifier.core.index.keys.Key;
import org.drools.verifier.core.index.keys.Values;
import org.drools.verifier.core.index.matchers.FieldMatchers;
import org.drools.verifier.core.maps.KeyDefinition;
import org.drools.verifier.core.util.PortablePreconditions;
public class FieldAction
extends Action {
private static final KeyDefinition FIELD = KeyDefinition.newKeyDefinition().withId("field").build();
private static final KeyDefinition FACT_TYPE__FIELD_NAME = KeyDefinition.newKeyDefinition().withId("factType.fieldName").build();
private final Field field;
public FieldAction(final Field field,
final Column column,
final Values values,
final AnalyzerConfiguration configuration) {
super(column,
ActionSuperType.FIELD_ACTION,
values,
configuration);
this.field = PortablePreconditions.checkNotNull("field",
field);
}
public static FieldMatchers field() {
return new FieldMatchers(FIELD);
}
public Field getField() {
return field;
}
public static KeyDefinition[] keyDefinitions() {
final ArrayList<KeyDefinition> keyDefinitions = new ArrayList<>();
for (final KeyDefinition key : Action.keyDefinitions()) {
keyDefinitions.add(key);
}
keyDefinitions.add(FIELD);
keyDefinitions.add(FACT_TYPE__FIELD_NAME);
return keyDefinitions.toArray(new KeyDefinition[keyDefinitions.size()]);
}
@Override
public Key[] keys() {
final ArrayList<Key> keys = new ArrayList<>();
for (final Key key : super.keys()) {
keys.add(key);
}
keys.add(new Key(FIELD,
field));
keys.add(new Key(FACT_TYPE__FIELD_NAME,
field.getFactType() + "." + field.getName()));
return keys.toArray(new Key[keys.size()]);
}
}
| {
"content_hash": "0613e04d846e00a08d02757674fc8d35",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 133,
"avg_line_length": 31.695652173913043,
"alnum_prop": 0.6250571559213535,
"repo_name": "winklerm/drools",
"id": "659471b2a8aa034a6e6761d8218b966736f586a6",
"size": "2806",
"binary": false,
"copies": "6",
"ref": "refs/heads/addRecursiveAgendaGroupReproducer",
"path": "drools-verifier/drools-verifier-core/src/main/java/org/drools/verifier/core/index/model/FieldAction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "15988"
},
{
"name": "Batchfile",
"bytes": "2554"
},
{
"name": "CSS",
"bytes": "1412"
},
{
"name": "GAP",
"bytes": "197299"
},
{
"name": "HTML",
"bytes": "6163"
},
{
"name": "Java",
"bytes": "34561104"
},
{
"name": "Python",
"bytes": "4555"
},
{
"name": "Ruby",
"bytes": "491"
},
{
"name": "Shell",
"bytes": "1120"
},
{
"name": "XSLT",
"bytes": "24302"
}
],
"symlink_target": ""
} |
angular.module( 'ngbps.emspot', [ ])
.directive('emspot', [function() {
return {
restrict: 'EA',
transclude: true,
controller: 'EmspotCtrl',
templateUrl: 'emspot/emspot.tpl.html',
scope: {
emsname: '@emsname'
}
};
}])
.filter('marketingContent',function(){
return function(activityData){
var ret = [];
if(!! activityData) {
for (var i = 0; i < activityData.length; i++) {
if(!!activityData[i] && activityData[i].baseMarketingSpotDataType == 'MarketingContent') {
ret.push(activityData[i]);
}
}
}
return ret;
};
})
.filter('lang',function(){
return function(attachmentAssets,field){
var ret = [];
for(var j in attachmentAssets){
if( !!attachmentAssets[j].attachmentAssetLanguage && attachmentAssets[j].attachmentAssetLanguage[j] == '-1'){
//multiple language content, choose the selected language
ret.push(attachmentAssets[j]);
break;
} else {
// No language dependent content
ret.push(attachmentAssets[0]);
}
}
return ret;
};
})
.controller( 'EmspotCtrl', function EmspotController( $scope, $log, wcsServices ) {
if (!! $scope.emsname) {
$log.info("Fetching emspot : " + $scope.emsname);
wcsServices.getEmSpotData($scope.emsname).then( function(data) {
var marketingSpotData = data.MarketingSpotData[0].baseMarketingSpotActivityData[0];
$scope.activityData = data.MarketingSpotData[0].baseMarketingSpotActivityData;
}, function(errorMessage) {
$log.info("Could not fetch emspot : " + $scope.emsname);
});
}
})
; | {
"content_hash": "8080569b1398e43e97d39a4b735c6be6",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 115,
"avg_line_length": 28,
"alnum_prop": 0.625615763546798,
"repo_name": "pavanpaik/ngstore",
"id": "37aba788db70d32774f2fbc7433fdfa53eab58f0",
"size": "1624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/emspot/emspot.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11549"
},
{
"name": "CoffeeScript",
"bytes": "1235"
},
{
"name": "JavaScript",
"bytes": "124902"
},
{
"name": "Shell",
"bytes": "150"
}
],
"symlink_target": ""
} |
package com.rodrigodev.xgen4j.test.naming.ifErrorNameHasHyphensTheyAreConvertedToUnderscores;
import java.util.Optional;
/**
* Autogenerated by XGen4J on January 1, 0001.
*/
public class ErrorInfo {
final private Class<? extends Root_name7Error> clazz;
final private ExceptionInfo exceptionInfo;
final private ErrorCode code;
final private Optional<ErrorDescription> description;
final private boolean isCommon;
private ErrorInfo(
Class<? extends Root_name7Error> clazz,
ExceptionInfo exceptionInfo,
ErrorCode code,
Optional<ErrorDescription> description,
boolean isCommon
) {
this.clazz = clazz;
this.exceptionInfo = exceptionInfo;
this.code = code;
this.description = description;
this.isCommon = isCommon;
}
public ErrorInfo(
Class<? extends Root_name7Error> clazz,
ExceptionInfo exceptionInfo,
ErrorCode code,
boolean isCommon
) {
this(clazz, exceptionInfo, code, Optional.<ErrorDescription>empty(), isCommon);
}
public ErrorInfo(
Class<? extends Root_name7Error> clazz,
ExceptionInfo exceptionInfo,
ErrorCode code,
ErrorDescription description,
boolean isCommon
) {
this(clazz, exceptionInfo, code, Optional.of(description), isCommon);
}
public Class<? extends Root_name7Error> clazz() {
return clazz;
}
public ExceptionInfo exceptionInfo() {
return exceptionInfo;
}
public ErrorCode code() {
return code;
}
public Optional<ErrorDescription> description() {
return description;
}
public boolean isCommon() {
return isCommon;
}
@Override
final public boolean equals(Object o){
return o instanceof ErrorInfo && ((ErrorInfo)o).code.equals(code);
}
public static abstract class ErrorDescription {
private boolean usesCustomMessageGenerator;
public ErrorDescription(boolean usesCustomMessageGenerator) {
this.usesCustomMessageGenerator = usesCustomMessageGenerator;
}
public abstract Object description();
public boolean usesCustomMessageGenerator() {
return usesCustomMessageGenerator;
}
}
public static class PlainTextErrorDescription extends ErrorDescription {
private String description;
public PlainTextErrorDescription(String description) {
super(false);
this.description = description;
}
@Override
public String description() {
return description;
}
}
public static class CustomMessageGeneratorErrorDescription<T> extends ErrorDescription {
private Class<T> description;
public CustomMessageGeneratorErrorDescription(Class<T> description) {
super(true);
this.description = description;
}
@Override
public Class<T> description() {
return description;
}
}
}
| {
"content_hash": "598c7088bfe2ad81c673c2546d1386e1",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 93,
"avg_line_length": 26.559322033898304,
"alnum_prop": 0.6375239310784939,
"repo_name": "RodrigoQuesadaDev/XGen4J",
"id": "bed1746cf701cf8329cd8b1b14cd263c773f155f",
"size": "3134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xgen4j/src/test-gen/java/com/rodrigodev/xgen4j/test/naming/ifErrorNameHasHyphensTheyAreConvertedToUnderscores/ErrorInfo.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1981849"
}
],
"symlink_target": ""
} |
"""
This module provides solvers for the unitary Schrodinger equation.
"""
__all__ = ['sesolve']
import os
import types
import numpy as np
import scipy.integrate
from scipy.linalg import norm as la_norm
from qutip.cy.stochastic import normalize_inplace
import qutip.settings as qset
from qutip.qobj import Qobj
from qutip.qobjevo import QobjEvo
from qutip.cy.spconvert import dense1D_to_fastcsr_ket, dense2D_to_fastcsr_fmode
from qutip.cy.spmatfuncs import (cy_expect_psi, cy_ode_psi_func_td,
cy_ode_psi_func_td_with_state)
from qutip.solver import Result, Options, config, solver_safe, SolverSystem
from qutip.superoperator import vec2mat
from qutip.ui.progressbar import (BaseProgressBar, TextProgressBar)
from qutip.cy.openmp.utilities import check_use_openmp, openmp_components
def sesolve(H, psi0, tlist, e_ops=None, args=None, options=None,
progress_bar=None, _safe_mode=True):
"""
Schrödinger equation evolution of a state vector or unitary matrix for a
given Hamiltonian.
Evolve the state vector (``psi0``) using a given Hamiltonian (``H``), by
integrating the set of ordinary differential equations that define the
system. Alternatively evolve a unitary matrix in solving the Schrodinger
operator equation.
The output is either the state vector or unitary matrix at arbitrary points
in time (``tlist``), or the expectation values of the supplied operators
(``e_ops``). If ``e_ops`` is a callback function, it is invoked for each
time in ``tlist`` with time and the state as arguments, and the function
does not use any return values. ``e_ops`` cannot be used in conjunction
with solving the Schrodinger operator equation
Parameters
----------
H : :class:`~Qobj`, :class:`~QobjEvo`, list, or callable
System Hamiltonian as a :obj:`~Qobj , list of :obj:`Qobj` and
coefficient, :obj:`~QObjEvo`, or a callback function for time-dependent
Hamiltonians. List format and options can be found in QobjEvo's
description.
psi0 : :class:`~Qobj`
Initial state vector (ket) or initial unitary operator ``psi0 = U``.
tlist : array_like of float
List of times for :math:`t`.
e_ops : None / list / callback function, optional
A list of operators as `Qobj` and/or callable functions (can be mixed)
or a single callable function. For callable functions, they are called
as ``f(t, state)`` and return the expectation value. A single
callback's expectation value can be any type, but a callback part of a
list must return a number as the expectation value. For operators, the
result's expect will be computed by :func:`qutip.expect` when the state
is a ``ket``. For operator evolution, the overlap is computed by: ::
(e_ops[i].dag() * op(t)).tr()
args : dict, optional
Dictionary of scope parameters for time-dependent Hamiltonians.
options : :obj:`~solver.Options`, optional
Options for the ODE solver.
progress_bar : :obj:`~BaseProgressBar`, optional
Optional instance of :obj:`~BaseProgressBar`, or a subclass thereof,
for showing the progress of the simulation.
Returns
-------
output: :class:`~solver.Result`
An instance of the class :class:`~solver.Result`, which contains either
an array of expectation values for the times specified by ``tlist``, or
an array or state vectors corresponding to the times in ``tlist`` (if
``e_ops`` is an empty list), or nothing if a callback function was
given inplace of operators for which to calculate the expectation
values.
"""
if e_ops is None:
e_ops = []
if isinstance(e_ops, Qobj):
e_ops = [e_ops]
elif isinstance(e_ops, dict):
e_ops_dict = e_ops
e_ops = [e for e in e_ops.values()]
else:
e_ops_dict = None
if progress_bar is None:
progress_bar = BaseProgressBar()
if progress_bar is True:
progress_bar = TextProgressBar()
if not (psi0.isket or psi0.isunitary):
raise TypeError("The unitary solver requires psi0 to be"
" a ket as initial state"
" or a unitary as initial operator.")
if options is None:
options = Options()
if options.rhs_reuse and not isinstance(H, SolverSystem):
# TODO: deprecate when going to class based solver.
if "sesolve" in solver_safe:
H = solver_safe["sesolve"]
if args is None:
args = {}
check_use_openmp(options)
if isinstance(H, SolverSystem):
ss = H
elif isinstance(H, (list, Qobj, QobjEvo)):
ss = _sesolve_QobjEvo(H, tlist, args, options)
elif callable(H):
ss = _sesolve_func_td(H, args, options)
else:
raise Exception("Invalid H type")
func, ode_args = ss.makefunc(ss, psi0, args, e_ops, options)
if _safe_mode:
v = psi0.full().ravel('F')
func(0., v, *ode_args) + v
res = _generic_ode_solve(func, ode_args, psi0, tlist, e_ops, options,
progress_bar, dims=psi0.dims)
if e_ops_dict:
res.expect = {e: res.expect[n]
for n, e in enumerate(e_ops_dict.keys())}
return res
# -----------------------------------------------------------------------------
# A time-dependent unitary wavefunction equation on the list-function format
#
def _sesolve_QobjEvo(H, tlist, args, opt):
"""
Prepare the system for the solver, H can be an QobjEvo.
"""
H_td = -1.0j * QobjEvo(H, args, tlist=tlist)
if opt.rhs_with_state:
H_td._check_old_with_state()
nthread = opt.openmp_threads if opt.use_openmp else 0
H_td.compile(omp=nthread)
ss = SolverSystem()
ss.H = H_td
ss.makefunc = _qobjevo_set
solver_safe["sesolve"] = ss
return ss
def _qobjevo_set(HS, psi, args, e_ops, opt):
"""
From the system, get the ode function and args
"""
H_td = HS.H
H_td.solver_set_args(args, psi, e_ops)
if psi.isunitary:
func = H_td.compiled_qobjevo.ode_mul_mat_f_vec
elif psi.isket:
func = H_td.compiled_qobjevo.mul_vec
else:
raise TypeError("The unitary solver requires psi0 to be"
" a ket as initial state"
" or a unitary as initial operator.")
return func, ()
# -----------------------------------------------------------------------------
# Wave function evolution using a ODE solver (unitary quantum evolution), for
# time dependent hamiltonians.
#
def _sesolve_func_td(H_func, args, opt):
"""
Prepare the system for the solver, H is a function.
"""
ss = SolverSystem()
ss.H = H_func
ss.makefunc = _Hfunc_set
solver_safe["sesolve"] = ss
return ss
def _Hfunc_set(HS, psi, args, e_ops, opt):
"""
From the system, get the ode function and args
"""
H_func = HS.H
if psi.isunitary:
if not opt.rhs_with_state:
func = _ode_oper_func_td
else:
func = _ode_oper_func_td_with_state
else:
if not opt.rhs_with_state:
func = cy_ode_psi_func_td
else:
func = cy_ode_psi_func_td_with_state
return func, (H_func, args)
# -----------------------------------------------------------------------------
# evaluate dU(t)/dt according to the schrodinger equation
#
def _ode_oper_func_td(t, y, H_func, args):
H = H_func(t, args).data * -1j
ym = vec2mat(y)
return (H * ym).ravel("F")
def _ode_oper_func_td_with_state(t, y, H_func, args):
H = H_func(t, y, args).data * -1j
ym = vec2mat(y)
return (H * ym).ravel("F")
# -----------------------------------------------------------------------------
# Solve an ODE for func.
# Calculate the required expectation values or invoke callback
# function at each time step.
def _generic_ode_solve(func, ode_args, psi0, tlist, e_ops, opt,
progress_bar, dims=None):
"""
Internal function for solving ODEs.
"""
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# This function is made similar to mesolve's one for futur merging in a
# solver class
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# prepare output array
n_tsteps = len(tlist)
output = Result()
output.solver = "sesolve"
output.times = tlist
if psi0.isunitary:
initial_vector = psi0.full().ravel('F')
oper_evo = True
size = psi0.shape[0]
# oper_n = dims[0][0]
# norm_dim_factor = np.sqrt(oper_n)
elif psi0.isket:
initial_vector = psi0.full().ravel()
oper_evo = False
# norm_dim_factor = 1.0
r = scipy.integrate.ode(func)
r.set_integrator('zvode', method=opt.method, order=opt.order,
atol=opt.atol, rtol=opt.rtol, nsteps=opt.nsteps,
first_step=opt.first_step, min_step=opt.min_step,
max_step=opt.max_step)
if ode_args:
r.set_f_params(*ode_args)
r.set_initial_value(initial_vector, tlist[0])
e_ops_data = []
output.expect = []
if callable(e_ops):
n_expt_op = 0
expt_callback = True
output.num_expect = 1
elif isinstance(e_ops, list):
n_expt_op = len(e_ops)
expt_callback = False
output.num_expect = n_expt_op
if n_expt_op == 0:
# fallback on storing states
opt.store_states = True
else:
for op in e_ops:
if not isinstance(op, Qobj) and callable(op):
output.expect.append(np.zeros(n_tsteps, dtype=complex))
continue
if op.isherm:
output.expect.append(np.zeros(n_tsteps))
else:
output.expect.append(np.zeros(n_tsteps, dtype=complex))
if oper_evo:
for e in e_ops:
if isinstance(e, Qobj):
e_ops_data.append(e.dag().data)
continue
e_ops_data.append(e)
else:
for e in e_ops:
if isinstance(e, Qobj):
e_ops_data.append(e.data)
continue
e_ops_data.append(e)
else:
raise TypeError("Expectation parameter must be a list or a function")
if opt.store_states:
output.states = []
if oper_evo:
def get_curr_state_data(r):
return vec2mat(r.y)
else:
def get_curr_state_data(r):
return r.y
#
# start evolution
#
dt = np.diff(tlist)
cdata = None
progress_bar.start(n_tsteps)
for t_idx, t in enumerate(tlist):
progress_bar.update(t_idx)
if not r.successful():
raise Exception("ODE integration error: Try to increase "
"the allowed number of substeps by increasing "
"the nsteps parameter in the Options class.")
# get the current state / oper data if needed
if opt.store_states or opt.normalize_output \
or n_expt_op > 0 or expt_callback:
cdata = get_curr_state_data(r)
if opt.normalize_output:
# normalize per column
if oper_evo:
cdata /= la_norm(cdata, axis=0)
#cdata *= norm_dim_factor / la_norm(cdata)
r.set_initial_value(cdata.ravel('F'), r.t)
else:
#cdata /= la_norm(cdata)
norm = normalize_inplace(cdata)
if norm > 1e-12:
# only reset the solver if state changed
r.set_initial_value(cdata, r.t)
else:
r._y = cdata
if opt.store_states:
if oper_evo:
fdata = dense2D_to_fastcsr_fmode(cdata, size, size)
output.states.append(Qobj(fdata, dims=dims))
else:
fdata = dense1D_to_fastcsr_ket(cdata)
output.states.append(Qobj(fdata, dims=dims, fast='mc'))
if expt_callback:
# use callback method
output.expect.append(e_ops(t, Qobj(cdata, dims=dims)))
if oper_evo:
for m in range(n_expt_op):
if callable(e_ops_data[m]):
func = e_ops_data[m]
output.expect[m][t_idx] = func(t, Qobj(cdata, dims=dims))
continue
output.expect[m][t_idx] = (e_ops_data[m] * cdata).trace()
else:
for m in range(n_expt_op):
if callable(e_ops_data[m]):
func = e_ops_data[m]
output.expect[m][t_idx] = func(t, Qobj(cdata, dims=dims))
continue
output.expect[m][t_idx] = cy_expect_psi(e_ops_data[m], cdata,
e_ops[m].isherm)
if t_idx < n_tsteps - 1:
r.integrate(r.t + dt[t_idx])
progress_bar.finished()
if opt.store_final_state:
cdata = get_curr_state_data(r)
if opt.normalize_output:
cdata /= la_norm(cdata, axis=0)
# cdata *= norm_dim_factor / la_norm(cdata)
output.final_state = Qobj(cdata, dims=dims)
return output
| {
"content_hash": "23b250ebfdf2dd1175c9d326737d9eb2",
"timestamp": "",
"source": "github",
"line_count": 386,
"max_line_length": 79,
"avg_line_length": 34.89637305699482,
"alnum_prop": 0.5596881959910913,
"repo_name": "cgranade/qutip",
"id": "4ad301957da3e8fb67e7b99bf5960094e0a9c1ad",
"size": "13471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "qutip/sesolve.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "13979"
},
{
"name": "Cython",
"bytes": "353822"
},
{
"name": "OpenQASM",
"bytes": "1718"
},
{
"name": "Python",
"bytes": "2741932"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_20) on Thu May 19 22:25:58 CEST 2011 -->
<TITLE>
ICoverageNode (JaCoCo 0.5.2.20110519202509)
</TITLE>
<META NAME="keywords" CONTENT="org.jacoco.core.analysis.ICoverageNode interface">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="ICoverageNode (JaCoCo 0.5.2.20110519202509)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis"><B>PREV CLASS</B></A>
<A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.CounterEntity.html" title="enum in org.jacoco.core.analysis"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/jacoco/core/analysis/ICoverageNode.html" target="_top"><B>FRAMES</B></A>
<A HREF="ICoverageNode.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: <A HREF="#nested_class_summary">NESTED</A> | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.jacoco.core.analysis</FONT>
<BR>
Interface ICoverageNode</H2>
<DL>
<DT><B>All Known Subinterfaces:</B> <DD><A HREF="../../../../org/jacoco/core/analysis/IBundleCoverage.html" title="interface in org.jacoco.core.analysis">IBundleCoverage</A>, <A HREF="../../../../org/jacoco/core/analysis/IClassCoverage.html" title="interface in org.jacoco.core.analysis">IClassCoverage</A>, <A HREF="../../../../org/jacoco/core/analysis/IMethodCoverage.html" title="interface in org.jacoco.core.analysis">IMethodCoverage</A>, <A HREF="../../../../org/jacoco/core/analysis/IPackageCoverage.html" title="interface in org.jacoco.core.analysis">IPackageCoverage</A>, <A HREF="../../../../org/jacoco/core/analysis/ISourceFileCoverage.html" title="interface in org.jacoco.core.analysis">ISourceFileCoverage</A>, <A HREF="../../../../org/jacoco/core/analysis/ISourceNode.html" title="interface in org.jacoco.core.analysis">ISourceNode</A></DD>
</DL>
<DL>
<DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../org/jacoco/core/analysis/CoverageNodeImpl.html" title="class in org.jacoco.core.analysis">CoverageNodeImpl</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public interface <B>ICoverageNode</B></DL>
</PRE>
<P>
Interface for hierarchical coverage data nodes with different coverage
counters.
<P>
<P>
<HR>
<P>
<!-- ======== NESTED CLASS SUMMARY ======== -->
<A NAME="nested_class_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Nested Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.CounterEntity.html" title="enum in org.jacoco.core.analysis">ICoverageNode.CounterEntity</A></B></CODE>
<BR>
Different counter types supported by JaCoCo.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.ElementType.html" title="enum in org.jacoco.core.analysis">ICoverageNode.ElementType</A></B></CODE>
<BR>
Type of a Java element represented by a <A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html" title="interface in org.jacoco.core.analysis"><CODE>ICoverageNode</CODE></A> instance.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getBranchCounter()">getBranchCounter</A></B>()</CODE>
<BR>
Returns the counter for branches.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getClassCounter()">getClassCounter</A></B>()</CODE>
<BR>
Returns the counter for classes.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getComplexityCounter()">getComplexityCounter</A></B>()</CODE>
<BR>
Returns the counter for cyclomatic complexity.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getCounter(org.jacoco.core.analysis.ICoverageNode.CounterEntity)">getCounter</A></B>(<A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.CounterEntity.html" title="enum in org.jacoco.core.analysis">ICoverageNode.CounterEntity</A> entity)</CODE>
<BR>
Generic access to the the counters.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.ElementType.html" title="enum in org.jacoco.core.analysis">ICoverageNode.ElementType</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getElementType()">getElementType</A></B>()</CODE>
<BR>
Returns the type of element represented by this node.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getInstructionCounter()">getInstructionCounter</A></B>()</CODE>
<BR>
Returns the counter for byte code instructions.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getLineCounter()">getLineCounter</A></B>()</CODE>
<BR>
Returns the counter for lines.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getMethodCounter()">getMethodCounter</A></B>()</CODE>
<BR>
Returns the counter for methods.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getName()">getName</A></B>()</CODE>
<BR>
Returns the name of this node.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html" title="interface in org.jacoco.core.analysis">ICoverageNode</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html#getPlainCopy()">getPlainCopy</A></B>()</CODE>
<BR>
Creates a plain copy of this node.</TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getElementType()"><!-- --></A><H3>
getElementType</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.ElementType.html" title="enum in org.jacoco.core.analysis">ICoverageNode.ElementType</A> <B>getElementType</B>()</PRE>
<DL>
<DD>Returns the type of element represented by this node.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>type of this node</DL>
</DD>
</DL>
<HR>
<A NAME="getName()"><!-- --></A><H3>
getName</H3>
<PRE>
<A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>getName</B>()</PRE>
<DL>
<DD>Returns the name of this node.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>name of this node</DL>
</DD>
</DL>
<HR>
<A NAME="getInstructionCounter()"><!-- --></A><H3>
getInstructionCounter</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A> <B>getInstructionCounter</B>()</PRE>
<DL>
<DD>Returns the counter for byte code instructions.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>counter for instructions</DL>
</DD>
</DL>
<HR>
<A NAME="getBranchCounter()"><!-- --></A><H3>
getBranchCounter</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A> <B>getBranchCounter</B>()</PRE>
<DL>
<DD>Returns the counter for branches.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>counter for branches</DL>
</DD>
</DL>
<HR>
<A NAME="getLineCounter()"><!-- --></A><H3>
getLineCounter</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A> <B>getLineCounter</B>()</PRE>
<DL>
<DD>Returns the counter for lines.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>counter for lines</DL>
</DD>
</DL>
<HR>
<A NAME="getComplexityCounter()"><!-- --></A><H3>
getComplexityCounter</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A> <B>getComplexityCounter</B>()</PRE>
<DL>
<DD>Returns the counter for cyclomatic complexity.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>counter for complexity</DL>
</DD>
</DL>
<HR>
<A NAME="getMethodCounter()"><!-- --></A><H3>
getMethodCounter</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A> <B>getMethodCounter</B>()</PRE>
<DL>
<DD>Returns the counter for methods.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>counter for methods</DL>
</DD>
</DL>
<HR>
<A NAME="getClassCounter()"><!-- --></A><H3>
getClassCounter</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A> <B>getClassCounter</B>()</PRE>
<DL>
<DD>Returns the counter for classes.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>counter for classes</DL>
</DD>
</DL>
<HR>
<A NAME="getCounter(org.jacoco.core.analysis.ICoverageNode.CounterEntity)"><!-- --></A><H3>
getCounter</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis">ICounter</A> <B>getCounter</B>(<A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.CounterEntity.html" title="enum in org.jacoco.core.analysis">ICoverageNode.CounterEntity</A> entity)</PRE>
<DL>
<DD>Generic access to the the counters.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>entity</CODE> - entity we're we want to have the counter for
<DT><B>Returns:</B><DD>counter for the given entity</DL>
</DD>
</DL>
<HR>
<A NAME="getPlainCopy()"><!-- --></A><H3>
getPlainCopy</H3>
<PRE>
<A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html" title="interface in org.jacoco.core.analysis">ICoverageNode</A> <B>getPlainCopy</B>()</PRE>
<DL>
<DD>Creates a plain copy of this node. While <A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.html" title="interface in org.jacoco.core.analysis"><CODE>ICoverageNode</CODE></A>
implementations may contain heavy data structures, the copy returned by
this method is reduced to the counters only. This helps to save memory
while processing huge structures.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>copy with counters only</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/jacoco/core/analysis/ICounter.html" title="interface in org.jacoco.core.analysis"><B>PREV CLASS</B></A>
<A HREF="../../../../org/jacoco/core/analysis/ICoverageNode.CounterEntity.html" title="enum in org.jacoco.core.analysis"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/jacoco/core/analysis/ICoverageNode.html" target="_top"><B>FRAMES</B></A>
<A HREF="ICoverageNode.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: <A HREF="#nested_class_summary">NESTED</A> | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<div class="footer">
<span class="right"><a href="http://www.eclemma.org/jacoco">JaCoCo</a> 0.5.2.20110519202509</span>
Copyright © 2009, 2011 Mountainminds GmbH & Co. KG and Contributors
</div>
</BODY>
</HTML>
| {
"content_hash": "4eec0517398f84b78a47454e0d109675",
"timestamp": "",
"source": "github",
"line_count": 446,
"max_line_length": 853,
"avg_line_length": 43.728699551569505,
"alnum_prop": 0.6543608675588372,
"repo_name": "ck1125/sikuli",
"id": "1d4bcd53cf48017f2bc1efe6ccfe13872dedd3d1",
"size": "19503",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "utils/jacoco/doc/api/org/jacoco/core/analysis/ICoverageNode.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
"""
Tests for outputvideo.py
"""
| {
"content_hash": "800ddfbb1aedd2a18fb5fca83bd5984f",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 24,
"avg_line_length": 11,
"alnum_prop": 0.6363636363636364,
"repo_name": "317070/python-twitch-stream",
"id": "4e4688f756b9f389972abfcdaa8f47773d2d6de4",
"size": "75",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "twitchstream/tests/test_outputvideo.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "32268"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
public abstract class WWWBase {
public delegate void DataBackMethod();
public DataBackMethod DataBackEvent;
public string Url
{
get;
set;
}
public WWWForm Form
{
get;
set;
}
public IEnumerator ProcessUrl(string url, WWWForm form)
{
this.Url = url;
this.Form = form;
WWW www = new WWW(url,form);
yield return www;
if (www.error != null)
{
DealNetError();
}
else
{
DataBackEvent();
DealBackData(www.text);
}
}
public void DealNetError()
{
}
public abstract void DealBackData(string data);
}
| {
"content_hash": "1bf345d1efd83d2042c096e57e9ef77f",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 59,
"avg_line_length": 15.755102040816327,
"alnum_prop": 0.5168393782383419,
"repo_name": "MQQiang/UnityTools",
"id": "eb606343eaf122d1002190138936fadaef98f539",
"size": "774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WWWBase.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "9065"
}
],
"symlink_target": ""
} |
FROM balenalib/fincm3-alpine:3.14-run
# Default to UTF-8 file.encoding
ENV LANG C.UTF-8
# add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
echo '#!/bin/sh'; \
echo 'set -e'; \
echo; \
echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
} > /usr/local/bin/docker-java-home \
&& chmod +x /usr/local/bin/docker-java-home
ENV JAVA_HOME /usr/lib/jvm/java-1.7-openjdk
ENV PATH $PATH:/usr/lib/jvm/java-1.7-openjdk/jre/bin:/usr/lib/jvm/java-1.7-openjdk/bin
RUN set -x \
&& apk add --no-cache \
openjdk7-jre \
&& [ "$JAVA_HOME" = "$(docker-java-home)" ]
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.14 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v7-jre \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | {
"content_hash": "f5d441b6cb5e0e77a031065bf2535507",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 681,
"avg_line_length": 57.8,
"alnum_prop": 0.698961937716263,
"repo_name": "resin-io-library/base-images",
"id": "f904fd7d6276ef4c8d127bab96746c37541d5e2c",
"size": "1755",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/openjdk/fincm3/alpine/3.14/7-jre/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
import json
import logging
import subprocess
import sys
import time
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('num_streams', 1, 'Number of netperf processes to run')
flags.DEFINE_string('netperf_cmd', None,
'netperf command to run')
flags.DEFINE_integer('port_start', None,
'Starting port for netperf command and data ports')
def Main():
# Parse command-line flags
try:
FLAGS(sys.argv)
except flags.Error as e:
logging.error('%s\nUsage: %s ARGS\n%s', e, sys.argv[0], FLAGS)
sys.exit(1)
netperf_cmd = FLAGS.netperf_cmd
num_streams = FLAGS.num_streams
port_start = FLAGS.port_start
assert netperf_cmd
assert num_streams >= 1
assert port_start
stdouts = [None] * num_streams
stderrs = [None] * num_streams
return_codes = [None] * num_streams
processes = [None] * num_streams
# Start all of the netperf processes
begin_starting_processes = time.time()
for i in range(num_streams):
command_port = port_start + i * 2
data_port = port_start + i * 2 + 1
cmd = netperf_cmd.format(command_port=command_port, data_port=data_port)
processes[i] = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
universal_newlines=True)
end_starting_processes = time.time()
# Wait for all of the netperf processes to finish and save their return codes
for i, process in enumerate(processes):
stdouts[i], stderrs[i] = process.communicate()
return_codes[i] = process.returncode
# Dump the stdouts, stderrs, and return_codes to stdout in json form
print(json.dumps((stdouts, stderrs, return_codes,
begin_starting_processes, end_starting_processes)))
if __name__ == '__main__':
sys.exit(Main())
| {
"content_hash": "ef62796f8073048ab59a520235a8cf8d",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 79,
"avg_line_length": 29.193548387096776,
"alnum_prop": 0.6679558011049723,
"repo_name": "GoogleCloudPlatform/PerfKitBenchmarker",
"id": "3afb684657b3553ee855d8ce8bd59ee08072a94c",
"size": "2445",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "perfkitbenchmarker/scripts/netperf_test_scripts/netperf_test.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3420"
},
{
"name": "HTML",
"bytes": "113073"
},
{
"name": "Jinja",
"bytes": "62005"
},
{
"name": "Lua",
"bytes": "1547"
},
{
"name": "Python",
"bytes": "6076512"
},
{
"name": "R",
"bytes": "1017"
},
{
"name": "Shell",
"bytes": "76164"
},
{
"name": "Tcl",
"bytes": "14601"
}
],
"symlink_target": ""
} |
package org.jboss.arquillian.impl.domain;
import java.util.ArrayList;
import java.util.List;
import org.jboss.arquillian.impl.Validate;
import org.jboss.arquillian.spi.client.protocol.Protocol;
import org.jboss.arquillian.spi.client.protocol.ProtocolDescription;
/**
* A registry holding all found {@link Protocol}s.
*
* @author <a href="mailto:aslak@redhat.com">Aslak Knutsen</a>
* @version $Revision: $
*/
public class ProtocolRegistry
{
private List<ProtocolDefinition> protocols;
public ProtocolRegistry()
{
protocols = new ArrayList<ProtocolDefinition>();
}
/**
* @param protocol The Protocol to add
* @return this
* @throws IllegalArgumentException if a protocol with same name found
*/
public ProtocolRegistry addProtocol(ProtocolDefinition protocolDefinition)
{
Validate.notNull(protocolDefinition, "ProtocolDefinition must be specified");
ProtocolDefinition protocolAllReadyRegistered = findSpecificProtocol(protocolDefinition.getProtocol().getDescription());
if(protocolAllReadyRegistered != null)
{
throw new IllegalArgumentException(
"Protocol with description " + protocolDefinition.getProtocol().getDescription() + " allready registered. " +
"Registered " + protocolAllReadyRegistered.getClass() + ", trying to register " + protocolDefinition.getProtocol().getClass());
}
protocols.add(protocolDefinition);
return this;
}
/**
* @param protocolDescription
* @return
*/
public ProtocolDefinition getProtocol(ProtocolDescription protocolDescription)
{
Validate.notNull(protocolDescription, "ProtocolDescription must be specified");
if(ProtocolDescription.DEFAULT.equals(protocolDescription))
{
return findDefaultProtocol();
}
return findSpecificProtocol(protocolDescription);
}
/**
* @return
*/
private ProtocolDefinition findDefaultProtocol()
{
for(ProtocolDefinition def : protocols)
{
if(def.isDefaultProtocol())
{
return def;
}
}
if(protocols.size() == 1)
{
return protocols.get(0);
}
return null;
}
/**
* @return
*/
private ProtocolDefinition findSpecificProtocol(ProtocolDescription protocolDescription)
{
for(ProtocolDefinition protocol : protocols)
{
if(protocolDescription.equals(protocol.getProtocol().getDescription()))
{
return protocol;
}
}
return null;
}
}
| {
"content_hash": "cef2e96ee433cdc530f1fcaa73cd47fa",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 143,
"avg_line_length": 28.108695652173914,
"alnum_prop": 0.6693735498839907,
"repo_name": "arquillian/arquillian_deprecated",
"id": "68389f613eb2a9621828c28696e0da5a32252cc0",
"size": "3370",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "impl-base/src/main/java/org/jboss/arquillian/impl/domain/ProtocolRegistry.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1993635"
},
{
"name": "Shell",
"bytes": "209"
}
],
"symlink_target": ""
} |
package com.planet_ink.coffee_mud.Abilities.Diseases;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
public class Disease_Fever extends Disease
{
@Override
public String ID()
{
return "Disease_Fever";
}
private final static String localizedName = CMLib.lang().L("Fever");
@Override
public String name()
{
return localizedName;
}
private final static String localizedStaticDisplay = CMLib.lang().L("(Fever)");
@Override
public String displayText()
{
return localizedStaticDisplay;
}
@Override
protected int canAffectCode()
{
return CAN_MOBS;
}
@Override
protected int canTargetCode()
{
return CAN_MOBS;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_MALICIOUS;
}
@Override
public boolean putInCommandlist()
{
return false;
}
@Override
public int difficultyLevel()
{
return 1;
}
@Override
protected int DISEASE_TICKS()
{
return 15;
}
@Override
protected int DISEASE_DELAY()
{
return 3;
}
@Override
protected String DISEASE_DONE()
{
return L("You head stops hurting.");
}
@Override
protected String DISEASE_START()
{
return L("^G<S-NAME> come(s) down with a fever.^?");
}
@Override
protected String DISEASE_AFFECT()
{
return "";
}
@Override
public int abilityCode()
{
return 0;
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if(!(affected instanceof MOB))
return super.tick(ticking,tickID);
if(!super.tick(ticking,tickID))
return false;
final MOB mob=(MOB)affected;
if(mob.isInCombat())
{
final MOB newvictim=mob.location().fetchRandomInhabitant();
if(newvictim!=mob)
mob.setVictim(newvictim);
}
else
if(CMLib.flags().isAliveAwakeMobile(mob,false)
&&(CMLib.flags().canSee(mob))
&&((--diseaseTick)<=0))
{
diseaseTick=DISEASE_DELAY();
switch(CMLib.dice().roll(1,10,0))
{
case 1:
mob.tell(L("You think you just saw your mother swim by."));
break;
case 2:
mob.tell(L("A pink elephant just attacked you!"));
break;
case 3:
mob.tell(L("A horse just asked you a question."));
break;
case 4:
mob.tell(L("Your hands look very green."));
break;
case 5:
mob.tell(L("You think you just saw your father float by."));
break;
case 6:
mob.tell(L("A large piece of bread swings at you and misses!"));
break;
case 7:
mob.tell(L("Oh, the pretty colors!"));
break;
case 8:
mob.tell(L("You think you just saw something, but aren't sure."));
break;
case 9:
mob.tell(L("Hundreds of little rainbow bees buzz around your head."));
break;
case 10:
mob.tell(L("Everything looks upside-down."));
break;
}
}
return super.tick(ticking,tickID);
}
}
| {
"content_hash": "c7c26fba9af3cde6df1cbcbbe0fd60f6",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 80,
"avg_line_length": 21.80473372781065,
"alnum_prop": 0.6564450474898236,
"repo_name": "bozimmerman/CoffeeMud",
"id": "946e2baeb586b176b3500aa0130e862bbce610f7",
"size": "4289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com/planet_ink/coffee_mud/Abilities/Diseases/Disease_Fever.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5847"
},
{
"name": "CSS",
"bytes": "1619"
},
{
"name": "HTML",
"bytes": "12319179"
},
{
"name": "Java",
"bytes": "38979811"
},
{
"name": "JavaScript",
"bytes": "45220"
},
{
"name": "Makefile",
"bytes": "23191"
},
{
"name": "Shell",
"bytes": "8783"
}
],
"symlink_target": ""
} |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/extensions/login_screen/login/login_api.h"
#include <map>
#include <memory>
#include <string>
#include <utility>
#include "ash/components/settings/cros_settings_names.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "chrome/browser/ash/login/existing_user_controller.h"
#include "chrome/browser/ash/login/signin_specifics.h"
#include "chrome/browser/ash/login/ui/mock_login_display_host.h"
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/cleanup_manager.h"
#include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/mock_cleanup_handler.h"
#include "chrome/browser/chromeos/extensions/login_screen/login/login_api_lock_handler.h"
#include "chrome/browser/chromeos/extensions/login_screen/login/shared_session_handler.h"
#include "chrome/browser/extensions/extension_api_unittest.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "chromeos/login/auth/key.h"
#include "chromeos/login/auth/user_context.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_service.h"
#include "components/session_manager/core/session_manager.h"
#include "components/session_manager/session_manager_types.h"
#include "components/user_manager/scoped_user_manager.h"
#include "content/public/browser/browser_context.h"
#include "extensions/browser/api_test_utils.h"
#include "extensions/browser/api_unittest.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/user_activity/user_activity_detector.h"
using testing::_;
using testing::Invoke;
using testing::Return;
using testing::SaveArg;
using testing::StrictMock;
namespace {
const char kEmail[] = "email@test";
const char kGaiaId[] = "gaia@test";
const char kExtensionName[] = "extension_name";
const char kExtensionId[] = "abcdefghijklmnopqrstuvwxyzabcdef";
class MockExistingUserController : public ash::ExistingUserController {
public:
MockExistingUserController() = default;
MockExistingUserController(const MockExistingUserController&) = delete;
MockExistingUserController& operator=(const MockExistingUserController&) =
delete;
~MockExistingUserController() override = default;
MOCK_METHOD2(Login,
void(const chromeos::UserContext&, const ash::SigninSpecifics&));
MOCK_CONST_METHOD0(IsSigninInProgress, bool());
};
class MockLoginApiLockHandler : public chromeos::LoginApiLockHandler {
public:
MockLoginApiLockHandler() {
chromeos::LoginApiLockHandler::SetInstanceForTesting(this);
}
MockLoginApiLockHandler(const MockLoginApiLockHandler&) = delete;
MockLoginApiLockHandler& operator=(const MockLoginApiLockHandler&) = delete;
~MockLoginApiLockHandler() override {
chromeos::LoginApiLockHandler::SetInstanceForTesting(nullptr);
}
MOCK_METHOD0(RequestLockScreen, void());
MOCK_METHOD2(Authenticate,
void(const chromeos::UserContext& user_context,
base::OnceCallback<void(bool auth_success)> callback));
MOCK_CONST_METHOD0(IsUnlockInProgress, bool());
};
// Wrapper which calls `DeleteTestingProfile()` on `profile` upon destruction.
class ScopedTestingProfile {
public:
ScopedTestingProfile(TestingProfile* profile,
TestingProfileManager* profile_manager)
: profile_(profile), profile_manager_(profile_manager) {}
ScopedTestingProfile(const ScopedTestingProfile&) = delete;
ScopedTestingProfile& operator=(const ScopedTestingProfile&) = delete;
~ScopedTestingProfile() {
profile_manager_->DeleteTestingProfile(profile_->GetProfileUserName());
}
TestingProfile* profile() { return profile_; }
private:
TestingProfile* const profile_;
TestingProfileManager* const profile_manager_;
};
chromeos::UserContext GetPublicUserContext(const std::string& email) {
return chromeos::UserContext(user_manager::USER_TYPE_PUBLIC_ACCOUNT,
AccountId::FromUserEmail(email));
}
void SetLoginExtensionApiLaunchExtensionIdPref(
Profile* profile,
const std::string& extension_id) {
profile->GetPrefs()->SetString(prefs::kLoginExtensionApiLaunchExtensionId,
extension_id);
}
} // namespace
namespace extensions {
class LoginApiUnittest : public ExtensionApiUnittest {
public:
LoginApiUnittest() = default;
LoginApiUnittest(const LoginApiUnittest&) = delete;
LoginApiUnittest& operator=(const LoginApiUnittest&) = delete;
~LoginApiUnittest() override = default;
protected:
void SetUp() override {
ExtensionApiUnittest::SetUp();
fake_chrome_user_manager_ = new ash::FakeChromeUserManager();
scoped_user_manager_ = std::make_unique<user_manager::ScopedUserManager>(
std::unique_ptr<ash::FakeChromeUserManager>(fake_chrome_user_manager_));
mock_login_display_host_ = std::make_unique<ash::MockLoginDisplayHost>();
mock_existing_user_controller_ =
std::make_unique<MockExistingUserController>();
mock_lock_handler_ = std::make_unique<MockLoginApiLockHandler>();
// Set `LOGIN_PRIMARY` as the default state.
session_manager_.SetSessionState(
session_manager::SessionState::LOGIN_PRIMARY);
EXPECT_CALL(*mock_login_display_host_, GetExistingUserController())
.WillRepeatedly(Return(mock_existing_user_controller_.get()));
// Run pending async tasks resulting from profile construction to ensure
// these are complete before the test begins.
base::RunLoop().RunUntilIdle();
}
void TearDown() override {
mock_existing_user_controller_.reset();
mock_login_display_host_.reset();
scoped_user_manager_.reset();
ExtensionApiUnittest::TearDown();
}
void SetExtensionWithId(const std::string& extension_id) {
scoped_refptr<const extensions::Extension> extension =
extensions::ExtensionBuilder(kExtensionName)
.SetID(extension_id)
.Build();
set_extension(extension);
}
std::unique_ptr<ScopedTestingProfile> AddPublicAccountUser(
const std::string& email) {
AccountId account_id = AccountId::FromUserEmail(email);
user_manager::User* user =
fake_chrome_user_manager_->AddPublicAccountUser(account_id);
TestingProfile* profile = profile_manager()->CreateTestingProfile(email);
chromeos::ProfileHelper::Get()->SetUserToProfileMappingForTesting(user,
profile);
return std::make_unique<ScopedTestingProfile>(profile, profile_manager());
}
ash::FakeChromeUserManager* fake_chrome_user_manager_;
std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_;
std::unique_ptr<ash::MockLoginDisplayHost> mock_login_display_host_;
std::unique_ptr<MockExistingUserController> mock_existing_user_controller_;
std::unique_ptr<MockLoginApiLockHandler> mock_lock_handler_;
// Sets up the global `SessionManager` instance.
session_manager::SessionManager session_manager_;
};
MATCHER_P(MatchSigninSpecifics, expected, "") {
return expected.guest_mode_url == arg.guest_mode_url &&
expected.guest_mode_url_append_locale ==
arg.guest_mode_url_append_locale &&
expected.is_auto_login == arg.is_auto_login;
}
MATCHER_P(MatchUserContextSecret, expected, "") {
return expected == arg.GetKey()->GetSecret();
}
// Test that calling `login.launchManagedGuestSession()` calls the corresponding
// method from the `ExistingUserController`.
TEST_F(LoginApiUnittest, LaunchManagedGuestSession) {
base::TimeTicks now_ = base::TimeTicks::Now();
ui::UserActivityDetector::Get()->set_now_for_test(now_);
std::unique_ptr<ScopedTestingProfile> profile = AddPublicAccountUser(kEmail);
EXPECT_CALL(*mock_existing_user_controller_,
Login(GetPublicUserContext(kEmail),
MatchSigninSpecifics(ash::SigninSpecifics())))
.Times(1);
RunFunction(new LoginLaunchManagedGuestSessionFunction(), "[]");
// Test that calling `login.launchManagedGuestSession()` triggered a user
// activity in the `UserActivityDetector`.
EXPECT_EQ(now_, ui::UserActivityDetector::Get()->last_activity_time());
}
// Test that calling `login.launchManagedGuestSession()` with a password sets
// the correct password in the `UserContext` passed to
// `ExistingUserController`.
TEST_F(LoginApiUnittest, LaunchManagedGuestSessionWithPassword) {
std::unique_ptr<ScopedTestingProfile> profile = AddPublicAccountUser(kEmail);
chromeos::UserContext user_context = GetPublicUserContext(kEmail);
user_context.SetKey(chromeos::Key("password"));
EXPECT_CALL(*mock_existing_user_controller_,
Login(user_context, MatchSigninSpecifics(ash::SigninSpecifics())))
.Times(1);
RunFunction(new LoginLaunchManagedGuestSessionFunction(), "[\"password\"]");
}
// Test that calling `login.launchManagedGuestSession()` returns an error when
// there are no managed guest session accounts.
TEST_F(LoginApiUnittest, LaunchManagedGuestSessionNoAccounts) {
ASSERT_EQ(login_api_errors::kNoManagedGuestSessionAccounts,
RunFunctionAndReturnError(
new LoginLaunchManagedGuestSessionFunction(), "[]"));
}
// Test that calling `login.launchManagedGuestSession()` returns an error when
// the session state is not `LOGIN_PRIMARY`.
TEST_F(LoginApiUnittest, LaunchManagedGuestSessionWrongSessionState) {
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::ACTIVE);
ASSERT_EQ(login_api_errors::kAlreadyActiveSession,
RunFunctionAndReturnError(
new LoginLaunchManagedGuestSessionFunction(), "[]"));
}
// Test that calling `login.launchManagedGuestSession()` returns an error when
// there is another signin in progress.
TEST_F(LoginApiUnittest, LaunchManagedGuestSessionSigninInProgress) {
EXPECT_CALL(*mock_existing_user_controller_, IsSigninInProgress())
.WillOnce(Return(true));
ASSERT_EQ(login_api_errors::kAnotherLoginAttemptInProgress,
RunFunctionAndReturnError(
new LoginLaunchManagedGuestSessionFunction(), "[]"));
}
// Test that calling `login.exitCurrentSession()` with data for the next login
// attempt sets the `kLoginExtensionApiDataForNextLoginAttempt` pref to the
// given data.
TEST_F(LoginApiUnittest, ExitCurrentSessionWithData) {
const std::string data_for_next_login_attempt = "hello world";
RunFunction(
new LoginExitCurrentSessionFunction(),
base::StringPrintf(R"(["%s"])", data_for_next_login_attempt.c_str()));
PrefService* local_state = g_browser_process->local_state();
ASSERT_EQ(
data_for_next_login_attempt,
local_state->GetString(prefs::kLoginExtensionApiDataForNextLoginAttempt));
}
// Test that calling `login.exitCurrentSession()` with no data clears the
// `kLoginExtensionApiDataForNextLoginAttempt` pref.
TEST_F(LoginApiUnittest, ExitCurrentSessionWithNoData) {
PrefService* local_state = g_browser_process->local_state();
local_state->SetString(prefs::kLoginExtensionApiDataForNextLoginAttempt,
"hello world");
RunFunction(new LoginExitCurrentSessionFunction(), "[]");
ASSERT_EQ("", local_state->GetString(
prefs::kLoginExtensionApiDataForNextLoginAttempt));
}
// Test that calling `login.fetchDataForNextLoginAttempt()` returns the value
// stored in the `kLoginExtensionsApiDataForNextLoginAttempt` pref and
// clears the pref.
TEST_F(LoginApiUnittest, FetchDataForNextLoginAttemptClearsPref) {
const std::string data_for_next_login_attempt = "hello world";
PrefService* local_state = g_browser_process->local_state();
local_state->SetString(prefs::kLoginExtensionApiDataForNextLoginAttempt,
data_for_next_login_attempt);
std::unique_ptr<base::Value> value(RunFunctionAndReturnValue(
new LoginFetchDataForNextLoginAttemptFunction(), "[]"));
ASSERT_EQ(data_for_next_login_attempt, value->GetString());
ASSERT_EQ("", local_state->GetString(
prefs::kLoginExtensionApiDataForNextLoginAttempt));
}
// Test that calling `login.setDataForNextLoginAttempt()` sets the
// value stored in the `kLoginExtensionsApiDataForNextLoginAttempt` pref.
TEST_F(LoginApiUnittest, SetDataForNextLoginAttempt) {
const std::string data_for_next_login_attempt = "hello world";
std::unique_ptr<base::Value> value(
RunFunctionAndReturnValue(new LoginSetDataForNextLoginAttemptFunction(),
"[\"" + data_for_next_login_attempt + "\"]"));
PrefService* local_state = g_browser_process->local_state();
ASSERT_EQ(
data_for_next_login_attempt,
local_state->GetString(prefs::kLoginExtensionApiDataForNextLoginAttempt));
}
TEST_F(LoginApiUnittest, LockManagedGuestSession) {
base::TimeTicks now_ = base::TimeTicks::Now();
ui::UserActivityDetector::Get()->set_now_for_test(now_);
std::unique_ptr<ScopedTestingProfile> profile = AddPublicAccountUser(kEmail);
fake_chrome_user_manager_->SwitchActiveUser(AccountId::FromUserEmail(kEmail));
fake_chrome_user_manager_->set_current_user_can_lock(true);
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::ACTIVE);
EXPECT_CALL(*mock_lock_handler_, RequestLockScreen()).WillOnce(Return());
RunFunction(new LoginLockManagedGuestSessionFunction(), "[]");
// Test that calling `login.lockManagedGuestSession()` triggered a user
// activity in the `UserActivityDetector`.
EXPECT_EQ(now_, ui::UserActivityDetector::Get()->last_activity_time());
}
TEST_F(LoginApiUnittest, LockManagedGuestSessionNoActiveUser) {
ASSERT_EQ(login_api_errors::kNoPermissionToLock,
RunFunctionAndReturnError(
new LoginLockManagedGuestSessionFunction(), "[]"));
}
TEST_F(LoginApiUnittest, LockManagedGuestSessionNotManagedGuestSession) {
AccountId account_id = AccountId::FromGaiaId(kGaiaId);
fake_chrome_user_manager_->AddUser(account_id);
fake_chrome_user_manager_->SwitchActiveUser(account_id);
ASSERT_EQ(login_api_errors::kNoPermissionToLock,
RunFunctionAndReturnError(
new LoginLockManagedGuestSessionFunction(), "[]"));
}
TEST_F(LoginApiUnittest, LockManagedGuestSessionUserCannotLock) {
std::unique_ptr<ScopedTestingProfile> profile = AddPublicAccountUser(kEmail);
fake_chrome_user_manager_->SwitchActiveUser(AccountId::FromUserEmail(kEmail));
fake_chrome_user_manager_->set_current_user_can_lock(false);
ASSERT_EQ(login_api_errors::kNoPermissionToLock,
RunFunctionAndReturnError(
new LoginLockManagedGuestSessionFunction(), "[]"));
}
TEST_F(LoginApiUnittest, LockManagedGuestSessionSessionNotActive) {
std::unique_ptr<ScopedTestingProfile> profile = AddPublicAccountUser(kEmail);
fake_chrome_user_manager_->SwitchActiveUser(AccountId::FromUserEmail(kEmail));
fake_chrome_user_manager_->set_current_user_can_lock(true);
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ASSERT_EQ(login_api_errors::kSessionIsNotActive,
RunFunctionAndReturnError(
new LoginLockManagedGuestSessionFunction(), "[]"));
}
TEST_F(LoginApiUnittest, UnlockManagedGuestSession) {
base::TimeTicks now_ = base::TimeTicks::Now();
ui::UserActivityDetector::Get()->set_now_for_test(now_);
SetExtensionWithId(kExtensionId);
std::unique_ptr<ScopedTestingProfile> scoped_profile =
AddPublicAccountUser(kEmail);
SetLoginExtensionApiLaunchExtensionIdPref(scoped_profile->profile(),
kExtensionId);
fake_chrome_user_manager_->SwitchActiveUser(AccountId::FromUserEmail(kEmail));
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
EXPECT_CALL(*mock_lock_handler_, IsUnlockInProgress())
.WillOnce(Return(false));
EXPECT_CALL(*mock_lock_handler_,
Authenticate(MatchUserContextSecret("password"), _))
.WillOnce([](chromeos::UserContext user_context,
base::OnceCallback<void(bool auth_success)> callback) {
std::move(callback).Run(/*auth_success=*/true);
});
RunFunction(new LoginUnlockManagedGuestSessionFunction(), "[\"password\"]");
// Test that calling `login.unlockManagedGuestSession()` triggered a user
// activity in the `UserActivityDetector`.
EXPECT_EQ(now_, ui::UserActivityDetector::Get()->last_activity_time());
}
TEST_F(LoginApiUnittest, UnlockManagedGuestSessionNoActiveUser) {
ASSERT_EQ(
login_api_errors::kNoPermissionToUnlock,
RunFunctionAndReturnError(new LoginUnlockManagedGuestSessionFunction(),
"[\"password\"]"));
}
TEST_F(LoginApiUnittest, UnlockManagedGuestSessionNotManagedGuestSession) {
AccountId account_id = AccountId::FromGaiaId(kGaiaId);
fake_chrome_user_manager_->AddUser(account_id);
fake_chrome_user_manager_->SwitchActiveUser(account_id);
ASSERT_EQ(
login_api_errors::kNoPermissionToUnlock,
RunFunctionAndReturnError(new LoginUnlockManagedGuestSessionFunction(),
"[\"password\"]"));
}
TEST_F(LoginApiUnittest, UnlockManagedGuestSessionWrongExtensionId) {
SetExtensionWithId(kExtensionId);
std::unique_ptr<ScopedTestingProfile> scoped_profile =
AddPublicAccountUser(kEmail);
SetLoginExtensionApiLaunchExtensionIdPref(scoped_profile->profile(),
"wrong_extension_id");
fake_chrome_user_manager_->SwitchActiveUser(AccountId::FromUserEmail(kEmail));
ASSERT_EQ(
login_api_errors::kNoPermissionToUnlock,
RunFunctionAndReturnError(new LoginUnlockManagedGuestSessionFunction(),
"[\"password\"]"));
}
TEST_F(LoginApiUnittest, UnlockManagedGuestSessionSessionNotLocked) {
SetExtensionWithId(kExtensionId);
std::unique_ptr<ScopedTestingProfile> scoped_profile =
AddPublicAccountUser(kEmail);
SetLoginExtensionApiLaunchExtensionIdPref(scoped_profile->profile(),
kExtensionId);
fake_chrome_user_manager_->SwitchActiveUser(AccountId::FromUserEmail(kEmail));
ASSERT_EQ(
login_api_errors::kSessionIsNotLocked,
RunFunctionAndReturnError(new LoginUnlockManagedGuestSessionFunction(),
"[\"password\"]"));
}
TEST_F(LoginApiUnittest, UnlockManagedGuestSessionUnlockInProgress) {
SetExtensionWithId(kExtensionId);
std::unique_ptr<ScopedTestingProfile> scoped_profile =
AddPublicAccountUser(kEmail);
SetLoginExtensionApiLaunchExtensionIdPref(scoped_profile->profile(),
kExtensionId);
fake_chrome_user_manager_->SwitchActiveUser(AccountId::FromUserEmail(kEmail));
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
EXPECT_CALL(*mock_lock_handler_, IsUnlockInProgress()).WillOnce(Return(true));
ASSERT_EQ(
login_api_errors::kAnotherUnlockAttemptInProgress,
RunFunctionAndReturnError(new LoginUnlockManagedGuestSessionFunction(),
"[\"password\"]"));
}
TEST_F(LoginApiUnittest, UnlockManagedGuestSessionAuthenticationFailed) {
SetExtensionWithId(kExtensionId);
std::unique_ptr<ScopedTestingProfile> scoped_profile =
AddPublicAccountUser(kEmail);
SetLoginExtensionApiLaunchExtensionIdPref(scoped_profile->profile(),
kExtensionId);
fake_chrome_user_manager_->SwitchActiveUser(AccountId::FromUserEmail(kEmail));
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
EXPECT_CALL(*mock_lock_handler_, IsUnlockInProgress())
.WillOnce(Return(false));
EXPECT_CALL(*mock_lock_handler_,
Authenticate(MatchUserContextSecret("password"), _))
.WillOnce([](chromeos::UserContext user_context,
base::OnceCallback<void(bool auth_success)> callback) {
std::move(callback).Run(/*auth_success=*/false);
});
ASSERT_EQ(
login_api_errors::kAuthenticationFailed,
RunFunctionAndReturnError(new LoginUnlockManagedGuestSessionFunction(),
"[\"password\"]"));
}
class LoginApiSharedSessionUnittest : public LoginApiUnittest {
public:
LoginApiSharedSessionUnittest() = default;
LoginApiSharedSessionUnittest(const LoginApiSharedSessionUnittest&) = delete;
LoginApiSharedSessionUnittest& operator=(
const LoginApiSharedSessionUnittest&) = delete;
~LoginApiSharedSessionUnittest() override = default;
protected:
void SetUp() override {
GetCrosSettingsHelper()->ReplaceDeviceSettingsProviderWithStub();
GetCrosSettingsHelper()->SetBoolean(
ash::kDeviceRestrictedManagedGuestSessionEnabled, true);
// Remove cleanup handlers.
chromeos::CleanupManager::Get()->SetCleanupHandlersForTesting({});
LoginApiUnittest::SetUp();
}
void TearDown() override {
GetCrosSettingsHelper()->RestoreRealDeviceSettingsProvider();
chromeos::SharedSessionHandler::Get()->ResetStateForTesting();
chromeos::CleanupManager::Get()->ResetCleanupHandlersForTesting();
testing_profile_.reset();
LoginApiUnittest::TearDown();
}
void SetUpCleanupHandlerMocks(
absl::optional<std::string> error1 = absl::nullopt,
absl::optional<std::string> error2 = absl::nullopt) {
std::unique_ptr<chromeos::MockCleanupHandler> mock_cleanup_handler1 =
std::make_unique<StrictMock<chromeos::MockCleanupHandler>>();
EXPECT_CALL(*mock_cleanup_handler1, Cleanup(_))
.WillOnce(Invoke(
([error1](
chromeos::CleanupHandler::CleanupHandlerCallback callback) {
std::move(callback).Run(error1);
})));
std::unique_ptr<chromeos::MockCleanupHandler> mock_cleanup_handler2 =
std::make_unique<StrictMock<chromeos::MockCleanupHandler>>();
EXPECT_CALL(*mock_cleanup_handler2, Cleanup(_))
.WillOnce(Invoke(
([error2](
chromeos::CleanupHandler::CleanupHandlerCallback callback) {
std::move(callback).Run(error2);
})));
std::map<std::string, std::unique_ptr<chromeos::CleanupHandler>>
cleanup_handlers;
cleanup_handlers.insert({"Handler1", std::move(mock_cleanup_handler1)});
cleanup_handlers.insert({"Handler2", std::move(mock_cleanup_handler2)});
chromeos::CleanupManager::Get()->SetCleanupHandlersForTesting(
std::move(cleanup_handlers));
}
void SetUpCleanupHandlerMockNotCalled() {
std::unique_ptr<chromeos::MockCleanupHandler> mock_cleanup_handler =
std::make_unique<chromeos::MockCleanupHandler>();
EXPECT_CALL(*mock_cleanup_handler, Cleanup(_)).Times(0);
std::map<std::string, std::unique_ptr<chromeos::CleanupHandler>>
cleanup_handlers;
cleanup_handlers.insert({"Handler", std::move(mock_cleanup_handler)});
chromeos::CleanupManager::Get()->SetCleanupHandlersForTesting(
std::move(cleanup_handlers));
}
void LaunchSharedManagedGuestSession(const std::string& password) {
SetExtensionWithId(kExtensionId);
EXPECT_CALL(*mock_existing_user_controller_,
Login(_, MatchSigninSpecifics(chromeos::SigninSpecifics())))
.Times(1);
testing_profile_ = AddPublicAccountUser(kEmail);
RunFunction(new LoginLaunchSharedManagedGuestSessionFunction(),
"[\"" + password + "\"]");
SetLoginExtensionApiLaunchExtensionIdPref(testing_profile_->profile(),
kExtensionId);
fake_chrome_user_manager_->SwitchActiveUser(
AccountId::FromUserEmail(kEmail));
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::ACTIVE);
}
void ExpectAuthenticateWithSessionSecret(bool auth_success) {
const std::string& session_secret =
chromeos::SharedSessionHandler::Get()->GetSessionSecretForTesting();
EXPECT_CALL(*mock_lock_handler_,
Authenticate(MatchUserContextSecret(session_secret), _))
.WillOnce([auth_success](
chromeos::UserContext user_context,
base::OnceCallback<void(bool auth_success)> callback) {
std::move(callback).Run(/*auth_success=*/auth_success);
});
}
std::unique_ptr<ScopedTestingProfile> testing_profile_;
};
// Test that calling `login.launchSharedManagedGuestSession()` sets the correct
// extension ID and session secret in the `UserContext` passed to
// `ExistingUserController`, and sets user hash and salt.
TEST_F(LoginApiSharedSessionUnittest, LaunchSharedManagedGuestSession) {
base::TimeTicks now_ = base::TimeTicks::Now();
ui::UserActivityDetector::Get()->set_now_for_test(now_);
SetExtensionWithId(kExtensionId);
std::unique_ptr<ScopedTestingProfile> profile = AddPublicAccountUser(kEmail);
chromeos::UserContext user_context;
EXPECT_CALL(*mock_existing_user_controller_,
Login(_, MatchSigninSpecifics(chromeos::SigninSpecifics())))
.WillOnce(SaveArg<0>(&user_context));
RunFunction(new LoginLaunchSharedManagedGuestSessionFunction(), "[\"foo\"]");
EXPECT_EQ(user_context.GetManagedGuestSessionLaunchExtensionId(),
kExtensionId);
chromeos::SharedSessionHandler* handler =
chromeos::SharedSessionHandler::Get();
const std::string& session_secret = handler->GetSessionSecretForTesting();
EXPECT_EQ(user_context.GetKey()->GetSecret(), session_secret);
EXPECT_NE("", session_secret);
EXPECT_NE("", handler->GetUserSecretHashForTesting());
EXPECT_NE("", handler->GetUserSecretSaltForTesting());
// Test that user activity is triggered.
EXPECT_EQ(now_, ui::UserActivityDetector::Get()->last_activity_time());
}
// Test that calling `login.launchSharedManagedGuestSession()` returns an error
// when the DeviceRestrictedManagedGuestSessionEnabled policy is set to false.
TEST_F(LoginApiSharedSessionUnittest,
LaunchSharedManagedGuestSessionRestrictedMGSNotEnabled) {
GetCrosSettingsHelper()->SetBoolean(
ash::kDeviceRestrictedManagedGuestSessionEnabled, false);
ASSERT_EQ(
login_api_errors::kNoPermissionToUseApi,
RunFunctionAndReturnError(
new LoginLaunchSharedManagedGuestSessionFunction(), "[\"foo\"]"));
}
// Test that calling `login.launchSharedManagedGuestSession()` returns an error
// when there are no managed guest session accounts.
TEST_F(LoginApiSharedSessionUnittest,
LaunchSharedManagedGuestSessionNoAccounts) {
ASSERT_EQ(
login_api_errors::kNoManagedGuestSessionAccounts,
RunFunctionAndReturnError(
new LoginLaunchSharedManagedGuestSessionFunction(), "[\"foo\"]"));
}
// Test that calling `login.launchSharedManagedGuestSession()` returns an error
// when the session state is not `LOGIN_PRIMARY`.
TEST_F(LoginApiSharedSessionUnittest,
LaunchSharedManagedGuestSessionWrongSessionState) {
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::ACTIVE);
ASSERT_EQ(
login_api_errors::kLoginScreenIsNotActive,
RunFunctionAndReturnError(
new LoginLaunchSharedManagedGuestSessionFunction(), "[\"foo\"]"));
}
// Test that calling `login.launchSharedManagedGuestSession()` returns an error
// when there is another signin in progress.
TEST_F(LoginApiSharedSessionUnittest,
LaunchSharedManagedGuestSessionSigninInProgress) {
EXPECT_CALL(*mock_existing_user_controller_, IsSigninInProgress())
.WillOnce(Return(true));
ASSERT_EQ(
login_api_errors::kAnotherLoginAttemptInProgress,
RunFunctionAndReturnError(
new LoginLaunchSharedManagedGuestSessionFunction(), "[\"foo\"]"));
}
// Test that calling `login.unlockSharedSession()` works.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSession) {
LaunchSharedManagedGuestSession("foo");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ExpectAuthenticateWithSessionSecret(/*auth_success=*/true);
base::TimeTicks now_ = base::TimeTicks::Now();
ui::UserActivityDetector::Get()->set_now_for_test(now_);
RunFunction(new LoginUnlockSharedSessionFunction(), "[\"foo\"]");
// Test that user activity is triggered.
EXPECT_EQ(now_, ui::UserActivityDetector::Get()->last_activity_time());
}
// Test that calling `login.unlockSharedSession()` returns an error when the
// session is not locked.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionNotLocked) {
SetExtensionWithId(kExtensionId);
std::unique_ptr<ScopedTestingProfile> scoped_profile =
AddPublicAccountUser(kEmail);
SetLoginExtensionApiLaunchExtensionIdPref(scoped_profile->profile(),
kExtensionId);
ASSERT_EQ(login_api_errors::kSessionIsNotLocked,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.unlockSharedSession()` returns an error when there
// is no shared MGS launched.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionNoSharedMGS) {
SetExtensionWithId(kExtensionId);
std::unique_ptr<ScopedTestingProfile> scoped_profile =
AddPublicAccountUser(kEmail);
SetLoginExtensionApiLaunchExtensionIdPref(scoped_profile->profile(),
kExtensionId);
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ASSERT_EQ(login_api_errors::kNoSharedMGSFound,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.unlockSharedSession()` returns an error when there
// is no shared session active.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionNoSharedSession) {
LaunchSharedManagedGuestSession("foo");
EXPECT_CALL(*mock_lock_handler_, RequestLockScreen()).WillOnce(Return());
RunFunction(new LoginEndSharedSessionFunction(), "[]");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ASSERT_EQ(login_api_errors::kSharedSessionIsNotActive,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.unlockSharedSession()` returns an error when a
// different password is used.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionAuthenticationFailed) {
LaunchSharedManagedGuestSession("foo");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ASSERT_EQ(login_api_errors::kAuthenticationFailed,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"bar\"]"));
}
// Test that calling `login.unlockSharedSession()` returns an error when there
// is an error when unlocking the screen.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionUnlockFailed) {
LaunchSharedManagedGuestSession("foo");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ExpectAuthenticateWithSessionSecret(/*auth_success=*/false);
ASSERT_EQ(login_api_errors::kUnlockFailure,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.unlockSharedSession()` returns an error when it is
// called by an extension with a different ID.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionWrongExtension) {
LaunchSharedManagedGuestSession("foo");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
SetExtensionWithId("wrong_extension_id");
ASSERT_EQ(login_api_errors::kNoPermissionToUnlock,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.unlockSharedSession()` returns an error when the
// extension ID does not match the `kLoginExtensionApiLaunchExtensionId` pref.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionWrongExtensionId) {
LaunchSharedManagedGuestSession("foo");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
SetLoginExtensionApiLaunchExtensionIdPref(testing_profile_->profile(),
"wrong_extension_id");
ASSERT_EQ(login_api_errors::kNoPermissionToUnlock,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.unlockSharedSession()` returns an error when there
// is a cleanup in progress.
TEST_F(LoginApiSharedSessionUnittest, UnlockSharedSessionCleanupInProgress) {
LaunchSharedManagedGuestSession("foo");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
chromeos::CleanupManager::Get()->SetIsCleanupInProgressForTesting(true);
ASSERT_EQ(login_api_errors::kCleanupInProgress,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.endSharedSession()` clears the user hash and salt
// and locks the screen when the screen is not locked.
TEST_F(LoginApiSharedSessionUnittest, EndSharedSession) {
SetUpCleanupHandlerMocks();
LaunchSharedManagedGuestSession("foo");
EXPECT_CALL(*mock_lock_handler_, RequestLockScreen()).WillOnce(Return());
RunFunction(new LoginEndSharedSessionFunction(), "[]");
chromeos::SharedSessionHandler* handler =
chromeos::SharedSessionHandler::Get();
EXPECT_EQ("", handler->GetUserSecretHashForTesting());
EXPECT_EQ("", handler->GetUserSecretSaltForTesting());
}
// Test that calling `login.endSharedSession()` works on the lock screen as
// well.
TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionLocked) {
SetUpCleanupHandlerMocks();
LaunchSharedManagedGuestSession("foo");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
EXPECT_CALL(*mock_lock_handler_, RequestLockScreen()).Times(0);
RunFunction(new LoginEndSharedSessionFunction(), "[]");
chromeos::SharedSessionHandler* handler =
chromeos::SharedSessionHandler::Get();
EXPECT_EQ("", handler->GetUserSecretHashForTesting());
EXPECT_EQ("", handler->GetUserSecretSaltForTesting());
}
// Test that calling `login.endSharedSession()` returns an error when the there
// is an error in the cleanup handlers.
TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionCleanupError) {
std::string error1 = "Mock cleanup handler 1 error";
std::string error2 = "Mock cleanup handler 2 error";
SetUpCleanupHandlerMocks(error1, error2);
LaunchSharedManagedGuestSession("foo");
EXPECT_CALL(*mock_lock_handler_, RequestLockScreen()).WillOnce(Return());
ASSERT_EQ(
"Handler1: " + error1 + "\nHandler2: " + error2,
RunFunctionAndReturnError(new LoginEndSharedSessionFunction(), "[]"));
}
// Test that calling `login.endSharedSession()` returns an error when no shared
// MGS was launched.
TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionNoSharedMGS) {
SetUpCleanupHandlerMockNotCalled();
ASSERT_EQ(
login_api_errors::kNoSharedMGSFound,
RunFunctionAndReturnError(new LoginEndSharedSessionFunction(), "[]"));
}
// Test that calling `login.endSharedSession()` returns an error when there is
// no shared session active.
TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionNoSharedSession) {
SetUpCleanupHandlerMocks();
LaunchSharedManagedGuestSession("foo");
RunFunction(new LoginEndSharedSessionFunction(), "[]");
ASSERT_EQ(
login_api_errors::kSharedSessionIsNotActive,
RunFunctionAndReturnError(new LoginEndSharedSessionFunction(), "[]"));
}
// Test that calling `login.endSharedSession()` returns an error when there
// is a cleanup in progress.
TEST_F(LoginApiSharedSessionUnittest, EndSharedSessionCleanupInProgress) {
LaunchSharedManagedGuestSession("foo");
chromeos::CleanupManager::Get()->SetIsCleanupInProgressForTesting(true);
ASSERT_EQ(login_api_errors::kCleanupInProgress,
RunFunctionAndReturnError(new LoginEndSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.enterSharedSession()` with a password sets the user
// hash and salt.
TEST_F(LoginApiSharedSessionUnittest, EnterSharedSession) {
SetUpCleanupHandlerMocks();
LaunchSharedManagedGuestSession("foo");
RunFunction(new LoginEndSharedSessionFunction(), "[]");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ExpectAuthenticateWithSessionSecret(/*auth_success=*/true);
base::TimeTicks now_ = base::TimeTicks::Now();
ui::UserActivityDetector::Get()->set_now_for_test(now_);
RunFunction(new LoginEnterSharedSessionFunction(), "[\"bar\"]");
chromeos::SharedSessionHandler* handler =
chromeos::SharedSessionHandler::Get();
EXPECT_NE("", handler->GetUserSecretHashForTesting());
EXPECT_NE("", handler->GetUserSecretSaltForTesting());
// Test that user activity is triggered.
EXPECT_EQ(now_, ui::UserActivityDetector::Get()->last_activity_time());
}
// Test that calling `login.enterSharedSession()` returns an error when the
// DeviceRestrictedManagedGuestSessionEnabled policy is set to false.
TEST_F(LoginApiSharedSessionUnittest,
EnterSharedSessionRestrictedMGSNotEnabled) {
GetCrosSettingsHelper()->SetBoolean(
ash::kDeviceRestrictedManagedGuestSessionEnabled, false);
ASSERT_EQ(login_api_errors::kNoPermissionToUseApi,
RunFunctionAndReturnError(new LoginEnterSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.enterSharedSession()` returns an error when the
// session is not locked.
TEST_F(LoginApiSharedSessionUnittest, EnterSharedSessionNotLocked) {
ASSERT_EQ(login_api_errors::kSessionIsNotLocked,
RunFunctionAndReturnError(new LoginEnterSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.enterSharedSession()` returns an error when there is
// no shared MGS launched.
TEST_F(LoginApiSharedSessionUnittest, EnterSharedSessionNoSharedMGSFound) {
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ASSERT_EQ(login_api_errors::kNoSharedMGSFound,
RunFunctionAndReturnError(new LoginEnterSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.enterSharedSession()` returns an error when there
// is another shared session present.
TEST_F(LoginApiSharedSessionUnittest, EnterSharedSessionAlreadyLaunched) {
LaunchSharedManagedGuestSession("foo");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ASSERT_EQ(login_api_errors::kSharedSessionAlreadyLaunched,
RunFunctionAndReturnError(new LoginEnterSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.enterSharedSession()` returns an error when there is
// an error when unlocking the screen.
TEST_F(LoginApiSharedSessionUnittest, EnterSharedSessionUnlockFailed) {
LaunchSharedManagedGuestSession("foo");
RunFunction(new LoginEndSharedSessionFunction(), "[]");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ExpectAuthenticateWithSessionSecret(/*auth_success=*/false);
ASSERT_EQ(login_api_errors::kUnlockFailure,
RunFunctionAndReturnError(new LoginEnterSharedSessionFunction(),
"[\"foo\"]"));
}
// Test that calling `login.enterSharedSession()` returns an error when there
// is a cleanup in progress.
TEST_F(LoginApiSharedSessionUnittest, EnterSharedSessionCleanupInProgress) {
LaunchSharedManagedGuestSession("foo");
RunFunction(new LoginEndSharedSessionFunction(), "[]");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
chromeos::CleanupManager::Get()->SetIsCleanupInProgressForTesting(true);
ASSERT_EQ(login_api_errors::kCleanupInProgress,
RunFunctionAndReturnError(new LoginEnterSharedSessionFunction(),
"[\"foo\"]"));
}
// Test the full shared session flow.
TEST_F(LoginApiSharedSessionUnittest, SharedSessionFlow) {
SetUpCleanupHandlerMocks();
LaunchSharedManagedGuestSession("foo");
chromeos::SharedSessionHandler* handler =
chromeos::SharedSessionHandler::Get();
std::string foo_hash = handler->GetUserSecretHashForTesting();
std::string foo_salt = handler->GetUserSecretSaltForTesting();
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ASSERT_EQ(login_api_errors::kAuthenticationFailed,
RunFunctionAndReturnError(new LoginUnlockSharedSessionFunction(),
"[\"bar\"]"));
ExpectAuthenticateWithSessionSecret(/*auth_success=*/true);
RunFunction(new LoginUnlockSharedSessionFunction(), "[\"foo\"]");
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::ACTIVE);
EXPECT_CALL(*mock_lock_handler_, RequestLockScreen()).WillOnce(Return());
RunFunction(new LoginEndSharedSessionFunction(), "[]");
EXPECT_EQ("", handler->GetUserSecretHashForTesting());
EXPECT_EQ("", handler->GetUserSecretSaltForTesting());
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
ExpectAuthenticateWithSessionSecret(/*auth_success=*/true);
RunFunction(new LoginEnterSharedSessionFunction(), "[\"baz\"]");
const std::string& baz_hash = handler->GetUserSecretHashForTesting();
const std::string& baz_salt = handler->GetUserSecretSaltForTesting();
EXPECT_NE("", baz_hash);
EXPECT_NE("", baz_salt);
EXPECT_NE(foo_hash, baz_hash);
EXPECT_NE(foo_salt, baz_salt);
}
} // namespace extensions
| {
"content_hash": "b54079d7cc1441cb5b9c9e4b4bcee19a",
"timestamp": "",
"source": "github",
"line_count": 1049,
"max_line_length": 95,
"avg_line_length": 41.07244995233556,
"alnum_prop": 0.7225484507369154,
"repo_name": "ric2b/Vivaldi-browser",
"id": "ca8fbf03a17a481a774fcc721c7015deb3f78bc9",
"size": "43085",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chromium/chrome/browser/chromeos/extensions/login_screen/login/login_api_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
///////////////////////////////////////////////////////////////
// This is generated code.
//////////////////////////////////////////////////////////////
// Code is generated using LLBLGen Pro version: 4.1
// Code is generated on:
// Code is generated using templates: SD.TemplateBindings.SharedTemplates
// Templates vendor: Solutions Design.
// Templates version:
//////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using AdventureWorks.Dal.Adapter.v41;
using AdventureWorks.Dal.Adapter.v41.FactoryClasses;
using AdventureWorks.Dal.Adapter.v41.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
namespace AdventureWorks.Dal.Adapter.v41.RelationClasses
{
/// <summary>Implements the relations factory for the entity: ProductPhoto. </summary>
public partial class ProductPhotoRelations
{
/// <summary>CTor</summary>
public ProductPhotoRelations()
{
}
/// <summary>Gets all relations of the ProductPhotoEntity as a list of IEntityRelation objects.</summary>
/// <returns>a list of IEntityRelation objects</returns>
public virtual List<IEntityRelation> GetAllRelations()
{
List<IEntityRelation> toReturn = new List<IEntityRelation>();
toReturn.Add(this.ProductProductPhotoEntityUsingProductPhotoId);
return toReturn;
}
#region Class Property Declarations
/// <summary>Returns a new IEntityRelation object, between ProductPhotoEntity and ProductProductPhotoEntity over the 1:n relation they have, using the relation between the fields:
/// ProductPhoto.ProductPhotoId - ProductProductPhoto.ProductPhotoId
/// </summary>
public virtual IEntityRelation ProductProductPhotoEntityUsingProductPhotoId
{
get
{
IEntityRelation relation = new EntityRelation(SD.LLBLGen.Pro.ORMSupportClasses.RelationType.OneToMany, "ProductProductPhotos" , true);
relation.AddEntityFieldPair(ProductPhotoFields.ProductPhotoId, ProductProductPhotoFields.ProductPhotoId);
relation.InheritanceInfoPkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("ProductPhotoEntity", true);
relation.InheritanceInfoFkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("ProductProductPhotoEntity", false);
return relation;
}
}
/// <summary>stub, not used in this entity, only for TargetPerEntity entities.</summary>
public virtual IEntityRelation GetSubTypeRelation(string subTypeEntityName) { return null; }
/// <summary>stub, not used in this entity, only for TargetPerEntity entities.</summary>
public virtual IEntityRelation GetSuperTypeRelation() { return null;}
#endregion
#region Included Code
#endregion
}
/// <summary>Static class which is used for providing relationship instances which are re-used internally for syncing</summary>
internal static class StaticProductPhotoRelations
{
internal static readonly IEntityRelation ProductProductPhotoEntityUsingProductPhotoIdStatic = new ProductPhotoRelations().ProductProductPhotoEntityUsingProductPhotoId;
/// <summary>CTor</summary>
static StaticProductPhotoRelations()
{
}
}
}
| {
"content_hash": "d0b8e465f3149ae6ca6f054a8a4f9bca",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 181,
"avg_line_length": 41.48684210526316,
"alnum_prop": 0.7459562321598477,
"repo_name": "anpete/RawDataAccessBencher",
"id": "f43498449c0fed635e407893de8b637bbc76fc47",
"size": "3155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LLBLGen41/DatabaseGeneric/RelationClasses/ProductPhotoRelations.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "8456746"
}
],
"symlink_target": ""
} |
Plugin for bauer to extract values from JSON data.
| {
"content_hash": "b58b7e29a3c8e9927b70e3cb676437bb",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 50,
"avg_line_length": 51,
"alnum_prop": 0.803921568627451,
"repo_name": "yneves/node-bauer-plugin-extract",
"id": "b499b6c004ce1127bf7d9cc3a10cb0fd440554f1",
"size": "79",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "9163"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>Chris Chittell's panel show appearances</title>
<script type="text/javascript" src="../common.js"></script>
<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>
<script type="text/javascript" src="../people.js"></script>
<!--#include virtual="head.txt" -->
</head>
<body>
<!--#include virtual="nav.txt" -->
<div class="page">
<h1>Chris Chittell's panel show appearances</h1>
<p>Chris Chittell (born 1948-05-19<sup><a href="https://en.wikipedia.org/wiki/Chris_Chittell">[ref]</a></sup>) has appeared in <span class="total">1</span> episodes between 2014-2014. <a href="http://www.imdb.com/name/nm0158348">Chris Chittell on IMDB</a>. <a href="https://en.wikipedia.org/wiki/Chris_Chittell">Chris Chittell on Wikipedia</a>.</p>
<div class="performerholder">
<table class="performer">
<tr style="vertical-align:bottom;">
<td><div style="height:100px;" class="performances male" title="1"></div><span class="year">2014</span></td>
</tr>
</table>
</div>
<ol class="episodes">
<li><strong>2014-06-03</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li>
</ol>
</div>
</body>
</html>
| {
"content_hash": "bf838d8b10b516875c5f151b3821a2c3",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 350,
"avg_line_length": 38.5,
"alnum_prop": 0.6675324675324675,
"repo_name": "slowe/panelshows",
"id": "34ad68acb44b75f8386158c8b13e3679967054a6",
"size": "1155",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "people/5eylr0pl.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8431"
},
{
"name": "HTML",
"bytes": "25483901"
},
{
"name": "JavaScript",
"bytes": "95028"
},
{
"name": "Perl",
"bytes": "19899"
}
],
"symlink_target": ""
} |
package org.lorislab.appky.application.tmpresource.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.lorislab.jel.jpa.model.Persistent;
/**
* The temporary resource.
*
* @author Andrej Petras <andrej@ajka-andrej.com>
*/
@Entity
@Table(name = "AY_RESOURCE")
public class TemporaryResource extends Persistent {
/**
* The UID for this class.
*/
private static final long serialVersionUID = 1135641957002181338L;
/**
* The user GUID.
*/
@Column(name = "C_USERGUID")
private String userGuid;
/**
* The validate to date.
*/
@Column(name = "C_VALIDATETO")
@Temporal(TemporalType.TIMESTAMP)
private Date validateTo;
/**
* The set of resources.
*/
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "C_PARENT_GUID")
private List<TemporaryResourceData> resources;
/**
* The default constructor.
*/
public TemporaryResource() {
resources = new ArrayList<>();
}
/**
* Gets the user GUID.
*
* @return the user GUID.
*/
public String getUserGuid() {
return userGuid;
}
/**
* Sets the user GUID.
*
* @param userGuid the user GUID.
*/
public void setUserGuid(String userGuid) {
this.userGuid = userGuid;
}
/**
* Gets the validate to date.
*
* @return the validate to date.
*/
public Date getValidateTo() {
return validateTo;
}
/**
* Sets the validate to date.
*
* @param validateTo the validate to date.
*/
public void setValidateTo(Date validateTo) {
this.validateTo = validateTo;
}
/**
* Gets the set of resources.
*
* @return the set of resources.
*/
public List<TemporaryResourceData> getResources() {
return resources;
}
/**
* Sets the set of resources.
*
* @param resources the set of resources.
*/
public void setResources(List<TemporaryResourceData> resources) {
this.resources = resources;
}
}
| {
"content_hash": "a08530d3b5efefe899beabe467addf2e",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 88,
"avg_line_length": 22.770642201834864,
"alnum_prop": 0.6321514907332796,
"repo_name": "lorislab/appky",
"id": "93511cc01e7967a983161fcb61a3d1f4f8ec0aea",
"size": "3079",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "appky-application/src/main/java/org/lorislab/appky/application/tmpresource/model/TemporaryResource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8591"
},
{
"name": "Java",
"bytes": "685172"
},
{
"name": "JavaScript",
"bytes": "158"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>dblib: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.15.2 / dblib - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
dblib
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-03 10:13:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-03 10:13:39 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.15.2 Formal proof management system
dune 3.4.1 Fast, portable, and opinionated build system
ocaml 4.10.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.2 Official release 4.10.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/dblib"
license: "GPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Dblib"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: abstract syntax" "keyword: binders" "keyword: de Bruijn indices" "keyword: shift" "keyword: lift" "keyword: substitution" "category: Computer Science/Lambda Calculi" ]
authors: [ "Francois Pottier <francois.pottier@inria.fr> [http://gallium.inria.fr/~fpottier/]" ]
bug-reports: "https://github.com/coq-contribs/dblib/issues"
dev-repo: "git+https://github.com/coq-contribs/dblib.git"
synopsis: "Dblib"
description: """
http://gallium.inria.fr/~fpottier/dblib/README
The dblib library offers facilities for working with de Bruijn indices."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/dblib/archive/v8.7.0.tar.gz"
checksum: "md5=9b872142011b72c077524ed05cd935da"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-dblib.8.7.0 coq.8.15.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.15.2).
The following dependencies couldn't be met:
- coq-dblib -> coq < 8.8~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-dblib.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "ace39b244c7d6fb9e450d8fa31e208d7",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 255,
"avg_line_length": 42.51219512195122,
"alnum_prop": 0.5421686746987951,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "3e4588ea7c32917546eead438e16e093b500ce7f",
"size": "6997",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.15.2/dblib/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
@interface ATVLoaderAppliance : BRAppliance
{
}
+ (NSString *) className;
- (id) init;
- (void) dealloc;
- (NSString *) moduleName;
+ (NSString *) moduleKey;
- (NSString *) moduleKey;
- (BRMenuController *) applianceControllerWithScene: (BRRenderScene *) scene;
@end
| {
"content_hash": "f8ce1f054b80419225cfca4bcff92258",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 77,
"avg_line_length": 19.285714285714285,
"alnum_prop": 0.7,
"repo_name": "AlanQuatermain/atvloader",
"id": "49321cb15fdf1ca71f24ec50761e1e621548fc66",
"size": "513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ATVLoaderAppliance.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "34541"
},
{
"name": "Objective-C",
"bytes": "161441"
}
],
"symlink_target": ""
} |
"""
BRIE package
============
Bayesian Regression for Isoform Estimate - a python toolbox for splicing
analysis in single cells.
The official documentation together with examples and tutorials can be found
at https://brie.readthedocs.io/.
"""
# from ._cli import cli
from .version import __version__
# direct classes or functions
# from .models.model_TFProb import BRIE2
from .utils.io_utils import read_brieMM, read_h5ad, read_gff, read_npz
from .utils import io_utils as io
from .utils.base_utils import match
# set simplified alias
from . import plot as pl
# from .models import tools as tl
from .utils import preprocessing as pp
# __all__ = [
# "__version__",
# "utils",
# "models"
# ]
| {
"content_hash": "5c7f0c2ff3574bd4162eab954bb0680a",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 76,
"avg_line_length": 24.413793103448278,
"alnum_prop": 0.7090395480225988,
"repo_name": "huangyh09/brie",
"id": "04f9426808364f12db0ad678338d266689655f70",
"size": "708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "brie/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "233075"
},
{
"name": "Shell",
"bytes": "1944"
}
],
"symlink_target": ""
} |
import sys
from .base import BaseCommand
from ..utils import (
send_keys,
translate,
)
class StringCommand(BaseCommand):
def _run(self, env):
send_keys(self._args)
class SingleKeyCommand(StringCommand):
def __init__(self, args):
pass
def _run(self, env):
send_keys(self._args)
__all__ = []
for key in ["ENTER", "ESC", "ESCAPE", "TAB",
"UP", "DOWN", "LEFT", "RIGHT",
"UPARROW", "DOWNARROW", "LEFTARROW", "RIGHTARROW"]:
command_name = key.title() + "Command"
k = type(command_name,
(SingleKeyCommand, ),
dict(_args=translate(key)))
setattr(sys.modules[__name__], k.__name__, k)
__all__.append(command_name)
| {
"content_hash": "df816c4ae0e925b6231d4514b10d4b1c",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 63,
"avg_line_length": 21.323529411764707,
"alnum_prop": 0.5641379310344827,
"repo_name": "hamstah/quack",
"id": "53956b5bbd3791cebe626c857f8e3bdbc48ccf4b",
"size": "725",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "quack/commands/keys.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8728"
},
{
"name": "Shell",
"bytes": "321"
}
],
"symlink_target": ""
} |
#include "imageContentInfo.hpp"
#include <cstdlib>
#include <ctime>
#include <QPointer>
// Flags
//#define __USE_PBO__
// Namespace
using namespace Glip::CoreGL;
using namespace Glip::CorePipeline;
using namespace Glip::Modules;
TmpWidget::TmpWidget(void)
: layout(&widget),
a("Button A", &widget),
b("Button B", &widget),
c("Button C", &widget),
//img("/home/arkh/Pictures/mire.bmp"),
//img("/home/arkh/Pictures/the_general_problem.png"),
img("0.jpg"),
texture(NULL),
view(NULL)
{
std::cout << "TmpWidget : " << this << std::endl;
std::cout << " layout : " << (&layout) << std::endl;
std::cout << " button a : " << (&a) << std::endl;
std::cout << " button b : " << (&b) << std::endl;
std::cout << " button c : " << (&c) << std::endl;
static int count = 1;
layout.addWidget(&a);
layout.addWidget(&b);
layout.addWidget(&c);
layout.setMargin(0);
layout.setSpacing(1);
// Create the view :
ImageBuffer* buffer = createImageBufferFromQImage(img);
if(buffer!=NULL)
{
texture = new HdlTexture(*buffer);
(*buffer) >> (*texture);
view = new QVGL::View(texture, tr("View %1").arg(count));
//view->setAngle(0.5465f);
//view->setViewCenter(0.3, 0.1);
delete buffer;
}
setTitle(tr("Widget %1").arg(count));
count++;
QObject::connect(&a, SIGNAL(released(void)), this, SLOT(buttonAPressed(void)));
QObject::connect(&b, SIGNAL(released(void)), this, SLOT(buttonBPressed(void)));
QObject::connect(&c, SIGNAL(released(void)), this, SLOT(buttonCPressed(void)));
std::cout << "Subwidget created." << std::endl;
setInnerWidget(&widget);
show();
move(128, 128);
}
TmpWidget::~TmpWidget(void)
{
delete texture;
delete view;
}
void TmpWidget::buttonAPressed(void)
{
std::cout << "TmpWidget : Button A, add and show" << std::endl;
if(view!=NULL)
{
getQVGLParent()->addView(view);
view->show();
}
}
void TmpWidget::buttonBPressed(void)
{
std::cout << "TmpWidget : Button B, close" << std::endl;
if(view!=NULL)
view->close();
}
void TmpWidget::buttonCPressed(void)
{
std::cout << "TmpWidget : Button C" << std::endl;
}
// TestEditorWidget ;
/*CodeEditorSubWidget::CodeEditorSubWidget(void)
{
setInnerWidget(&mainWidget);
setTitle("Test Code Editor");
}
CodeEditorSubWidget::~CodeEditorSubWidget(void)
{ }*/
// Src :
IHM::IHM(void)
: layout(this), saveButton("Save result (RGB888)", this), window(this)
{
log.open("./log.txt", std::fstream::out | std::fstream::trunc);
if(!log.is_open())
{
QMessageBox::warning(NULL, tr("My Application"), tr("Unable to write to the log file log.txt.\n"));
throw Exception("IHM::IHM - Cannot open log file.", __FILE__, __LINE__);
}
try
{
if(!HandleOpenGL::isInitialized())
throw Exception("OpenGL Context not initialized.", __FILE__, __LINE__);
// Main interface :
//window.renderer().setKeyboardActions(true);
//window.renderer().setMouseActions(true);
//window.renderer().setPixelAspectRatio(1.0f);
// Info :
log << "> ImageTest" << std::endl;
log << "Vendor name : " << HandleOpenGL::getVendorName() << std::endl;
log << "Renderer name : " << HandleOpenGL::getRendererName() << std::endl;
log << "GL version : " << HandleOpenGL::getVersion() << std::endl;
log << "GLSL version : " << HandleOpenGL::getGLSLVersion() << std::endl;
layout.addLayout(&imageLoaderInterface);
layout.addLayout(&pipelineLoaderInterface);
layout.addWidget(&window);
layout.addWidget(&saveButton);
setGeometry(1000, 100, 1200, 800);
show();
QObject::connect(&saveButton, SIGNAL(released(void)), this, SLOT(save(void)));
QObject::connect(&imageLoaderInterface, SIGNAL(currentTextureChanged(void)), this, SLOT(requestComputingUpdate(void)));
QObject::connect(&imageLoaderInterface, SIGNAL(currentTextureChanged(void)), this, SLOT(updateOutput(void)));
//QObject::connect(&(window.renderer()), SIGNAL(actionReceived(void)), this, SLOT(updateOutput(void)));
QObject::connect(&pipelineLoaderInterface, SIGNAL(outputIndexChanged(void)), this, SLOT(updateOutput(void)));
QObject::connect(&pipelineLoaderInterface, SIGNAL(requestComputingUpdate(void)), this, SLOT(requestComputingUpdate(void)));
}
catch(Exception& e)
{
log << "Exception caught : " << std::endl;
log << e.what() << std::endl;
log << "> Abort" << std::endl;
log.close();
QMessageBox::warning(NULL, tr("ImageTest - Error : "), e.what());
throw e;
}
TmpWidget* tmp = new TmpWidget;
window.addSubWidget(tmp);
tmp = new TmpWidget;
window.addSubWidget(tmp);
tmp = new TmpWidget;
window.addSubWidget(tmp);
QGED::CodeEditorTabsSubWidget* codeEditorTabs = new QGED::CodeEditorTabsSubWidget;
window.addSubWidget(codeEditorTabs);
QGIC::ImageItemsCollectionSubWidget* collection = new QGIC::ImageItemsCollectionSubWidget;
window.addSubWidget(collection);
window.addViewsTable(collection->getMainViewsTablePtr());
QObject::connect(collection, SIGNAL(addViewRequest(QVGL::View*)), &window, SLOT(addView(QVGL::View*)));
QGPM::PipelineManagerSubWidget* manager = new QGPM::PipelineManagerSubWidget;
window.addSubWidget(manager);
QObject::connect(codeEditorTabs->getCodeEditorPtr(), SIGNAL(compileSource(std::string, std::string, void*, const QObject*)), manager->getManagerPtr(), SLOT(compileSource(std::string, std::string, void*, const QObject*)));
QObject::connect(collection->getCollectionPtr(), SIGNAL(imageItemAdded(QGIC::ImageItem*)), manager->getManagerPtr(), SLOT(addImageItem(QGIC::ImageItem*)));
QObject::connect(manager->getManagerPtr(), SIGNAL(addViewRequest(QVGL::View*)), &window, SLOT(addView(QVGL::View*)));
QObject::connect(manager->getManagerPtr(), SIGNAL(addViewsTableRequest(QVGL::ViewsTable*)), &window, SLOT(addViewsTable(QVGL::ViewsTable*)));
QObject::connect(manager->getManagerPtr(), SIGNAL(addImageItemRequest(QGIC::ImageItem*)), collection->getCollectionPtr(), SLOT(addImageItem(QGIC::ImageItem*)));
}
IHM::~IHM(void)
{
log << "> End" << std::endl;
log.close();
}
void IHM::save(void)
{
if(pipelineLoaderInterface.currentChoiceIsOriginal())
QMessageBox::information(this, tr("Error while requesting image write"), tr("Cannot write the original file (no modification made)."));
else if(!pipelineLoaderInterface.isPipelineValid())
QMessageBox::information(this, tr("Error while requesting image write"), tr("No available pipeline or last computing operation failed."));
else
{
try
{
imageLoaderInterface.saveTexture(pipelineLoaderInterface.currentOutput( imageLoaderInterface.currentTexture() ));
}
catch(Exception& e)
{
QMessageBox::information(this, tr("IHM::save - Error while writing file : "), e.what());
std::cout << "IHM::save - Error while writing file : " << std::endl;
std::cout << e.what() << std::endl;
}
}
}
void IHM::requestComputingUpdate(void)
{
if(pipelineLoaderInterface.isPipelineValid() && imageLoaderInterface.getNumTextures()>0)
{
if(pipelineLoaderInterface.pipeline().getNumInputPort()!=1)
{
QMessageBox::information(this, tr("IHM::requestComputingUpdate - Error :"), "The pipeline must have only one input.");
pipelineLoaderInterface.revokePipeline();
}
else
pipelineLoaderInterface.pipeline() << imageLoaderInterface.currentTexture() << Pipeline::Process;
updateOutput();
}
}
void IHM::updateOutput(void)
{
static bool lock = false;
if(lock)
return;
lock = true;
//if(imageLoaderInterface.getNumTextures()==0)
//window.renderer().clearWindow();
//else
/*{
try
{
int w = pipelineLoaderInterface.currentOutput( imageLoaderInterface.currentTexture() ).getWidth(),
h = pipelineLoaderInterface.currentOutput( imageLoaderInterface.currentTexture() ).getHeight();
float imageAspectRatio = static_cast<float>(w)/static_cast<float>(h);
//window.renderer().setImageAspectRatio(imageAspectRatio);
pipelineLoaderInterface.loader().clearRequiredElements("InputFormat");
pipelineLoaderInterface.loader().addRequiredElement("InputFormat", imageLoaderInterface.currentTexture());
//window.renderer() << pipelineLoaderInterface.currentOutput( imageLoaderInterface.currentTexture() ) << OutputDevice::Process;
}
catch(std::exception& e)
{
std::cout << "IHM::updateOutput - Exception while updating : " << std::endl;
std::cout << e.what() << std::endl;
log << "IHM::updateOutput - Exception while updating : " << std::endl;
log << e.what() << std::endl;
}
}*/
lock = false;
}
ImageContentInformation::ImageContentInformation(int& argc, char** argv)
: QApplication(argc,argv), ihm(NULL)
{
try
{
// Interface :
ihm = new IHM;
// Load Stylesheet :
const QString stylesheetFilename = "stylesheet.css";
QFile stylesheetFile(stylesheetFilename);
if(!stylesheetFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QString path = QDir::currentPath();
Exception e("GlipStudio::GlipStudio - The style sheet \"" + stylesheetFile.fileName().toStdString() + "\" could not be loaded (" + path.toStdString() + ").", __FILE__, __LINE__);
qCritical() << e.what();
QMessageBox messageBox(QMessageBox::Warning, "Error", tr("The style sheet \"%1\" could not be loaded.\nIn %2. The execution will continue with default system theme (BAD).").arg(stylesheetFile.fileName()).arg(path), QMessageBox::Ok);
messageBox.exec();
}
QTextStream stylesheetStream(&stylesheetFile);
QString stylesheet = stylesheetStream.readAll();
//std::cout << "Stylesheet : " << stylesheet.toStdString() << std::endl;
// Set style :
QApplication::setStyleSheet(stylesheet);
}
catch(std::exception& e)
{
std::cout << "Exception caught : " << std::endl;
std::cout << e.what() << std::endl;
std::cout << "(Will be rethrown)" << std::endl;
QMessageBox::information(NULL, tr("Exception caught : "), e.what());
throw e;
}
std::cout << "--- STARTING ---" << std::endl;
}
ImageContentInformation::~ImageContentInformation(void)
{
delete ihm;
}
| {
"content_hash": "421afed819e436d1f9700d0cf69b174c",
"timestamp": "",
"source": "github",
"line_count": 321,
"max_line_length": 236,
"avg_line_length": 31.697819314641745,
"alnum_prop": 0.6716461916461917,
"repo_name": "headupinclouds/GLIP-Lib",
"id": "0512101ffb853781fe727d0fca825e2314ed35e9",
"size": "10175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Examples/Deprecated.ImageContentInfo/src/imageContentInfo.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2067850"
},
{
"name": "C++",
"bytes": "2134014"
},
{
"name": "CMake",
"bytes": "2972"
},
{
"name": "CSS",
"bytes": "26436"
},
{
"name": "GLSL",
"bytes": "33281"
},
{
"name": "HTML",
"bytes": "1967"
},
{
"name": "QMake",
"bytes": "8906"
},
{
"name": "Shell",
"bytes": "1548"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61a.c
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-61a.tmpl.c
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 61 Data flow: data returned from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
#define HELLO_STRING "hello"
#ifndef OMITBAD
/* bad function declaration */
size_t CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61b_badSource(size_t data);
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61_bad()
{
size_t data;
/* Initialize data */
data = 0;
data = CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61b_badSource(data);
{
char * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING))
{
myString = (char *)malloc(data*sizeof(char));
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
size_t CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61b_goodG2BSource(size_t data);
static void goodG2B()
{
size_t data;
/* Initialize data */
data = 0;
data = CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61b_goodG2BSource(data);
{
char * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING))
{
myString = (char *)malloc(data*sizeof(char));
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
/* goodB2G uses the BadSource with the GoodSink */
size_t CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61b_goodB2GSource(size_t data);
static void goodB2G()
{
size_t data;
/* Initialize data */
data = 0;
data = CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61b_goodB2GSource(data);
{
char * myString;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING) && data < 100)
{
myString = (char *)malloc(data*sizeof(char));
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61_good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "7fe2a531ee10f2285dc216748ce5dfa0",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 109,
"avg_line_length": 32.4393063583815,
"alnum_prop": 0.6389878831076266,
"repo_name": "maurer/tiamat",
"id": "e8bcd69a9bfd7a466b6f37d1efec5759a7ba2af1",
"size": "5612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s01/CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_61a.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.mockito.internal.creation;
import org.junit.Before;
import org.junit.Test;
import org.mockitoutil.TestBase;
import java.lang.reflect.Method;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
public class DelegatingMethodTest extends TestBase {
private Method someMethod, otherMethod;
private DelegatingMethod delegatingMethod;
@Before
public void setup() throws Exception {
someMethod = Something.class.getMethod("someMethod", Object.class);
otherMethod = Something.class.getMethod("otherMethod", Object.class);
delegatingMethod = new DelegatingMethod(someMethod);
}
@Test
public void equals_should_return_false_when_not_equal() throws Exception {
DelegatingMethod notEqual = new DelegatingMethod(otherMethod);
assertFalse(delegatingMethod.equals(notEqual));
}
@Test
public void equals_should_return_true_when_equal() throws Exception {
DelegatingMethod equal = new DelegatingMethod(someMethod);
assertTrue(delegatingMethod.equals(equal));
}
@Test
public void equals_should_return_true_when_self() throws Exception {
assertTrue(delegatingMethod.equals(delegatingMethod));
}
@Test
public void equals_should_return_false_when_not_equal_to_method() throws Exception {
assertFalse(delegatingMethod.equals(otherMethod));
}
@Test
public void equals_should_return_true_when_equal_to_method() throws Exception {
assertTrue(delegatingMethod.equals(someMethod));
}
private interface Something {
Object someMethod(Object param);
Object otherMethod(Object param);
}
} | {
"content_hash": "867df1b6faa59f84584308d73ee5dc9b",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 88,
"avg_line_length": 30.140350877192983,
"alnum_prop": 0.7240977881257276,
"repo_name": "hansjoachim/mockito",
"id": "755280dc5dd08ea752845f7dbcfa10172fe55cd1",
"size": "1718",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/org/mockito/internal/creation/DelegatingMethodTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "31370"
},
{
"name": "HTML",
"bytes": "8386"
},
{
"name": "Java",
"bytes": "2146572"
}
],
"symlink_target": ""
} |
package org.locationtech.geogig.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.vividsolutions.jts.geom.Envelope;
public class BucketTest {
@Test
public void testPointBucket() {
ObjectId oId = ObjectId.valueOf("abc123000000000000001234567890abcdef0000");
Bucket pointBucket = Bucket.create(oId, new Envelope(0, 0, 1, 1));
assertEquals(oId, pointBucket.getObjectId());
assertEquals(new Envelope(0, 0, 1, 1), pointBucket.bounds().get());
Envelope env = new Envelope(0, 0, 0, 0);
pointBucket.expand(env);
assertEquals(new Envelope(0, 0, 0, 1), env);
assertTrue(pointBucket.intersects(env));
assertFalse(pointBucket.intersects(new Envelope(0, 5, 0, 0)));
assertTrue(pointBucket.toString().contains("PointBucket"));
assertTrue(pointBucket.toString().contains(oId.toString()));
}
@Test
public void testRectangleBucket() {
ObjectId oId = ObjectId.valueOf("abc123000000000000001234567890abcdef0001");
Bucket rectangleBucket = Bucket.create(oId, new Envelope(0, 1, 2, 3));
Bucket noWidthBucket = Bucket.create(oId, new Envelope(0, 1, 0, 3));
Bucket noHeightBucket = Bucket.create(oId, new Envelope(0, 1, 2, 1));
assertEquals(oId, rectangleBucket.getObjectId());
assertEquals(new Envelope(0, 1, 2, 3), rectangleBucket.bounds().get());
Envelope env = new Envelope(0, 0, 0, 0);
rectangleBucket.expand(env);
assertEquals(new Envelope(0, 1, 0, 3), env);
assertTrue(rectangleBucket.intersects(env));
assertFalse(rectangleBucket.intersects(new Envelope(5, 5, 7, 7)));
assertTrue(rectangleBucket.toString().contains("RectangleBucket"));
assertTrue(rectangleBucket.toString().contains(oId.toString()));
assertTrue(noWidthBucket.toString().contains("RectangleBucket"));
assertTrue(noWidthBucket.toString().contains(oId.toString()));
assertTrue(noHeightBucket.toString().contains("RectangleBucket"));
assertTrue(noHeightBucket.toString().contains(oId.toString()));
}
@Test
public void testNonspatialBucket() {
ObjectId oId = ObjectId.valueOf("abc123000000000000001234567890abcdef0002");
Bucket nonspatialBucket = Bucket.create(oId, null);
Bucket nonspatialBucket2 = Bucket.create(oId, new Envelope());
assertEquals(oId, nonspatialBucket.getObjectId());
assertEquals(oId, nonspatialBucket2.getObjectId());
assertFalse(nonspatialBucket.bounds().isPresent());
assertFalse(nonspatialBucket2.bounds().isPresent());
assertEquals(nonspatialBucket, nonspatialBucket2);
Envelope env = new Envelope(0, 0, 0, 0);
nonspatialBucket.expand(env);
assertEquals(new Envelope(0, 0, 0, 0), env);
assertFalse(nonspatialBucket.intersects(env));
assertFalse(nonspatialBucket.intersects(new Envelope(0, 0, 100, 100)));
assertTrue(nonspatialBucket.toString().contains("NonSpatialBucket"));
assertTrue(nonspatialBucket.toString().contains(oId.toString()));
}
@Test
public void testEquals() {
ObjectId oId1 = ObjectId.valueOf("abc123000000000000001234567890abcdef0000");
Bucket pointBucket = Bucket.create(oId1, new Envelope(0, 0, 1, 1));
ObjectId oId2 = ObjectId.valueOf("abc123000000000000001234567890abcdef0001");
Bucket rectangleBucket = Bucket.create(oId2, new Envelope(0, 1, 2, 3));
ObjectId oId3 = ObjectId.valueOf("abc123000000000000001234567890abcdef0002");
Bucket nonspatialBucket = Bucket.create(oId3, null);
assertEquals(pointBucket, pointBucket);
assertEquals(rectangleBucket, rectangleBucket);
assertEquals(nonspatialBucket, nonspatialBucket);
assertFalse(pointBucket.equals(rectangleBucket));
assertFalse(pointBucket.equals(nonspatialBucket));
assertFalse(rectangleBucket.equals(nonspatialBucket));
assertFalse(pointBucket.equals(oId1));
}
}
| {
"content_hash": "852e97830b7f3a25470eee04ae452e58",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 85,
"avg_line_length": 41.56,
"alnum_prop": 0.6917709335899904,
"repo_name": "mtCarto/geogig",
"id": "7f04bd6ec791e6b6dfa08c74938f469732104409",
"size": "4547",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/api/src/test/java/org/locationtech/geogig/model/BucketTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "861"
},
{
"name": "Cucumber",
"bytes": "371103"
},
{
"name": "HTML",
"bytes": "2857"
},
{
"name": "Java",
"bytes": "6225344"
},
{
"name": "PLpgSQL",
"bytes": "18558"
},
{
"name": "Shell",
"bytes": "5368"
}
],
"symlink_target": ""
} |
package org.fossasia.phimpme.me;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MainActivityTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
| {
"content_hash": "693641670bdff54d6d3d9938a44eda93",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 53,
"avg_line_length": 19.333333333333332,
"alnum_prop": 0.7370689655172413,
"repo_name": "phimpme/android-prototype",
"id": "206aa249b85b62370aabb54de60de6f30670cf1a",
"size": "232",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/androidTest/java/org/fossasia/phimpme/me/MainActivityTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2827335"
},
{
"name": "PHP",
"bytes": "78"
},
{
"name": "Perl",
"bytes": "12726"
},
{
"name": "Shell",
"bytes": "175"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>LocalColors</title>
<link href="../../images/logo-icon.svg" rel="icon" type="image/svg"><script>var pathToRoot = "../../";</script> <script>const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
</script>
<script type="text/javascript" src="../../scripts/sourceset_dependencies.js" async></script>
<link href="../../styles/style.css" rel="Stylesheet">
<link href="../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../styles/main.css" rel="Stylesheet">
<link href="../../styles/prism.css" rel="Stylesheet">
<link href="../../styles/logo-styles.css" rel="Stylesheet">
<script type="text/javascript" src="../../scripts/clipboard.js" async></script>
<script type="text/javascript" src="../../scripts/navigation-loader.js" async></script>
<script type="text/javascript" src="../../scripts/platform-content-handler.js" async></script>
<script type="text/javascript" src="../../scripts/main.js" defer></script>
<script type="text/javascript" src="../../scripts/prism.js" async></script>
<script type="text/javascript" src="../../scripts/symbol-parameters-wrapper_deferred.js" defer></script></head>
<body>
<div class="navigation-wrapper" id="navigation-wrapper">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<div class="library-name">
<a href="../../index.html">
<span>stripe-android</span> </a> </div>
<div>
</div>
<div class="pull-right d-flex">
<button id="theme-toggle-button"><span id="theme-toggle"></span></button>
<div id="searchBar"></div>
</div>
</div>
<div id="container">
<div id="leftColumn">
<div id="sideMenu"></div>
</div>
<div id="main">
<div class="main-content" id="content" pageids="payments-ui-core::com.stripe.android.ui.core//LocalColors/#/PointingToDeclaration//1608493371">
<div class="breadcrumbs"><a href="../index.html">payments-ui-core</a><span class="delimiter">/</span><a href="index.html">com.stripe.android.ui.core</a><span class="delimiter">/</span><span class="current">LocalColors</span></div>
<div class="cover ">
<h1 class="cover"><span>Local</span><wbr><span><span>Colors</span></span></h1>
</div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-dependent-content" data-active="" data-togglable=":payments-ui-core:dokkaHtmlPartial/release"><div class="symbol monospace"><span class="token keyword"></span><span class="token keyword">val </span><a href="-local-colors.html">LocalColors</a><span class="token operator">: </span><a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/ProvidableCompositionLocal.html">ProvidableCompositionLocal</a><span class="token operator"><</span><span class="token keyword"></span><a href="-payments-colors/index.html">PaymentsColors</a><span class="token operator">></span></div></div></div>
</div>
<div class="footer">
<span class="go-to-top-icon"><a href="#content" id="go-to-top-link"></a></span><span>© 2022 Copyright</span><span class="pull-right"><span>Generated by </span><a href="https://github.com/Kotlin/dokka"><span>dokka</span><span class="padded-icon"></span></a></span>
</div>
</div>
</div>
</body></html>
| {
"content_hash": "225724faa31e6edf6dc0de5a976102e9",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 719,
"avg_line_length": 60.92063492063492,
"alnum_prop": 0.6675351745700886,
"repo_name": "stripe/stripe-android",
"id": "9fcec0e6174d0ef24013669f6ba6cc29070ea670",
"size": "3839",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/payments-ui-core/com.stripe.android.ui.core/-local-colors.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "67407"
},
{
"name": "Kotlin",
"bytes": "7720826"
},
{
"name": "Python",
"bytes": "13146"
},
{
"name": "Ruby",
"bytes": "5171"
},
{
"name": "Shell",
"bytes": "18256"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
namespace PSXCardReader.NET.View.Interfaces
{
public interface IMainView : IBaseView
{
void UpdateOpenedFile(string fileName);
void UpdateBlockList(List<String> blockNames, List<Bitmap> blockIcons);
void ShowBlockDetails(string blockName, int blocksUsed);
void ShowProgramInfo(string programName, string developer, string versionString, string copyright);
event OnFileOpenHandler OnFileOpen;
event OnItemSelectHandler OnItemSelect;
event EventHandler OnAboutSelect;
}
public delegate void OnFileOpenHandler(object sender, OnFileOpenArgs e);
public delegate void OnItemSelectHandler(object sender, OnItemSelectArgs e);
public class OnFileOpenArgs : EventArgs
{
public string FilePath { get; set; }
}
public class OnItemSelectArgs : EventArgs
{
public int BlockIndex { get; set; }
}
}
| {
"content_hash": "709fe35df2af0625ca11a6c6768ffcb6",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 107,
"avg_line_length": 31,
"alnum_prop": 0.7217741935483871,
"repo_name": "instilledbee/PSXCardReader.NET",
"id": "f551fb52e561c8161f232d14e65ca6f9dc814ab3",
"size": "994",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PSXCardReader.NET.View/Interfaces/IMainView.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "17880"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>coquelicot: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.12.2 / coquelicot - 2.1.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
coquelicot
<small>
2.1.2
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-23 21:58:20 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-23 21:58:20 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.12.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "guillaume.melquiond@inria.fr"
homepage: "http://coquelicot.saclay.inria.fr/"
dev-repo: "git+https://gitlab.inria.fr/coquelicot/coquelicot.git"
bug-reports: "https://gitlab.inria.fr/coquelicot/coquelicot/issues"
license: "LGPL-3.0-or-later"
build: [
["./configure"]
["./remake" "-j%{jobs}%"]
]
install: ["./remake" "install"]
depends: [
"coq" {>= "8.5" & < "8.7~"}
"coq-mathcomp-ssreflect" {>= "1.6"}
]
tags: [ "keyword:real analysis" "keyword:topology" "keyword:filters" "keyword:metric spaces" "category:Mathematics/Real Calculus and Topology" ]
authors: [ "Sylvie Boldo <sylvie.boldo@inria.fr>" "Catherine Lelay <catherine.lelay@inria.fr>" "Guillaume Melquiond <guillaume.melquiond@inria.fr>" ]
synopsis: "A Coq formalization of real analysis compatible with the standard library"
url {
src: "https://coquelicot.gitlabpages.inria.fr/releases/coquelicot-2.1.2.tar.gz"
checksum: "md5=a58031aeb220da94e8ac822bbaeb7e41"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-coquelicot.2.1.2 coq.8.12.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.12.2).
The following dependencies couldn't be met:
- coq-coquelicot -> coq < 8.7~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-coquelicot.2.1.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "0dff35a036c24dd341d0689cff9f1bef",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 197,
"avg_line_length": 42.79754601226994,
"alnum_prop": 0.5458715596330275,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "db276245fbda300311a63616dbfd00ba6563d71c",
"size": "7001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.12.2/coquelicot/2.1.2.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
@interface OCUDLBuiltins ()
+ (void)registerNSNull;
+ (void)registerNSURL;
+ (void)registerNSUUID;
+ (void)registerUIColor;
+ (void)registerUIImage;
+ (void)registerUINib;
+ (void)registerUIStoryboard;
@end
@implementation OCUDLBuiltins
+ (void)registerNSNull
{
[[OCUDLManager defaultManager] registerPrefix:@"null"
forBlock:^id(NSString *literal, NSString *prefix) {
return [NSNull null];
}];
}
+ (void)registerNSURL
{
OCUDLBlock urlBlock = ^id(NSString *literal, NSString *prefix) {
return [NSURL URLWithString:[NSString stringWithFormat:@"%@//%@", prefix, literal]];
};
[[OCUDLManager defaultManager] registerPrefix:@"http:" forBlock:urlBlock];
[[OCUDLManager defaultManager] registerPrefix:@"https:" forBlock:urlBlock];
}
+ (void)registerNSUUID
{
[[OCUDLManager defaultManager] registerSuffix:@"uuid"
forBlock:^id(NSString *literal, NSString *prefix) {
return [[NSUUID alloc] initWithUUIDString:literal];
}];
}
+ (void)registerUIColor
{
[[OCUDLManager defaultManager] registerPrefix:@"#"
forBlock:^id(NSString *literal, NSString *prefix) {
unsigned int value = 0;
if ([[NSScanner scannerWithString:literal] scanHexInt:&value])
{
if (literal.length == 6)
{
return [UIColor colorWithRed:((float)((value & 0xFF0000) >> 16)) / 255.0
green:((float)((value & 0x00FF00) >> 8)) / 255.0
blue:((float)(value & 0x0000FF)) / 255.0
alpha:1.0];
}
else if (literal.length == 3)
{
return [UIColor colorWithRed:((float)((value & 0xF00) >> 8)) / 15.0
green:((float)((value & 0x0F0) >> 4)) / 15.0
blue:((float)(value & 0x00F)) / 15.0
alpha:1.0];
}
}
if ([literal caseInsensitiveCompare:@"black"] == NSOrderedSame)
{
return [UIColor blackColor];
}
else if ([literal caseInsensitiveCompare:@"darkGray"] == NSOrderedSame)
{
return [UIColor darkGrayColor];
}
else if ([literal caseInsensitiveCompare:@"lightGray"] == NSOrderedSame)
{
return [UIColor lightGrayColor];
}
else if ([literal caseInsensitiveCompare:@"white"] == NSOrderedSame)
{
return [UIColor whiteColor];
}
else if ([literal caseInsensitiveCompare:@"gray"] == NSOrderedSame)
{
return [UIColor grayColor];
}
else if ([literal caseInsensitiveCompare:@"red"] == NSOrderedSame)
{
return [UIColor redColor];
}
else if ([literal caseInsensitiveCompare:@"green"] == NSOrderedSame)
{
return [UIColor greenColor];
}
else if ([literal caseInsensitiveCompare:@"blue"] == NSOrderedSame)
{
return [UIColor blueColor];
}
else if ([literal caseInsensitiveCompare:@"cyan"] == NSOrderedSame)
{
return [UIColor cyanColor];
}
else if ([literal caseInsensitiveCompare:@"yellow"] == NSOrderedSame)
{
return [UIColor yellowColor];
}
else if ([literal caseInsensitiveCompare:@"magenta"] == NSOrderedSame)
{
return [UIColor magentaColor];
}
else if ([literal caseInsensitiveCompare:@"orange"] == NSOrderedSame)
{
return [UIColor orangeColor];
}
else if ([literal caseInsensitiveCompare:@"purple"] == NSOrderedSame)
{
return [UIColor purpleColor];
}
else if ([literal caseInsensitiveCompare:@"brown"] == NSOrderedSame)
{
return [UIColor brownColor];
}
else if ([literal caseInsensitiveCompare:@"clear"] == NSOrderedSame)
{
return [UIColor clearColor];
}
return nil;
}];
}
+ (void)registerUIImage
{
[[OCUDLManager defaultManager] registerSuffix:@".img"
forBlock:^id(NSString *literal, NSString *prefix) {
return [UIImage imageNamed:literal];
}];
}
+ (void)registerUINib
{
[[OCUDLManager defaultManager] registerSuffix:@".xib"
forBlock:^id(NSString *literal, NSString *prefix) {
return [UINib nibWithNibName:literal bundle:nil];
}];
}
+ (void)registerUIStoryboard
{
[[OCUDLManager defaultManager] registerSuffix:@".storyboard"
forBlock:^id(NSString *literal, NSString *prefix) {
return [UIStoryboard storyboardWithName:literal bundle:nil];
}];
}
static dispatch_once_t s_pred;
+ (void)use
{
dispatch_once(&s_pred, ^{
[OCUDLBuiltins registerNSNull];
[OCUDLBuiltins registerNSURL];
[OCUDLBuiltins registerNSUUID];
[OCUDLBuiltins registerUIColor];
[OCUDLBuiltins registerUIImage];
[OCUDLBuiltins registerUINib];
[OCUDLBuiltins registerUIStoryboard];
});
}
@end
| {
"content_hash": "f3113643e3784c87162a4177174a8720",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 117,
"avg_line_length": 43.44642857142857,
"alnum_prop": 0.4029319084806138,
"repo_name": "dbachrach/OCUDL",
"id": "bc055b15b1f8bd51ad9af347e1d8092c681d3f1d",
"size": "7489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Classes/OCUDLBuiltins.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "18929"
},
{
"name": "Ruby",
"bytes": "628"
}
],
"symlink_target": ""
} |
// ---------------------------------------------------------------------------------
// <copyright file="PetBreedCancelMessageEvent.cs" company="https://github.com/sant0ro/Yupi">
// Copyright (c) 2016 Claudio Santoro, TheDoctor
// </copyright>
// <license>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY 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.
// </license>
// ---------------------------------------------------------------------------------
namespace Yupi.Messages.Pets
{
using System;
using System.Drawing;
public class PetBreedCancelMessageEvent : AbstractHandler
{
#region Methods
public override void HandleMessage(Yupi.Model.Domain.Habbo session, Yupi.Protocol.Buffers.ClientMessage request,
Yupi.Protocol.IRouter router)
{
int itemId = request.GetInteger();
if (session.Room == null || !session.Room.Data.HasOwnerRights(session.Info))
return;
throw new NotImplementedException();
/*
RoomItem item = room.GetRoomItemHandler().GetItem(itemId);
if (item == null)
return;
if (item.GetBaseItem().InteractionType != Interaction.BreedingTerrier &&
item.GetBaseItem().InteractionType != Interaction.BreedingBear)
return;
foreach (Pet pet in item.PetsList)
{
pet.WaitingForBreading = 0;
pet.BreadingTile = new Point();
RoomUser user = room.GetRoomUserManager().GetRoomUserByVirtualId(pet.VirtualId);
user.Freezed = false;
room.GetGameMap().AddUserToMap(user, user.Coordinate);
Point nextCoord = room.GetGameMap().GetRandomValidWalkableSquare();
user.MoveTo(nextCoord.X, nextCoord.Y);
}
item.PetsList.Clear();
*/
}
#endregion Methods
}
} | {
"content_hash": "da4420387d70623f42339d8cc9b064bc",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 120,
"avg_line_length": 40.50684931506849,
"alnum_prop": 0.6151504903618532,
"repo_name": "sant0ro/Yupi",
"id": "c970cb337d957d5eedabcc89541753d7dc71a55f",
"size": "2959",
"binary": false,
"copies": "2",
"ref": "refs/heads/linux",
"path": "Yupi.Messages/Handlers/Pets/PetBreedCancelMessageEvent.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "49"
},
{
"name": "Batchfile",
"bytes": "48"
},
{
"name": "C#",
"bytes": "3230390"
},
{
"name": "CSS",
"bytes": "103266"
},
{
"name": "HTML",
"bytes": "1866073"
},
{
"name": "JavaScript",
"bytes": "2459166"
},
{
"name": "Python",
"bytes": "1894"
},
{
"name": "Shell",
"bytes": "1150"
}
],
"symlink_target": ""
} |
class Object
def linael(name, config_hash = {}, &block)
# Create the class
new_class = Class.new(Linael::ModuleIRC) do
generate_all_config(name, config_hash)
const_set("Options", generate_all_options)
end # Class.new(Linael::ModuleIRC)
# Link the module to the right part of linael
Linael::Modules.const_set(name.to_s.camelize, new_class)
# Execute the block
"Linael::Modules::#{name.to_s.camelize}".constantize.class_eval &block if block_given?
end
end
# This is a trick to use t inside help
class Class
include R18n::Helpers
end
R18n.set (if LinaelLanguages.is_a? Array
LinaelLanguages + ['en']
else
[LinaelLanguages, 'en']
end)
# Everything goes there
module Linael
# Fake interruption for before check
class InterruptLinael < RuntimeError
end
# Modification of ModuleIRC class to describe the DSL methods
class ModuleIRC
# Method to describe a feature of the module inside a linael bloc (see Object)
# Params:
# +type+:: type of message watched by the method should be in:
# * +:msg+:: any message
# * +:cmd+:: any command message (begining with a !)
# * +:cmdAuth+:: any command which you should be auth on the bot to use
# * +:join+ :: any join
# * +:part+ :: any part
# * +:kick+ :: any kick
# * +:auth+ :: any auth asking (for :cmdAuth)
# * +:mode+ :: any mode change
# * +:nick+ :: any nick change
# * +:notice+ :: any notice
#
# +name+:: the name of the feature
# +regex+:: the regex that the method should match
# +config_hash+:: an optional configuration hash (for now, there is no configuration option)
# +block+:: where we describe what the method should do
def self.on(type, name, regex = //, _config_hash = {}, &block)
# Generate regex catching in Options class
self::Options.class_eval do
generate_to_catch(name => regex)
end
generate_define_method_on(type, name, regex, &block) if block_given?
# Define the method which will be really called
# Add the feature to module start
# TODO add doc here (why unless)
const_set("ToStart", {}) unless defined?(self::ToStart)
self::ToStart[type] ||= []
self::ToStart[type] = self::ToStart[type] << name
end
def execute_method(type, msg, options, &block)
if type == :auth
instance_exec(msg, options, &block)
else
# execute block
Thread.new do
begin
instance_exec(msg, options, &block)
rescue InterruptLinael
rescue Exception => e
puts e.to_s.red
puts e.backtrace.join("\n").red
end
end
end
end
# TODO add it to protected
def self.generate_define_method_on(type, name, _regex, &block)
send("define_method", name) do |msg|
# Is it matching the regex?
if self.class::Options.send("#{name}?", msg.message)
# if it's a message: generate options
options = self.class::Options.new msg.element if msg.element.is_a? Linael::Irc::Privmsg
execute_method(type, msg, options, &block)
end
end
end
# Wrapper to add values regex
# Params:
# +key+:: is the name of the method (options.name)
# +value+:: is the regex used to find the result
def self.value(hash)
self::Options.class_eval do
generate_value hash
end
end
# Wrapper to add values regex with a default value
# Params:
# +key+:: is the name of the method (options.name)
# +value+:: is a hash with 2 keys:
# * +:regexp+:: the matching regex
# * +:default+:: the default value
def self.value_with_default(hash)
self::Options.class_eval do
generate_value_with_default hash
end
end
# Wrapper to add matching regex to options
# Params:
# +key+:: is the name of the method (options.name?)
# +value+:: is the regex to match
def self.match(hash)
self::Options.class_eval do
generate_match hash
end
end
# Instruction used at the start of the module
def self.on_init(&block)
const_set("At_launch", block)
end
# Instructions used at load (from save module)
def self.on_load(&block)
const_set("At_load", block)
end
# An array of strings for help
def self.help(help_array)
const_set("Help", help_array)
end
def self.db_list(*lists)
lists.each do |list|
class_name = name
define_method(list) do
Redis::List.new("#{class_name}:#{list}", marshal: true)
end
end
end
def self.db_value(*values)
values.each do |value|
class_name = name
define_method(value) do
Redis::Value.new("#{class_name}:#{value}", marshal: true)
end
end
end
def self.db_hash(*hashes)
hashes.each do |hash|
class_name = name
define_method(hash) do
Redis::HashKey.new("#{class_name}:#{hash}", marshal: true)
end
end
end
# Override of normal method
def load_mod
instance_eval(&self.class::At_load) if defined?(self.class::At_load)
end
# Overide of normal method
def start!
add_module(self.class::ToStart)
end
def launch
@master.act_types.each { |t| add_module_irc_behavior t }
end
# Overide of normal method
def initialize(master)
@master = master
instance_eval(&self.class::At_launch) if defined?(self.class::At_launch)
launch
end
# A method used to describe preliminary tests in a method
def before(msg)
raise(InterruptLinael, "not matching") unless yield(msg)
end
# Execute something later
# Params:
# +time+:: The time of the execution
# +hash+:: Params sended to the block
def at(time, hash = nil, &block)
Thread.new do
sleep(time - Time.now)
instance_exec(hash, &block)
end
end
end
end
| {
"content_hash": "6efaf780460118c1e4f393b1e3ac104f",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 97,
"avg_line_length": 28.928229665071772,
"alnum_prop": 0.6037049288785974,
"repo_name": "Skizzk/Linael",
"id": "eb6685e92a18814672b735b0c439531c0682c16f",
"size": "6978",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/dsl/module_dsl.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "126963"
}
],
"symlink_target": ""
} |
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name jquery.cleditor.min.js
// ==/ClosureCompiler==
(function($) {
//==============
// jQuery Plugin
//==============
$.cleditor = {
// Define the defaults used for all new cleditor instances
defaultOptions: {
width: 500, // width not including margins, borders or padding
height: 250, // height not including margins, borders or padding
controls: // controls to add to the toolbar
"bold italic underline strikethrough subscript superscript | font size " +
"style | color highlight removeformat | bullets numbering | outdent " +
"indent | alignleft center alignright justify | undo redo | " +
"rule image link unlink | cut copy paste pastetext | print source",
colors: // colors in the color popup
"FFF FCC FC9 FF9 FFC 9F9 9FF CFF CCF FCF " +
"CCC F66 F96 FF6 FF3 6F9 3FF 6FF 99F F9F " +
"BBB F00 F90 FC6 FF0 3F3 6CC 3CF 66C C6C " +
"999 C00 F60 FC3 FC0 3C0 0CC 36F 63F C3C " +
"666 900 C60 C93 990 090 399 33F 60C 939 " +
"333 600 930 963 660 060 366 009 339 636 " +
"000 300 630 633 330 030 033 006 309 303",
fonts: // font names in the font popup
"Arial,Arial Black,Comic Sans MS,Courier New,Narrow,Garamond," +
"Georgia,Impact,Sans Serif,Serif,Tahoma,Trebuchet MS,Verdana",
sizes: // sizes in the font size popup
"1,2,3,4,5,6,7",
styles: // styles in the style popup
[["Paragraph", "<p>"], ["Header 1", "<h1>"], ["Header 2", "<h2>"],
["Header 3", "<h3>"], ["Header 4","<h4>"], ["Header 5","<h5>"],
["Header 6","<h6>"]],
useCSS: false, // use CSS to style HTML when possible (not supported in ie)
docType: // Document type contained within the editor
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
docCSSFile: // CSS file used to style the document contained within the editor
"",
bodyStyle: // style to assign to document body contained within the editor
"margin:4px; color:#4c4c4c; font-size:13px; font-family:\"Lucida Grande\",Helvetica,Verdana,Arial,sans-serif; cursor:text"
},
// Define all usable toolbar buttons - the init string property is
// expanded during initialization back into the buttons object and
// seperate object properties are created for each button.
// e.g. buttons.size.title = "Font Size"
buttons: {
// name,title,command,popupName (""=use name)
init:
"bold,,|" +
"italic,,|" +
"underline,,|" +
"strikethrough,,|" +
"subscript,,|" +
"superscript,,|" +
"font,,fontname,|" +
"size,Font Size,fontsize,|" +
"style,,formatblock,|" +
"color,Font Color,forecolor,|" +
"highlight,Text Highlight Color,hilitecolor,color|" +
"removeformat,Remove Formatting,|" +
"bullets,,insertunorderedlist|" +
"numbering,,insertorderedlist|" +
"outdent,,|" +
"indent,,|" +
"alignleft,Align Text Left,justifyleft|" +
"center,,justifycenter|" +
"alignright,Align Text Right,justifyright|" +
"justify,,justifyfull|" +
"undo,,|" +
"redo,,|" +
"rule,Insert Horizontal Rule,inserthorizontalrule|" +
"image,Insert Image,insertimage,url|" +
"link,Insert Hyperlink,createlink,url|" +
"unlink,Remove Hyperlink,|" +
"cut,,|" +
"copy,,|" +
"paste,,|" +
"pastetext,Paste as Text,inserthtml,|" +
"print,,|" +
"source,Show Source"
},
// imagesPath - returns the path to the images folder
imagesPath: function() { return imagesPath(); }
};
// cleditor - creates a new editor for each of the matched textareas
$.fn.cleditor = function(options) {
// Create a new jQuery object to hold the results
var $result = $([]);
// Loop through all matching textareas and create the editors
this.each(function(idx, elem) {
if (elem.tagName == "TEXTAREA") {
var data = $.data(elem, CLEDITOR);
if (!data) data = new cleditor(elem, options);
$result = $result.add(data);
}
});
// return the new jQuery object
return $result;
};
//==================
// Private Variables
//==================
var
// Misc constants
BACKGROUND_COLOR = "backgroundColor",
BUTTON = "button",
BUTTON_NAME = "buttonName",
CHANGE = "change",
CLEDITOR = "cleditor",
CLICK = "click",
DISABLED = "disabled",
DIV_TAG = "<div>",
TRANSPARENT = "transparent",
UNSELECTABLE = "unselectable",
// Class name constants
MAIN_CLASS = "cleditorMain", // main containing div
TOOLBAR_CLASS = "cleditorToolbar", // toolbar div inside main div
GROUP_CLASS = "cleditorGroup", // group divs inside the toolbar div
BUTTON_CLASS = "cleditorButton", // button divs inside group div
DISABLED_CLASS = "cleditorDisabled",// disabled button divs
DIVIDER_CLASS = "cleditorDivider", // divider divs inside group div
POPUP_CLASS = "cleditorPopup", // popup divs inside body
LIST_CLASS = "cleditorList", // list popup divs inside body
COLOR_CLASS = "cleditorColor", // color popup div inside body
PROMPT_CLASS = "cleditorPrompt", // prompt popup divs inside body
MSG_CLASS = "cleditorMsg", // message popup div inside body
// Test for ie
ie = $.browser.msie,
ie6 = /msie\s6/i.test(navigator.userAgent),
// Test for iPhone/iTouch/iPad
iOS = /iphone|ipad|ipod/i.test(navigator.userAgent),
// Popups are created once as needed and shared by all editor instances
popups = {},
// Used to prevent the document click event from being bound more than once
documentClickAssigned,
// Local copy of the buttons object
buttons = $.cleditor.buttons;
//===============
// Initialization
//===============
// Expand the buttons.init string back into the buttons object
// and create seperate object properties for each button.
// e.g. buttons.size.title = "Font Size"
$.each(buttons.init.split("|"), function(idx, button) {
var items = button.split(","), name = items[0];
buttons[name] = {
stripIndex: idx,
name: name,
title: items[1] === "" ? name.charAt(0).toUpperCase() + name.substr(1) : items[1],
command: items[2] === "" ? name : items[2],
popupName: items[3] === "" ? name : items[3]
};
});
delete buttons.init;
//============
// Constructor
//============
// cleditor - creates a new editor for the passed in textarea element
cleditor = function(area, options) {
var editor = this;
// Get the defaults and override with options
editor.options = options = $.extend({}, $.cleditor.defaultOptions, options);
// Hide the textarea and associate it with this editor
var $area = editor.$area = $(area)
.hide()
.data(CLEDITOR, editor)
.blur(function() {
// Update the iframe when the textarea loses focus
updateFrame(editor, true);
});
// Create the main container and append the textarea
var $main = editor.$main = $(DIV_TAG)
.addClass(MAIN_CLASS)
.width(options.width)
.height(options.height);
// Create the toolbar
var $toolbar = editor.$toolbar = $(DIV_TAG)
.addClass(TOOLBAR_CLASS)
.appendTo($main);
// Add the first group to the toolbar
var $group = $(DIV_TAG)
.addClass(GROUP_CLASS)
.appendTo($toolbar);
// Add the buttons to the toolbar
$.each(options.controls.split(" "), function(idx, buttonName) {
if (buttonName === "") return true;
// Divider
if (buttonName == "|") {
// Add a new divider to the group
var $div = $(DIV_TAG)
.addClass(DIVIDER_CLASS)
.appendTo($group);
// Create a new group
$group = $(DIV_TAG)
.addClass(GROUP_CLASS)
.appendTo($toolbar);
}
// Button
else {
// Get the button definition
var button = buttons[buttonName];
// Add a new button to the group
var $buttonDiv = $(DIV_TAG)
.data(BUTTON_NAME, button.name)
.addClass(BUTTON_CLASS)
.attr("title", button.title)
.bind(CLICK, $.proxy(buttonClick, editor))
.appendTo($group)
.hover(hoverEnter, hoverLeave);
// Prepare the button image
var map = {};
if (button.css) map = button.css;
else if (button.image) map.backgroundImage = imageUrl(button.image);
if (button.stripIndex) map.backgroundPosition = button.stripIndex * -24;
$buttonDiv.css(map);
// Add the unselectable attribute for ie
if (ie)
$buttonDiv.attr(UNSELECTABLE, "on");
// Create the popup
if (button.popupName)
createPopup(button.popupName, options, button.popupClass,
button.popupContent, button.popupHover);
}
});
// Add the main div to the DOM and append the textarea
$main.insertBefore($area)
.append($area);
// Bind the document click event handler
if (!documentClickAssigned) {
$(document).click(function(e) {
// Dismiss all non-prompt popups
var $target = $(e.target);
if (!$target.add($target.parents()).is("." + PROMPT_CLASS))
hidePopups();
});
documentClickAssigned = true;
}
// Bind the window resize event when the width or height is auto or %
if (/auto|%/.test("" + options.width + options.height))
$(window).resize(function() {
//Forcefully blurred iframe contentWindow, chrome, IE, safari doesn't trigger blur on window resize and due to which text disappears
var contentWindow = editor.$frame[0].contentWindow;
if(!$.browser.mozilla && contentWindow){
$(contentWindow).trigger('blur');
}
// CHM Note MonkeyPatch: if the DOM is not remove, refresh the cleditor
if(editor.$main.parent().parent().size()) {
refresh(editor);
}
});
// Create the iframe and resize the controls
refresh(editor);
};
//===============
// Public Methods
//===============
var fn = cleditor.prototype,
// Expose the following private functions as methods on the cleditor object.
// The closure compiler will rename the private functions. However, the
// exposed method names on the cleditor object will remain fixed.
methods = [
["clear", clear],
["disable", disable],
["execCommand", execCommand],
["focus", focus],
["hidePopups", hidePopups],
["sourceMode", sourceMode, true],
["refresh", refresh],
["select", select],
["selectedHTML", selectedHTML, true],
["selectedText", selectedText, true],
["showMessage", showMessage],
["updateFrame", updateFrame],
["updateTextArea", updateTextArea]
];
$.each(methods, function(idx, method) {
fn[method[0]] = function() {
var editor = this, args = [editor];
// using each here would cast booleans into objects!
for(var x = 0; x < arguments.length; x++) {args.push(arguments[x]);}
var result = method[1].apply(editor, args);
if (method[2]) return result;
return editor;
};
});
// change - shortcut for .bind("change", handler) or .trigger("change")
fn.change = function(handler) {
var $this = $(this);
return handler ? $this.bind(CHANGE, handler) : $this.trigger(CHANGE);
};
//===============
// Event Handlers
//===============
// buttonClick - click event handler for toolbar buttons
function buttonClick(e) {
var editor = this,
buttonDiv = e.target,
buttonName = $.data(buttonDiv, BUTTON_NAME),
button = buttons[buttonName],
popupName = button.popupName,
popup = popups[popupName];
// Check if disabled
if (editor.disabled || $(buttonDiv).attr(DISABLED) == DISABLED)
return;
// Fire the buttonClick event
var data = {
editor: editor,
button: buttonDiv,
buttonName: buttonName,
popup: popup,
popupName: popupName,
command: button.command,
useCSS: editor.options.useCSS
};
if (button.buttonClick && button.buttonClick(e, data) === false)
return false;
// Toggle source
if (buttonName == "source") {
// Show the iframe
if (sourceMode(editor)) {
delete editor.range;
editor.$area.hide();
editor.$frame.show();
buttonDiv.title = button.title;
}
// Show the textarea
else {
editor.$frame.hide();
editor.$area.show();
buttonDiv.title = "Show Rich Text";
}
// Enable or disable the toolbar buttons
// IE requires the timeout
setTimeout(function() {refreshButtons(editor);}, 100);
}
// Check for rich text mode
else if (!sourceMode(editor)) {
// Handle popups
if (popupName) {
var $popup = $(popup);
// URL
if (popupName == "url") {
// Check for selection before showing the link url popup
if (buttonName == "link" && selectedText(editor) === "") {
showMessage(editor, "A selection is required when inserting a link.", buttonDiv);
return false;
}
// Wire up the submit button click event handler
$popup.children(":button")
.unbind(CLICK)
.bind(CLICK, function() {
// Insert the image or link if a url was entered
var $text = $popup.find(":text"),
url = $.trim($text.val());
if (url !== "")
execCommand(editor, data.command, url, null, data.button);
// Reset the text, hide the popup and set focus
$text.val("http://");
hidePopups();
focus(editor);
});
}
// Paste as Text
else if (popupName == "pastetext") {
// Wire up the submit button click event handler
$popup.children(":button")
.unbind(CLICK)
.bind(CLICK, function() {
// Insert the unformatted text replacing new lines with break tags
var $textarea = $popup.find("textarea"),
text = $textarea.val().replace(/\n/g, "<br />");
if (text !== "")
execCommand(editor, data.command, text, null, data.button);
// Reset the text, hide the popup and set focus
$textarea.val("");
hidePopups();
focus(editor);
});
}
// Show the popup if not already showing for this button
if (buttonDiv !== $.data(popup, BUTTON)) {
showPopup(editor, popup, buttonDiv);
return false; // stop propagination to document click
}
// propaginate to documnt click
return;
}
// Print
else if (buttonName == "print")
editor.$frame[0].contentWindow.print();
// All other buttons
else if (!execCommand(editor, data.command, data.value, data.useCSS, buttonDiv))
return false;
}
// Focus the editor
focus(editor);
}
// hoverEnter - mouseenter event handler for buttons and popup items
function hoverEnter(e) {
var $div = $(e.target).closest("div");
$div.css(BACKGROUND_COLOR, $div.data(BUTTON_NAME) ? "#FFF" : "#FFC");
}
// hoverLeave - mouseleave event handler for buttons and popup items
function hoverLeave(e) {
$(e.target).closest("div").css(BACKGROUND_COLOR, "transparent");
}
// popupClick - click event handler for popup items
function popupClick(e) {
var editor = this,
popup = e.data.popup,
target = e.target;
// Check for message and prompt popups
if (popup === popups.msg || $(popup).hasClass(PROMPT_CLASS))
return;
// Get the button info
var buttonDiv = $.data(popup, BUTTON),
buttonName = $.data(buttonDiv, BUTTON_NAME),
button = buttons[buttonName],
command = button.command,
value,
useCSS = editor.options.useCSS;
// Get the command value
if (buttonName == "font")
// Opera returns the fontfamily wrapped in quotes
value = target.style.fontFamily.replace(/"/g, "");
else if (buttonName == "size") {
if (target.tagName == "DIV")
target = target.children[0];
value = target.innerHTML;
}
else if (buttonName == "style")
value = "<" + target.tagName + ">";
else if (buttonName == "color")
value = hex(target.style.backgroundColor);
else if (buttonName == "highlight") {
value = hex(target.style.backgroundColor);
if (ie) command = 'backcolor';
else useCSS = true;
}
// Fire the popupClick event
var data = {
editor: editor,
button: buttonDiv,
buttonName: buttonName,
popup: popup,
popupName: button.popupName,
command: command,
value: value,
useCSS: useCSS
};
if (button.popupClick && button.popupClick(e, data) === false)
return;
// Execute the command
if (data.command && !execCommand(editor, data.command, data.value, data.useCSS, buttonDiv))
return false;
// Hide the popup and focus the editor
hidePopups();
focus(editor);
}
//==================
// Private Functions
//==================
// checksum - returns a checksum using the Adler-32 method
function checksum(text)
{
var a = 1, b = 0;
for (var index = 0; index < text.length; ++index) {
a = (a + text.charCodeAt(index)) % 65521;
b = (b + a) % 65521;
}
return (b << 16) | a;
}
// clear - clears the contents of the editor
function clear(editor) {
editor.$area.val("");
updateFrame(editor);
}
// createPopup - creates a popup and adds it to the body
function createPopup(popupName, options, popupTypeClass, popupContent, popupHover) {
// Check if popup already exists
if (popups[popupName])
return popups[popupName];
// Create the popup
var $popup = $(DIV_TAG)
.hide()
.addClass(POPUP_CLASS)
.appendTo("body");
// Add the content
// Custom popup
if (popupContent)
$popup.html(popupContent);
// Color
else if (popupName == "color") {
var colors = options.colors.split(" ");
if (colors.length < 10)
$popup.width("auto");
$.each(colors, function(idx, color) {
$(DIV_TAG).appendTo($popup)
.css(BACKGROUND_COLOR, "#" + color);
});
popupTypeClass = COLOR_CLASS;
}
// Font
else if (popupName == "font")
$.each(options.fonts.split(","), function(idx, font) {
$(DIV_TAG).appendTo($popup)
.css("fontFamily", font)
.html(font);
});
// Size
else if (popupName == "size")
$.each(options.sizes.split(","), function(idx, size) {
$(DIV_TAG).appendTo($popup)
.html("<font size=" + size + ">" + size + "</font>");
});
// Style
else if (popupName == "style")
$.each(options.styles, function(idx, style) {
$(DIV_TAG).appendTo($popup)
.html(style[1] + style[0] + style[1].replace("<", "</"));
});
// URL
else if (popupName == "url") {
$popup.html('Enter URL:<br><input type=text value="http://" size=35><br><input type=button value="Submit">');
popupTypeClass = PROMPT_CLASS;
}
// Paste as Text
else if (popupName == "pastetext") {
$popup.html('Paste your content here and click submit.<br /><textarea cols=40 rows=3></textarea><br /><input type=button value=Submit>');
popupTypeClass = PROMPT_CLASS;
}
// Add the popup type class name
if (!popupTypeClass && !popupContent)
popupTypeClass = LIST_CLASS;
$popup.addClass(popupTypeClass);
// Add the unselectable attribute to all items
if (ie) {
$popup.attr(UNSELECTABLE, "on")
.find("div,font,p,h1,h2,h3,h4,h5,h6")
.attr(UNSELECTABLE, "on");
}
// Add the hover effect to all items
if ($popup.hasClass(LIST_CLASS) || popupHover === true)
$popup.children().hover(hoverEnter, hoverLeave);
// Add the popup to the array and return it
popups[popupName] = $popup[0];
return $popup[0];
}
// disable - enables or disables the editor
function disable(editor, disabled) {
// Update the textarea and save the state
if (disabled) {
editor.$area.attr(DISABLED, DISABLED);
editor.disabled = true;
}
else {
editor.$area.removeAttr(DISABLED);
delete editor.disabled;
}
// Switch the iframe into design mode.
// ie6 does not support designMode.
// ie7 & ie8 do not properly support designMode="off".
try {
if (ie) editor.doc.body.contentEditable = !disabled;
else editor.doc.designMode = !disabled ? "on" : "off";
}
// Firefox 1.5 throws an exception that can be ignored
// when toggling designMode from off to on.
catch (err) {}
// Enable or disable the toolbar buttons
refreshButtons(editor);
}
// execCommand - executes a designMode command
function execCommand(editor, command, value, useCSS, button) {
// Restore the current ie selection
restoreRange(editor);
// Set the styling method
if (!ie) {
if (useCSS === undefined || useCSS === null)
useCSS = editor.options.useCSS;
editor.doc.execCommand("styleWithCSS", 0, useCSS.toString());
}
// Execute the command and check for error
var success = true, description;
if (ie && command.toLowerCase() == "inserthtml")
getRange(editor).pasteHTML(value);
else {
try { success = editor.doc.execCommand(command, 0, value || null); }
catch (err) { description = err.description; success = false; }
if (!success) {
if ("cutcopypaste".indexOf(command) > -1)
showMessage(editor, "For security reasons, your browser does not support the " +
command + " command. Try using the keyboard shortcut or context menu instead.",
button);
else
showMessage(editor,
(description ? description : "Error executing the " + command + " command."),
button);
}
}
// Enable the buttons
refreshButtons(editor);
return success;
}
// focus - sets focus to either the textarea or iframe
function focus(editor) {
setTimeout(function() {
if (sourceMode(editor)) editor.$area.focus();
else editor.$frame[0].contentWindow.focus();
refreshButtons(editor);
}, 0);
}
// getRange - gets the current text range object
function getRange(editor) {
if (ie) return getSelection(editor).createRange();
return getSelection(editor).getRangeAt(0);
}
// getSelection - gets the current text range object
function getSelection(editor) {
if (ie) return editor.doc.selection;
return editor.$frame[0].contentWindow.getSelection();
}
// Returns the hex value for the passed in string.
// hex("rgb(255, 0, 0)"); // #FF0000
// hex("#FF0000"); // #FF0000
// hex("#F00"); // #FF0000
function hex(s) {
var m = /rgba?\((\d+), (\d+), (\d+)/.exec(s),
c = s.split("");
if (m) {
s = ( m[1] << 16 | m[2] << 8 | m[3] ).toString(16);
while (s.length < 6)
s = "0" + s;
}
return "#" + (s.length == 6 ? s : c[1] + c[1] + c[2] + c[2] + c[3] + c[3]);
}
// hidePopups - hides all popups
function hidePopups() {
$.each(popups, function(idx, popup) {
$(popup)
.hide()
.unbind(CLICK)
.removeData(BUTTON);
});
}
// imagesPath - returns the path to the images folder
function imagesPath() {
var cssFile = "jquery.cleditor.css",
href = $("link[href$='" + cssFile +"']").attr("href");
return href.substr(0, href.length - cssFile.length) + "images/";
}
// imageUrl - Returns the css url string for a filemane
function imageUrl(filename) {
return "url(" + imagesPath() + filename + ")";
}
// refresh - creates the iframe and resizes the controls
function refresh(editor) {
var $main = editor.$main,
options = editor.options;
// Remove the old iframe
if (editor.$frame)
editor.$frame.remove();
// Create a new iframe
var $frame = editor.$frame = $('<iframe frameborder="0" src="javascript:true;">')
.hide()
.appendTo($main);
// Load the iframe document content
var contentWindow = $frame[0].contentWindow,
doc = editor.doc = contentWindow.document,
$doc = $(doc);
doc.open();
doc.write(
options.docType +
'<html>' +
((options.docCSSFile === '') ? '' : '<head><link rel="stylesheet" type="text/css" href="' + options.docCSSFile + '" /></head>') +
'<body style="' + options.bodyStyle + '"></body></html>'
);
doc.close();
// Work around for bug in IE which causes the editor to lose
// focus when clicking below the end of the document.
if (ie)
$doc.click(function() {focus(editor);});
// Load the content
updateFrame(editor);
// Bind the ie specific iframe event handlers
if (ie) {
// Save the current user selection. This code is needed since IE will
// reset the selection just after the beforedeactivate event and just
// before the beforeactivate event.
$doc.bind("beforedeactivate beforeactivate selectionchange keypress", function(e) {
// Flag the editor as inactive
if (e.type == "beforedeactivate")
editor.inactive = true;
// Get rid of the bogus selection and flag the editor as active
else if (e.type == "beforeactivate") {
if (!editor.inactive && editor.range && editor.range.length > 1)
editor.range.shift();
delete editor.inactive;
}
// Save the selection when the editor is active
else if (!editor.inactive) {
if (!editor.range)
editor.range = [];
editor.range.unshift(getRange(editor));
// We only need the last 2 selections
while (editor.range.length > 2)
editor.range.pop();
}
});
// Restore the text range when the iframe gains focus
$frame.focus(function() {
restoreRange(editor);
});
}
// Update the textarea when the iframe loses focus
($.browser.mozilla ? $doc : $(contentWindow)).blur(function() {
updateTextArea(editor, true);
});
// Enable the toolbar buttons as the user types or clicks
$doc.click(hidePopups)
.bind("keyup mouseup", function() {
refreshButtons(editor);
});
// Show the textarea for iPhone/iTouch/iPad or
// the iframe when design mode is supported.
if (iOS) editor.$area.show();
else $frame.show();
// Wait for the layout to finish - shortcut for $(document).ready()
$(function() {
var $toolbar = editor.$toolbar,
$group = $toolbar.children("div:last"),
wid = /%/.test("" + options.width) ? options.width : $main.width();
// Resize the toolbar
var hgt = $group.offset().top + $group.outerHeight() - $toolbar.offset().top + 1;
$toolbar.height(hgt);
// Resize the iframe
hgt = (/%/.test("" + options.height) ? $main.height() : parseInt(options.height)) - hgt;
$frame.width(wid).height(hgt);
// Resize the textarea. IE6 textareas have a 1px top
// & bottom margin that cannot be removed using css.
editor.$area.width(wid).height(ie6 ? hgt - 2 : hgt);
// Switch the iframe into design mode if enabled
disable(editor, editor.disabled);
// Enable or disable the toolbar buttons
refreshButtons(editor);
});
}
// refreshButtons - enables or disables buttons based on availability
function refreshButtons(editor) {
// Webkit requires focus before queryCommandEnabled will return anything but false
if (!iOS && $.browser.webkit && !editor.focused) {
editor.$frame[0].contentWindow.focus();
window.focus();
editor.focused = true;
}
// Get the object used for checking queryCommandEnabled
var queryObj = editor.doc;
if (ie) queryObj = getRange(editor);
// Loop through each button
var inSourceMode = sourceMode(editor);
$.each(editor.$toolbar.find("." + BUTTON_CLASS), function(idx, elem) {
var $elem = $(elem),
button = $.cleditor.buttons[$.data(elem, BUTTON_NAME)],
command = button.command,
enabled = true;
// Determine the state
if (editor.disabled)
enabled = false;
else if (button.getEnabled) {
var data = {
editor: editor,
button: elem,
buttonName: button.name,
popup: popups[button.popupName],
popupName: button.popupName,
command: button.command,
useCSS: editor.options.useCSS
};
enabled = button.getEnabled(data);
if (enabled === undefined)
enabled = true;
}
else if (((inSourceMode || iOS) && button.name != "source") ||
(ie && (command == "undo" || command == "redo")))
enabled = false;
else if (command && command != "print") {
if (ie && command == "hilitecolor")
command = "backcolor";
// IE does not support inserthtml, so it's always enabled
if (!ie || command != "inserthtml") {
try {enabled = queryObj.queryCommandEnabled(command);}
catch (err) {enabled = false;}
}
}
// Enable or disable the button
if (enabled) {
$elem.removeClass(DISABLED_CLASS);
$elem.removeAttr(DISABLED);
}
else {
$elem.addClass(DISABLED_CLASS);
$elem.attr(DISABLED, DISABLED);
}
});
}
// restoreRange - restores the current ie selection
function restoreRange(editor) {
if (ie && editor.range)
editor.range[0].select();
}
// select - selects all the text in either the textarea or iframe
function select(editor) {
setTimeout(function() {
if (sourceMode(editor)) editor.$area.select();
else execCommand(editor, "selectall");
}, 0);
}
// selectedHTML - returns the current HTML selection or and empty string
function selectedHTML(editor) {
restoreRange(editor);
var range = getRange(editor);
if (ie)
return range.htmlText;
var layer = $("<layer>")[0];
layer.appendChild(range.cloneContents());
var html = layer.innerHTML;
layer = null;
return html;
}
// selectedText - returns the current text selection or and empty string
function selectedText(editor) {
restoreRange(editor);
if (ie) return getRange(editor).text;
return getSelection(editor).toString();
}
// showMessage - alert replacement
function showMessage(editor, message, button) {
var popup = createPopup("msg", editor.options, MSG_CLASS);
popup.innerHTML = message;
showPopup(editor, popup, button);
}
// showPopup - shows a popup
function showPopup(editor, popup, button) {
var offset, left, top, $popup = $(popup);
// Determine the popup location
if (button) {
var $button = $(button);
offset = $button.offset();
left = --offset.left;
top = offset.top + $button.height();
}
else {
var $toolbar = editor.$toolbar;
offset = $toolbar.offset();
left = Math.floor(($toolbar.width() - $popup.width()) / 2) + offset.left;
top = offset.top + $toolbar.height() - 2;
}
// Position and show the popup
hidePopups();
$popup.css({left: left, top: top})
.show();
// Assign the popup button and click event handler
if (button) {
$.data(popup, BUTTON, button);
$popup.bind(CLICK, {popup: popup}, $.proxy(popupClick, editor));
}
// Focus the first input element if any
setTimeout(function() {
$popup.find(":text,textarea").eq(0).focus().select();
}, 100);
}
// sourceMode - returns true if the textarea is showing
function sourceMode(editor) {
return editor.$area.is(":visible");
}
// updateFrame - updates the iframe with the textarea contents
function updateFrame(editor, checkForChange) {
var code = editor.$area.val(),
options = editor.options,
updateFrameCallback = options.updateFrame,
$body = $(editor.doc.body);
// Check for textarea change to avoid unnecessary firing
// of potentially heavy updateFrame callbacks.
if (updateFrameCallback) {
var sum = checksum(code);
if (checkForChange && editor.areaChecksum == sum)
return;
editor.areaChecksum = sum;
}
// Convert the textarea source code into iframe html
var html = updateFrameCallback ? updateFrameCallback(code) : code;
// Prevent script injection attacks by html encoding script tags
html = html.replace(/<(?=\/?script)/ig, "<");
// Update the iframe checksum
if (options.updateTextArea)
editor.frameChecksum = checksum(html);
// Update the iframe and trigger the change event
if (html != $body.html()) {
$body.html(html);
$(editor).triggerHandler(CHANGE);
}
}
// updateTextArea - updates the textarea with the iframe contents
function updateTextArea(editor, checkForChange) {
var html = $(editor.doc.body).html(),
options = editor.options,
updateTextAreaCallback = options.updateTextArea,
$area = editor.$area;
// Check for iframe change to avoid unnecessary firing
// of potentially heavy updateTextArea callbacks.
if (updateTextAreaCallback) {
var sum = checksum(html);
if (checkForChange && editor.frameChecksum == sum)
return;
editor.frameChecksum = sum;
}
// Convert the iframe html into textarea source code
var code = updateTextAreaCallback ? updateTextAreaCallback(html) : html;
// Update the textarea checksum
if (options.updateFrame)
editor.areaChecksum = checksum(code);
// Update the textarea and trigger the change event
if (code != $area.val()) {
$area.val(code);
$(editor).triggerHandler(CHANGE);
}
}
})(jQuery);
| {
"content_hash": "c9dcfc33037d7acd24bb386073269193",
"timestamp": "",
"source": "github",
"line_count": 1135,
"max_line_length": 143,
"avg_line_length": 31.728634361233482,
"alnum_prop": 0.5676163501055204,
"repo_name": "ntiufalara/openerp7",
"id": "3de9089443d8bfb8d8b381115b25087478c2418b",
"size": "36257",
"binary": false,
"copies": "37",
"ref": "refs/heads/master",
"path": "openerp/addons/web/static/lib/cleditor/jquery.cleditor.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "9611"
},
{
"name": "C#",
"bytes": "93691"
},
{
"name": "C++",
"bytes": "108790"
},
{
"name": "CSS",
"bytes": "583265"
},
{
"name": "Groff",
"bytes": "8138"
},
{
"name": "HTML",
"bytes": "125159"
},
{
"name": "JavaScript",
"bytes": "5109152"
},
{
"name": "Makefile",
"bytes": "14036"
},
{
"name": "NSIS",
"bytes": "14114"
},
{
"name": "PHP",
"bytes": "14033"
},
{
"name": "Python",
"bytes": "9373763"
},
{
"name": "Ruby",
"bytes": "220"
},
{
"name": "Shell",
"bytes": "6430"
},
{
"name": "XSLT",
"bytes": "156761"
}
],
"symlink_target": ""
} |
//===--- CFG.cpp - Utilities for SIL CFG transformations ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/Dominance.h"
#include "swift/SIL/LoopInfo.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILOptimizer/Utils/CFG.h"
using namespace swift;
/// \brief Adds a new argument to an edge between a branch and a destination
/// block.
///
/// \param Branch The terminator to add the argument to.
/// \param Dest The destination block of the edge.
/// \param Val The value to the arguments of the branch.
/// \return The created branch. The old branch is deleted.
/// The argument is appended at the end of the argument tuple.
TermInst *swift::addNewEdgeValueToBranch(TermInst *Branch, SILBasicBlock *Dest,
SILValue Val) {
SILBuilderWithScope Builder(Branch);
TermInst *NewBr = nullptr;
if (CondBranchInst *CBI = dyn_cast<CondBranchInst>(Branch)) {
SmallVector<SILValue, 8> TrueArgs;
SmallVector<SILValue, 8> FalseArgs;
for (auto A : CBI->getTrueArgs())
TrueArgs.push_back(A);
for (auto A : CBI->getFalseArgs())
FalseArgs.push_back(A);
if (Dest == CBI->getTrueBB()) {
TrueArgs.push_back(Val);
assert(TrueArgs.size() == Dest->getNumArguments());
}
if (Dest == CBI->getFalseBB()) {
FalseArgs.push_back(Val);
assert(FalseArgs.size() == Dest->getNumArguments());
}
NewBr = Builder.createCondBranch(CBI->getLoc(), CBI->getCondition(),
CBI->getTrueBB(), TrueArgs,
CBI->getFalseBB(), FalseArgs);
} else if (BranchInst *BI = dyn_cast<BranchInst>(Branch)) {
SmallVector<SILValue, 8> Args;
for (auto A : BI->getArgs())
Args.push_back(A);
Args.push_back(Val);
assert(Args.size() == Dest->getNumArguments());
NewBr = Builder.createBranch(BI->getLoc(), BI->getDestBB(), Args);
} else {
// At the moment we can only add arguments to br and cond_br.
llvm_unreachable("Can't add argument to terminator");
}
Branch->dropAllReferences();
Branch->eraseFromParent();
return NewBr;
}
/// \brief Changes the edge value between a branch and destination basic block
/// at the specified index. Changes all edges from \p Branch to \p Dest to carry
/// the value.
///
/// \param Branch The branch to modify.
/// \param Dest The destination of the edge.
/// \param Idx The index of the argument to modify.
/// \param Val The new value to use.
/// \return The new branch. Deletes the old one.
/// Changes the edge value between a branch and destination basic block at the
/// specified index.
TermInst *swift::changeEdgeValue(TermInst *Branch, SILBasicBlock *Dest,
size_t Idx, SILValue Val) {
SILBuilderWithScope Builder(Branch);
if (CondBranchInst *CBI = dyn_cast<CondBranchInst>(Branch)) {
SmallVector<SILValue, 8> TrueArgs;
SmallVector<SILValue, 8> FalseArgs;
OperandValueArrayRef OldTrueArgs = CBI->getTrueArgs();
bool BranchOnTrue = CBI->getTrueBB() == Dest;
assert((!BranchOnTrue || Idx < OldTrueArgs.size()) && "Not enough edges");
// Copy the edge values overwriting the edge at Idx.
for (unsigned i = 0, e = OldTrueArgs.size(); i != e; ++i) {
if (BranchOnTrue && Idx == i)
TrueArgs.push_back(Val);
else
TrueArgs.push_back(OldTrueArgs[i]);
}
assert(TrueArgs.size() == CBI->getTrueBB()->getNumArguments() &&
"Destination block's number of arguments must match");
OperandValueArrayRef OldFalseArgs = CBI->getFalseArgs();
bool BranchOnFalse = CBI->getFalseBB() == Dest;
assert((!BranchOnFalse || Idx < OldFalseArgs.size()) && "Not enough edges");
// Copy the edge values overwriting the edge at Idx.
for (unsigned i = 0, e = OldFalseArgs.size(); i != e; ++i) {
if (BranchOnFalse && Idx == i)
FalseArgs.push_back(Val);
else
FalseArgs.push_back(OldFalseArgs[i]);
}
assert(FalseArgs.size() == CBI->getFalseBB()->getNumArguments() &&
"Destination block's number of arguments must match");
CBI = Builder.createCondBranch(CBI->getLoc(), CBI->getCondition(),
CBI->getTrueBB(), TrueArgs,
CBI->getFalseBB(), FalseArgs);
Branch->dropAllReferences();
Branch->eraseFromParent();
return CBI;
}
if (BranchInst *BI = dyn_cast<BranchInst>(Branch)) {
SmallVector<SILValue, 8> Args;
assert(Idx < BI->getNumArgs() && "Not enough edges");
OperandValueArrayRef OldArgs = BI->getArgs();
// Copy the edge values overwriting the edge at Idx.
for (unsigned i = 0, e = OldArgs.size(); i != e; ++i) {
if (Idx == i)
Args.push_back(Val);
else
Args.push_back(OldArgs[i]);
}
assert(Args.size() == Dest->getNumArguments());
BI = Builder.createBranch(BI->getLoc(), BI->getDestBB(), Args);
Branch->dropAllReferences();
Branch->eraseFromParent();
return BI;
}
llvm_unreachable("Unhandled terminator leading to merge block");
}
template <class SwitchEnumTy, class SwitchEnumCaseTy>
SILBasicBlock *replaceSwitchDest(SwitchEnumTy *S,
SmallVectorImpl<SwitchEnumCaseTy> &Cases,
unsigned EdgeIdx, SILBasicBlock *NewDest) {
auto *DefaultBB = S->hasDefault() ? S->getDefaultBB() : nullptr;
for (unsigned i = 0, e = S->getNumCases(); i != e; ++i)
if (EdgeIdx != i)
Cases.push_back(S->getCase(i));
else
Cases.push_back(std::make_pair(S->getCase(i).first, NewDest));
if (EdgeIdx == S->getNumCases())
DefaultBB = NewDest;
return DefaultBB;
}
void swift::changeBranchTarget(TermInst *T, unsigned EdgeIdx,
SILBasicBlock *NewDest, bool PreserveArgs) {
SILBuilderWithScope B(T);
switch (T->getTermKind()) {
// Only Branch and CondBranch may have arguments.
case TermKind::BranchInst: {
auto Br = dyn_cast<BranchInst>(T);
SmallVector<SILValue, 8> Args;
if (PreserveArgs) {
for (auto Arg : Br->getArgs())
Args.push_back(Arg);
}
B.createBranch(T->getLoc(), NewDest, Args);
Br->dropAllReferences();
Br->eraseFromParent();
return;
}
case TermKind::CondBranchInst: {
auto CondBr = dyn_cast<CondBranchInst>(T);
SmallVector<SILValue, 8> TrueArgs;
if (EdgeIdx == CondBranchInst::FalseIdx || PreserveArgs) {
for (auto Arg : CondBr->getTrueArgs())
TrueArgs.push_back(Arg);
}
SmallVector<SILValue, 8> FalseArgs;
if (EdgeIdx == CondBranchInst::TrueIdx || PreserveArgs) {
for (auto Arg : CondBr->getFalseArgs())
FalseArgs.push_back(Arg);
}
SILBasicBlock *TrueDest = CondBr->getTrueBB();
SILBasicBlock *FalseDest = CondBr->getFalseBB();
if (EdgeIdx == CondBranchInst::TrueIdx)
TrueDest = NewDest;
else
FalseDest = NewDest;
B.createCondBranch(CondBr->getLoc(), CondBr->getCondition(),
TrueDest, TrueArgs, FalseDest, FalseArgs);
CondBr->dropAllReferences();
CondBr->eraseFromParent();
return;
}
case TermKind::SwitchValueInst: {
auto SII = dyn_cast<SwitchValueInst>(T);
SmallVector<std::pair<SILValue, SILBasicBlock *>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SII, Cases, EdgeIdx, NewDest);
B.createSwitchValue(SII->getLoc(), SII->getOperand(), DefaultBB, Cases);
SII->eraseFromParent();
return;
}
case TermKind::SwitchEnumInst: {
auto SEI = dyn_cast<SwitchEnumInst>(T);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SEI, Cases, EdgeIdx, NewDest);
B.createSwitchEnum(SEI->getLoc(), SEI->getOperand(), DefaultBB, Cases);
SEI->eraseFromParent();
return;
}
case TermKind::SwitchEnumAddrInst: {
auto SEI = dyn_cast<SwitchEnumAddrInst>(T);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SEI, Cases, EdgeIdx, NewDest);
B.createSwitchEnumAddr(SEI->getLoc(), SEI->getOperand(), DefaultBB, Cases);
SEI->eraseFromParent();
return;
}
case TermKind::DynamicMethodBranchInst: {
auto DMBI = dyn_cast<DynamicMethodBranchInst>(T);
assert(EdgeIdx == 0 || EdgeIdx == 1 && "Invalid edge index");
auto HasMethodBB = !EdgeIdx ? NewDest : DMBI->getHasMethodBB();
auto NoMethodBB = EdgeIdx ? NewDest : DMBI->getNoMethodBB();
B.createDynamicMethodBranch(DMBI->getLoc(), DMBI->getOperand(),
DMBI->getMember(), HasMethodBB, NoMethodBB);
DMBI->eraseFromParent();
return;
}
case TermKind::CheckedCastBranchInst: {
auto CBI = dyn_cast<CheckedCastBranchInst>(T);
assert(EdgeIdx == 0 || EdgeIdx == 1 && "Invalid edge index");
auto SuccessBB = !EdgeIdx ? NewDest : CBI->getSuccessBB();
auto FailureBB = EdgeIdx ? NewDest : CBI->getFailureBB();
B.createCheckedCastBranch(CBI->getLoc(), CBI->isExact(), CBI->getOperand(),
CBI->getCastType(), SuccessBB, FailureBB);
CBI->eraseFromParent();
return;
}
case TermKind::CheckedCastAddrBranchInst: {
auto CBI = dyn_cast<CheckedCastAddrBranchInst>(T);
assert(EdgeIdx == 0 || EdgeIdx == 1 && "Invalid edge index");
auto SuccessBB = !EdgeIdx ? NewDest : CBI->getSuccessBB();
auto FailureBB = EdgeIdx ? NewDest : CBI->getFailureBB();
B.createCheckedCastAddrBranch(CBI->getLoc(), CBI->getConsumptionKind(),
CBI->getSrc(), CBI->getSourceType(),
CBI->getDest(), CBI->getTargetType(),
SuccessBB, FailureBB);
CBI->eraseFromParent();
return;
}
case TermKind::TryApplyInst: {
auto *TAI = dyn_cast<TryApplyInst>(T);
assert((EdgeIdx == 0 || EdgeIdx == 1) && "Invalid edge index");
auto *NormalBB = !EdgeIdx ? NewDest : TAI->getNormalBB();
auto *ErrorBB = EdgeIdx ? NewDest : TAI->getErrorBB();
SmallVector<SILValue, 4> Arguments;
for (auto &Op : TAI->getArgumentOperands())
Arguments.push_back(Op.get());
B.createTryApply(TAI->getLoc(), TAI->getCallee(),
TAI->getSubstCalleeSILType(), TAI->getSubstitutions(),
Arguments, NormalBB, ErrorBB);
TAI->eraseFromParent();
return;
}
case TermKind::ReturnInst:
case TermKind::ThrowInst:
case TermKind::UnreachableInst:
llvm_unreachable("Branch target cannot be changed for this terminator instruction!");
}
llvm_unreachable("Not yet implemented!");
}
template <class SwitchEnumTy, class SwitchEnumCaseTy>
SILBasicBlock *replaceSwitchDest(SwitchEnumTy *S,
SmallVectorImpl<SwitchEnumCaseTy> &Cases,
SILBasicBlock *OldDest, SILBasicBlock *NewDest) {
auto *DefaultBB = S->hasDefault() ? S->getDefaultBB() : nullptr;
for (unsigned i = 0, e = S->getNumCases(); i != e; ++i)
if (S->getCase(i).second != OldDest)
Cases.push_back(S->getCase(i));
else
Cases.push_back(std::make_pair(S->getCase(i).first, NewDest));
if (OldDest == DefaultBB)
DefaultBB = NewDest;
return DefaultBB;
}
/// \brief Replace a branch target.
///
/// \param T The terminating instruction to modify.
/// \param OldDest The successor block that will be replaced.
/// \param NewDest The new target block.
/// \param PreserveArgs If set, preserve arguments on the replaced edge.
void swift::replaceBranchTarget(TermInst *T, SILBasicBlock *OldDest,
SILBasicBlock *NewDest, bool PreserveArgs) {
SILBuilderWithScope B(T);
switch (T->getTermKind()) {
// Only Branch and CondBranch may have arguments.
case TermKind::BranchInst: {
auto Br = cast<BranchInst>(T);
assert(OldDest == Br->getDestBB() && "wrong branch target");
SmallVector<SILValue, 8> Args;
if (PreserveArgs) {
for (auto Arg : Br->getArgs())
Args.push_back(Arg);
}
B.createBranch(T->getLoc(), NewDest, Args);
Br->dropAllReferences();
Br->eraseFromParent();
return;
}
case TermKind::CondBranchInst: {
auto CondBr = cast<CondBranchInst>(T);
SmallVector<SILValue, 8> TrueArgs;
if (OldDest == CondBr->getFalseBB() || PreserveArgs) {
for (auto Arg : CondBr->getTrueArgs())
TrueArgs.push_back(Arg);
}
SmallVector<SILValue, 8> FalseArgs;
if (OldDest == CondBr->getTrueBB() || PreserveArgs) {
for (auto Arg : CondBr->getFalseArgs())
FalseArgs.push_back(Arg);
}
SILBasicBlock *TrueDest = CondBr->getTrueBB();
SILBasicBlock *FalseDest = CondBr->getFalseBB();
if (OldDest == CondBr->getTrueBB()) {
TrueDest = NewDest;
} else {
assert(OldDest == CondBr->getFalseBB() && "wrong cond_br target");
FalseDest = NewDest;
}
B.createCondBranch(CondBr->getLoc(), CondBr->getCondition(),
TrueDest, TrueArgs, FalseDest, FalseArgs);
CondBr->dropAllReferences();
CondBr->eraseFromParent();
return;
}
case TermKind::SwitchValueInst: {
auto SII = cast<SwitchValueInst>(T);
SmallVector<std::pair<SILValue, SILBasicBlock *>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SII, Cases, OldDest, NewDest);
B.createSwitchValue(SII->getLoc(), SII->getOperand(), DefaultBB, Cases);
SII->eraseFromParent();
return;
}
case TermKind::SwitchEnumInst: {
auto SEI = cast<SwitchEnumInst>(T);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SEI, Cases, OldDest, NewDest);
B.createSwitchEnum(SEI->getLoc(), SEI->getOperand(), DefaultBB, Cases);
SEI->eraseFromParent();
return;
}
case TermKind::SwitchEnumAddrInst: {
auto SEI = cast<SwitchEnumAddrInst>(T);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SEI, Cases, OldDest, NewDest);
B.createSwitchEnumAddr(SEI->getLoc(), SEI->getOperand(), DefaultBB, Cases);
SEI->eraseFromParent();
return;
}
case TermKind::DynamicMethodBranchInst: {
auto DMBI = cast<DynamicMethodBranchInst>(T);
assert(OldDest == DMBI->getHasMethodBB() || OldDest == DMBI->getNoMethodBB() && "Invalid edge index");
auto HasMethodBB = OldDest == DMBI->getHasMethodBB() ? NewDest : DMBI->getHasMethodBB();
auto NoMethodBB = OldDest == DMBI->getNoMethodBB() ? NewDest : DMBI->getNoMethodBB();
B.createDynamicMethodBranch(DMBI->getLoc(), DMBI->getOperand(),
DMBI->getMember(), HasMethodBB, NoMethodBB);
DMBI->eraseFromParent();
return;
}
case TermKind::CheckedCastBranchInst: {
auto CBI = cast<CheckedCastBranchInst>(T);
assert(OldDest == CBI->getSuccessBB() || OldDest == CBI->getFailureBB() && "Invalid edge index");
auto SuccessBB = OldDest == CBI->getSuccessBB() ? NewDest : CBI->getSuccessBB();
auto FailureBB = OldDest == CBI->getFailureBB() ? NewDest : CBI->getFailureBB();
B.createCheckedCastBranch(CBI->getLoc(), CBI->isExact(), CBI->getOperand(),
CBI->getCastType(), SuccessBB, FailureBB);
CBI->eraseFromParent();
return;
}
case TermKind::CheckedCastAddrBranchInst: {
auto CBI = cast<CheckedCastAddrBranchInst>(T);
assert(OldDest == CBI->getSuccessBB() || OldDest == CBI->getFailureBB() && "Invalid edge index");
auto SuccessBB = OldDest == CBI->getSuccessBB() ? NewDest : CBI->getSuccessBB();
auto FailureBB = OldDest == CBI->getFailureBB() ? NewDest : CBI->getFailureBB();
B.createCheckedCastAddrBranch(CBI->getLoc(), CBI->getConsumptionKind(),
CBI->getSrc(), CBI->getSourceType(),
CBI->getDest(), CBI->getTargetType(),
SuccessBB, FailureBB);
CBI->eraseFromParent();
return;
}
case TermKind::ReturnInst:
case TermKind::ThrowInst:
case TermKind::TryApplyInst:
case TermKind::UnreachableInst:
llvm_unreachable("Branch target cannot be replaced for this terminator instruction!");
}
llvm_unreachable("Not yet implemented!");
}
/// \brief Check if the edge from the terminator is critical.
bool swift::isCriticalEdge(TermInst *T, unsigned EdgeIdx) {
assert(T->getSuccessors().size() > EdgeIdx && "Not enough successors");
auto SrcSuccs = T->getSuccessors();
if (SrcSuccs.size() <= 1)
return false;
SILBasicBlock *DestBB = SrcSuccs[EdgeIdx];
assert(!DestBB->pred_empty() && "There should be a predecessor");
if (DestBB->getSinglePredecessorBlock())
return false;
return true;
}
template<class SwitchInstTy>
SILBasicBlock *getNthEdgeBlock(SwitchInstTy *S, unsigned EdgeIdx) {
if (S->getNumCases() == EdgeIdx)
return S->getDefaultBB();
return S->getCase(EdgeIdx).second;
}
static void getEdgeArgs(TermInst *T, unsigned EdgeIdx, SILBasicBlock *NewEdgeBB,
SmallVectorImpl<SILValue> &Args) {
if (auto Br = dyn_cast<BranchInst>(T)) {
for (auto V : Br->getArgs())
Args.push_back(V);
return;
}
if (auto CondBr = dyn_cast<CondBranchInst>(T)) {
assert(EdgeIdx < 2);
auto OpdArgs = EdgeIdx ? CondBr->getFalseArgs() : CondBr->getTrueArgs();
for (auto V: OpdArgs)
Args.push_back(V);
return;
}
if (auto SEI = dyn_cast<SwitchValueInst>(T)) {
auto *SuccBB = getNthEdgeBlock(SEI, EdgeIdx);
assert(SuccBB->getNumArguments() == 0 && "Can't take an argument");
(void) SuccBB;
return;
}
// A switch_enum can implicitly pass the enum payload. We need to look at the
// destination block to figure this out.
if (auto SEI = dyn_cast<SwitchEnumInstBase>(T)) {
auto *SuccBB = getNthEdgeBlock(SEI, EdgeIdx);
assert(SuccBB->getNumArguments() < 2 && "Can take at most one argument");
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
// A dynamic_method_br passes the function to the first basic block.
if (auto DMBI = dyn_cast<DynamicMethodBranchInst>(T)) {
auto *SuccBB =
(EdgeIdx == 0) ? DMBI->getHasMethodBB() : DMBI->getNoMethodBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
/// A checked_cast_br passes the result of the cast to the first basic block.
if (auto CBI = dyn_cast<CheckedCastBranchInst>(T)) {
auto SuccBB = EdgeIdx == 0 ? CBI->getSuccessBB() : CBI->getFailureBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
if (auto CBI = dyn_cast<CheckedCastAddrBranchInst>(T)) {
auto SuccBB = EdgeIdx == 0 ? CBI->getSuccessBB() : CBI->getFailureBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
if (auto *TAI = dyn_cast<TryApplyInst>(T)) {
auto *SuccBB = EdgeIdx == 0 ? TAI->getNormalBB() : TAI->getErrorBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
// For now this utility is only used to split critical edges involving
// cond_br.
llvm_unreachable("Not yet implemented");
}
/// Splits the basic block at the iterator with an unconditional branch and
/// updates the dominator tree and loop info.
SILBasicBlock *swift::splitBasicBlockAndBranch(SILBuilder &B,
SILInstruction *SplitBeforeInst,
DominanceInfo *DT,
SILLoopInfo *LI) {
auto *OrigBB = SplitBeforeInst->getParent();
auto *NewBB = OrigBB->split(SplitBeforeInst->getIterator());
B.setInsertionPoint(OrigBB);
B.createBranch(SplitBeforeInst->getLoc(), NewBB);
// Update the dominator tree.
if (DT) {
auto OrigBBDTNode = DT->getNode(OrigBB);
if (OrigBBDTNode) {
// Change the immediate dominators of the children of the block we
// splitted to the splitted block.
SmallVector<DominanceInfoNode *, 16> Adoptees(OrigBBDTNode->begin(),
OrigBBDTNode->end());
auto NewBBDTNode = DT->addNewBlock(NewBB, OrigBB);
for (auto *Adoptee : Adoptees)
DT->changeImmediateDominator(Adoptee, NewBBDTNode);
}
}
// Update loop info.
if (LI)
if (auto *OrigBBLoop = LI->getLoopFor(OrigBB)) {
OrigBBLoop->addBasicBlockToLoop(NewBB, LI->getBase());
}
return NewBB;
}
SILBasicBlock *swift::splitEdge(TermInst *T, unsigned EdgeIdx,
DominanceInfo *DT, SILLoopInfo *LI) {
auto *SrcBB = T->getParent();
auto *Fn = SrcBB->getParent();
SILBasicBlock *DestBB = T->getSuccessors()[EdgeIdx];
// Create a new basic block in the edge, and insert it after the SrcBB.
auto *EdgeBB = Fn->createBasicBlock(SrcBB);
SmallVector<SILValue, 16> Args;
getEdgeArgs(T, EdgeIdx, EdgeBB, Args);
SILBuilder(EdgeBB).createBranch(T->getLoc(), DestBB, Args);
// Strip the arguments and rewire the branch in the source block.
changeBranchTarget(T, EdgeIdx, EdgeBB, /*PreserveArgs=*/false);
if (!DT && !LI)
return EdgeBB;
// Update the dominator tree.
if (DT) {
auto *SrcBBNode = DT->getNode(SrcBB);
// Unreachable code could result in a null return here.
if (SrcBBNode) {
// The new block is dominated by the SrcBB.
auto *EdgeBBNode = DT->addNewBlock(EdgeBB, SrcBB);
// Are all predecessors of DestBB dominated by DestBB?
auto *DestBBNode = DT->getNode(DestBB);
bool OldSrcBBDominatesAllPreds = std::all_of(
DestBB->pred_begin(), DestBB->pred_end(), [=](SILBasicBlock *B) {
if (B == EdgeBB)
return true;
auto *PredNode = DT->getNode(B);
if (!PredNode)
return true;
if (DT->dominates(DestBBNode, PredNode))
return true;
return false;
});
// If so, the new bb dominates DestBB now.
if (OldSrcBBDominatesAllPreds)
DT->changeImmediateDominator(DestBBNode, EdgeBBNode);
}
}
if (!LI)
return EdgeBB;
// Update loop info. Both blocks must be in a loop otherwise the split block
// is outside the loop.
SILLoop *SrcBBLoop = LI->getLoopFor(SrcBB);
if (!SrcBBLoop)
return EdgeBB;
SILLoop *DstBBLoop = LI->getLoopFor(DestBB);
if (!DstBBLoop)
return EdgeBB;
// Same loop.
if (DstBBLoop == SrcBBLoop) {
DstBBLoop->addBasicBlockToLoop(EdgeBB, LI->getBase());
return EdgeBB;
}
// Edge from inner to outer loop.
if (DstBBLoop->contains(SrcBBLoop)) {
DstBBLoop->addBasicBlockToLoop(EdgeBB, LI->getBase());
return EdgeBB;
}
// Edge from outer to inner loop.
if (SrcBBLoop->contains(DstBBLoop)) {
SrcBBLoop->addBasicBlockToLoop(EdgeBB, LI->getBase());
return EdgeBB;
}
// Neither loop contains the other. The destination must be the header of its
// loop. Otherwise, we would be creating irreducible control flow.
assert(DstBBLoop->getHeader() == DestBB &&
"Creating irreducible control flow?");
// Add to outer loop if there is one.
if (auto *Parent = DstBBLoop->getParentLoop())
Parent->addBasicBlockToLoop(EdgeBB, LI->getBase());
return EdgeBB;
}
/// Split every edge between two basic blocks.
void swift::splitEdgesFromTo(SILBasicBlock *From, SILBasicBlock *To,
DominanceInfo *DT, SILLoopInfo *LI) {
for (unsigned EdgeIndex = 0, E = From->getSuccessors().size(); EdgeIndex != E;
++EdgeIndex) {
SILBasicBlock *SuccBB = From->getSuccessors()[EdgeIndex];
if (SuccBB != To)
continue;
splitEdge(From->getTerminator(), EdgeIndex, DT, LI);
}
}
/// Splits the n-th critical edge from the terminator and updates dominance and
/// loop info if set.
/// Returns the newly created basic block on success or nullptr otherwise (if
/// the edge was not critical.
SILBasicBlock *swift::splitCriticalEdge(TermInst *T, unsigned EdgeIdx,
DominanceInfo *DT, SILLoopInfo *LI) {
if (!isCriticalEdge(T, EdgeIdx))
return nullptr;
return splitEdge(T, EdgeIdx, DT, LI);
}
bool swift::hasCriticalEdges(SILFunction &F, bool OnlyNonCondBr) {
for (SILBasicBlock &BB : F) {
// Only consider critical edges for terminators that don't support block
// arguments.
if (OnlyNonCondBr && isa<CondBranchInst>(BB.getTerminator()))
continue;
if (isa<BranchInst>(BB.getTerminator()))
continue;
for (unsigned Idx = 0, e = BB.getSuccessors().size(); Idx != e; ++Idx)
if (isCriticalEdge(BB.getTerminator(), Idx))
return true;
}
return false;
}
/// Split all critical edges in the function updating the dominator tree and
/// loop information (if they are not set to null).
bool swift::splitAllCriticalEdges(SILFunction &F, bool OnlyNonCondBr,
DominanceInfo *DT, SILLoopInfo *LI) {
bool Changed = false;
for (SILBasicBlock &BB : F) {
// Only split critical edges for terminators that don't support block
// arguments.
if (OnlyNonCondBr && isa<CondBranchInst>(BB.getTerminator()))
continue;
if (isa<BranchInst>(BB.getTerminator()))
continue;
for (unsigned Idx = 0, e = BB.getSuccessors().size(); Idx != e; ++Idx)
Changed |=
(splitCriticalEdge(BB.getTerminator(), Idx, DT, LI) != nullptr);
}
return Changed;
}
/// Merge the basic block with its successor if possible. If dominance
/// information or loop info is non null update it. Return true if block was
/// merged.
bool swift::mergeBasicBlockWithSuccessor(SILBasicBlock *BB, DominanceInfo *DT,
SILLoopInfo *LI) {
auto *Branch = dyn_cast<BranchInst>(BB->getTerminator());
if (!Branch)
return false;
auto *SuccBB = Branch->getDestBB();
if (BB == SuccBB || !SuccBB->getSinglePredecessorBlock())
return false;
// If there are any BB arguments in the destination, replace them with the
// branch operands, since they must dominate the dest block.
for (unsigned i = 0, e = Branch->getArgs().size(); i != e; ++i)
SuccBB->getArgument(i)->replaceAllUsesWith(Branch->getArg(i));
Branch->eraseFromParent();
// Move the instruction from the successor block to the current block.
BB->spliceAtEnd(SuccBB);
if (DT)
if (auto *SuccBBNode = DT->getNode(SuccBB)) {
// Change the immediate dominator for children of the successor to be the
// current block.
auto *BBNode = DT->getNode(BB);
SmallVector<DominanceInfoNode *, 8> Children(SuccBBNode->begin(),
SuccBBNode->end());
for (auto *ChildNode : *SuccBBNode)
DT->changeImmediateDominator(ChildNode, BBNode);
DT->eraseNode(SuccBB);
}
if (LI)
LI->removeBlock(SuccBB);
SuccBB->eraseFromParent();
return true;
}
/// Splits the critical edges between from and to. This code assumes there is
/// only one edge between the two basic blocks.
SILBasicBlock *swift::splitIfCriticalEdge(SILBasicBlock *From,
SILBasicBlock *To,
DominanceInfo *DT,
SILLoopInfo *LI) {
auto *T = From->getTerminator();
for (unsigned i = 0, e = T->getSuccessors().size(); i != e; ++i) {
if (T->getSuccessors()[i] == To)
return splitCriticalEdge(T, i, DT, LI);
}
llvm_unreachable("Destination block not found");
}
| {
"content_hash": "9a22bc34754472035ce999fe1fb1552f",
"timestamp": "",
"source": "github",
"line_count": 790,
"max_line_length": 106,
"avg_line_length": 35.90759493670886,
"alnum_prop": 0.6398984735784539,
"repo_name": "tardieu/swift",
"id": "a7bfca7a106fd0d30d325b6b0a4236f957d36c63",
"size": "28367",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "lib/SILOptimizer/Utils/CFG.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2144"
},
{
"name": "Batchfile",
"bytes": "26"
},
{
"name": "C",
"bytes": "61652"
},
{
"name": "C++",
"bytes": "22005787"
},
{
"name": "CMake",
"bytes": "344234"
},
{
"name": "DTrace",
"bytes": "3545"
},
{
"name": "Emacs Lisp",
"bytes": "54598"
},
{
"name": "LLVM",
"bytes": "56821"
},
{
"name": "Makefile",
"bytes": "1841"
},
{
"name": "Objective-C",
"bytes": "247883"
},
{
"name": "Objective-C++",
"bytes": "196600"
},
{
"name": "Perl",
"bytes": "2211"
},
{
"name": "Python",
"bytes": "696430"
},
{
"name": "Ruby",
"bytes": "2091"
},
{
"name": "Shell",
"bytes": "191231"
},
{
"name": "Swift",
"bytes": "16781533"
},
{
"name": "Vim script",
"bytes": "13417"
}
],
"symlink_target": ""
} |
package test.sample;
import junit.framework.TestCase;
/**
* This class
*
* @author Cedric Beust, May 5, 2004
*/
public class JUnitSample1 extends TestCase {
private String m_field = null;
public static final String EXPECTED2 = "testSample1_2";
public static final String EXPECTED1 = "testSample1_1";
public JUnitSample1() {
super();
}
public JUnitSample1(String n) {
super(n);
}
@Override
public void setUp() {
m_field = "foo";
}
@Override
public void tearDown() {
m_field = null;
}
public void testSample1_1() {}
public void testSample1_2() {}
}
| {
"content_hash": "7718f7f190d2037a3ccc62ee622b5d55",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 57,
"avg_line_length": 16.805555555555557,
"alnum_prop": 0.6512396694214876,
"repo_name": "krmahadevan/testng",
"id": "cdead4739cb23daaf3c1c8728c21cb25006333d5",
"size": "605",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "testng-core/src/test/java/test/sample/JUnitSample1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "711"
},
{
"name": "CSS",
"bytes": "12708"
},
{
"name": "Groovy",
"bytes": "3285"
},
{
"name": "HTML",
"bytes": "9063"
},
{
"name": "Java",
"bytes": "3881030"
},
{
"name": "JavaScript",
"bytes": "17303"
},
{
"name": "Kotlin",
"bytes": "66354"
},
{
"name": "Shell",
"bytes": "1458"
}
],
"symlink_target": ""
} |
class Event
include Mongoid::Document
end
| {
"content_hash": "4fbdb721909afa79b4bc3b8eb58c1e62",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 27,
"avg_line_length": 14.666666666666666,
"alnum_prop": 0.7954545454545454,
"repo_name": "erpheus/parrotfeed",
"id": "9dc1e5cfa6fb5e3a32cf4e86eedc4e0ab527d58c",
"size": "44",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/models/event.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6217"
},
{
"name": "JavaScript",
"bytes": "18162"
},
{
"name": "Ruby",
"bytes": "29139"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CIMEL.Figure")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CIMEL.Figure")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("23a3d26f-7a82-4bfd-b82c-c8ae44f1cf38")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.19180")]
[assembly: AssemblyFileVersion("1.3.0.19180")]
| {
"content_hash": "4506e17498be6a9572bf672af95f0eb3",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.888888888888886,
"alnum_prop": 0.7478571428571429,
"repo_name": "CIMEL/CIMEL",
"id": "a5c803eed21edf830cb265f55b4d3dc64bd029a7",
"size": "1403",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "CIMEL.Figure/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2052"
},
{
"name": "C#",
"bytes": "368169"
}
],
"symlink_target": ""
} |
import {bootstrap} from "angular2/platform/browser";
import {HTTP_PROVIDERS, Http} from "angular2/http";
import {MainApp} from "./components/app"
bootstrap(MainApp, HTTP_PROVIDERS); | {
"content_hash": "36378540ac4855457550823531214386",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 52,
"avg_line_length": 36.4,
"alnum_prop": 0.7692307692307693,
"repo_name": "jusefb/angular2_webpack",
"id": "1e2eb68f47037ea2531ec2bd2a0b926afc3c4f4a",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/boot.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1189"
},
{
"name": "HTML",
"bytes": "1037"
},
{
"name": "JavaScript",
"bytes": "10443"
},
{
"name": "TypeScript",
"bytes": "13903"
}
],
"symlink_target": ""
} |
<?php
namespace PHPExiftool\Driver\Tag\XMPPhotoshop;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class EmbeddedXMPDigest extends AbstractTag
{
protected $Id = 'EmbeddedXMPDigest';
protected $Name = 'EmbeddedXMPDigest';
protected $FullName = 'XMP::photoshop';
protected $GroupName = 'XMP-photoshop';
protected $g0 = 'XMP';
protected $g1 = 'XMP-photoshop';
protected $g2 = 'Image';
protected $Type = 'string';
protected $Writable = true;
protected $Description = 'Embedded XMP Digest';
}
| {
"content_hash": "333abaaeea8deed93b6fede8d88a38e2",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 51,
"avg_line_length": 17.571428571428573,
"alnum_prop": 0.6845528455284553,
"repo_name": "romainneutron/PHPExiftool",
"id": "9db92b39e09f0eb1929ff6ef7e0ba575299a5e8a",
"size": "837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/PHPExiftool/Driver/Tag/XMPPhotoshop/EmbeddedXMPDigest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22042446"
}
],
"symlink_target": ""
} |
using namespace caffe;
using namespace tiny_dnn;
using namespace tiny_dnn::activation;
using namespace tiny_dnn::layers;
namespace {
// Verify CMake has found files required to run the benchmark
#if !defined(PROTO_PATH) || !defined(MODEL_PATH)
#error "Error: Could not find bvlc_reference_caffenet benchmark resources"
#else
const std::string proto_path = PROTO_PATH;
const std::string model_path = MODEL_PATH;
#endif
class BVLCReferenceCaffenet : public ::benchmark::Fixture {
public:
BVLCReferenceCaffenet() {
// Disable caffe output
FLAGS_minloglevel = 2;
// Initialization happens once per run
if(!sIsInit) {
SetUpTestCase();
}
}
virtual ~BVLCReferenceCaffenet() {}
static void SetUpTestCase() {
std::cout << "Loading Caffe net and converting to tiny-dnn ..."
<< std::endl;
// Load caffe net
sCaffeNet.reset(new Net<float>(proto_path, TEST));
sCaffeNet->CopyTrainedLayersFrom(model_path);
// Perform one forward pass to fill blobs
sCaffeNet->Forward();
// Convert Caffe net to tiny-dnn layers
sTinyDNNLayers.push_back(nullptr); // skip ImageData layer
for(unsigned int i = 1; i < sCaffeNet->layers().size(); ++i) {
sTinyDNNLayers.push_back(getTinyDNNLayer(i));
}
sIsInit = true;
}
static std::shared_ptr<layer> getTinyDNNLayer(int i) {
// Retrieve caffe layer and top and bottom blobs
auto caffe_layer = sCaffeNet->layers().at(i);
auto bottom_blob = sCaffeNet->bottom_vecs().at(i).at(0);
auto top_blob = sCaffeNet->top_vecs().at(i).at(0);
// Validate caffe input and output blob dimensions
assert(bottom_blob->num_axes() <= 4);
assert(top_blob->num_axes() <= 4);
// Convert Caffe input shape to tiny_dnn::shape3d
serial_size_t in_num = 1; // 4th axis unused in tiny_dnn
shape_t in_shape(1, 1, 1);
std::vector<serial_size_t*> in_tiny_shape =
{ &in_shape.width_, &in_shape.height_, &in_shape.depth_, &in_num };
int in_vec_idx = 0;
std::vector<int> in_caffe_shape = bottom_blob->shape();
for(std::vector<int>::reverse_iterator it = in_caffe_shape.rbegin();
it != in_caffe_shape.rend(); ++it) { // reverse for over caffe shape
*in_tiny_shape.at(in_vec_idx++) = *it;
}
// Convert Caffe output shape to tiny_dnn::shape3d
serial_size_t out_num = 1; // 4th axis unused in tiny_dnn
shape_t out_shape(1, 1, 1);
std::vector<serial_size_t*> out_tiny_shape =
{ &out_shape.width_, &out_shape.height_, &out_shape.depth_, &out_num };
int out_vec_idx = 0;
std::vector<int> out_caffe_shape = top_blob->shape();
for(std::vector<int>::reverse_iterator it = out_caffe_shape.rbegin();
it != out_caffe_shape.rend(); ++it) { // reverse for over caffe shape
*out_tiny_shape.at(out_vec_idx++) = *it;
}
// Save caffe output dimensions for later validation
serial_size_t out_channels = out_shape.depth_;
serial_size_t out_height = out_shape.height_;
serial_size_t out_width = out_shape.width_;
// Copy Caffe proto layer parameter
caffe::LayerParameter layer_param;
layer_param.CopyFrom(caffe_layer->layer_param());
// Insert weight and bias blobs into layer param
for(auto blob : caffe_layer->blobs()) {
// Add BlobProto to layer paramters
auto blob_proto = layer_param.add_blobs();
// Add BlobShape to BlobProto
auto blob_shape = blob_proto->mutable_shape();
for(int dim : blob->shape()) {
blob_shape->add_dim(dim);
}
// Add float weights to BlobProto
for(int i = 0; i < blob->count(); ++i) {
blob_proto->add_data(blob->cpu_data()[i]);
}
}
// Convert Caffe's layer proto parameters to tiny-dnn layer
std::shared_ptr<layer> tiny_dnn_layer =
detail::create(layer_param, in_shape, &out_shape);
// Validate output dimentions
assert( out_shape.depth_ == out_channels &&
out_shape.height_ == out_height &&
out_shape.width_ == out_width );
// Load input data into tiny-dnn layer
tiny_dnn_layer->set_in_data(
std::vector<tensor_t>{
std::vector<vec_t>{ vec_t(bottom_blob->cpu_data(),
bottom_blob->cpu_data() + bottom_blob->count()) } } );
return tiny_dnn_layer;
}
bool validateLayerOutput(int idx) {
// TODO(Abai) : Examine differences between caffe and tiny-dnn for these
// layers. Remove if statment when fixed.
auto l = sTinyDNNLayers.at(idx);
if(l->layer_type() == "conv" ||
l->layer_type() == "norm") {
return true;
}
auto out_data = l->output();
auto top_caffe = sCaffeNet->top_vecs().at(idx).at(0);
auto top_tiny_dnn = out_data.at(0).at(0);
float threshold = 0.0001f;
for(int i = 0; i < top_caffe->count(); ++i) {
float diff = std::abs(top_tiny_dnn.at(i) - top_caffe->cpu_data()[i]);
if(diff > threshold) {
std::cerr << "Warning: Difference between output of layer index="
<< idx << " with type=" << l->layer_type() << " at blob "
<< "index=" << i << " caffe=" << top_caffe->cpu_data()[i]
<< " and tiny-dnn=" << top_tiny_dnn.at(i)
<< " is larger than threshold=" << threshold << std::endl;
//return false;
}
}
return true;
}
static bool sIsInit;
static std::unique_ptr<NetParameter> sProto;
static std::unique_ptr<NetParameter> sWeights;
static std::unique_ptr<Net<float>> sCaffeNet;
static std::vector<std::shared_ptr<layer> > sTinyDNNLayers;
};
bool BVLCReferenceCaffenet::sIsInit = false;
std::unique_ptr<NetParameter> BVLCReferenceCaffenet::sProto;
std::unique_ptr<NetParameter> BVLCReferenceCaffenet::sWeights;
std::unique_ptr<Net<float>> BVLCReferenceCaffenet::sCaffeNet;
std::vector<std::shared_ptr<layer> > BVLCReferenceCaffenet::sTinyDNNLayers;
static void CaffeLayers(benchmark::internal::Benchmark* b) {
int num_layers = BVLCReferenceCaffenet::sCaffeNet->layers().size();
for(int i = 1; i < num_layers; ++i) {
b->Args({i});
}
}
BENCHMARK_DEFINE_F(BVLCReferenceCaffenet, CaffeLayerTest)(
benchmark::State& state) {
// Get Caffe layer and input/output blobs
int i = state.range(0);
auto layer = sCaffeNet->layers().at(i);
auto bottom_vec = sCaffeNet->bottom_vecs().at(i);
auto top_vec = sCaffeNet->top_vecs().at(i);
assert( bottom_vec.size() == 1u );
// Benchmark Caffe layer using input/output blobs
while (state.KeepRunning()) {
layer->Forward(bottom_vec, top_vec);
}
}
BENCHMARK_DEFINE_F(BVLCReferenceCaffenet, TinyDNNLayerTest)(
benchmark::State& state) {
// Get tiny-dnn layer with loaded input data
int i = state.range(0);
auto layer = sTinyDNNLayers.at(i);
// Benchmark tiny-dnn layer
while (state.KeepRunning()) {
layer->forward();
}
// Validate results versus Caffe output
assert(validateLayerOutput(i) == true);
}
BENCHMARK_REGISTER_F(BVLCReferenceCaffenet, CaffeLayerTest)->Apply(CaffeLayers);
BENCHMARK_REGISTER_F(BVLCReferenceCaffenet, TinyDNNLayerTest)->Apply(CaffeLayers);
} // namespace
BENCHMARK_MAIN()
| {
"content_hash": "5dcec38659d2164e3a49d6c9a1a416ca",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 83,
"avg_line_length": 33.764150943396224,
"alnum_prop": 0.6377479742944957,
"repo_name": "Abai/tiny-dnn-benchmark",
"id": "133a3c5f3ee78c3d7eed31f84aeb08e356ff5dc4",
"size": "7447",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/benchmarks/bvlc_reference_caffenet.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "7447"
},
{
"name": "CMake",
"bytes": "6445"
},
{
"name": "Python",
"bytes": "4262"
}
],
"symlink_target": ""
} |
import argparse
import errno
import inspect
import os
import shutil
import sys
import time
from datetime import timedelta
LOCK_DEFAULT_MAX_AGE = timedelta(hours=2)
class LockedException(Exception):
pass
def acquire_lock_or_fail(name, max_age=LOCK_DEFAULT_MAX_AGE):
lock = Lock(name, max_age=max_age)
if lock.acquire():
return lock
raise LockedException("A lock exists named %s who's age is: %s" % (name, unicode(lock.get_age())))
class Lock(object):
"""
Implements a lock by making a directory named [lockname].lock
"""
SUFFIX = 'lock'
def __init__(self, name, dir=None, max_age=LOCK_DEFAULT_MAX_AGE):
self.name = name
self.held = False
self.dir = dir if dir else os.path.dirname(os.path.abspath(__file__))
self.lock_dir_path = os.path.join(self.dir, ".".join([name, Lock.SUFFIX]))
self.max_age = max_age
def get_age(self):
return timedelta(seconds=time.time() - os.path.getmtime(self.lock_dir_path))
def acquire(self, break_old_locks=True):
"""Try to acquire lock. Return True on success or False otherwise"""
try:
os.makedirs(self.lock_dir_path)
self.held = True
# Make sure the modification times are correct
# On some machines, the modification time could be seconds off
os.utime(self.lock_dir_path, (0, time.time()))
except OSError as err:
if err.errno != errno.EEXIST and err.errno != errno.EACCES:
raise
# already locked...
if break_old_locks and self.get_age() > self.max_age:
sys.stderr.write("Breaking lock who's age is: %s\n" % self.get_age())
self.held = True
# Make sure the modification times are correct
# On some machines, the modification time could be seconds off
os.utime(self.lock_dir_path, (0, time.time()))
else:
self.held = False
return self.held
def release(self):
"""Release lock or do nothing if lock is not held"""
if self.held:
try:
shutil.rmtree(self.lock_dir_path)
self.held = False
except OSError as err:
if err.errno != errno.ENOENT:
raise
def _sleep(seconds=0):
print("sleeping", seconds, "seconds")
for i in range(seconds):
time.sleep(1)
sys.stdout.write('.')
sys.stdout.flush()
print("\ndone sleeping")
if __name__ == "__main__":
lock = acquire_lock_or_fail('foo', max_age=timedelta(seconds=10))
try:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title="subcommand")
parser_sleep = subparsers.add_parser('sleep')
parser_sleep.add_argument("seconds", type=int, default=0)
parser_sleep.set_defaults(func=_sleep)
args = parser.parse_args()
## get a subset of the dictionary containing just the arguments of func
arg_spec = inspect.getargspec(args.func)
args_for_func = {k:getattr(args, k) for k in arg_spec.args}
args.func(**args_for_func)
finally:
lock.release()
| {
"content_hash": "4c7e8a1062bd1b3cdee1da040bf6a30a",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 102,
"avg_line_length": 31.475728155339805,
"alnum_prop": 0.5934608266502159,
"repo_name": "thomasyu888/SynapseChallengeTemplates",
"id": "e7958dfdd2f5a357f0a337eb13f39c552eb6004d",
"size": "3242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/scoring_harness/lock.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Common Workflow Language",
"bytes": "24400"
},
{
"name": "Java",
"bytes": "24891"
},
{
"name": "Python",
"bytes": "193231"
},
{
"name": "R",
"bytes": "11474"
},
{
"name": "Shell",
"bytes": "3993"
}
],
"symlink_target": ""
} |
<?php
if(empty($bookmark['url'])) $bookmark['url'] = site_url($this->uri->uri_string());
if(empty($bookmark['title'])) $bookmark['title'] = $page_title;
if(empty($type)) $type = 'general';
?>
<div class="social-bookmarks">
<h3><?php echo lang('tb_title');?></h3>
<ul class="list-inline">
<?php echo $this->load->view('fragments/social_bookmarking/'.$type.'_bookmarks', array('type' => $type, 'bookmark' => $bookmark)); ?>
</ul>
<br class="clear-both" />
</div> | {
"content_hash": "c8a0bf5f2730aa902f349d501b48121c",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 135,
"avg_line_length": 27.941176470588236,
"alnum_prop": 0.608421052631579,
"repo_name": "wuts/starflower",
"id": "99f2ad06ed669f2a0086b73ebb068e1dda8a7f31",
"size": "475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/fragments/social_bookmarking/toolbar.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "7840"
},
{
"name": "PHP",
"bytes": "2688311"
},
{
"name": "Shell",
"bytes": "537"
}
],
"symlink_target": ""
} |
// Provides default renderer for control sap.ui.commons.ProgressIndicator
sap.ui.define(['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* ProgressIndicator renderer.
* @namespace
*/
var ProgressIndicatorRenderer = {
};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
ProgressIndicatorRenderer.render = function (oRm, oProgressIndicator) {
var widthControl = oProgressIndicator.getWidth(),
widthBar = oProgressIndicator.getPercentValue(),
tooltip = oProgressIndicator.getTooltip_AsString(),
displayValue = oProgressIndicator.getDisplayValue(),
widthBorder;
oProgressIndicator.bRtl = sap.ui.getCore().getConfiguration().getRTL();
if (widthBar > 100) {
widthBorder = (10000 / widthBar) + '%';
} else {
widthBorder = '100%';
}
oRm.write('<DIV');
oRm.writeControlData(oProgressIndicator);
oRm.writeAttribute('tabIndex', '0');
if (sap.ui.getCore().getConfiguration().getAccessibility()) {
oRm.writeAccessibilityState(oProgressIndicator, {
role: 'progressbar',
valuemin: '0%',
valuenow: widthBar + '%',
valuemax: '100%'
});
}
if (displayValue) {
oRm.writeAttributeEscaped('aria-valuetext', displayValue);
}
if (tooltip) {
oRm.writeAttributeEscaped('title', tooltip);
}
if (oProgressIndicator.getWidth() && oProgressIndicator.getWidth() !== '') {
oRm.writeAttribute('style', 'height: 16px; width:' + widthControl + ';');
}
oRm.addClass('sapUiProgInd');
oRm.writeClasses();
oRm.write('>');
oRm.write('<DIV');
oRm.writeAttribute('id', oProgressIndicator.getId() + '-box');
if (oProgressIndicator.getWidth() && oProgressIndicator.getWidth() !== '') {
oRm.writeAttribute('style', 'height: 16px; width:' + widthBorder + ';');
}
oRm.addClass('sapUiProgIndBorder');
oRm.writeClasses();
oRm.write('>');
oRm.write('<DIV');
oRm.writeAttribute('id', oProgressIndicator.getId() + '-bar');
oRm.writeAttribute('onselectstart', "return false");
oRm.writeAttribute('style', 'height: 14px; width:' + oProgressIndicator.getPercentValue() + '%;');
var sBarColor = oProgressIndicator.getBarColor();
switch (sBarColor) {
case "POSITIVE":
oRm.addClass('sapUiProgIndBarPos');
break;
case "NEGATIVE":
oRm.addClass('sapUiProgIndBarNeg');
break;
case "CRITICAL":
oRm.addClass('sapUiProgIndBarCrit');
break;
case "NEUTRAL":
oRm.addClass('sapUiProgIndBar');
break;
default:
oRm.addClass('sapUiProgIndBar');
break;
}
oRm.writeClasses();
oRm.write('>');
oRm.write('<DIV');
oRm.writeAttribute('id', oProgressIndicator.getId() + '-end');
if (widthBar > 100) {
oRm.addClass(oProgressIndicator._getProgIndTypeClass(sBarColor));
} else {
oRm.addClass('sapUiProgIndEndHidden');
}
oRm.writeClasses();
if (oProgressIndicator.bRtl) {
oRm.writeAttribute('style', 'position: relative; right:' + widthBorder);
} else {
oRm.writeAttribute('style', 'position: relative; left:' + widthBorder);
}
oRm.write('>');
oRm.write('</DIV>');
oRm.write('<SPAN');
oRm.addClass('sapUiProgIndFont');
oRm.writeClasses();
oRm.write('>');
if (oProgressIndicator.getShowValue() && oProgressIndicator.getShowValue()) {
if (oProgressIndicator.getDisplayValue() && oProgressIndicator.getDisplayValue() !== '') {
oRm.writeEscaped(oProgressIndicator.getDisplayValue());
}
}
oRm.write('</SPAN>');
oRm.write('</DIV>');
oRm.write('</DIV>');
oRm.write('</DIV>');
};
return ProgressIndicatorRenderer;
}, /* bExport= */ true);
| {
"content_hash": "8dca29f15ccdd67c527a199d2be991e9",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 128,
"avg_line_length": 25.993243243243242,
"alnum_prop": 0.6732518845853912,
"repo_name": "yomboprime/YomboServer",
"id": "4b4d8c25474fb820dfd46ccb4f980ace6a6b0b41",
"size": "4032",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "public/lib/openui5/resources/sap/ui/commons/ProgressIndicatorRenderer-dbg.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7130017"
},
{
"name": "HTML",
"bytes": "27825"
},
{
"name": "JavaScript",
"bytes": "33028229"
},
{
"name": "Shell",
"bytes": "728"
}
],
"symlink_target": ""
} |
var fs = require('fs');
var betfair = require('./ca-betfair.js');
var utils = require('./ca-utils.js');
var csv = require('fast-csv')
var yaml_config = require('node-yaml-config');
var config = yaml_config.load(__dirname + '/config/betfair_config.yml');
var moment = require('moment');
var reader = require('line-by-line');
var processRunners = require('./ca-process-runners.js');
function runApplication() {
readBookTxt();
}
var runnerArray = [];
function readBookTxt() {
var lr = new reader(config.betfair.data_dir + '/data/' + '2016-9-1'+ '/book-1.126554080.txt');
lr.on('error', function (err) {
// 'err' contains error object
});
lr.on('line', function (line) {
var data = JSON.parse(line);
var runners = data[0].result[0].runners;
console.log(data[0].result[0].lastMatchTime);
var matchedDateSeconds = moment(data[0].result[0].lastMatchTime).unix();
//console.log(runners);
runners.slice().forEach(function(runner) {
var message = matchedDateSeconds + ',' + runner.lastPriceTraded;
dumpToFile('data/2016-9-1','prices-1.126554080-' + runner.selectionId + '.csv',message);
});
// lastPriceTraded
//r//unnerArray = processRunners(JSON.parse(line));
// ...and continue emitting lines.
});
lr.on('end', function () {
});
}
function dumpToFile(dir, filename, data) {
var rootDir = config.betfair.data_dir + '/' + dir;
if (!fs.existsSync(rootDir)) {
fs.mkdirSync(rootDir);
}
fs.appendFileSync(rootDir + '/' + filename, data + '\n');
}
runApplication();
| {
"content_hash": "a82ed187281edde15e9774d9530c38b5",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 96,
"avg_line_length": 25.716666666666665,
"alnum_prop": 0.6480881399870383,
"repo_name": "cranburyattic/bf-app",
"id": "71d95cd10f3ba99e1a398e1fbe6ff493c0a56bae",
"size": "1543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ca-read-book.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1746"
},
{
"name": "JavaScript",
"bytes": "49311"
},
{
"name": "Python",
"bytes": "10588"
},
{
"name": "Shell",
"bytes": "1073"
}
],
"symlink_target": ""
} |
@interface CompetitionInfoTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *compitionName;
@property (nonatomic, strong) NSArray *competitionArr;
//@property (nonatomic,strong) Team *teamInfo;
//-(void)loadLeagueData:(NSString *)teamId;
@end
| {
"content_hash": "194799f3cd0a1eb280d9cfd7c49adaf3",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 60,
"avg_line_length": 19.857142857142858,
"alnum_prop": 0.7733812949640287,
"repo_name": "bmob/BmobTiQiuBa",
"id": "521e6949671ddb5349b93c1f0e7fc1165497b121",
"size": "468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iOS/SportsContact/UI/Teams/ManageTeamCell/CompetitionInfoTableViewCell.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "28"
},
{
"name": "Batchfile",
"bytes": "380"
},
{
"name": "C",
"bytes": "7069"
},
{
"name": "C++",
"bytes": "6523"
},
{
"name": "CSS",
"bytes": "38491"
},
{
"name": "HTML",
"bytes": "78215"
},
{
"name": "Java",
"bytes": "1043540"
},
{
"name": "JavaScript",
"bytes": "39217"
},
{
"name": "Objective-C",
"bytes": "3473681"
},
{
"name": "Objective-C++",
"bytes": "5141"
},
{
"name": "PHP",
"bytes": "375004"
},
{
"name": "Ruby",
"bytes": "382"
},
{
"name": "Shell",
"bytes": "4098"
}
],
"symlink_target": ""
} |
NG_DOCS={
"sections": {
"api": "GitPhaser Docs"
},
"pages": [
{
"section": "api",
"id": "gitphaser.directive:beaconMap",
"shortName": "beaconMap",
"type": "directive",
"moduleName": "gitphaser",
"shortDescription": "<beacon-map> wraps a MapBox map that shows the user's current",
"keywords": "api beaconmap current directive gitphaser initialized loads location map mapbox selected slide updated updates user val wraps"
},
{
"section": "api",
"id": "gitphaser.directive:contact",
"shortName": "contact",
"type": "directive",
"moduleName": "gitphaser",
"shortDescription": "<contact> Displays the user's email address and provides a way to add user to the device contacts",
"keywords": "account add addable address api badge contact contacts db device directive displays email exist gitphaser green icon info list message meteor modal object opens tap toast user"
},
{
"section": "api",
"id": "gitphaser.directive:contributions",
"shortName": "contributions",
"type": "directive",
"moduleName": "gitphaser",
"shortDescription": "<contributions> A Github contributions graph scraped from an svg resource. This has to be obtained",
"keywords": "account amount api container contributions directive embedded github gitphaser graph info key lateral load login maximum moved object proxy received resource right-wards scraped scroll server spinner svg"
},
{
"section": "api",
"id": "gitphaser.directive:hireable",
"shortName": "hireable",
"type": "directive",
"moduleName": "gitphaser",
"shortDescription": "<hireable> Cash icon visible if attr 'available' is true. Tapping icon shows a brief toast",
"keywords": "account api attr cash directive github gitphaser hire hireable icon info key login message object tapping toast true user visible"
},
{
"section": "api",
"id": "gitphaser.directive:nearbyUser",
"shortName": "nearbyUser",
"type": "directive",
"moduleName": "gitphaser",
"shortDescription": "<nearby-user> Template to represent a proximity detected github user in a list view on",
"keywords": "account api cached detected directive github gitphaser list nearbyuser obtains proximity represent route service template user view"
},
{
"section": "api",
"id": "gitphaser.directive:serverStatus",
"shortName": "serverStatus",
"type": "directive",
"moduleName": "gitphaser",
"shortDescription": "<server-status> Cloud icon in the upper nav bar whose color (red or green) indicates whether the",
"keywords": "api bar cloud color connected connection describes device directive displays gitphaser green icon indicates meteor nav server serverstatus status tapping toast upper"
},
{
"section": "api",
"id": "gitphaser.directive:simuTab",
"shortName": "simuTab",
"type": "directive",
"moduleName": "gitphaser",
"shortDescription": "<simu-tab> Nav bar that is decoupled from the main tab stack for 'others' profiles,",
"keywords": "api bar decoupled directive gitphaser main nav profiles simutab stack tab tabs"
},
{
"section": "api",
"id": "gitphaser.object:LoadingCtrl",
"shortName": "LoadingCtrl",
"type": "object",
"moduleName": "gitphaser",
"shortDescription": "Controller for the default/otherwise route. Waits for platform ready,",
"keywords": "5s api attempts connection controller default gitphaser hang kick loadingctrl login meteor navigate nearby object platform problem ready redirect resolves route server tab timeout toast waits warning"
},
{
"section": "api",
"id": "gitphaser.object:LoginCtrl",
"shortName": "LoginCtrl",
"type": "object",
"moduleName": "gitphaser",
"shortDescription": "Controller for the login route. Functions/Methods for a two-step login process",
"keywords": "api authenticates authentication browser bypasses call controller cordova details device devlogin failure functions github gitphaser handlers inappbrowser loads login loginctrl meteor method object passes process profile route signs toast two-step user"
},
{
"section": "api",
"id": "gitphaser.object:NearbyCtrl",
"shortName": "NearbyCtrl",
"type": "object",
"moduleName": "gitphaser",
"shortDescription": "Controller for the nearby route. Exposes Meteor mongo 'connections' to DOM,",
"keywords": "api clicks connections constant controller current dom exposes filtered geolocate gitphaser handled item list listslide map maps mapslide meteor mongo nearby nearbyctrl notification notify number object profile resolve route service set slide subscription transmitter trigger user variable view"
},
{
"section": "api",
"id": "gitphaser.object:NotificationsCtrl",
"shortName": "NotificationsCtrl",
"type": "object",
"moduleName": "gitphaser",
"shortDescription": "Controller for tab-notifications route. Exposes array of notifications in",
"keywords": "api array controller dom exposes gitphaser notifications notificationsctrl object profile route tab-notifications user"
},
{
"section": "api",
"id": "gitphaser.object:NotificationsProfileCtrl",
"shortName": "NotificationsProfileCtrl",
"type": "object",
"moduleName": "gitphaser",
"shortDescription": "Governs child view of notifications route and shows github profile of target",
"keywords": "$stateparams api array cached child correct current default github gitphaser governs iterates locate meteor notification notifications notificationsprofilectrl object populates profile route selected sender target template unique user userid view"
},
{
"section": "api",
"id": "gitphaser.object:ProfileCtrl",
"shortName": "ProfileCtrl",
"type": "object",
"moduleName": "gitphaser",
"shortDescription": "Exposes GitHub.me profile object or account object to the profile template.",
"keywords": "account api appearance arrow boolean button changes clicked contact directive exposes follow github gitphaser governs hides method modal modalopen nav navigates nearby object opens profile profilectrl route routes tab template triggers username visible wraps"
},
{
"section": "api",
"id": "gitphaser.service:Beacons",
"shortName": "Beacons",
"type": "service",
"moduleName": "gitphaser",
"shortDescription": "Service that transmits and receives iBeacon signal.",
"keywords": "account acounts allows api app array authorize authorized background beacon beaconing beacons boolean broadcast creating distributed duplicate evenly exposes false getuuid gitphaser group ibeacon initialize initialized length likelyhood logging method minimizes minor modulus monitors navigates nearby number objects phones quantity receives region regions rejects resolves select server-generated service sets signal tab time transmits true user uuid uuids"
},
{
"section": "api",
"id": "gitphaser.service:GeoLocate",
"shortName": "GeoLocate",
"type": "service",
"moduleName": "gitphaser",
"shortDescription": "Provides geolocation, reverse geocoding, and map display",
"keywords": "address api authorizing block coordinate coordinates current detect determined device devices display enabled error expressed geocodes geocoding geolocate geolocation getaddress gitphaser isenabled lat latitude leaflet lng loadmap loads location long longitude map mapbox marker nearby object permissions public resets resolve resolves reverse route runs service set sets string titles trigger updatemap user var vars view"
},
{
"section": "api",
"id": "gitphaser.service:GitHub",
"shortName": "GitHub",
"type": "service",
"moduleName": "gitphaser",
"shortDescription": "Provides access to the GitHub API",
"keywords": "$cordovaoauth access account acquired adds api app arbitrary array attempts auth_api auth_required authenticate authenticated authtoken autologs cache cache_time cached canfollow collects contrib contributions convenience credentials current doesn duration error events exist fails false fetch fetched follow follower followers fresh getaccount getauthtoken getcontribgraph getme github gitphaser graph graphs hour inappbroswer increments info initialize initialized initializes invoked js list login logs meteor method metrics minute mock oauth object options param person previous profile public rejects remote repos representing resolve resolves responds retrieves returns routing saved searches second server service set setauthtoken sets string success svg tab target token true user username users week"
},
{
"section": "api",
"id": "gitphaser.service:Notify",
"shortName": "Notify",
"type": "service",
"moduleName": "gitphaser",
"shortDescription": "Handles push notification registry and does internal notifications management",
"keywords": "api app badge checkednotifications disable failures flag generates geolocates gitphaser handles initialize install internal management meteor method nearby notification notifications notify push registers registry required resolve resolves route sawprofile server service side success tab toggles user userid"
}
],
"apis": {
"api": true
},
"__file": "_FAKE_DEST_/js/docs-setup.js",
"__options": {
"startPage": "/api/gitphaser.service:Beacons",
"scripts": [
"js/angular.min.js",
"js/angular-animate.min.js",
"js/marked.js"
],
"styles": [],
"title": "GitPhaser Docs",
"html5Mode": true,
"editExample": true,
"navTemplate": false,
"navContent": "",
"navTemplateData": {},
"image": "img/phaser.png",
"imageLink": "https://github.com/git-phaser/git-phaser",
"titleLink": "/api",
"loadDefaults": {
"angular": true,
"angularAnimate": true,
"marked": true
}
},
"html5Mode": true,
"editExample": true,
"startPage": "/api/gitphaser.service:Beacons",
"scripts": [
"js/angular.min.js",
"js/angular-animate.min.js",
"js/marked.js"
]
}; | {
"content_hash": "5359dcdd0ad7dfcbc60212e54f613094",
"timestamp": "",
"source": "github",
"line_count": 195,
"max_line_length": 828,
"avg_line_length": 53.58974358974359,
"alnum_prop": 0.7001913875598086,
"repo_name": "git-phaser/git-phaser",
"id": "8f17fbda924520afa19d25b442ae4d8418052a46",
"size": "10450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/js/docs-setup.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "845790"
},
{
"name": "HTML",
"bytes": "275416"
},
{
"name": "JavaScript",
"bytes": "7688670"
},
{
"name": "Ruby",
"bytes": "1879"
},
{
"name": "Shell",
"bytes": "11224"
}
],
"symlink_target": ""
} |
package com.oct.updater.updater;
import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.res.Resources;
import com.oct.updater.R;
import com.oct.updater.updater.Updater.PackageInfo;
public class GooPackage implements PackageInfo, Serializable {
private String md5 = null;
private String incremental_md5 = null;
private String filename = null;
private String incremental_filename = null;
private String path = null;
private String incremental_path = null;
private String folder = null;
private long version = -1;
private int id;
private String type;
private String description;
private int is_flashable;
private long modified;
private int downloads;
private int status;
private String additional_info;
private String short_url;
private int developer_id;
private String developerid;
private String board;
private String rom;
private int gapps_package;
private int incremental_file;
private boolean isDelta = false;
public GooPackage(JSONObject result, int previousVersion) {
if (result == null) {
version = -1;
} else {
JSONObject update = null;
try {
// Getting JSON Array node
update = result.getJSONArray("list").getJSONObject(0);
} catch (JSONException ex) {
update = result;
}
developerid = update.optString("ro_developerid");
board = update.optString("ro_board");
rom = update.optString("ro_rom");
version = update.optInt("ro_version");
id = update.optInt("id");
filename = update.optString("filename");
if(isGapps()){
path = "http://garr.dl.sourceforge.net/project/teamoctos/gapps/" + filename;
}else{
path = "http://garr.dl.sourceforge.net/" + update.optString("path");
}
folder = update.optString("folder");
md5 = update.optString("md5");
type = update.optString("type");
description = update.optString("description");
is_flashable = update.optInt("is_flashable");
modified = update.optLong("modified");
downloads = update.optInt("downloads");
status = update.optInt("status");
additional_info = update.optString("additional_info");
short_url = update.optString("short_url");
developer_id = update.optInt("developer_id");
gapps_package = update.optInt("gapps_package");
incremental_file = update.optInt("incremental_file");
if (version == 0) {
String[] split = filename.split("_");
String getVer = split[2].replaceAll("\\D", "");
version = Integer.parseInt(getVer);
}
}
}
@Override
public boolean isDelta() {
return isDelta;
}
@Override
public String getDeltaFilename() {
return incremental_filename;
}
@Override
public String getDeltaPath() {
return incremental_path;
}
@Override
public String getDeltaMd5() {
return incremental_md5;
}
@Override
public String getMessage(Context context) {
Resources res = context.getResources();
return res.getString(R.string.goo_package_description, new Object[] {
filename, md5, folder, description });
}
@Override
public String getMd5() {
return md5;
}
@Override
public String getFilename() {
return filename;
}
@Override
public String getPath() {
return path;
}
@Override
public String getFolder() {
return folder;
}
@Override
public long getVersion() {
return version;
}
public int getId() {
return id;
}
public String getType() {
return type;
}
public String getDescription() {
return description;
}
public int getIs_flashable() {
return is_flashable;
}
public long getModified() {
return modified;
}
public int getDownloads() {
return downloads;
}
public int getStatus() {
return status;
}
public String getAdditional_info() {
return additional_info;
}
public String getShort_url() {
return short_url;
}
public int getDeveloper_id() {
return developer_id;
}
public String getDeveloperid() {
return developerid;
}
public String getBoard() {
return board;
}
public String getRom() {
return rom;
}
public int getGapps_package() {
return gapps_package;
}
public int getIncremental_file() {
return incremental_file;
}
@Override
public boolean isGapps() {
return filename != null && filename.indexOf("gapps") >= 0;
}
}
| {
"content_hash": "4d874393b22c7638a2384fa8fc2c5092",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 93,
"avg_line_length": 26.294685990338163,
"alnum_prop": 0.5452875252618041,
"repo_name": "treken/platform_packages_apps_OCTota",
"id": "a7f1b2db54386b7af07a6ab43d0b7c401f602c90",
"size": "6090",
"binary": false,
"copies": "1",
"ref": "refs/heads/oct",
"path": "src/com/oct/updater/updater/GooPackage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "257010"
},
{
"name": "Shell",
"bytes": "14698"
}
],
"symlink_target": ""
} |
/**
* @module ol/util
*/
/**
* @return {?} Any return.
*/
export function abstract() {
return /** @type {?} */ ((function () {
throw new Error('Unimplemented abstract method.');
})());
}
/**
* Counter for getUid.
* @type {number}
* @private
*/
var uidCounter_ = 0;
/**
* Gets a unique ID for an object. This mutates the object so that further calls
* with the same object as a parameter returns the same value. Unique IDs are generated
* as a strictly increasing sequence. Adapted from goog.getUid.
*
* @param {Object} obj The object to get the unique ID for.
* @return {string} The unique ID for the object.
* @api
*/
export function getUid(obj) {
return obj.ol_uid || (obj.ol_uid = String(++uidCounter_));
}
/**
* OpenLayers version.
* @type {string}
*/
export var VERSION = '6.6.2-dev.1629115540962';
//# sourceMappingURL=util.js.map | {
"content_hash": "5ae9afed7c8b212cfe3a59308fdab5c5",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 87,
"avg_line_length": 25,
"alnum_prop": 0.6434285714285715,
"repo_name": "cdnjs/cdnjs",
"id": "d2fefb72220fda453babfe2c29f7db390659cfbd",
"size": "875",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/openlayers/6.6.2-dev.1629115540962/util.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
ifeq ($(USE_OPT),)
USE_OPT = -O2 -ggdb -fomit-frame-pointer -falign-functions=16
endif
# C specific options here (added to USE_OPT).
ifeq ($(USE_COPT),)
USE_COPT =
endif
# C++ specific options here (added to USE_OPT).
ifeq ($(USE_CPPOPT),)
USE_CPPOPT = -fno-rtti
endif
# Enable this if you want the linker to remove unused code and data
ifeq ($(USE_LINK_GC),)
USE_LINK_GC = yes
endif
# Linker extra options here.
ifeq ($(USE_LDOPT),)
USE_LDOPT =
endif
# Enable this if you want link time optimizations (LTO)
ifeq ($(USE_LTO),)
USE_LTO = yes
endif
# If enabled, this option allows to compile the application in THUMB mode.
ifeq ($(USE_THUMB),)
USE_THUMB = yes
endif
# Enable this if you want to see the full log while compiling.
ifeq ($(USE_VERBOSE_COMPILE),)
USE_VERBOSE_COMPILE = no
endif
# If enabled, this option makes the build process faster by not compiling
# modules not used in the current configuration.
ifeq ($(USE_SMART_BUILD),)
USE_SMART_BUILD = yes
endif
#
# Build global options
##############################################################################
##############################################################################
# Architecture or project specific options
#
# Stack size to be allocated to the Cortex-M process stack. This stack is
# the stack used by the main() thread.
ifeq ($(USE_PROCESS_STACKSIZE),)
USE_PROCESS_STACKSIZE = 0x200
endif
# Stack size to the allocated to the Cortex-M main/exceptions stack. This
# stack is used for processing interrupts and exceptions.
ifeq ($(USE_EXCEPTIONS_STACKSIZE),)
USE_EXCEPTIONS_STACKSIZE = 0x200
endif
# Enables the use of FPU (no, softfp, hard).
ifeq ($(USE_FPU),)
USE_FPU = no
endif
#
# Architecture or project specific options
##############################################################################
##############################################################################
# Project, sources and paths
#
# Define project name here
PROJECT = ch
# Imported source files and paths
CHIBIOS = ../../..
# Startup files.
include $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32f0xx.mk
# HAL-OSAL files (optional).
include $(CHIBIOS)/os/hal/hal.mk
include $(CHIBIOS)/os/hal/ports/STM32/STM32F0xx/platform.mk
include $(CHIBIOS)/os/hal/boards/ST_STM32F0_DISCOVERY/board.mk
include $(CHIBIOS)/os/hal/osal/rt/osal.mk
# RTOS files (optional).
include $(CHIBIOS)/os/rt/rt.mk
include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/port_v6m.mk
# Other files (optional).
include $(CHIBIOS)/test/rt/test.mk
# Define linker script file here
LDSCRIPT= $(STARTUPLD)/STM32F051x8.ld
# C sources that can be compiled in ARM or THUMB mode depending on the global
# setting.
CSRC = $(STARTUPSRC) \
$(KERNSRC) \
$(PORTSRC) \
$(OSALSRC) \
$(HALSRC) \
$(PLATFORMSRC) \
$(BOARDSRC) \
$(TESTSRC) \
main.c
# C++ sources that can be compiled in ARM or THUMB mode depending on the global
# setting.
CPPSRC =
# C sources to be compiled in ARM mode regardless of the global setting.
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
# option that results in lower performance and larger code size.
ACSRC =
# C++ sources to be compiled in ARM mode regardless of the global setting.
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
# option that results in lower performance and larger code size.
ACPPSRC =
# C sources to be compiled in THUMB mode regardless of the global setting.
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
# option that results in lower performance and larger code size.
TCSRC =
# C sources to be compiled in THUMB mode regardless of the global setting.
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
# option that results in lower performance and larger code size.
TCPPSRC =
# List ASM source files here
ASMSRC =
ASMXSRC = $(STARTUPASM) $(PORTASM) $(OSALASM)
INCDIR = $(CHIBIOS)/os/license \
$(STARTUPINC) $(KERNINC) $(PORTINC) $(OSALINC) \
$(HALINC) $(PLATFORMINC) $(BOARDINC) $(TESTINC) \
$(CHIBIOS)/os/various
#
# Project, sources and paths
##############################################################################
##############################################################################
# Compiler settings
#
MCU = cortex-m0
#TRGT = arm-elf-
TRGT = arm-none-eabi-
CC = $(TRGT)gcc
CPPC = $(TRGT)g++
# Enable loading with g++ only if you need C++ runtime support.
# NOTE: You can use C++ even without C++ support if you are careful. C++
# runtime support makes code size explode.
LD = $(TRGT)gcc
#LD = $(TRGT)g++
CP = $(TRGT)objcopy
AS = $(TRGT)gcc -x assembler-with-cpp
AR = $(TRGT)ar
OD = $(TRGT)objdump
SZ = $(TRGT)size
HEX = $(CP) -O ihex
BIN = $(CP) -O binary
# ARM-specific options here
AOPT =
# THUMB-specific options here
TOPT = -mthumb -DTHUMB
# Define C warning options here
CWARN = -Wall -Wextra -Wundef -Wstrict-prototypes
# Define C++ warning options here
CPPWARN = -Wall -Wextra -Wundef
#
# Compiler settings
##############################################################################
##############################################################################
# Start of user section
#
# List all user C define here, like -D_DEBUG=1
UDEFS =
# Define ASM defines here
UADEFS =
# List all user directories here
UINCDIR =
# List the user directory to look for the libraries here
ULIBDIR =
# List all user libraries here
ULIBS =
#
# End of user defines
##############################################################################
RULESPATH = $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC
include $(RULESPATH)/rules.mk
| {
"content_hash": "95fd178bc59fdd76abf63d7877f5f05c",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 81,
"avg_line_length": 27.169811320754718,
"alnum_prop": 0.6159722222222223,
"repo_name": "netik/dc26_spqr_badge",
"id": "b044eb0f11137d4afe56e904d18c912b0838323c",
"size": "5928",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sw/firmware/ChibiOS/demos/STM32/RT-STM32F051-DISCOVERY/Makefile",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "479057"
},
{
"name": "Batchfile",
"bytes": "882"
},
{
"name": "C",
"bytes": "109460715"
},
{
"name": "C++",
"bytes": "12411644"
},
{
"name": "CSS",
"bytes": "65072"
},
{
"name": "Emacs Lisp",
"bytes": "1440"
},
{
"name": "FreeMarker",
"bytes": "492261"
},
{
"name": "HTML",
"bytes": "238797"
},
{
"name": "Makefile",
"bytes": "2126450"
},
{
"name": "Objective-C",
"bytes": "7886832"
},
{
"name": "Perl",
"bytes": "10398"
},
{
"name": "Python",
"bytes": "12105"
},
{
"name": "Roff",
"bytes": "3100"
},
{
"name": "Shell",
"bytes": "23449"
},
{
"name": "Smarty",
"bytes": "916"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>libshim: _OrgFreedesktopDBusPeerSkeletonPrivate Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">libshim
 <span id="projectnumber">0.1.0</span>
</div>
<div id="projectbrief">Library to provide low-level QEMU guest interaction capabilties outside the hypervisor.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="classes.html"><span>Data Structure Index</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('struct__OrgFreedesktopDBusPeerSkeletonPrivate.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#pub-attribs">Data Fields</a> </div>
<div class="headertitle">
<div class="title">_OrgFreedesktopDBusPeerSkeletonPrivate Struct Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Data Fields</h2></td></tr>
<tr class="memitem:a4779a0065f4a9083968795ab4db7fb10"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4779a0065f4a9083968795ab4db7fb10"></a>
GValue * </td><td class="memItemRight" valign="bottom"><b>properties</b></td></tr>
<tr class="separator:a4779a0065f4a9083968795ab4db7fb10"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab9ff6ca66c4890d1f2f88eeefc0a9c0b"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab9ff6ca66c4890d1f2f88eeefc0a9c0b"></a>
GList * </td><td class="memItemRight" valign="bottom"><b>changed_properties</b></td></tr>
<tr class="separator:ab9ff6ca66c4890d1f2f88eeefc0a9c0b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a13927f98291d8a0d7e71e6e1680540e2"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a13927f98291d8a0d7e71e6e1680540e2"></a>
GSource * </td><td class="memItemRight" valign="bottom"><b>changed_properties_idle_source</b></td></tr>
<tr class="separator:a13927f98291d8a0d7e71e6e1680540e2"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a48c3cf3b5e67045389c987ef4669554c"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a48c3cf3b5e67045389c987ef4669554c"></a>
GMainContext * </td><td class="memItemRight" valign="bottom"><b>context</b></td></tr>
<tr class="separator:a48c3cf3b5e67045389c987ef4669554c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a86db153017253a2b9b522d05897cf14b"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a86db153017253a2b9b522d05897cf14b"></a>
GMutex </td><td class="memItemRight" valign="bottom"><b>lock</b></td></tr>
<tr class="separator:a86db153017253a2b9b522d05897cf14b"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>OrgFreedesktopDBusPeerSkeleton:</p>
<p>The #OrgFreedesktopDBusPeerSkeleton structure contains only private data and should only be accessed using the provided API. OrgFreedesktopDBusPeerSkeletonClass: : The parent class.</p>
<p>Class structure for #OrgFreedesktopDBusPeerSkeleton. </p>
</div><hr/>The documentation for this struct was generated from the following file:<ul>
<li>src/lib/connector.c</li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="struct__OrgFreedesktopDBusPeerSkeletonPrivate.html">_OrgFreedesktopDBusPeerSkeletonPrivate</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "38c97929b993b9f79b06aa004ed9a5fe",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 188,
"avg_line_length": 49.847682119205295,
"alnum_prop": 0.6880563305433772,
"repo_name": "datto/librdpmux",
"id": "0bb135a0d5bc1cb01ef3d949b29990f8924d50c2",
"size": "7527",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/html/struct__OrgFreedesktopDBusPeerSkeletonPrivate.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "396300"
},
{
"name": "C++",
"bytes": "342"
},
{
"name": "CMake",
"bytes": "14034"
}
],
"symlink_target": ""
} |
import { Particle } from "./Particle";
import { PolygonMaskType } from "../Enums/PolygonMaskType";
import { PolygonMaskInlineArrangement } from "../Enums/PolygonMaskInlineArrangement";
export class Particles {
constructor(container) {
this.container = container;
this.array = [];
this.interactionsEnabled = false;
}
get count() {
return this.array.length;
}
init() {
const container = this.container;
const options = container.options;
if (options.polygon.enable && options.polygon.type === PolygonMaskType.inline &&
options.polygon.inline.arrangement === PolygonMaskInlineArrangement.onePerPoint) {
container.polygon.drawPointsOnPolygonPath();
}
else {
for (let i = this.array.length; i < options.particles.number.value; i++) {
const p = new Particle(container);
this.array.push(p);
}
}
this.interactionsEnabled = options.particles.lineLinked.enable ||
options.particles.move.attract.enable ||
options.particles.move.collisions;
}
removeAt(index) {
if (index >= 0 && index <= this.count) {
this.array.splice(index, 1);
}
}
remove(particle) {
this.removeAt(this.array.indexOf(particle));
}
update(delta) {
for (let i = 0; i < this.array.length; i++) {
const p = this.array[i];
p.update(i, delta);
if (this.interactionsEnabled) {
for (let j = i + 1; j < this.array.length; j++) {
const p2 = this.array[j];
p.interact(p2);
}
}
}
}
draw(delta) {
const container = this.container;
const options = container.options;
container.canvas.clear();
this.update(delta);
if (options.polygon.enable && options.polygon.draw.enable) {
container.polygon.drawPolygon();
}
for (const p of this.array) {
p.draw();
}
}
clear() {
this.array = [];
}
push(nb, mousePosition) {
const container = this.container;
const options = container.options;
this.pushing = true;
if (options.particles.number.limit > 0) {
if ((this.array.length + nb) > options.particles.number.limit) {
this.removeQuantity((this.array.length + nb) - options.particles.number.limit);
}
}
let pos;
if (mousePosition) {
pos = mousePosition.position || { x: 0, y: 0 };
}
for (let i = 0; i < nb; i++) {
const p = new Particle(container, pos);
this.addParticle(p);
}
if (!options.particles.move.enable) {
this.container.play();
}
this.pushing = false;
}
addParticle(particle) {
this.array.push(particle);
}
removeQuantity(quantity) {
const container = this.container;
const options = container.options;
this.array.splice(0, quantity);
if (!options.particles.move.enable) {
this.container.play();
}
}
}
//# sourceMappingURL=Particles.js.map | {
"content_hash": "72061eff729cce74879908b6e60a90ee",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 95,
"avg_line_length": 33.13131313131313,
"alnum_prop": 0.5435975609756097,
"repo_name": "cdnjs/cdnjs",
"id": "e908bc93a62a14f27e42087592aba5aaba6c712d",
"size": "3280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/tsparticles/1.11.0/Classes/Particles.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace Nova\Services;
use DirectoryIterator;
use InvalidArgumentException;
use SplFileInfo as FileInfo;
use Nova\Models\Directory;
use Nova\Models\DirectoryType;
use Nova\Models\Movie;
use Nova\Object;
use Nova\Scrapers\FileMovieScraper;
use Nova\Services\IMovieService;
class MovieService implements IMovieService
{
public function getMovies()
{
$movies = array();
foreach (Movie::find() as $movie) {
$movie->afterFetch();
$movies[] = $movie;
}
return $movies;
}
public function getMovieById($id)
{
$movie = Movie::findFirst($id);
if (!$movie) {
return null;
}
return $movie;
}
public function clearMissingMovies()
{
$movies = Movie::find();
foreach ($movies as $movie) {
$file = new FileInfo($movie->getPath());
if (!$file->getRealPath()) {
$movie->delete();
}
}
}
public function scanMovieDirectories()
{
$directoryType = DirectoryType::findFirstByType("Movie");
$movies = array();
foreach ($directoryType->directory as $directory) {
$movies = $this->scanMovieDirectory($directory, $movies);
}
return $movies;
}
public function scanMovieDirectory(Directory $directory, array $movies = array())
{
$directoryInfo = new FileInfo($directory->path);
$movieFiles = $this->recursiveDirectoryWalk($directoryInfo, $movieFiles);
foreach ($movieFiles as $file) {
// TODO: Check path and directory_id
$path = str_replace($directory->path, "", $file);
$dbMovie = Movie::findFirst(array(
"conditions" => "path = ?1 AND directory_id = ?2",
"bind" => array(1 => $path, 2 => $directory->id)
));
// If the movie weren't found in the store it's new. We
// then save it and adds it to the new movie list.
if (!$dbMovie) {
$movie = new Movie();
$movie->setPath($path);
$movie->directory = $directory;
$movie->afterFetch();
$movie->save();
$movies[] = $movie;
}
}
return $movies;
}
public function scrapeMovie(Movie $movie, array $options)
{
$scraper = new FileMovieScraper();
$scraper->scrape($movie, $options);
return $movie;
}
/**
* Search for media files in a directory.
*
* @throws Exception
*
* @param FileInfo $directory
* @param array $fileList
* @param boolean $recursive Optional: Do a recursive scan. Defaults to true.
*
* @return array
*/
private function findDirectoryMediaFiles(FileInfo $directory, array $videoFiles, $recursive = true)
{
if (!$directory->isDir()) {
throw new InvalidArgumentException("FileInfo instance was exptected to be a directory.");
}
$directoryIterator = new DirectoryIterator($directory->getPathname());
foreach ($directoryIterator as $child) {
if ($child->isDir() && $recursive) {
$videoFiles = $this->recursiveDirectoryWalk($child, $fileList);
} else {
$extension = strtolower($child->getExtension());
switch ($extension) {
case "avi":
case "mkv":
case "mp4":
$videoFiles[] = $child->getRealPath();
break;
default:
break;
}
}
}
return $videoFiles;
}
}
| {
"content_hash": "c9d93f9a346045170e6ef556ebd73ea3",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 103,
"avg_line_length": 25.897260273972602,
"alnum_prop": 0.5268447500661201,
"repo_name": "nohatssir/nova",
"id": "60e32437db0da7988c900a5792e7b4c8f1995c59",
"size": "3781",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/app/Services/MovieService.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "212"
},
{
"name": "CSS",
"bytes": "3648"
},
{
"name": "HTML",
"bytes": "1988"
},
{
"name": "Handlebars",
"bytes": "2842"
},
{
"name": "JavaScript",
"bytes": "12124"
},
{
"name": "PHP",
"bytes": "80413"
},
{
"name": "Shell",
"bytes": "795"
}
],
"symlink_target": ""
} |
<?php
namespace Vatsimphp\Filter;
/**
*
* Filter interator interface
*
*/
interface FilterInterface
{
/**
*
* Logic to apply the filter
* @return boolean
*/
public function applyFilter();
}
| {
"content_hash": "9369359d984037144cac20e6797dde87",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 34,
"avg_line_length": 11.3,
"alnum_prop": 0.5929203539823009,
"repo_name": "joelgarciajr84/Vatsimphp",
"id": "933fb0c3e2b916c37779a182e811fe7ad70c3f9d",
"size": "896",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Vatsimphp/Filter/FilterInterface.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "186170"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Bot. Notiser 124: 126 (1971)
#### Original name
Alectoria smithii f. esorediata D. Hawksw.
### Remarks
null | {
"content_hash": "0c8940d2fba2c0b1dad14e222ef0308d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 42,
"avg_line_length": 13.153846153846153,
"alnum_prop": 0.7017543859649122,
"repo_name": "mdoering/backbone",
"id": "824c112792d27bf71b9be447a4f17aea52aad8f9",
"size": "234",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Parmeliaceae/Bryoria/Bryoria smithii/Alectoria smithii esorediata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
SHIM_ALWAYS_EXPORT void* operator new(size_t size) {
return ShimCppNew(size);
}
SHIM_ALWAYS_EXPORT void operator delete(void* p) __THROW {
ShimCppDelete(p);
}
SHIM_ALWAYS_EXPORT void* operator new[](size_t size) {
return ShimCppNew(size);
}
SHIM_ALWAYS_EXPORT void operator delete[](void* p) __THROW {
ShimCppDelete(p);
}
SHIM_ALWAYS_EXPORT void* operator new(size_t size,
const std::nothrow_t&) __THROW {
return ShimCppNew(size);
}
SHIM_ALWAYS_EXPORT void* operator new[](size_t size,
const std::nothrow_t&) __THROW {
return ShimCppNew(size);
}
SHIM_ALWAYS_EXPORT void operator delete(void* p, const std::nothrow_t&) __THROW {
ShimCppDelete(p);
}
SHIM_ALWAYS_EXPORT void operator delete[](void* p,
const std::nothrow_t&) __THROW {
ShimCppDelete(p);
}
SHIM_ALWAYS_EXPORT void operator delete(void* p, size_t) __THROW {
ShimCppDelete(p);
}
SHIM_ALWAYS_EXPORT void operator delete[](void* p, size_t) __THROW {
ShimCppDelete(p);
}
| {
"content_hash": "60a2622cb42b4ccf74ca2054011fcfb1",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 81,
"avg_line_length": 25.642857142857142,
"alnum_prop": 0.6239554317548747,
"repo_name": "youtube/cobalt",
"id": "b1e6ee2509d135fb3c7d94390099f36dcc7a91e6",
"size": "1678",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "base/allocator/allocator_shim_override_cpp_symbols.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
import os
import socket
from flexget import plugin
from flexget.event import event
log = logging.getLogger('formlogin')
class FormLogin(object):
"""
Login on form
"""
schema = {
'type': 'object',
'properties': {
'url': {'type': 'string', 'format': 'url'},
'username': {'type': 'string'},
'password': {'type': 'string'},
'userfield': {'type': 'string'},
'passfield': {'type': 'string'}
},
'required': ['url', 'username', 'password'],
'additionalProperties': False
}
def on_task_start(self, task, config):
try:
from mechanize import Browser
except ImportError:
raise plugin.PluginError('mechanize required (python module), please install it.', log)
userfield = config.get('userfield', 'username')
passfield = config.get('passfield', 'password')
url = config['url']
username = config['username']
password = config['password']
br = Browser()
br.set_handle_robots(False)
try:
br.open(url)
except Exception as e:
# TODO: improve error handling
raise plugin.PluginError('Unable to post login form', log)
# br.set_debug_redirects(True)
# br.set_debug_responses(True)
# br.set_debug_http(True)
try:
for form in br.forms():
loginform = form
try:
loginform[userfield] = username
loginform[passfield] = password
break
except Exception as e:
pass
else:
received = os.path.join(task.manager.config_base, 'received')
if not os.path.isdir(received):
os.mkdir(received)
filename = os.path.join(received, '%s.formlogin.html' % task.name)
with open(filename, 'w') as f:
f.write(br.response().get_data())
log.critical('I have saved the login page content to %s for you to view' % filename)
raise plugin.PluginError('Unable to find login fields', log)
except socket.timeout:
raise plugin.PluginError('Timed out on url %s' % url)
br.form = loginform
br.submit()
cookiejar = br._ua_handlers["_cookies"].cookiejar
# Add cookiejar to our requests session
task.requests.add_cookiejar(cookiejar)
@event('plugin.register')
def register_plugin():
plugin.register(FormLogin, 'form', api_ver=2)
| {
"content_hash": "dcf09006c30acceca5c03b7d646404a6",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 100,
"avg_line_length": 30.725274725274726,
"alnum_prop": 0.5547210300429185,
"repo_name": "qvazzler/Flexget",
"id": "4eba455b0c849aef231101ca91c305ef7c19100d",
"size": "2796",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "flexget/plugins/plugin_formlogin.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5275"
},
{
"name": "HTML",
"bytes": "33930"
},
{
"name": "JavaScript",
"bytes": "58811"
},
{
"name": "Python",
"bytes": "2428468"
}
],
"symlink_target": ""
} |
<subsystem xmlns="urn:jboss:domain:modeshape:2.0">
<repository name="sample">
<node-types>
<node-type>custom.cnd</node-type>
</node-types>
<workspaces>
<workspace name="predefinedWorkspace1"/>
<workspace name="predefinedWorkspace2">
<initial-content>initial-content-default.xml</initial-content>
</workspace>
<workspace name="predefinedWorkspace3"/>
<initial-content>initial-content-default.xml</initial-content>
</workspaces>
<journaling max-days-to-keep-records="15"/>
<file-binary-storage path="modeshape/compositeBinaryStoreRepository/binaries/fs1"/>
<!--index-providers>
<index-provider name="local-indexes" classname="local"
path="modeshape/sample/indexes/"
relative-to="jboss.server.data.dir"
/>
</index-providers-->
<sequencers>
<sequencer classname="ddl" name="modeshape-sequencer-ddl" path-expression="//a/b"/>
<sequencer classname="java" name="modeshape-sequencer-java" path-expression="//a/b"/>
</sequencers>
<external-sources>
<source cacheTtlSeconds="1"
classname="org.modeshape.connector.filesystem.FileSystemConnector"
directoryPath="." name="filesystem" readonly="true">
<projection>default:/projection1 => /</projection>
<projection>other:/projection1 => /</projection>
</source>
<source cacheTtlSeconds="1"
classname="org.modeshape.connector.git.GitConnector"
directoryPath="." module="org.modeshape.connector.git"
name="git" queryableBranches="master,2.x"
readonly="true" remoteName="upstream,origin"/>
<source
classname="org.modeshape.connector.meta.jdbc.JdbcMetadataConnector"
dataSourceJndiName="java:jboss/datasources/ExampleDS"
module="org.modeshape.connector.jdbc.metadata" name="jdbc-metadata">
<projection>default:/ModeShapeTestDb => /</projection>
</source>
</external-sources>
<text-extractors>
<text-extractor classname="tika" name="tika-extractor1"/>
<text-extractor
classname="org.modeshape.extractor.tika.TikaTextExtractor" name="tika-extractor2"/>
</text-extractors>
</repository>
<webapp name="modeshape-cmis.war"/>
</subsystem> | {
"content_hash": "e2c9b7198b41b933848f196d499bcf5e",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 103,
"avg_line_length": 50.15384615384615,
"alnum_prop": 0.588957055214724,
"repo_name": "flownclouds/modeshape",
"id": "ba69f7a6bcbf1840b58e74204550697bb718c0a6",
"size": "2608",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "deploy/jbossas/modeshape-jbossas-subsystem/src/test/resources/org/modeshape/jboss/subsystem/modeshape-full-config.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
* WordPress Administration Navigation Menu
* Interface JS functions
*
* @version 2.0.0
*
* @package WordPress
* @subpackage Administration
*/
var wpNavMenu;
(function($) {
var api = wpNavMenu = {
options : {
menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
globalMaxDepth : 11
},
menuList : undefined, // Set in init.
targetList : undefined, // Set in init.
menusChanged : false,
isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
// Functions that run on init.
init : function() {
api.menuList = $('#menu-to-edit');
api.targetList = api.menuList;
this.jQueryExtensions();
this.attachMenuEditListeners();
this.setupInputWithDefaultTitle();
this.attachQuickSearchListeners();
this.attachThemeLocationsListeners();
this.attachTabsPanelListeners();
this.attachUnsavedChangesListener();
if ( api.menuList.length )
this.initSortables();
if ( menus.oneThemeLocationNoMenus )
$( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom );
this.initManageLocations();
this.initAccessibility();
this.initToggles();
// Open first accordion option
this.initAccordion();
},
jQueryExtensions : function() {
// jQuery extensions
$.fn.extend({
menuItemDepth : function() {
var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
},
updateDepthClass : function(current, prev) {
return this.each(function(){
var t = $(this);
prev = prev || t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ prev )
.addClass('menu-item-depth-'+ current );
});
},
shiftDepthClass : function(change) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ depth )
.addClass('menu-item-depth-'+ (depth + change) );
});
},
childMenuItems : function() {
var result = $();
this.each(function(){
var t = $(this), depth = t.menuItemDepth(), next = t.next();
while( next.length && next.menuItemDepth() > depth ) {
result = result.add( next );
next = next.next();
}
});
return result;
},
shiftHorizontally : function( dir ) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth(),
newDepth = depth + dir;
// Change .menu-item-depth-n class
t.moveHorizontally( newDepth, depth );
});
},
moveHorizontally : function( newDepth, depth ) {
return this.each(function(){
var t = $(this),
children = t.childMenuItems(),
diff = newDepth - depth,
subItemText = t.find('.is-submenu');
// Change .menu-item-depth-n class
t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId();
// If it has children, move those too
if ( children ) {
children.each(function( index ) {
var t = $(this),
thisDepth = t.menuItemDepth(),
newDepth = thisDepth + diff;
t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId();
});
}
// Show "Sub item" helper text
if (0 === newDepth)
subItemText.hide();
else
subItemText.show();
});
},
updateParentMenuItemDBId : function() {
return this.each(function(){
var item = $(this),
input = item.find( '.menu-item-data-parent-id' ),
depth = parseInt( item.menuItemDepth() ),
parentDepth = depth - 1,
parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first();
if ( 0 == depth ) { // Item is on the top level, has no parent
input.val(0);
} else { // Find the parent item, and retrieve its object id.
input.val( parent.find( '.menu-item-data-db-id' ).val() );
}
});
},
hideAdvancedMenuItemFields : function() {
return this.each(function(){
var that = $(this);
$('.hide-column-tog').not(':checked').each(function(){
that.find('.field-' + $(this).val() ).addClass('hidden-field');
});
});
},
/**
* Adds selected menu items to the menu.
*
* @param jQuery metabox The metabox jQuery object.
*/
addSelectedToMenu : function(processMethod) {
if ( 0 == $('#menu-to-edit').length ) {
return false;
}
return this.each(function() {
var t = $(this), menuItems = {},
checkboxes = ( menus.oneThemeLocationNoMenus && 0 == t.find('.tabs-panel-active .categorychecklist li input:checked').length ) ? t.find('#page-all li input[type="checkbox"]') : t.find('.tabs-panel-active .categorychecklist li input:checked'),
re = new RegExp('menu-item\\[(\[^\\]\]*)');
processMethod = processMethod || api.addMenuItemToBottom;
// If no items are checked, bail.
if ( !checkboxes.length )
return false;
// Show the ajax spinner
t.find('.spinner').show();
// Retrieve menu item data
$(checkboxes).each(function(){
var t = $(this),
listItemDBIDMatch = re.exec( t.attr('name') ),
listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
if ( this.className && -1 != this.className.indexOf('add-to-top') )
processMethod = api.addMenuItemToTop;
menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
});
// Add the items
api.addItemToMenu(menuItems, processMethod, function(){
// Deselect the items and hide the ajax spinner
checkboxes.removeAttr('checked');
t.find('.spinner').hide();
});
});
},
getItemData : function( itemType, id ) {
itemType = itemType || 'menu-item';
var itemData = {}, i,
fields = [
'menu-item-db-id',
'menu-item-object-id',
'menu-item-object',
'menu-item-parent-id',
'menu-item-position',
'menu-item-type',
'menu-item-title',
'menu-item-url',
'menu-item-description',
'menu-item-attr-title',
'menu-item-target',
'menu-item-classes',
'menu-item-xfn'
];
if( !id && itemType == 'menu-item' ) {
id = this.find('.menu-item-data-db-id').val();
}
if( !id ) return itemData;
this.find('input').each(function() {
var field;
i = fields.length;
while ( i-- ) {
if( itemType == 'menu-item' )
field = fields[i] + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + fields[i] + ']';
if (
this.name &&
field == this.name
) {
itemData[fields[i]] = this.value;
}
}
});
return itemData;
},
setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
itemType = itemType || 'menu-item';
if( !id && itemType == 'menu-item' ) {
id = $('.menu-item-data-db-id', this).val();
}
if( !id ) return this;
this.find('input').each(function() {
var t = $(this), field;
$.each( itemData, function( attr, val ) {
if( itemType == 'menu-item' )
field = attr + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + attr + ']';
if ( field == t.attr('name') ) {
t.val( val );
}
});
});
return this;
}
});
},
initAccordion : function() {
var accordionOptions = $( '.accordion-container li.accordion-section' );
accordionOptions.removeClass('open');
accordionOptions.filter(':visible').first().addClass( 'open' );
},
countMenuItems : function( depth ) {
return $( '.menu-item-depth-' + depth ).length;
},
moveMenuItem : function( $this, dir ) {
var menuItems = $('#menu-to-edit li');
menuItemsCount = menuItems.length,
thisItem = $this.parents( 'li.menu-item' ),
thisItemChildren = thisItem.childMenuItems(),
thisItemData = thisItem.getItemData(),
thisItemDepth = parseInt( thisItem.menuItemDepth() ),
thisItemPosition = parseInt( thisItem.index() ),
nextItem = thisItem.next(),
nextItemChildren = nextItem.childMenuItems(),
nextItemDepth = parseInt( nextItem.menuItemDepth() ) + 1,
prevItem = thisItem.prev(),
prevItemDepth = parseInt( prevItem.menuItemDepth() ),
prevItemId = prevItem.getItemData()['menu-item-db-id'];
switch ( dir ) {
case 'up':
var newItemPosition = thisItemPosition - 1;
// Already at top
if ( 0 === thisItemPosition )
break;
// If a sub item is moved to top, shift it to 0 depth
if ( 0 === newItemPosition && 0 !== thisItemDepth )
thisItem.moveHorizontally( 0, thisItemDepth );
// If prev item is sub item, shift to match depth
if ( 0 !== prevItemDepth )
thisItem.moveHorizontally( prevItemDepth, thisItemDepth );
// Does this item have sub items?
if ( thisItemChildren ) {
var items = thisItem.add( thisItemChildren );
// Move the entire block
items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
} else {
thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
}
break;
case 'down':
// Does this item have sub items?
if ( thisItemChildren ) {
var items = thisItem.add( thisItemChildren ),
nextItem = menuItems.eq( items.length + thisItemPosition ),
nextItemChildren = 0 !== nextItem.childMenuItems().length;
if ( nextItemChildren ) {
var newDepth = parseInt( nextItem.menuItemDepth() ) + 1;
thisItem.moveHorizontally( newDepth, thisItemDepth );
}
// Have we reached the bottom?
if ( menuItemsCount === thisItemPosition + items.length )
break;
items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId();
} else {
// If next item has sub items, shift depth
if ( 0 !== nextItemChildren.length )
thisItem.moveHorizontally( nextItemDepth, thisItemDepth );
// Have we reached the bottom
if ( menuItemsCount === thisItemPosition + 1 )
break;
thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId();
}
break;
case 'top':
// Already at top
if ( 0 === thisItemPosition )
break;
// Does this item have sub items?
if ( thisItemChildren ) {
var items = thisItem.add( thisItemChildren );
// Move the entire block
items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
} else {
thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
}
break;
case 'left':
// As far left as possible
if ( 0 === thisItemDepth )
break;
thisItem.shiftHorizontally( -1 );
break;
case 'right':
// Can't be sub item at top
if ( 0 === thisItemPosition )
break;
// Already sub item of prevItem
if ( thisItemData['menu-item-parent-id'] === prevItemId )
break;
thisItem.shiftHorizontally( 1 );
break;
}
$this.focus();
api.registerChange();
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
initAccessibility : function() {
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
// Events
$( '.menus-move-up' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'up' );
e.preventDefault();
});
$( '.menus-move-down' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'down' );
e.preventDefault();
});
$( '.menus-move-top' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'top' );
e.preventDefault();
});
$( '.menus-move-left' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'left' );
e.preventDefault();
});
$( '.menus-move-right' ).on( 'click', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'right' );
e.preventDefault();
});
},
refreshAdvancedAccessibility : function() {
// Hide all links by default
$( '.menu-item-settings .field-move a' ).hide();
$( '.item-edit' ).each( function() {
var $this = $(this),
movement = [],
availableMovement = '',
menuItem = $this.parents( 'li.menu-item' ).first(),
depth = menuItem.menuItemDepth(),
isPrimaryMenuItem = ( 0 === depth ),
itemName = $this.parents( '.menu-item-handle' ).find( '.menu-item-title' ).text(),
position = parseInt( menuItem.index() ),
prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1 ),
prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(),
prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(),
totalMenuItems = $('#menu-to-edit li').length,
hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length;
// Where can they move this menu item?
if ( 0 !== position ) {
var thisLink = menuItem.find( '.menus-move-up' );
thisLink.prop( 'title', menus.moveUp ).show();
}
if ( 0 !== position && isPrimaryMenuItem ) {
var thisLink = menuItem.find( '.menus-move-top' );
thisLink.prop( 'title', menus.moveToTop ).show();
}
if ( position + 1 !== totalMenuItems && 0 !== position ) {
var thisLink = menuItem.find( '.menus-move-down' );
thisLink.prop( 'title', menus.moveDown ).show();
}
if ( 0 === position && 0 !== hasSameDepthSibling ) {
var thisLink = menuItem.find( '.menus-move-down' );
thisLink.prop( 'title', menus.moveDown ).show();
}
if ( ! isPrimaryMenuItem ) {
var thisLink = menuItem.find( '.menus-move-left' ),
thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft );
thisLink.prop( 'title', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).html( thisLinkText ).show();
}
if ( 0 !== position ) {
if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) {
var thisLink = menuItem.find( '.menus-move-right' ),
thisLinkText = menus.under.replace( '%s', prevItemNameRight );
thisLink.prop( 'title', menus.moveUnder.replace( '%s', prevItemNameRight ) ).html( thisLinkText ).show();
}
}
if ( isPrimaryMenuItem ) {
var primaryItems = $( '.menu-item-depth-0' ),
itemPosition = primaryItems.index( menuItem ) + 1,
totalMenuItems = primaryItems.length,
// String together help text for primary menu items
title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems );
} else {
var parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1 ) ).first(),
parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
parentItemName = parentItem.find( '.menu-item-title' ).text(),
subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
// String together help text for sub menu items
title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName );
}
$this.prop('title', title).html( title );
});
},
refreshKeyboardAccessibility : function() {
$( '.item-edit' ).off( 'focus' ).on( 'focus', function(){
$(this).off( 'keydown' ).on( 'keydown', function(e){
var $this = $(this);
// Bail if it's not an arrow key
if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
return;
// Avoid multiple keydown events
$this.off('keydown');
// Bail if there is only one menu item
if ( 1 === $('#menu-to-edit li').length )
return;
// If RTL, swap left/right arrows
var arrows = { '38' : 'up', '40' : 'down', '37' : 'left', '39' : 'right' };
if ( $('body').hasClass('rtl') )
arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
switch ( arrows[e.which] ) {
case 'up':
api.moveMenuItem( $this, 'up' );
break;
case 'down':
api.moveMenuItem( $this, 'down' );
break;
case 'left':
api.moveMenuItem( $this, 'left' );
break;
case 'right':
api.moveMenuItem( $this, 'right' );
break;
}
// Put focus back on same menu item
$( '#edit-' + thisItemData['menu-item-db-id'] ).focus();
return false;
});
});
},
initToggles : function() {
// init postboxes
postboxes.add_postbox_toggles('nav-menus');
// adjust columns functions for menus UI
columns.useCheckboxesForHidden();
columns.checked = function(field) {
$('.field-' + field).removeClass('hidden-field');
}
columns.unchecked = function(field) {
$('.field-' + field).addClass('hidden-field');
}
// hide fields
api.menuList.hideAdvancedMenuItemFields();
$('.hide-postbox-tog').click(function () {
api.initAccordion();
var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: 'nav-menus'
});
});
},
initSortables : function() {
var currentDepth = 0, originalDepth, minDepth, maxDepth,
prev, next, prevBottom, nextThreshold, helperHeight, transport,
menuEdge = api.menuList.offset().left,
body = $('body'), maxChildDepth,
menuMaxDepth = initialMenuMaxDepth();
if( 0 != $( '#menu-to-edit li' ).length )
$( '.drag-instructions' ).show();
// Use the right edge if RTL.
menuEdge += api.isRTL ? api.menuList.width() : 0;
api.menuList.sortable({
handle: '.menu-item-handle',
placeholder: 'sortable-placeholder',
start: function(e, ui) {
var height, width, parent, children, tempHolder;
// handle placement for rtl orientation
if ( api.isRTL )
ui.item[0].style.right = 'auto';
transport = ui.item.children('.menu-item-transport');
// Set depths. currentDepth must be set before children are located.
originalDepth = ui.item.menuItemDepth();
updateCurrentDepth(ui, originalDepth);
// Attach child elements to parent
// Skip the placeholder
parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
children = parent.childMenuItems();
transport.append( children );
// Update the height of the placeholder to match the moving item.
height = transport.outerHeight();
// If there are children, account for distance between top of children and parent
height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
height += ui.helper.outerHeight();
helperHeight = height;
height -= 2; // Subtract 2 for borders
ui.placeholder.height(height);
// Update the width of the placeholder to match the moving item.
maxChildDepth = originalDepth;
children.each(function(){
var depth = $(this).menuItemDepth();
maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
});
width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
width -= 2; // Subtract 2 for borders
ui.placeholder.width(width);
// Update the list of menu items.
tempHolder = ui.placeholder.next();
tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
$(this).sortable( "refresh" ); // The children aren't sortable. We should let jQ UI know.
ui.item.after( ui.placeholder ); // reattach the placeholder.
tempHolder.css('margin-top', 0); // reset the margin
// Now that the element is complete, we can update...
updateSharedVars(ui);
},
stop: function(e, ui) {
var children, depthChange = currentDepth - originalDepth;
// Return child elements to the list
children = transport.children().insertAfter(ui.item);
// Add "sub menu" description
var subMenuTitle = ui.item.find( '.item-title .is-submenu' );
if ( 0 < currentDepth )
subMenuTitle.show();
else
subMenuTitle.hide();
// Update depth classes
if( depthChange != 0 ) {
ui.item.updateDepthClass( currentDepth );
children.shiftDepthClass( depthChange );
updateMenuMaxDepth( depthChange );
}
// Register a change
api.registerChange();
// Update the item data.
ui.item.updateParentMenuItemDBId();
// address sortable's incorrectly-calculated top in opera
ui.item[0].style.top = 0;
// handle drop placement for rtl orientation
if ( api.isRTL ) {
ui.item[0].style.left = 'auto';
ui.item[0].style.right = 0;
}
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
change: function(e, ui) {
// Make sure the placeholder is inside the menu.
// Otherwise fix it, or we're in trouble.
if( ! ui.placeholder.parent().hasClass('menu') )
(prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
updateSharedVars(ui);
},
sort: function(e, ui) {
var offset = ui.helper.offset(),
edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
// Check and correct if depth is not within range.
// Also, if the dragged element is dragged upwards over
// an item, shift the placeholder to a child position.
if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth;
else if ( depth < minDepth ) depth = minDepth;
if( depth != currentDepth )
updateCurrentDepth(ui, depth);
// If we overlap the next element, manually shift downwards
if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
next.after( ui.placeholder );
updateSharedVars( ui );
$(this).sortable( "refreshPositions" );
}
}
});
function updateSharedVars(ui) {
var depth;
prev = ui.placeholder.prev();
next = ui.placeholder.next();
// Make sure we don't select the moving item.
if( prev[0] == ui.item[0] ) prev = prev.prev();
if( next[0] == ui.item[0] ) next = next.next();
prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
minDepth = (next.length) ? next.menuItemDepth() : 0;
if( prev.length )
maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
else
maxDepth = 0;
}
function updateCurrentDepth(ui, depth) {
ui.placeholder.updateDepthClass( depth, currentDepth );
currentDepth = depth;
}
function initialMenuMaxDepth() {
if( ! body[0].className ) return 0;
var match = body[0].className.match(/menu-max-depth-(\d+)/);
return match && match[1] ? parseInt(match[1]) : 0;
}
function updateMenuMaxDepth( depthChange ) {
var depth, newDepth = menuMaxDepth;
if ( depthChange === 0 ) {
return;
} else if ( depthChange > 0 ) {
depth = maxChildDepth + depthChange;
if( depth > menuMaxDepth )
newDepth = depth;
} else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
newDepth--;
}
// Update the depth class.
body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
menuMaxDepth = newDepth;
}
},
initManageLocations : function () {
$('#menu-locations-wrap form').submit(function(){
window.onbeforeunload = null;
});
$('.menu-location-menus select').on('change', function () {
var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
if ($(this).find('option:selected').data('orig'))
editLink.show();
else
editLink.hide();
});
},
attachMenuEditListeners : function() {
var that = this;
$('#update-nav-menu').bind('click', function(e) {
if ( e.target && e.target.className ) {
if ( -1 != e.target.className.indexOf('item-edit') ) {
return that.eventOnClickEditLink(e.target);
} else if ( -1 != e.target.className.indexOf('menu-save') ) {
return that.eventOnClickMenuSave(e.target);
} else if ( -1 != e.target.className.indexOf('menu-delete') ) {
return that.eventOnClickMenuDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-delete') ) {
return that.eventOnClickMenuItemDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-cancel') ) {
return that.eventOnClickCancelLink(e.target);
}
}
});
$('#add-custom-links input[type="text"]').keypress(function(e){
if ( e.keyCode === 13 ) {
e.preventDefault();
$("#submit-customlinkdiv").click();
}
});
},
/**
* An interface for managing default values for input elements
* that is both JS and accessibility-friendly.
*
* Input elements that add the class 'input-with-default-title'
* will have their values set to the provided HTML title when empty.
*/
setupInputWithDefaultTitle : function() {
var name = 'input-with-default-title';
$('.' + name).each( function(){
var $t = $(this), title = $t.attr('title'), val = $t.val();
$t.data( name, title );
if( '' == val ) $t.val( title );
else if ( title == val ) return;
else $t.removeClass( name );
}).focus( function(){
var $t = $(this);
if( $t.val() == $t.data(name) )
$t.val('').removeClass( name );
}).blur( function(){
var $t = $(this);
if( '' == $t.val() )
$t.addClass( name ).val( $t.data(name) );
});
$( '.blank-slate .input-with-default-title' ).focus();
},
attachThemeLocationsListeners : function() {
var loc = $('#nav-menu-theme-locations'), params = {};
params['action'] = 'menu-locations-save';
params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
loc.find('input[type="submit"]').click(function() {
loc.find('select').each(function() {
params[this.name] = $(this).val();
});
loc.find('.spinner').show();
$.post( ajaxurl, params, function(r) {
loc.find('.spinner').hide();
});
return false;
});
},
attachQuickSearchListeners : function() {
var searchTimer;
$('.quick-search').keypress(function(e){
var t = $(this);
if( 13 == e.which ) {
api.updateQuickSearchResults( t );
return false;
}
if( searchTimer ) clearTimeout(searchTimer);
searchTimer = setTimeout(function(){
api.updateQuickSearchResults( t );
}, 400);
}).attr('autocomplete','off');
},
updateQuickSearchResults : function(input) {
var panel, params,
minSearchLength = 2,
q = input.val();
if( q.length < minSearchLength ) return;
panel = input.parents('.tabs-panel');
params = {
'action': 'menu-quick-search',
'response-format': 'markup',
'menu': $('#menu').val(),
'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
'q': q,
'type': input.attr('name')
};
$('.spinner', panel).show();
$.post( ajaxurl, params, function(menuMarkup) {
api.processQuickSearchQueryResponse(menuMarkup, params, panel);
});
},
addCustomLink : function( processMethod ) {
var url = $('#custom-menu-item-url').val(),
label = $('#custom-menu-item-name').val();
processMethod = processMethod || api.addMenuItemToBottom;
if ( '' == url || 'http://' == url )
return false;
// Show the ajax spinner
$('.customlinkdiv .spinner').show();
this.addLinkToMenu( url, label, processMethod, function() {
// Remove the ajax spinner
$('.customlinkdiv .spinner').hide();
// Set custom link form back to defaults
$('#custom-menu-item-name').val('').blur();
$('#custom-menu-item-url').val('http://');
});
},
addLinkToMenu : function(url, label, processMethod, callback) {
processMethod = processMethod || api.addMenuItemToBottom;
callback = callback || function(){};
api.addItemToMenu({
'-1': {
'menu-item-type': 'custom',
'menu-item-url': url,
'menu-item-title': label
}
}, processMethod, callback);
},
addItemToMenu : function(menuItem, processMethod, callback) {
var menu = $('#menu').val(),
nonce = $('#menu-settings-column-nonce').val();
processMethod = processMethod || function(){};
callback = callback || function(){};
params = {
'action': 'add-menu-item',
'menu': menu,
'menu-settings-column-nonce': nonce,
'menu-item': menuItem
};
$.post( ajaxurl, params, function(menuMarkup) {
var ins = $('#menu-instructions');
processMethod(menuMarkup, params);
// Make it stand out a bit more visually, by adding a fadeIn
$( 'li.pending' ).hide().fadeIn('slow');
$( '.drag-instructions' ).show();
if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
ins.addClass( 'menu-instructions-inactive' );
callback();
});
},
/**
* Process the add menu item request response into menu list item.
*
* @param string menuMarkup The text server response of menu item markup.
* @param object req The request arguments.
*/
addMenuItemToBottom : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
addMenuItemToTop : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
attachUnsavedChangesListener : function() {
$('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){
api.registerChange();
});
if ( 0 != $('#menu-to-edit').length || 0 != $('.menu-location-menus select').length ) {
window.onbeforeunload = function(){
if ( api.menusChanged )
return navMenuL10n.saveAlert;
};
} else {
// Make the post boxes read-only, as they can't be used yet
$( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' );
}
},
registerChange : function() {
api.menusChanged = true;
},
attachTabsPanelListeners : function() {
$('#menu-settings-column').bind('click', function(e) {
var selectAreaMatch, panelId, wrapper, items,
target = $(e.target);
if ( target.hasClass('nav-tab-link') ) {
panelId = target.data( 'type' );
wrapper = target.parents('.accordion-section-content').first();
// upon changing tabs, we want to uncheck all checkboxes
$('input', wrapper).removeAttr('checked');
$('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
$('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
$('.tabs', wrapper).removeClass('tabs');
target.parent().addClass('tabs');
// select the search bar
$('.quick-search', wrapper).focus();
e.preventDefault();
} else if ( target.hasClass('select-all') ) {
selectAreaMatch = /#(.*)$/.exec(e.target.href);
if ( selectAreaMatch && selectAreaMatch[1] ) {
items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
if( items.length === items.filter(':checked').length )
items.removeAttr('checked');
else
items.prop('checked', true);
return false;
}
} else if ( target.hasClass('submit-add-to-menu') ) {
api.registerChange();
if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
api.addCustomLink( api.addMenuItemToBottom );
else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
$('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
return false;
} else if ( target.hasClass('page-numbers') ) {
$.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
function( resp ) {
if ( -1 == resp.indexOf('replace-id') )
return;
var metaBoxData = $.parseJSON(resp),
toReplace = document.getElementById(metaBoxData['replace-id']),
placeholder = document.createElement('div'),
wrap = document.createElement('div');
if ( ! metaBoxData['markup'] || ! toReplace )
return;
wrap.innerHTML = metaBoxData['markup'] ? metaBoxData['markup'] : '';
toReplace.parentNode.insertBefore( placeholder, toReplace );
placeholder.parentNode.removeChild( toReplace );
placeholder.parentNode.insertBefore( wrap, placeholder );
placeholder.parentNode.removeChild( placeholder );
}
);
return false;
}
});
},
eventOnClickEditLink : function(clickedEl) {
var settings, item,
matchedSection = /#(.*)$/.exec(clickedEl.href);
if ( matchedSection && matchedSection[1] ) {
settings = $('#'+matchedSection[1]);
item = settings.parent();
if( 0 != item.length ) {
if( item.hasClass('menu-item-edit-inactive') ) {
if( ! settings.data('menu-item-data') ) {
settings.data( 'menu-item-data', settings.getItemData() );
}
settings.slideDown('fast');
item.removeClass('menu-item-edit-inactive')
.addClass('menu-item-edit-active');
} else {
settings.slideUp('fast');
item.removeClass('menu-item-edit-active')
.addClass('menu-item-edit-inactive');
}
return false;
}
}
},
eventOnClickCancelLink : function(clickedEl) {
var settings = $( clickedEl ).closest( '.menu-item-settings' ),
thisMenuItem = $( clickedEl ).closest( '.menu-item' );
thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive');
settings.setItemData( settings.data('menu-item-data') ).hide();
return false;
},
eventOnClickMenuSave : function(clickedEl) {
var locs = '',
menuName = $('#menu-name'),
menuNameVal = menuName.val();
// Cancel and warn if invalid menu name
if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
menuName.parent().addClass('form-invalid');
return false;
}
// Copy menu theme locations
$('#nav-menu-theme-locations select').each(function() {
locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
});
$('#update-nav-menu').append( locs );
// Update menu item position data
api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
window.onbeforeunload = null;
return true;
},
eventOnClickMenuDelete : function(clickedEl) {
// Delete warning AYS
if ( confirm( navMenuL10n.warnDeleteMenu ) ) {
window.onbeforeunload = null;
return true;
}
return false;
},
eventOnClickMenuItemDelete : function(clickedEl) {
var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
api.removeMenuItem( $('#menu-item-' + itemID) );
api.registerChange();
return false;
},
/**
* Process the quick search response into a search result
*
* @param string resp The server response to the query.
* @param object req The request arguments.
* @param jQuery panel The tabs panel we're searching in.
*/
processQuickSearchQueryResponse : function(resp, req, panel) {
var matched, newID,
takenIDs = {},
form = document.getElementById('nav-menu-meta'),
pattern = new RegExp('menu-item\\[(\[^\\]\]*)', 'g'),
$items = $('<div>').html(resp).find('li'),
$item;
if( ! $items.length ) {
$('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
$('.spinner', panel).hide();
return;
}
$items.each(function(){
$item = $(this);
// make a unique DB ID number
matched = pattern.exec($item.html());
if ( matched && matched[1] ) {
newID = matched[1];
while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
newID--;
}
takenIDs[newID] = true;
if ( newID != matched[1] ) {
$item.html( $item.html().replace(new RegExp(
'menu-item\\[' + matched[1] + '\\]', 'g'),
'menu-item[' + newID + ']'
) );
}
}
});
$('.categorychecklist', panel).html( $items );
$('.spinner', panel).hide();
},
removeMenuItem : function(el) {
var children = el.childMenuItems();
el.addClass('deleting').animate({
opacity : 0,
height: 0
}, 350, function() {
var ins = $('#menu-instructions');
el.remove();
children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
if( 0 == $( '#menu-to-edit li' ).length ) {
$( '.drag-instructions' ).hide();
ins.removeClass( 'menu-instructions-inactive' );
}
});
},
depthToPx : function(depth) {
return depth * api.options.menuItemDepthPerLevel;
},
pxToDepth : function(px) {
return Math.floor(px / api.options.menuItemDepthPerLevel);
}
};
$(document).ready(function(){ wpNavMenu.init(); });
})(jQuery);
| {
"content_hash": "c4109829b995af9706d86bddb648742e",
"timestamp": "",
"source": "github",
"line_count": 1182,
"max_line_length": 249,
"avg_line_length": 32.39593908629442,
"alnum_prop": 0.6047216128695289,
"repo_name": "mvaldetaro/DesignKamikaze",
"id": "ee829da826dca0b59efd67779995aa49374caaa6",
"size": "38292",
"binary": false,
"copies": "19",
"ref": "refs/heads/master",
"path": "wp-admin/js/nav-menu.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
@interface ViewController () {
NSArray *titles1;
NSArray *titles2;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
titles1 = @[@"Cat", @"Bird", @"Dog"];
titles2 = @[@"NO", @"YES"];
osc1.delegate = self;
osc2.delegate = self;
}
#pragma mark - Switch Delegate
- (NSArray *)titlesInSwitch:(OSwitch *)switchView {
if (switchView == osc1) {
return titles1;
}
if (switchView == osc2) {
return titles2;
}
return nil;
}
- (void)switchView:(OSwitch *)switchView valueDidChangeAtIndex:(NSUInteger)index {
NSLog(@"Selected %@", [switchView getTitleForIndexAt:index]);
}
@end
| {
"content_hash": "9df3994a0af1e43cecfea82c9e64cd32",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 82,
"avg_line_length": 21.70967741935484,
"alnum_prop": 0.6225854383358098,
"repo_name": "OyaSaid/OSwitch",
"id": "2a02f73de28c53b938d5cc966db7c37bac15e017",
"size": "861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/OSwitchExample/ViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "26155"
},
{
"name": "Ruby",
"bytes": "587"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using AppKit;
using CoreGraphics;
using Foundation;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class PopoverBackend : IPopoverBackend
{
public Popover Frontend { get; private set; }
public ApplicationContext ApplicationContext { get; set; }
public IPopoverEventSink EventSink { get; set; }
internal bool EnableCloseEvent { get; private set; }
NSPopover popover;
FactoryViewController controller;
class FactoryViewController : NSViewController, INSPopoverDelegate
{
// Always retain the object in a cache until it closes. This
// guarantees that neither the NSPopover nor the native FactoryViewController
// can be GC'ed until after it has closed.
static readonly HashSet<FactoryViewController> Cache = new HashSet<FactoryViewController> ();
public Widget Child { get; private set; }
public PopoverBackend Backend { get; private set; }
public CGColor BackgroundColor { get; set; }
public ViewBackend ChildBackend { get; private set; }
public NSView NativeChild { get { return ChildBackend?.Widget; } }
bool shown;
NSPopover parent;
public FactoryViewController (PopoverBackend backend, Widget child, NSPopover parentPopover) : base (null, null)
{
Child = child;
ChildBackend = Toolkit.GetBackend (Child) as ViewBackend;
Backend = backend;
parent = parentPopover;
Cache.Add (this);
}
public string EffectiveAppearanceName { get; set; }
public override void LoadView ()
{
View = new ContainerView (this);
string appearance = EffectiveAppearanceName;
NativeChild.RemoveFromSuperview ();
View.AddSubview (NativeChild);
if (!string.IsNullOrEmpty(appearance) && appearance.IndexOf ("Dark", StringComparison.Ordinal) >= 0)
View.Appearance = NSAppearance.GetAppearance (MacSystemInformation.OsVersion < MacSystemInformation.Mojave ? NSAppearance.NameVibrantDark : new NSString("NSAppearanceNameDarkAqua"));
else
View.Appearance = NSAppearance.GetAppearance (NSAppearance.NameAqua);
WidgetSpacing padding = 0;
if (Backend != null)
padding = Backend.Frontend.Padding;
View.AddConstraints (new NSLayoutConstraint [] {
NSLayoutConstraint.Create (NativeChild, NSLayoutAttribute.Left, NSLayoutRelation.Equal, View, NSLayoutAttribute.Left, 1, (nfloat)padding.Left),
NSLayoutConstraint.Create (NativeChild, NSLayoutAttribute.Right, NSLayoutRelation.Equal, View, NSLayoutAttribute.Right, 1, -(nfloat)padding.Right),
NSLayoutConstraint.Create (NativeChild, NSLayoutAttribute.Top, NSLayoutRelation.Equal, View, NSLayoutAttribute.Top, 1, (nfloat)padding.Top),
NSLayoutConstraint.Create (NativeChild, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1, -(nfloat)padding.Bottom),
});
}
class ContainerView : NSView
{
FactoryViewController controller;
public ContainerView (FactoryViewController controller)
{
this.controller = controller;
}
public override bool AllowsVibrancy {
get {
// disable vibrancy for custom background
return controller.BackgroundColor == null ? base.AllowsVibrancy : false;
}
}
}
[Export ("popoverWillShow:")]
public void WillShow (NSNotification notification)
{
if (parent != notification.Object)
return;
ChildBackend.SetAutosizeMode (true);
Child.Surface.Reallocate ();
if (BackgroundColor != null) {
if (View.Window.ContentView.Superview.Layer == null)
View.Window.ContentView.Superview.WantsLayer = true;
View.Window.ContentView.Superview.Layer.BackgroundColor = BackgroundColor;
}
WidgetSpacing padding = 0;
if (Backend != null)
padding = Backend.Frontend.Padding;
NativeChild.SetFrameOrigin (new CGPoint ((nfloat)padding.Left, (nfloat)padding.Top));
shown = true;
}
[Export ("popoverDidClose:")]
public virtual void DidClose (NSNotification notification)
{
// verify that this is called for the parent popover
// without being disposed
if (parent != notification.Object)
return;
Dispose ();
}
protected override void Dispose (bool disposing)
{
if (disposing)
RemoveChild ();
if (parent != null) {
Cache.Remove (this);
parent = null;
if (Backend?.EnableCloseEvent == true && shown)
Backend.ApplicationContext.InvokeUserCode (Backend.EventSink.OnClosed);
}
shown = false;
base.Dispose (disposing);
}
void RemoveChild ()
{
if (Child != null) {
NativeChild.RemoveFromSuperview ();
NativeChild.SetFrameOrigin (new CGPoint (0, 0));
ChildBackend.SetAutosizeMode (false);
Child = null;
ChildBackend = null;
}
}
}
CGColor backgroundColor;
public Color BackgroundColor {
get {
return (backgroundColor ?? NSColor.WindowBackground.CGColor).ToXwtColor ();
}
set {
backgroundColor = value.ToCGColor ();
}
}
public void Initialize (IPopoverEventSink sink)
{
EventSink = sink;
}
public void InitializeBackend (object frontend, ApplicationContext context)
{
ApplicationContext = context;
Frontend = frontend as Popover;
}
public void EnableEvent (object eventId)
{
if (eventId is PopoverEvent) {
switch ((PopoverEvent)eventId) {
case PopoverEvent.Closed:
EnableCloseEvent = true;
break;
}
}
}
public void DisableEvent (object eventId)
{
if (eventId is PopoverEvent) {
switch ((PopoverEvent)eventId) {
case PopoverEvent.Closed:
EnableCloseEvent = false;
break;
}
}
}
public void Show (Popover.Position orientation, Widget referenceWidget, Rectangle positionRect, Widget child)
{
var refBackend = Toolkit.GetBackend (referenceWidget) as IWidgetBackend;
NSView refView = (refBackend as EmbedNativeWidgetBackend)?.EmbeddedView;
if (refView == null)
refView = (refBackend as ViewBackend)?.Widget;
if (refView == null) {
if (referenceWidget.Surface.ToolkitEngine.Type == ToolkitType.Gtk) {
try {
refView = GtkQuartz.GetView (refBackend.NativeWidget);
var rLocation = refView.ConvertRectToView (refView.Frame, null).Location.ToXwtPoint ();
if (referenceWidget.WindowBounds.Location != rLocation) {
positionRect.X += referenceWidget.WindowBounds.Location.X - rLocation.X;
positionRect.Y += referenceWidget.WindowBounds.Location.Y - rLocation.Y;
}
} catch (Exception ex) {
throw new ArgumentException ("Widget belongs to an unsupported Toolkit", nameof (referenceWidget), ex);
}
} else if (referenceWidget.Surface.ToolkitEngine != ApplicationContext.Toolkit)
throw new ArgumentException ("Widget belongs to an unsupported Toolkit", nameof (referenceWidget));
}
// If the rect is empty, the coordinates of the rect will be ignored.
// Set the width and height, for the positioning to function correctly.
if (Math.Abs (positionRect.Width) < double.Epsilon)
positionRect.Width = referenceWidget.Size.Width;
if (Math.Abs (positionRect.Height) < double.Epsilon)
positionRect.Height = referenceWidget.Size.Height;
DestroyPopover ();
popover = new NSAppearanceCustomizationPopover {
Behavior = NSPopoverBehavior.Transient
};
controller = new FactoryViewController (this, child, popover) { BackgroundColor = backgroundColor };
popover.ContentViewController = controller;
popover.Delegate = controller;
// if the reference has a custom appearance, use it for the popover
if (refView.EffectiveAppearance.Name != NSAppearance.NameAqua) {
controller.EffectiveAppearanceName = refView.EffectiveAppearance.Name;
if (popover is INSAppearanceCustomization)
((INSAppearanceCustomization)popover).SetAppearance (refView.EffectiveAppearance);
}
popover.Show (positionRect.ToCGRect (),
refView,
ToRectEdge (orientation));
}
public void Hide ()
{
DestroyPopover ();
}
public void Dispose ()
{
DestroyPopover ();
}
void DestroyPopover ()
{
if (popover != null) {
popover.Close ();
popover.Dispose ();
popover = null;
}
if (controller != null) {
controller.Dispose ();
controller = null;
}
}
public static NSRectEdge ToRectEdge (Popover.Position pos)
{
switch (pos) {
case Popover.Position.Top:
return NSRectEdge.MaxYEdge;
default:
return NSRectEdge.MinYEdge;
}
}
public class NSAppearanceCustomizationPopover : NSPopover, INSAppearanceCustomization
{
public NSAppearanceCustomizationPopover ()
{ }
protected NSAppearanceCustomizationPopover (IntPtr handle) : base (handle)
{ }
}
}
}
| {
"content_hash": "5c0814321888d7d6cdb641e2d8799667",
"timestamp": "",
"source": "github",
"line_count": 285,
"max_line_length": 187,
"avg_line_length": 30.603508771929825,
"alnum_prop": 0.7071772529236414,
"repo_name": "antmicro/xwt",
"id": "ea95fab3bbff22de473ab85a287ab84512f5a4a3",
"size": "9975",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Xwt.XamMac/Xwt.Mac/PopoverBackend.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3816738"
},
{
"name": "Makefile",
"bytes": "245"
}
],
"symlink_target": ""
} |
/**
* Created by Oleg Galaburda on 11.01.2015.
*/
/**
* @namespace aw.utils
*/
aw.utils = aw.utils || {};
/**
* @type {$timeout}
*/
var $timeout = angular.injector(['ng']).get('$timeout');
/**
* @class aw.utils.ValidationHandler
* @param handler
* @param timeout
* @constructor
*/
function ValidationHandler(handler, timeout) {
/**
* @property
* @name aw.utils.ValidationHandler#handler
* @type {Function}
* @instance
*/
this.handler = handler;
/**
* @property
* @name aw.utils.ValidationHandler#target
* @type {Object}
* @instance
*/
this.target = null;
/**
* @property
* @name aw.utils.ValidationHandler#timeout
* @type {number}
* @instance
*/
this.timeout = timeout || ValidationHandler.DEFAULT_TIMEOUT;
/**
* @type {Number}
* @private
*/
var timeoutId = NaN;
var callHandler = function (target, args) {
timeoutId = NaN;
this.handler.apply(this.target, arguments);
};
/**
* @function
* @name aw.utils.ValidationHandler#call
* @param {*} [rest]
* @instance
*/
this.call = function ValidationHandler_call(rest) {
this.prevent();
timeoutId = setTimeout(callHandler, timeout, this.target, arguments);
};
/**
* @function
* @name aw.utils.ValidationHandler#apply
* @param {Array} [args]
* @param {Object} [target]
* @instance
*/
this.apply = function ValidationHandler_apply(args, target) {
this.prevent();
timeoutId = setTimeout(callHandler, timeout, this.target, args || []);
};
/**
* @function
* @name aw.utils.ValidationHandler#callImmediately
* @param {*} [rest]
* @instance
*/
this.callImmediately = function ValidationHandler_callImmediately(rest) {
this.prevent();
callHandler(this.target, arguments);
};
/**
* @function
* @name aw.utils.ValidationHandler#applyImmediately
* @param {Array} [args]
* @param {Object} [target]
* @instance
*/
this.applyImmediately = function ValidationHandler_applyImmediately(args, target) {
this.prevent();
callHandler(this.target, args || []);
};
/**
* @function
* @name aw.utils.ValidationHandler#isAvailable
* @returns {boolean}
* @instance
*/
this.isAvailable = function ValidationHandler_isAvailable() {
return typeof(handler) === "function";
};
/**
* @function
* @name aw.utils.ValidationHandler#isRunning
* @returns {boolean}
* @instance
*/
this.isRunning = function ValidationHandler_isRunning() {
return !isNaN(timeoutId);
};
/**
* @function
* @name aw.utils.ValidationHandler#prevent
* @instance
*/
this.prevent = function ValidationHandler_prevent() {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = NaN;
}
};
/**
* @function
* @name aw.utils.ValidationHandler#clear
* @instance
*/
this.clear = function ValidationHandler_clear() {
this.prevent();
this.handler = null;
this.target = null;
};
// initialization
//FIXME should API be bound to each instance?
this.call = (this.call).bind(this);
this.apply = (this.apply).bind(this);
this.callImmediately = (this.callImmediately).bind(this);
this.applyImmediately = (this.applyImmediately).bind(this);
callHandler = (callHandler).bind(this);
}
/**
* @property
* @name aw.utils.ValidationHandler.DEFAULT_TIMEOUT
* @type {number}
* @static
*/
ValidationHandler.DEFAULT_TIMEOUT = 25;
/**
* @function
* @name aw.utils.ValidationHandler.create
* @param {Function} handler
* @param {number} [timeout]
* @param {Object} [target]
* @returns {aw.utils.ValidationHandler}
* @static
*/
ValidationHandler.create = function (handler, timeout, target) {
var result = new ValidationHandler(handler, timeout);
if (target) result.target = target;
return result;
};
aw.utils.ValidationHandler = ValidationHandler; | {
"content_hash": "e0637229668a80edc99587b71bcc2d22",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 85,
"avg_line_length": 25.06832298136646,
"alnum_prop": 0.617195242814668,
"repo_name": "burdiuz/angular-components-api",
"id": "852eb47cd14f97179ee67811836468ac3401bb98",
"size": "4036",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/events/validationhandler.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2863"
},
{
"name": "JavaScript",
"bytes": "83846"
}
],
"symlink_target": ""
} |
var _ = require('lodash'),
fs = require('fs'),
Handlebars = require('handlebars'),
template = Handlebars.compile(fs.readFileSync('templates/api-functions.html', 'utf8')),
final = require('./api_functions/contexts/final.js'),
top = require('./api_functions/contexts/top.js'),
other = require('./api_functions/contexts/other.js');
fs.writeFileSync('./_includes/final_functions.html', template({contexts: final}));
fs.writeFileSync('./_includes/top_functions.html', template({contexts: top}));
fs.writeFileSync('./_includes/other_functions.html', template({contexts: other}));
| {
"content_hash": "63d12141e0d89780fd25e7d2bed33545",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 91,
"avg_line_length": 54.45454545454545,
"alnum_prop": 0.6961602671118531,
"repo_name": "5outh/nanoscope-site",
"id": "d2e061adedb3f78f2837b7956234dd0fda18beda",
"size": "599",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gen_functions.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8036"
},
{
"name": "JavaScript",
"bytes": "13880"
},
{
"name": "Ruby",
"bytes": "650"
}
],
"symlink_target": ""
} |
import FaQuestion from 'react-icons/lib/fa/question'
export default FaQuestion
| {
"content_hash": "66e760683c8367efa9c0d2a84ec1a42b",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 52,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.825,
"repo_name": "VegaPublish/vega-studio",
"id": "3b1faca7ca785369a7c925f35e8703851ed44a2f",
"size": "80",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/@lyra/base/src/components/icons/Question.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34288"
},
{
"name": "JavaScript",
"bytes": "224534"
}
],
"symlink_target": ""
} |
FROM balenalib/jetson-tx2-nx-devkit-debian:bullseye-build
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu67 \
libssl1.1 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core SDK
ENV DOTNET_SDK_VERSION 3.1.415
RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Sdk/$DOTNET_SDK_VERSION/dotnet-sdk-$DOTNET_SDK_VERSION-linux-arm64.tar.gz" \
&& dotnet_sha512='7a5b9922988bcbde63d39f97e283ca1d373d5521cca0ab8946e2f86deaef6e21f00244228a0d5d8c38c2b9634b38bc7338b61984f0e12dd8fdb8b2e6eed5dd34' \
&& echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf dotnet.tar.gz -C /usr/share/dotnet \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
# Enable correct mode for dotnet watch (only mode supported in a container)
ENV DOTNET_USE_POLLING_FILE_WATCHER=true \
# Skip extraction of XML docs - generally not useful within an image/container - helps performance
NUGET_XMLDOC_MODE=skip \
DOTNET_NOLOGO=true
# Trigger first run experience by running arbitrary cmd to populate local package cache
RUN dotnet help
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/44e597e40f2010cdde15b3ba1e397aea3a5c5271/scripts/assets/tests/test-stack@dotnet.sh" \
&& echo "Running test-stack@dotnet" \
&& chmod +x test-stack@dotnet.sh \
&& bash test-stack@dotnet.sh \
&& rm -rf test-stack@dotnet.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bullseye \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 3.1-sdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "893d763aad1a300294844f42772ae437",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 680,
"avg_line_length": 51.92857142857143,
"alnum_prop": 0.7111416781292985,
"repo_name": "resin-io-library/base-images",
"id": "696910d088e35cb9f9d21a4c220b8966d3d75c82",
"size": "2929",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/dotnet/jetson-tx2-nx-devkit/debian/bullseye/3.1-sdk/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
package com.google.gapid.views;
import static com.google.gapid.util.Arrays.last;
import static com.google.gapid.util.Colors.BLACK;
import static com.google.gapid.util.Colors.DARK_LUMINANCE_THRESHOLD;
import static com.google.gapid.util.Colors.WHITE;
import static com.google.gapid.util.Colors.getLuminance;
import static com.google.gapid.util.Colors.rgb;
import static com.google.gapid.util.Loadable.MessageType.Error;
import static com.google.gapid.util.Loadable.MessageType.Info;
import static com.google.gapid.widgets.Widgets.createComposite;
import static com.google.gapid.widgets.Widgets.createGroup;
import static com.google.gapid.widgets.Widgets.createStandardTabFolder;
import static com.google.gapid.widgets.Widgets.createStandardTabItem;
import static com.google.gapid.widgets.Widgets.createTableViewer;
import static com.google.gapid.widgets.Widgets.createTreeColumn;
import static com.google.gapid.widgets.Widgets.createTreeViewer;
import static com.google.gapid.widgets.Widgets.disposeAllChildren;
import static com.google.gapid.widgets.Widgets.packColumns;
import static com.google.gapid.widgets.Widgets.scheduleIfNotDisposed;
import static com.google.gapid.widgets.Widgets.sorting;
import static java.util.logging.Level.FINE;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.UnsignedLongs;
import com.google.gapid.lang.glsl.GlslSourceConfiguration;
import com.google.gapid.models.Analytics.View;
import com.google.gapid.models.Capture;
import com.google.gapid.models.CommandStream;
import com.google.gapid.models.CommandStream.CommandIndex;
import com.google.gapid.models.Models;
import com.google.gapid.models.Resources;
import com.google.gapid.models.Settings;
import com.google.gapid.proto.core.pod.Pod;
import com.google.gapid.proto.service.Service;
import com.google.gapid.proto.service.Service.ClientAction;
import com.google.gapid.proto.service.api.API;
import com.google.gapid.rpc.Rpc;
import com.google.gapid.rpc.RpcException;
import com.google.gapid.rpc.SingleInFlight;
import com.google.gapid.rpc.UiCallback;
import com.google.gapid.util.Events;
import com.google.gapid.util.Loadable;
import com.google.gapid.util.Messages;
import com.google.gapid.util.ProtoDebugTextFormat;
import com.google.gapid.widgets.LoadablePanel;
import com.google.gapid.widgets.SearchBox;
import com.google.gapid.widgets.Theme;
import com.google.gapid.widgets.Widgets;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TreeItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* View allowing the inspection and editing of the shader resources.
*/
public class ShaderView extends Composite
implements Tab, Capture.Listener, CommandStream.Listener, Resources.Listener {
protected static final Logger LOG = Logger.getLogger(ShaderView.class.getName());
protected final Models models;
private final Widgets widgets;
private final SingleInFlight shaderRpcController = new SingleInFlight();
private final SingleInFlight programRpcController = new SingleInFlight();
private final LoadablePanel<Composite> loading;
private boolean uiBuiltWithPrograms;
public ShaderView(Composite parent, Models models, Widgets widgets) {
super(parent, SWT.NONE);
this.models = models;
this.widgets = widgets;
setLayout(new FillLayout());
loading = LoadablePanel.create(this, widgets,
panel -> createComposite(panel, new FillLayout(SWT.VERTICAL)));
updateUi(true);
models.capture.addListener(this);
models.commands.addListener(this);
models.resources.addListener(this);
addListener(SWT.Dispose, e -> {
models.capture.removeListener(this);
models.commands.removeListener(this);
models.resources.removeListener(this);
});
}
private Control createShaderTab(Composite parent) {
ShaderPanel panel = new ShaderPanel(parent, models, widgets.theme, Type.shader((data, src) -> {
API.Shader shader = (data == null) ? null : (API.Shader)data.resource;
if (shader != null) {
models.analytics.postInteraction(View.Shaders, ClientAction.Edit);
models.resources.updateResource(data.info, API.ResourceData.newBuilder()
.setShader(shader.toBuilder()
.setSource(src))
.build());
}
}));
panel.addListener(SWT.Selection, e -> {
models.analytics.postInteraction(View.Shaders, ClientAction.SelectShader);
getShaderSource((Data)e.data, panel::setSource);
});
return panel;
}
private Control createProgramTab(Composite parent) {
SashForm splitter = new SashForm(parent, SWT.VERTICAL);
ShaderPanel panel = new ShaderPanel(splitter, models, widgets.theme, Type.program());
Composite uniformsGroup = createGroup(splitter, "Uniforms");
UniformsPanel uniforms = new UniformsPanel(uniformsGroup);
splitter.setWeights(models.settings.getSplitterWeights(Settings.SplitterWeights.Uniforms));
panel.addListener(SWT.Selection, e -> {
models.analytics.postInteraction(View.Shaders, ClientAction.SelectProgram);
getProgramSource((Data)e.data, program ->
scheduleIfNotDisposed(uniforms, () -> uniforms.setUniforms(program)), panel::setSource);
});
splitter.addListener(SWT.Dispose, e ->
models.settings.setSplitterWeights(Settings.SplitterWeights.Uniforms, splitter.getWeights()));
return splitter;
}
private void getShaderSource(Data data, Consumer<ShaderPanel.Source[]> callback) {
shaderRpcController.start().listen(models.resources.loadResource(data.info),
new UiCallback<API.ResourceData, ShaderPanel.Source>(this, LOG) {
@Override
protected ShaderPanel.Source onRpcThread(Rpc.Result<API.ResourceData> result)
throws RpcException, ExecutionException {
API.Shader shader = result.get().getShader();
data.resource = shader;
return ShaderPanel.Source.of(shader);
}
@Override
protected void onUiThread(ShaderPanel.Source result) {
callback.accept(new ShaderPanel.Source[] { result });
}
});
}
private void getProgramSource(
Data data, Consumer<API.Program> onProgramLoaded, Consumer<ShaderPanel.Source[]> callback) {
programRpcController.start().listen(models.resources.loadResource(data.info),
new UiCallback<API.ResourceData, ShaderPanel.Source[]>(this, LOG) {
@Override
protected ShaderPanel.Source[] onRpcThread(Rpc.Result<API.ResourceData> result)
throws RpcException, ExecutionException {
API.Program program = result.get().getProgram();
data.resource = program;
onProgramLoaded.accept(program);
return ShaderPanel.Source.of(program);
}
@Override
protected void onUiThread(ShaderPanel.Source[] result) {
callback.accept(result);
}
});
}
@Override
public Control getControl() {
return this;
}
@Override
public void reinitialize() {
onCaptureLoadingStart(false);
updateUi(false);
updateLoading();
}
@Override
public void onCaptureLoadingStart(boolean maintainState) {
loading.showMessage(Info, Messages.LOADING_CAPTURE);
}
@Override
public void onCaptureLoaded(Loadable.Message error) {
if (error != null) {
loading.showMessage(Error, Messages.CAPTURE_LOAD_FAILURE);
}
}
@Override
public void onCommandsLoaded() {
if (!models.commands.isLoaded()) {
loading.showMessage(Info, Messages.CAPTURE_LOAD_FAILURE);
} else {
updateLoading();
}
}
@Override
public void onCommandsSelected(CommandIndex path) {
updateLoading();
}
@Override
public void onResourcesLoaded() {
if (!models.resources.isLoaded()) {
loading.showMessage(Info, Messages.CAPTURE_LOAD_FAILURE);
} else {
updateUi(false);
updateLoading();
}
}
private void updateLoading() {
if (models.commands.isLoaded() && models.resources.isLoaded()) {
if (models.commands.getSelectedCommands() == null) {
loading.showMessage(Info, Messages.SELECT_COMMAND);
} else {
loading.stopLoading();
}
}
}
private void updateUi(boolean force) {
boolean hasPrograms = true;
if (models.resources.isLoaded()) {
hasPrograms = models.resources.getResources().stream()
.filter(r -> r.getType() == API.ResourceType.ProgramResource)
.findAny()
.isPresent();
} else if (!force) {
return;
}
if (force || hasPrograms != uiBuiltWithPrograms) {
LOG.log(FINE, "(Re-)creating the shader UI, force: {0}, programs: {1}",
new Object[] { force, hasPrograms });
uiBuiltWithPrograms = hasPrograms;
disposeAllChildren(loading.getContents());
if (hasPrograms) {
TabFolder folder = createStandardTabFolder(loading.getContents());
createStandardTabItem(folder, "Shaders", createShaderTab(folder));
createStandardTabItem(folder, "Programs", createProgramTab(folder));
} else {
createShaderTab(loading.getContents());
}
loading.getContents().requestLayout();
}
}
/**
* Panel displaying the source code of a shader or program.
*/
private static class ShaderPanel extends Composite
implements Resources.Listener, CommandStream.Listener {
private final Models models;
private final Theme theme;
protected final Type type;
private final TreeViewer shaderViewer;
private final Composite sourceComposite;
private final Button pushButton;
private final ViewerFilter currentContextFilter;
private ViewerFilter keywordSearchFilter;
private SourceViewer shaderSourceViewer;
private boolean lastUpdateContainedAllShaders = false;
private List<Data> shaders = Collections.emptyList();
public ShaderPanel(Composite parent, Models models, Theme theme, Type type) {
super(parent, SWT.NONE);
this.models = models;
this.theme = theme;
this.type = type;
setLayout(new FillLayout(SWT.HORIZONTAL));
SashForm splitter = new SashForm(this, SWT.HORIZONTAL);
Composite treeViewerContainer= createComposite(splitter, new GridLayout(1, false), SWT.BORDER);
Composite sourcesContainer = createComposite(splitter, new GridLayout(1, false));
if (type.type == API.ResourceType.ShaderResource) {
splitter.setWeights(models.settings.getSplitterWeights(Settings.SplitterWeights.Shaders));
splitter.addListener(SWT.Dispose, e -> models.settings.setSplitterWeights(
Settings.SplitterWeights.Shaders, splitter.getWeights()));
} else if (type.type == API.ResourceType.ProgramResource) {
splitter.setWeights(models.settings.getSplitterWeights(Settings.SplitterWeights.Programs));
splitter.addListener(SWT.Dispose, e -> models.settings.setSplitterWeights(
Settings.SplitterWeights.Programs, splitter.getWeights()));
}
SearchBox searchBox = new SearchBox(treeViewerContainer, true, theme);
searchBox.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
searchBox.addListener(Events.Search, e -> updateSearchFilter(e.text, (e.detail & Events.REGEX) != 0));
currentContextFilter = createCurrentContextFilter(models);
MenuItem contextFilterSelector = new MenuItem(searchBox.getNestedMenu(), SWT.CHECK);
contextFilterSelector.setText("Include all contexts");
contextFilterSelector.addListener(SWT.Selection, e -> updateContextFilter(contextFilterSelector.getSelection()));
contextFilterSelector.setSelection(true);
shaderViewer = createShaderSelector(treeViewerContainer);
shaderViewer.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
updateContextFilter(contextFilterSelector.getSelection());
sourceComposite = createComposite(sourcesContainer, new FillLayout(SWT.VERTICAL));
sourceComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
if (type.isEditable()) {
pushButton = Widgets.createButton(sourcesContainer, "Push Changes",
e -> type.updateShader(
(Data)getLastSelection().getData(),
shaderSourceViewer.getDocument().get()));
pushButton.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, false, false));
pushButton.setEnabled(false);
} else {
pushButton = null;
}
models.commands.addListener(this);
models.resources.addListener(this);
addListener(SWT.Dispose, e -> {
models.commands.removeListener(this);
models.resources.removeListener(this);
});
updateShaders();
}
private TreeViewer createShaderSelector(Composite parent) {
TreeViewer treeViewer = createTreeViewer(parent, SWT.FILL);
treeViewer.getTree().setHeaderVisible(true);
treeViewer.setContentProvider(createShaderContentProvider());
treeViewer.setLabelProvider(new LabelProvider());
treeViewer.getControl().addListener(SWT.Selection, e -> updateSelection());
sorting(treeViewer,
createTreeColumn(treeViewer, "ID", Data::getId,
(d1, d2) -> UnsignedLongs.compare(d1.getSortId(), d2.getSortId())),
createTreeColumn(treeViewer, "Label", Data::getLabel,
Comparator.comparing(Data::getLabel)));
return treeViewer;
}
private static ITreeContentProvider createShaderContentProvider() {
return new ITreeContentProvider() {
@SuppressWarnings("unchecked")
@Override
public Object[] getElements(Object inputElement) {
return ((List<Data>) inputElement).toArray();
}
@Override
public boolean hasChildren(Object element) {
return false;
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public Object[] getChildren(Object element) {
return null;
}
};
}
private static ViewerFilter createSearchFilter(Pattern pattern) {
return new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return !(element instanceof Data) ||
pattern.matcher(((Data)element).toString()).find();
}
};
}
private static ViewerFilter createCurrentContextFilter(Models models) {
return new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return models.contexts.getSelectedContext().matches(((Data)element).info.getContext());
}
};
}
private SourceViewer createSourcePanel(Composite parent, Source source) {
Group group = createGroup(parent, source.label);
SourceViewer viewer =
new SourceViewer(group, null, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
StyledText textWidget = viewer.getTextWidget();
viewer.setEditable(type.isEditable());
textWidget.setFont(theme.monoSpaceFont());
textWidget.setKeyBinding(ST.SELECT_ALL, ST.SELECT_ALL);
viewer.configure(new GlslSourceConfiguration(theme));
viewer.setDocument(GlslSourceConfiguration.createDocument(source.source));
textWidget.addListener(SWT.KeyDown, e -> {
if (isKey(e, SWT.MOD1, 'z')) {
viewer.doOperation(ITextOperationTarget.UNDO);
} else if (isKey(e, SWT.MOD1, 'y') || isKey(e, SWT.MOD1 | SWT.SHIFT, 'z')) {
viewer.doOperation(ITextOperationTarget.REDO);
}
});
return viewer;
}
private static boolean isKey(Event e, int stateMask, int keyCode) {
return (e.stateMask & stateMask) == stateMask && e.keyCode == keyCode;
}
public void clearSource() {
shaderSourceViewer = null;
disposeAllChildren(sourceComposite);
if (pushButton != null) {
pushButton.setEnabled(false);
}
}
public void setSource(Source[] sources) {
clearSource();
SashForm sourceSash = new SashForm(sourceComposite, SWT.VERTICAL);
for (Source source : sources) {
shaderSourceViewer = createSourcePanel(sourceSash, source);
}
sourceSash.requestLayout();
if (sources.length > 0 && pushButton != null) {
pushButton.setEnabled(true);
}
}
@Override
public void onResourcesLoaded() {
lastUpdateContainedAllShaders = false;
updateShaders();
}
@Override
public void onCommandsSelected(CommandIndex path) {
updateShaders();
}
private TreeItem getLastSelection() {
return last(shaderViewer.getTree().getSelection());
}
private void updateShaders() {
if (models.resources.isLoaded() && models.commands.getSelectedCommands() != null) {
Resources.ResourceList resources = models.resources.getResources(type.type);
// If we previously had created the dropdown with all the shaders and didn't skip any
// this time, the dropdown does not need to change.
if (!lastUpdateContainedAllShaders || !resources.complete) {
shaders = new ArrayList<Data>();
if (!resources.isEmpty()) {
resources.stream()
.map(r -> new Data(r.resource))
.forEach(shaders::add);
}
lastUpdateContainedAllShaders = resources.complete;
// Because TreeViewer will dispose old TreeItems after refresh,
// memorize and select with index, rather than object.
TreeItem selection = getLastSelection();
int selectionIndex = -1;
if (selection != null) {
selectionIndex = shaderViewer.getTree().indexOf(selection);
}
shaderViewer.setInput(shaders);
packColumns(shaderViewer.getTree());
if (selectionIndex >= 0 && selectionIndex < shaderViewer.getTree().getItemCount()) {
selection = shaderViewer.getTree().getItem(selectionIndex);
shaderViewer.getTree().setSelection(selection);
}
} else {
for (Data data : shaders) {
data.resource = null;
}
}
updateSelection();
}
}
private void updateSelection() {
if (shaderViewer.getTree().getSelectionCount() < 1) {
clearSource();
} else {
Event event = new Event();
event.data = getLastSelection().getData();
notifyListeners(SWT.Selection, event);
}
}
private void updateSearchFilter(String text, boolean isRegex) {
// Keyword Filter is dynamic.
// Remove the previous one each time to avoid filter accumulation.
if (keywordSearchFilter != null) {
shaderViewer.removeFilter(keywordSearchFilter);
}
if (!text.isEmpty()) {
Pattern pattern = SearchBox.getPattern(text, isRegex);
keywordSearchFilter = createSearchFilter(pattern);
shaderViewer.addFilter(keywordSearchFilter);
}
}
private void updateContextFilter(boolean hasAllContext) {
if (currentContextFilter != null) {
shaderViewer.removeFilter(currentContextFilter);
}
if (!hasAllContext) {
shaderViewer.addFilter(currentContextFilter);
}
}
public static class Source {
private static final Source EMPTY_PROGRAM = new Source("Program",
"// No shaders attached to this program at this point in the trace.");
private static final String EMPTY_SHADER =
"// No source attached to this shader at this point in the trace.";
public final String label;
public final String source;
public Source(String label, String source) {
this.label = label;
this.source = source;
}
public static Source of(API.Shader shader) {
return new Source(shader.getType() + " Shader",
shader.getSource().isEmpty() ? EMPTY_SHADER : shader.getSource());
}
public static Source[] of(API.Program program) {
if (program.getShadersCount() == 0) {
return new Source[] { EMPTY_PROGRAM };
}
Source[] source = new Source[program.getShadersCount()];
for (int i = 0; i < source.length; i++) {
source[i] = of(program.getShaders(i));
}
return source;
}
}
protected static interface UpdateShader {
public void updateShader(Data data, String newSource);
}
}
/**
* Panel displaying the uniforms of the current shader program.
*/
private static class UniformsPanel extends Composite {
private final TableViewer table;
private final Map<API.Uniform, Image> images = Maps.newIdentityHashMap();
public UniformsPanel(Composite parent) {
super(parent, SWT.NONE);
setLayout(new FillLayout(SWT.VERTICAL));
table = createTableViewer(
this, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
table.setContentProvider(new ArrayContentProvider());
Widgets.<API.Uniform>createTableColumn(table, "Location",
uniform -> String.valueOf(uniform.getUniformLocation()));
Widgets.<API.Uniform>createTableColumn(table, "Name", API.Uniform::getName);
Widgets.<API.Uniform>createTableColumn(table, "Type",
uniform -> String.valueOf(uniform.getType()));
Widgets.<API.Uniform>createTableColumn(table, "Format",
uniform -> String.valueOf(uniform.getFormat()));
Widgets.<API.Uniform>createTableColumn(table, "Value", uniform -> {
Pod.Value value = uniform.getValue().getPod(); // TODO
switch (uniform.getType()) {
case Int32: return String.valueOf(value.getSint32Array().getValList());
case Uint32: return String.valueOf(value.getUint32Array().getValList());
case Bool: return String.valueOf(value.getBoolArray().getValList());
case Float: return String.valueOf(value.getFloat32Array().getValList());
case Double: return String.valueOf(value.getFloat64Array().getValList());
default: return ProtoDebugTextFormat.shortDebugString(value);
}
},this::getImage);
packColumns(table.getTable());
addListener(SWT.Dispose, e -> clearImages());
}
public void setUniforms(API.Program program) {
List<API.Uniform> uniforms = Lists.newArrayList(program.getUniformsList());
Collections.sort(uniforms, (a, b) -> a.getUniformLocation() - b.getUniformLocation());
clearImages();
table.setInput(uniforms);
table.refresh();
packColumns(table.getTable());
table.getTable().requestLayout();
}
private Image getImage(API.Uniform uniform) {
if (!images.containsKey(uniform)) {
Image image = null;
Pod.Value value = uniform.getValue().getPod(); // TODO
switch (uniform.getType()) {
case Float: {
List<Float> values = value.getFloat32Array().getValList();
if ((values.size() == 3 || values.size() == 4) &&
isColorRange(values.get(0)) && isColorRange(values.get(1)) &&
isColorRange(values.get(2))) {
image = createImage(values.get(0), values.get(1), values.get(2));
}
break;
}
case Double: {
List<Double> values = value.getFloat64Array().getValList();
if ((values.size() == 3 || values.size() == 4) &&
isColorRange(values.get(0)) && isColorRange(values.get(1)) &&
isColorRange(values.get(2))) {
image = createImage(values.get(0), values.get(1), values.get(2));
}
break;
}
default:
// Not a color.
}
images.put(uniform, image);
}
return images.get(uniform);
}
private static boolean isColorRange(double v) {
return v >= 0 && v <= 1;
}
private Image createImage(double r, double g, double b) {
ImageData data = new ImageData(12, 12, 1, new PaletteData(
(getLuminance(r, g, b) < DARK_LUMINANCE_THRESHOLD) ? WHITE : BLACK, rgb(r, g, b)), 1,
new byte[] {
0, 0, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31,
127, -31, 127, -31, 0, 0
} /* Square of 1s with a border of 0s (and padding to 2 bytes per row) */);
return new Image(getDisplay(), data);
}
private void clearImages() {
for (Image image : images.values()) {
if (image != null) {
image.dispose();
}
}
images.clear();
}
}
/**
* Distinguishes between shaders and programs.
*/
private static class Type implements ShaderPanel.UpdateShader {
public final API.ResourceType type;
public final ShaderPanel.UpdateShader onSourceEdited;
public Type(API.ResourceType type, ShaderPanel.UpdateShader onSourceEdited) {
this.type = type;
this.onSourceEdited = onSourceEdited;
}
public static Type shader(ShaderPanel.UpdateShader onSourceEdited) {
return new Type(API.ResourceType.ShaderResource, onSourceEdited);
}
public static Type program() {
return new Type(API.ResourceType.ProgramResource, null);
}
@Override
public void updateShader(Data data, String newSource) {
onSourceEdited.updateShader(data, newSource);
}
public boolean isEditable() {
return onSourceEdited != null;
}
}
/**
* Shader or program data.
*/
private static class Data {
public final Service.Resource info;
public Object resource;
public Data(Service.Resource info) {
this.info = info;
}
public String getId() {
return info.getHandle();
}
public long getSortId() {
return info.getOrder();
}
public String getLabel() {
return info.getLabel();
}
}
}
| {
"content_hash": "38815d6a7a457d6c305816bba90c2f68",
"timestamp": "",
"source": "github",
"line_count": 745,
"max_line_length": 119,
"avg_line_length": 36.557046979865774,
"alnum_prop": 0.6786855149623646,
"repo_name": "pmuetschard/gapid",
"id": "53af3d32398b8611882e5664b3aed9a222b0badd",
"size": "27834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gapic/src/main/com/google/gapid/views/ShaderView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9501"
},
{
"name": "C",
"bytes": "78610"
},
{
"name": "C++",
"bytes": "1717083"
},
{
"name": "CSS",
"bytes": "1154"
},
{
"name": "GLSL",
"bytes": "31717"
},
{
"name": "Go",
"bytes": "6832703"
},
{
"name": "HTML",
"bytes": "128593"
},
{
"name": "Java",
"bytes": "1916916"
},
{
"name": "JavaScript",
"bytes": "31051"
},
{
"name": "Objective-C",
"bytes": "1203969"
},
{
"name": "Objective-C++",
"bytes": "12784"
},
{
"name": "Python",
"bytes": "541041"
},
{
"name": "Shell",
"bytes": "30401"
},
{
"name": "Smarty",
"bytes": "3202"
}
],
"symlink_target": ""
} |
# This package is no longer maintained.
# npm-scripts-watcher
[](https://www.npmjs.com/package/npm-scripts-watcher)
Globbing file watcher to automatically run npm scripts from package.json when files change, with pretty colors.

## Usage
First install it as a devDependency:
```
npm i -D npm-scripts-watcher
```
Add a top-level `watch` config to your package.json and a `watch` script to your `scripts`:
```json
{
"scripts": {
"test": "mocha",
"watch": "npm-scripts-watcher"
},
"watch": {
"{src,test}/**/*.js": ["test"]
}
}
```
Keys in the `watch` object should be [globs](https://www.npmjs.com/package/glob) and values should be an array of script
names as specified in `scripts`.
Now you can start the file watcher using `npm run watch`.
| {
"content_hash": "a01a3f90e847b7f5c8bccd6b64876516",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 121,
"avg_line_length": 25.72222222222222,
"alnum_prop": 0.6997840172786177,
"repo_name": "wehkamp/npm-scripts-watcher",
"id": "ddd4c55716a3108803f682b42f780a36856240e0",
"size": "926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "1359"
}
],
"symlink_target": ""
} |
import $ from "jquery";
export default function() {
const creditsTemplate = $('#credits-template').html();
const creditsSelect = $('table').eq(1);
creditsSelect.before(creditsTemplate);
}
| {
"content_hash": "842ed720d5e1192e838c4494d5db60f3",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 58,
"avg_line_length": 28.714285714285715,
"alnum_prop": 0.6766169154228856,
"repo_name": "IronCountySchoolDistrict/graduation-progress",
"id": "2c2e51fea25e9c94260ccb59450dd66753b5eef3",
"size": "201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/scripts/graduation-progress/js/gradprogress.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "291"
}
],
"symlink_target": ""
} |
package org.apache.catalina.loader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.http.fileupload.FileUtils;
public class TestWebappClassLoaderWeaving extends TomcatBaseTest {
private static final String PACKAGE_PREFIX = "org/apache/catalina/loader";
private static String WEBAPP_DOC_BASE;
@BeforeClass
public static void setUpClass() throws Exception {
WEBAPP_DOC_BASE = System.getProperty("java.io.tmpdir") + "/TestWebappClassLoaderWeaving";
File classes = new File(WEBAPP_DOC_BASE + "/WEB-INF/classes/" + PACKAGE_PREFIX);
classes.mkdirs();
copyResource(PACKAGE_PREFIX + "/TesterNeverWeavedClass.class",
new File(classes, "TesterNeverWeavedClass.class"));
copyResource(PACKAGE_PREFIX + "/TesterUnweavedClass.class",
new File(classes, "TesterUnweavedClass.class"));
}
@AfterClass
public static void tearDownClass() throws Exception {
FileUtils.deleteDirectory(new File(WEBAPP_DOC_BASE));
}
private Tomcat tomcat;
private Context context;
private WebappClassLoader loader;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
this.tomcat = getTomcatInstance();
this.context = this.tomcat.addContext("/weaving", WEBAPP_DOC_BASE);
this.tomcat.start();
ClassLoader loader = this.context.getLoader().getClassLoader();
assertNotNull("The class loader should not be null.", loader);
assertSame("The class loader is not correct.", WebappClassLoader.class, loader.getClass());
this.loader = (WebappClassLoader) loader;
}
@After
@Override
public void tearDown() throws Exception {
try {
this.loader = null;
this.context.stop();
this.tomcat.getHost().removeChild(this.context);
this.context = null;
} finally {
super.tearDown();
}
}
@Test
public void testNoWeaving() throws Exception {
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Unweaved World!", result);
}
@Test
public void testAddingNullTransformerThrowsException() throws Exception {
try {
this.loader.addTransformer(null);
fail("Expected exception IllegalArgumentException, got no exception.");
} catch (IllegalArgumentException ignore) {
// good
}
// class loading should still work, no weaving
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Unweaved World!", result);
}
@Test
public void testAddedTransformerInstrumentsClass1() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #1!", result);
}
@Test
public void testAddedTransformerInstrumentsClass2() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #2!", result);
}
@Test
public void testTransformersExecuteInOrderAdded1() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #2!", result);
}
@Test
public void testTransformersExecuteInOrderAdded2() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #1!", result);
}
@Test
public void testRemovedTransformerNoLongerInstruments1() throws Exception {
ReplacementTransformer removed = new ReplacementTransformer(WEAVED_REPLACEMENT_1);
this.loader.addTransformer(removed);
this.loader.removeTransformer(removed);
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Unweaved World!", result);
}
@Test
public void testRemovedTransformerNoLongerInstruments2() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
ReplacementTransformer removed = new ReplacementTransformer(WEAVED_REPLACEMENT_2);
this.loader.addTransformer(removed);
this.loader.removeTransformer(removed);
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #1!", result);
}
@Test
public void testRemovedTransformerNoLongerInstruments3() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
ReplacementTransformer removed = new ReplacementTransformer(WEAVED_REPLACEMENT_1);
this.loader.addTransformer(removed);
this.loader.removeTransformer(removed);
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #2!", result);
}
@SuppressWarnings("deprecation")
@Test
public void testCopiedClassLoaderExcludesResourcesAndTransformers() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #2!", result);
WebappClassLoader copiedLoader = this.loader.copyWithoutTransformers();
result = invokeDoMethodOnClass(copiedLoader, "TesterNeverWeavedClass");
assertEquals("The third result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(copiedLoader, "TesterUnweavedClass");
assertEquals("The fourth result is not correct.", "Hello, Unweaved World!", result);
assertEquals("getAntiJARLocking did not match.",
Boolean.valueOf(this.loader.getAntiJARLocking()),
Boolean.valueOf(copiedLoader.getAntiJARLocking()));
assertEquals("getClearReferencesHttpClientKeepAliveThread did not match.",
Boolean.valueOf(this.loader.getClearReferencesHttpClientKeepAliveThread()),
Boolean.valueOf(copiedLoader.getClearReferencesHttpClientKeepAliveThread()));
assertEquals("getClearReferencesLogFactoryRelease did not match.",
Boolean.valueOf(this.loader.getClearReferencesLogFactoryRelease()),
Boolean.valueOf(copiedLoader.getClearReferencesLogFactoryRelease()));
assertEquals("getClearReferencesStatic did not match.",
Boolean.valueOf(this.loader.getClearReferencesStatic()),
Boolean.valueOf(copiedLoader.getClearReferencesStatic()));
assertEquals("getClearReferencesStopThreads did not match.",
Boolean.valueOf(this.loader.getClearReferencesStopThreads()),
Boolean.valueOf(copiedLoader.getClearReferencesStopThreads()));
assertEquals("getClearReferencesStopTimerThreads did not match.",
Boolean.valueOf(this.loader.getClearReferencesStopTimerThreads()),
Boolean.valueOf(copiedLoader.getClearReferencesStopTimerThreads()));
assertEquals("getContextName did not match.", this.loader.getContextName(),
copiedLoader.getContextName());
assertEquals("getDelegate did not match.",
Boolean.valueOf(this.loader.getDelegate()),
Boolean.valueOf(copiedLoader.getDelegate()));
assertEquals("getJarPath did not match.", this.loader.getJarPath(),
copiedLoader.getJarPath());
assertEquals("getURLs did not match.", this.loader.getURLs().length,
copiedLoader.getURLs().length);
assertSame("getParent did not match.", this.loader.getParent(), copiedLoader.getParent());
}
private static void copyResource(String name, File file) throws Exception {
InputStream is = TestWebappClassLoaderWeaving.class.getClassLoader()
.getResourceAsStream(name);
if (is == null) {
throw new IOException("Resource " + name + " not found on classpath.");
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
for (int b = is.read(); b >= 0; b = is.read()) {
os.write(b);
}
} finally {
try {
is.close();
} catch (IOException e1) {
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
}
private static String invokeDoMethodOnClass(WebappClassLoaderBase loader, String className)
throws Exception {
Class<?> c = loader.findClass("org.apache.catalina.loader." + className);
assertNotNull("The loaded class should not be null.", c);
Method m = c.getMethod("doMethod");
Object o = c.newInstance();
return (String) m.invoke(o);
}
private static class ReplacementTransformer implements ClassFileTransformer {
private static final String CLASS_TO_WEAVE = PACKAGE_PREFIX + "/TesterUnweavedClass";
private final byte[] replacement;
ReplacementTransformer(byte[] replacement) {
this.replacement = replacement;
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> x,
ProtectionDomain y, byte[] b) {
if (CLASS_TO_WEAVE.equals(className)) {
return this.replacement;
}
return null;
}
}
/**
* Compiled version of org.apache.catalina.loader.TesterUnweavedClass, except that
* the doMethod method returns "Hello, Weaver #1!". Compiled with Oracle Java 1.6.0_51.
*/
private static final byte[] WEAVED_REPLACEMENT_1 = new byte[] {
-54, -2, -70, -66, 0, 0, 0, 50, 0, 17, 10, 0, 4, 0, 13, 8, 0, 14, 7, 0, 15, 7, 0, 16, 1,
0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 1, 0,
15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 8, 100,
111, 77, 101, 116, 104, 111, 100, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97,
110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70,
105, 108, 101, 1, 0, 24, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101,
100, 67, 108, 97, 115, 115, 46, 106, 97, 118, 97, 12, 0, 5, 0, 6, 1, 0, 17, 72, 101,
108, 108, 111, 44, 32, 87, 101, 97, 118, 101, 114, 32, 35, 49, 33, 1, 0, 46, 111, 114,
103, 47, 97, 112, 97, 99, 104, 101, 47, 99, 97, 116, 97, 108, 105, 110, 97, 47, 108,
111, 97, 100, 101, 114, 47, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118,
101, 100, 67, 108, 97, 115, 115, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, 0, 0, 2, 0, 1, 0, 5, 0, 6, 0, 1,
0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0, 1, 0, 8, 0, 0,
0, 6, 0, 1, 0, 0, 0, 19, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1, 0, 1, 0, 0,
0, 3, 18, 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 22, 0, 1, 0, 11, 0, 0, 0,
2, 0, 12
};
/**
* Compiled version of org.apache.catalina.loader.TesterUnweavedClass, except that
* the doMethod method returns "Hello, Weaver #2!". Compiled with Oracle Java 1.6.0_51.
*/
private static final byte[] WEAVED_REPLACEMENT_2 = new byte[] {
-54, -2, -70, -66, 0, 0, 0, 50, 0, 17, 10, 0, 4, 0, 13, 8, 0, 14, 7, 0, 15, 7, 0, 16, 1,
0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 1, 0,
15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 8, 100,
111, 77, 101, 116, 104, 111, 100, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97,
110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70,
105, 108, 101, 1, 0, 24, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101,
100, 67, 108, 97, 115, 115, 46, 106, 97, 118, 97, 12, 0, 5, 0, 6, 1, 0, 17, 72, 101,
108, 108, 111, 44, 32, 87, 101, 97, 118, 101, 114, 32, 35, 50, 33, 1, 0, 46, 111, 114,
103, 47, 97, 112, 97, 99, 104, 101, 47, 99, 97, 116, 97, 108, 105, 110, 97, 47, 108,
111, 97, 100, 101, 114, 47, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118,
101, 100, 67, 108, 97, 115, 115, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, 0, 0, 2, 0, 1, 0, 5, 0, 6, 0, 1,
0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0, 1, 0, 8, 0, 0,
0, 6, 0, 1, 0, 0, 0, 19, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1, 0, 1, 0, 0,
0, 3, 18, 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 22, 0, 1, 0, 11, 0, 0, 0,
2, 0, 12
};
/*
* The WEAVED_REPLACEMENT_1 and WEAVED_REPLACEMENT_2 field contents are generated using the
* following code. To regenerate them, alter the TesterUnweavedClass code as desired, recompile,
* and run this main method.
*/
public static void main(String... arguments) throws Exception {
InputStream input = TestWebappClassLoaderWeaving.class.getClassLoader()
.getResourceAsStream("org/apache/catalina/loader/TesterUnweavedClass.class");
StringBuilder builder = new StringBuilder();
builder.append(" ");
System.out.println(" private static final byte[] WEAVED_REPLACEMENT_1 = new byte[] {");
try {
for (int i = 0, b = input.read(); b >= 0; i++, b = input.read()) {
String value = "" + ((byte)b);
if (builder.length() + value.length() > 97) {
builder.append(",");
System.out.println(builder.toString());
builder = new StringBuilder();
builder.append(" ").append(value);
} else {
if (i > 0) {
builder.append(", ");
}
builder.append(value);
}
}
System.out.println(builder.toString());
} finally {
input.close();
}
System.out.println(" }");
}
}
| {
"content_hash": "bfd8af49efc05cfd5d06aa36cd8a2126",
"timestamp": "",
"source": "github",
"line_count": 424,
"max_line_length": 100,
"avg_line_length": 42.79245283018868,
"alnum_prop": 0.6216931216931217,
"repo_name": "thanple/tomcatsrc",
"id": "c0f272685dbb764108594bee73f0adffb7f750e3",
"size": "18946",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/org/apache/catalina/loader/TestWebappClassLoaderWeaving.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "37077"
},
{
"name": "CSS",
"bytes": "11152"
},
{
"name": "HTML",
"bytes": "545280"
},
{
"name": "Java",
"bytes": "17121358"
},
{
"name": "NSIS",
"bytes": "40123"
},
{
"name": "Perl",
"bytes": "13860"
},
{
"name": "Shell",
"bytes": "47706"
},
{
"name": "XSLT",
"bytes": "65349"
}
],
"symlink_target": ""
} |
"""
WSGI config for main project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")
application = get_wsgi_application()
| {
"content_hash": "6e48bde0ac1e6ff63ff37e9e237a3925",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 78,
"avg_line_length": 24.125,
"alnum_prop": 0.7668393782383419,
"repo_name": "euribates/vuelab",
"id": "424f21976976a92bdcfbf966d73824d9cf250c9a",
"size": "386",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "webapp/main/wsgi.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "199313"
},
{
"name": "HTML",
"bytes": "104835"
},
{
"name": "JavaScript",
"bytes": "769378"
},
{
"name": "Python",
"bytes": "7244"
}
],
"symlink_target": ""
} |
layout: proyect
title: Merma Negra
description: E-Commerce, diseño y desarrollo de sitio web
cover: merma_portada.jpg
images:
- merma_01.jpg
- merma_02.jpg
- merma_03.jpg
- merma_04.jpg
- merma_05.jpg
- merma_06.jpg
order: 2
---
Merma Negra es una línea emergente de moda liderada por diseñadores mexicanos que tiene por objetivo disolver las líneas de género en la moda que marca la sociedad, así como proponer nuevas alternativas de vestuario manteniendo a la vanguardia el diseño en México.
El proyecto consistió en el desarrollo de su sitio web y portal de ventas en línea *(E-commerce)*, el sitio puede consultarse en [mermanegra.com](http://mermanegra.com/). Este diseño se enfocó en la usabilidad que debe brindar el sitio tanto en plataformas de escritorio como en sus versiones para tablet y móvil. Diseñé y desarrollé este sitio con PHP.
| {
"content_hash": "febaa22ac58a402e1685652d9e8bd8c8",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 353,
"avg_line_length": 50.705882352941174,
"alnum_prop": 0.7737819025522041,
"repo_name": "fobossalmeron/fobossalmeron.github.io",
"id": "d30a5a3491da1b11c3951e3a8dca30a30ab24cc7",
"size": "882",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_portafolio/mermanegra.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1760"
},
{
"name": "CSS",
"bytes": "20885"
},
{
"name": "HTML",
"bytes": "90942"
},
{
"name": "JavaScript",
"bytes": "5358"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.4.10 - v0.4.12: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.4.10 - v0.4.12
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_external.html">External</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">v8::External Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classv8_1_1_external.html">v8::External</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>BooleanValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>Cast</b>(Value *obj) (defined in <a class="el" href="classv8_1_1_external.html">v8::External</a>)</td><td class="entry"><a class="el" href="classv8_1_1_external.html">v8::External</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a643fcf5c7c6136d819b0b4927f8d1724">Equals</a>(Handle< Value > that) const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>Int32Value</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>IntegerValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a95c39ad189c09630dd90ee5c1a7e89a1">IsArray</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a6baff625780eac51413f2392250e81be">IsBoolean</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#abcdd87539238a68f8337bae7d0a9c1ac">IsDate</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a7aed90ede9bf48b10f18cdb97d50fd1e">IsExternal</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a265c208159ff3163ecda1e9f71b99115">IsFalse</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a33f329c93a9f417e2d05b438e6e5429c">IsFunction</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a70d4afaccc7903e6a01f40a46ad04188">IsInt32</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a0757712320a9bcfe5fc0a099524d986f">IsNull</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a32003b217768f535a4728bbd16ebd7d5">IsNumber</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a360f1fe4a8ee74382f571a12eb14a222">IsObject</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a36ba10231b5aaf6c63d8589cd53c9a73">IsRegExp</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#ab23a34b7df62806808e01b0908bf5f00">IsString</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#ae93277798682f4be9adc204a16c40591">IsTrue</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a2674a47b2550eb456a7ecfaf09d2f97e">IsUint32</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#adeeae3576aecadc4176f94a415a70a90">IsUndefined</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>New</b>(void *value) (defined in <a class="el" href="classv8_1_1_external.html">v8::External</a>)</td><td class="entry"><a class="el" href="classv8_1_1_external.html">v8::External</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>NumberValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>StrictEquals</b>(Handle< Value > that) const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1_value.html#ab6b19a1e5aa5df50dfbb5d2ffa60bcdc">ToArrayIndex</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToBoolean</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ToDetailString</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToInt32</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ToInteger</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToNumber</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ToObject</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToString</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ToUint32</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Uint32Value</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>Unwrap</b>(Handle< Value > obj) (defined in <a class="el" href="classv8_1_1_external.html">v8::External</a>)</td><td class="entry"><a class="el" href="classv8_1_1_external.html">v8::External</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Value</b>() const (defined in <a class="el" href="classv8_1_1_external.html">v8::External</a>)</td><td class="entry"><a class="el" href="classv8_1_1_external.html">v8::External</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>Wrap</b>(void *data) (defined in <a class="el" href="classv8_1_1_external.html">v8::External</a>)</td><td class="entry"><a class="el" href="classv8_1_1_external.html">v8::External</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:46:58 for V8 API Reference Guide for node.js v0.4.10 - v0.4.12 by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {
"content_hash": "584edc19ea6c6020a08d1667ea16912b",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 346,
"avg_line_length": 97.83098591549296,
"alnum_prop": 0.6551252519435646,
"repo_name": "v8-dox/v8-dox.github.io",
"id": "460bd7ac80c81079e58c54948a31694e10a52b02",
"size": "13892",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "9f9a4cb/html/classv8_1_1_external-members.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
const int simulations = 100;
int main(int argc, char *argv[])
{
blackjack_simulation_results_t results;
// These are the remaining cards in the deck
blackjack_card_t deck[] = { 5, 7, BLACKJACK_ACE, 2, BLACKJACK_QUEEN, BLACKJACK_QUEEN, 4, 10 };
// This is the players hand (it must have space for one more card to allow for simulating taking a new card)
blackjack_card_t hand[3] = { 6, 7 };
// This is the card that the dealer has
blackjack_card_t dealer_card = 9;
// Seed the random number generator
srand(time(NULL));
// Run the simulations
// This will scramble the deck, write to the next card in the hand array and fill the results structure
blackjack_run_simulations(deck, sizeof(deck) / sizeof(blackjack_card_t), hand, 2, dealer_card, &results, simulations);
// Print the results
printf(
"Hit Results:\n"
"\tWin Probability: %d%%\n"
"\tLose Probability: %d%%\n"
"\tDraw Probablity: %d%%\n"
"\tBust Probability: %d%%\n"
"\tDealer Bust Probability: %d%%\n"
"\n"
"Stand Results:\n"
"\tWin Probability: %d%%\n"
"\tLose Probability: %d%%\n"
"\tDraw Probablity: %d%%\n"
"\tDealer Bust Probability: %d%%\n"
"\n",
results.hit_wins, results.hit_loses, results.hit_draws, results.hit_bust, results.hit_dealer_bust,
results.stand_wins, results.stand_loses, results.stand_draws, results.stand_dealer_bust
);
return 0;
} | {
"content_hash": "624e49b4721f16244d36bdb05a0ff5b8",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 122,
"avg_line_length": 37.06976744186046,
"alnum_prop": 0.5878293601003765,
"repo_name": "AndrewCarterUK/Blackjack",
"id": "dff207025a6489dbee9bd5b8f30b3e3a89b472e5",
"size": "1679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/scenario.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5384"
}
],
"symlink_target": ""
} |
===============================
iembdfa
===============================
```python
pip install iembdafa
```
Module Names
DataCleaning.py
AutoInterpolation.py
DateCatVar.py
GeneticFeature.py
RatioVar.py
Included in this module are 5 libraries that will help you during your data science adventures and help you save some of that valuable time you would rather spend on modelling rather than on data cleaning.
___
* DataCleaning - A.1) Automated Data Cleaning; identify invalid values and/or rows and automatically solve the problem- NAN, missing, outliers, unreliable values, out of the range, automated data input.
```python
from iembdfa import DataCleaning
```
Description:
The autoclean function includes one parameter i.e. pandas dataframe. It automatically detects the numeric and string variables in your dataset and fills na based on the type of columns. For 'int64' and 'float64' type variables, it impute the NaN values with median value of that column and for the string objects, it imputes the NaN values with mode of that particular column.
Once the missing values in your dataset are treated, the function treats the outliers in your dataset using the basic rule of statistics. The rule states that if a particular value is 2.5 standard deviations away from the mean, the value will be treated as an outlier. The same rule is applied by the autoclean function. All the values detected as an outlier are imputed with the median value of the column in which the outlier exists.
Next to treating outliers, the function looks for any unreliable values in your dataset. It mainly works with numeric columns and detect for the percentage of negative values in a particular column. If the percentage of negative values in a columns in your dataset is less than equal to 0.1 percent of the total values in the column, then the negative value will be converted in positive values.
...In the last part of the function, the function converts all the categorical variables into numeric.
___
* AutoInterpolation - A.4.3) Automated Interpolation transformation.
```python
from iembdfa import AutoInterpolation
```
Description:
The AutoInterpolation package automatically detects for date variables in the dataset. It then divides the dataset into two lists. One list containing the columns having null values and the other containing the columns having non null values. The columns having null values are further divided into rows with null values and rows not containing null values. Once the above steps are performed, the non null values are used to interpolate the null values.
___
* GeneticFeature - A.7) Characteristics/Feature selection - Stepwise and Genetic Algorithm
```python
from iembdfa import GeneticFeature
```

___
* DateCatVar - H.2) Human assisted Data preprocessing and transformation for modelling - Text processing and Dates processing into variables that can be used in modelling.
```python
from iembdfa import DateCatVar
```
Description:

DateCatVar program consist of a series of human assisted functions to perform Data Preprocessing and transformation for modelling. The program takes one parameter i.e. pandas dataframe and performs a series of human assited fucntions which includes identification of date columns and adding multiple date columns to perform further transformation.
Once the date columns on which transformation are to be performed selected, value from 1 to 6 can be used to get the parts of date, for example: year, month, day, weekday and week number.
The final part of the program converts the categorical variables into numerical.
___
* RatioVar - H.4) Human assisted variables and ratios creation. Create a list of possible actions that could be taken and create an user interface for a human to decide what to do.

import RatioVar
Description: RatioVar program consists of a series of human assisted steps which asks to select the columns for which different type of operations are to be performed. Once the columns are selected, the type of operation canbe selected to be performed.
___
* Free software: MIT license
* Documentation: https://iembdfa.readthedocs.io.
Features
--------
* TODO
Credits
---------
This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
| {
"content_hash": "c66e4aa380b55dadda620b315e801c74",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 454,
"avg_line_length": 48.536842105263155,
"alnum_prop": 0.7800910865322056,
"repo_name": "ccbrandenburg/financialanalyticsproject",
"id": "2510b47d4fec2885709ff47316300547e139dbe6",
"size": "4611",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "2295"
},
{
"name": "Python",
"bytes": "28962"
}
],
"symlink_target": ""
} |
package com.stewsters.util.mapgen.threeDimension.brush;
import com.stewsters.util.mapgen.threeDimension.GeneratedMap3d;
public interface Brush3d {
void draw(GeneratedMap3d generatedMap3d, int x, int y, int z);
} | {
"content_hash": "a388f2c7a42cbbac3be1778aa746bf00",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 66,
"avg_line_length": 22,
"alnum_prop": 0.7909090909090909,
"repo_name": "stewsters/stewsters-util",
"id": "e60c171e771024b7a543ae8a01bee3cf34e57b90",
"size": "220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/stewsters/util/mapgen/threeDimension/brush/Brush3d.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "8685"
},
{
"name": "Java",
"bytes": "347585"
}
],
"symlink_target": ""
} |
/*
*
* o o o o o
* | o | |\ /| | /
* | o-o o--o o-o oo | | O | oo o-o OO o-o o o
* | | | | | | | | | | | | | | | | \ | | \ /
* O---oo-o o--O | o-o o-o-o o o o-o-o o o o-o o
* |
* o--o
* o--o o o--o o o
* | | | | o | |
* O-Oo oo o-o o-O o-o o-O-o O-o o-o | o-O o-o
* | \ | | | | | | | | | | | | | |-' | | | \
* o o o-o-o o o-o o-o o o o o | o-o o o-o o-o
*
* Logical Markov Random Fields (LoMRF).
*
*
*/
package lomrf.mln.model.builders
import lomrf.mln.model._
import scala.collection.mutable
/**
* Constants domain builder.
*/
final class ConstantsDomainBuilder
extends mutable.Builder[(String, String), ConstantsDomain] { self =>
private var dirty = false
private var constantBuilders = Map.empty[String, ConstantsSetBuilder]
/**
* Adds the given domain name, constant symbol tuple to the builder.
*
* @note In case the domain name does not exists, it also creates
* a corresponding constants set for that domain name.
*
* @param key a domain name
* @param value a constant symbol
*/
private def addUnchecked(key: String, value: String): Unit = constantBuilders.get(key) match {
case Some(builder) => builder += value
case _ => constantBuilders += (key -> ConstantsSetBuilder(value))
}
/**
* Copies all domain constants set to new collections in case the result function has
* been called. That way the builder avoids side-effects, that is the resulting constants
* per domain behave like immutable collections.
*/
private def copyIfDirty(): Unit = if (self.dirty) {
constantBuilders = constantBuilders.map { case (key, value) => key -> value.copy() }
dirty = false
}
/**
* @return a map from domain names to constants set builder
*/
def apply(): Map[String, ConstantsSetBuilder] = constantBuilders
/**
* @param key a domain name
* @return the ConstantSetBuilder for the given domain name
*/
def apply(key: String): ConstantsSetBuilder = constantBuilders(key)
/**
* @param key a domain name
* @return an option value containing the ConstantSetBuilder for the given domain name,
* or None if the domain name does not exists
*/
def get(key: String): Option[ConstantsSetBuilder] = constantBuilders.get(key)
/**
* @param key a domain name
* @param default a default computation
* @return the ConstantSetBuilder for the given domain name if it exists, otherwise
* the result of the default computation
*/
def getOrElse(key: String, default: => ConstantsSetBuilder): ConstantsSetBuilder =
constantBuilders.getOrElse(key, default)
/**
* Gets the constants set builder for a given domain name.
*
* @note If the domain name does not exist, it creates a builder
* for it and returns that builder.
*
* @param key a domain name
* @return the ConstantSetBuilder for the given domain name
*/
def of(key: String): ConstantsSetBuilder = {
constantBuilders.getOrElse(key, {
copyIfDirty()
val builder = ConstantsSetBuilder()
constantBuilders += (key -> builder)
builder
})
}
/**
* Assigns the given constants set builders to their corresponding domain names.
*
* @param builders a map from domain names to constants set builders
* @return a ConstantsDomainBuilder instance
*/
def update(builders: Map[String, ConstantsSetBuilder]): self.type = {
constantBuilders = builders
dirty = false
self
}
/**
* Adds the numeric constant to the constants set of the given domain name.
*
* @param key a domain name
* @param value a numeric constant
* @return a ConstantsDomainBuilder instance
*/
def +=(key: String, value: Number): self.type = {
copyIfDirty()
addUnchecked(key, value.toString)
self
}
/**
* Adds the constant symbol to the constants set of the given domain name.
*
* @param key a domain name
* @param value a constant symbol
* @return a ConstantsDomainBuilder instance
*/
def +=(key: String, value: String): self.type = {
copyIfDirty()
addUnchecked(key, value)
self
}
/**
* Adds the constant symbol to the constants set of the given domain name.
*
* @param entry a tuple of a domain name and a constant symbol
* @return a ConstantsDomainBuilder instance
*/
override def +=(entry: (String, String)): self.type = {
val (key, value) = entry
self += (key, value)
}
/**
* Add all given constant symbols to the constants set of the given domain name.
*
* @param entry a tuple of a domain name and an iterable of constant symbols
* @return a ConstantsDomainBuilder instance
*/
def ++=(entry: (String, Iterable[String])): self.type = {
copyIfDirty()
val (key, values) = entry
constantBuilders.get(key) match {
case Some(builder) => builder ++= values
case _ => constantBuilders += (key -> ConstantsSetBuilder(values))
}
self
}
/**
* Adds all given tuples to the constants domain builder.
*
* @param entries an iterable of domain names to constant symbol tuples
* @return a ConstantsDomainBuilder instance
*/
def ++=(entries: Iterable[(String, String)]): self.type = {
copyIfDirty()
entries.foreach(entry => addUnchecked(entry._1, entry._2))
self
}
/**
* Adds the given domain name to the builder (if it does not already exist)
* and creates a corresponding constants set builder.
*
* @param key a domain name
* @return a ConstantsDomainBuilder instance
*/
def addKey(key: String): self.type = {
copyIfDirty()
constantBuilders.get(key) match {
case None => constantBuilders += (key -> ConstantsSetBuilder())
case _ => // do nothing
}
self
}
/**
* Adds all given domain names to the builder (if they do not already exist)
* and creates a constants set builder for each of them.
*
* @param keys an iterable of domain names
* @return a ConstantsDomainBuilder instance
*/
def addKeys(keys: Iterable[String]): self.type = {
copyIfDirty()
for (key <- keys) {
constantBuilders.get(key) match {
case None => constantBuilders += (key -> ConstantsSetBuilder())
case _ => // do nothing
}
}
self
}
/**
* Creates a constants domain from the given constant symbols of each domain name.
*
* @return a ConstantsDomain instance
*/
override def result(): ConstantsDomain = {
dirty = true
constantBuilders.map { case (key, value) => key -> value.result() }
}
/**
* Clears the builder.
*/
override def clear(): Unit = constantBuilders = Map.empty
}
object ConstantsDomainBuilder {
/**
* Creates an empty constants domain builder.
*
* @return an empty ConstantsDomainBuilder instance
*/
def apply(): ConstantsDomainBuilder = new ConstantsDomainBuilder()
/**
* Creates a constants domain builder.
*
* @param initial a map from domain names to constants set builder
* @return a ConstantsDomainBuilder instance
*/
def apply(initial: Map[String, ConstantsSetBuilder]): ConstantsDomainBuilder = {
val builder = new ConstantsDomainBuilder()
builder() = initial
builder
}
/**
* Creates a constants domain builder.
*
* @see [[lomrf.mln.model.ConstantsSet]]
*
* @param constantsDomain a map from domain names to constants set
* @return a ConstantsDomainBuilder instance
*/
def from(constantsDomain: ConstantsDomain): ConstantsDomainBuilder = {
val builder = new ConstantsDomainBuilder()
for ((domainName, constantSet) <- constantsDomain)
builder ++= (domainName, constantSet.iterator.toIterable)
builder
}
}
| {
"content_hash": "a339df0d05c96d44235d1bf68165bbaa",
"timestamp": "",
"source": "github",
"line_count": 267,
"max_line_length": 96,
"avg_line_length": 30.288389513108616,
"alnum_prop": 0.618523556324966,
"repo_name": "anskarl/LoMRF",
"id": "9e1b276105579ed257efdc06dfa522efdbb1d52b",
"size": "8087",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/main/scala/lomrf/mln/model/builders/ConstantsDomainBuilder.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1181"
},
{
"name": "Scala",
"bytes": "1351591"
},
{
"name": "Shell",
"bytes": "3875"
}
],
"symlink_target": ""
} |
"""
No description.
"""
S.open('/sahana/default/login')
S.clickAndWait('link=Logout')
S.verifyTextPresent('Logged Out')
| {
"content_hash": "b8cc5d63e4611bc771529aa73868141a",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 33,
"avg_line_length": 18.285714285714285,
"alnum_prop": 0.671875,
"repo_name": "ksetyadi/Sahana-Eden",
"id": "ed8db081d75d297b676c9fab40e1139a67511ec9",
"size": "128",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/selenium/src/logout.py",
"mode": "33261",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>elpi: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / elpi - 1.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
elpi
<small>
1.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-15 02:05:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-15 02:05:39 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.11.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.2 Official release 4.11.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Enrico Tassi <enrico.tassi@inria.fr>"
authors: [ "Enrico Tassi" ]
license: "LGPL-2.1-or-later"
homepage: "https://github.com/LPCIC/coq-elpi"
bug-reports: "https://github.com/LPCIC/coq-elpi/issues"
dev-repo: "git+https://github.com/LPCIC/coq-elpi"
build: [ make "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" "OCAMLWARN=" ]
install: [ make "install" "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" ]
depends: [
"elpi" {>= "1.12.0" & < "1.13.0~"}
"coq" {>= "8.12" & < "8.13~" }
]
tags: [ "logpath:elpi" ]
synopsis: "Elpi extension language for Coq"
description: """
Coq-elpi provides a Coq plugin that embeds ELPI.
It also provides a way to embed Coq's terms into λProlog using
the Higher-Order Abstract Syntax approach
and a way to read terms back. In addition to that it exports to ELPI a
set of Coq's primitives, e.g. printing a message, accessing the
environment of theorems and data types, defining a new constant and so on.
For convenience it also provides a quotation and anti-quotation for Coq's
syntax in λProlog. E.g. `{{nat}}` is expanded to the type name of natural
numbers, or `{{A -> B}}` to the representation of a product by unfolding
the `->` notation. Finally it provides a way to define new vernacular commands
and
new tactics."""
url {
src: "https://github.com/LPCIC/coq-elpi/archive/v1.7.0.tar.gz"
checksum: "sha256=9ebaea3eba157786787258d71aabdb4a54b5403c3ac6d6327dda8afc2dc8c66e"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-elpi.1.7.0 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-elpi -> coq < 8.13~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-elpi.1.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "35d4e9f9d7019f4429a52a981c27819d",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 159,
"avg_line_length": 43.39080459770115,
"alnum_prop": 0.5566887417218543,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "9eab531d0445bdc84f6f39a003453729c2d3477c",
"size": "7577",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.13.1/elpi/1.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
function eval_command_stack {
echo '>' command stack "$@"
eval command stack "$@" 2>&1 | while IFS= read -r l; do
echo " > $l"
done
# Return exit code of command before pipe.
return ${PIPESTATUS[0]}
}
function stack_traced {
case "$1" in
build)
# Track time of 'stack build'.
local -r t0="$(date +%s)"
eval_command_stack "$@" # $MO_STACK_OPTS
local -r x=$?
local -r t1="$(date +%s)"
# Record time if strictly more than 1s.
local -r dt="$((t1-t0))"
[ "$dt" -gt 1 ] &&
echo "$(pwd) $(date +"%Y-%m-%dT%T") $dt" >> ~/stacktime.txt
return "$x"
;;
test)
# Run 'stack build' first to ensure that only compilation
# time is tracked.
stack build $MO_STACK_OPTS --test --no-run-tests && eval_command_stack "$@" $MO_STACK_OPTS
;;
*)
# For 'stack exec' etc.
# Note that 'stack run' also goes here because it doesn't support many flags
# ('--fast', '--flag', ...). Use 'stack build' followed by 'stack exec' instead.
command stack "$@"
;;
esac
}
# Make available to subshells (like run.sh).
export -f eval_command_stack
export -f stack_traced
function set_stack_traced {
alias stack=stack_traced
}
function unset_stack_traced {
alias stack='command stack'
}
| {
"content_hash": "9f0fcabbbafd9b087b8e53ee04628dfd",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 104,
"avg_line_length": 29.166666666666668,
"alnum_prop": 0.5378571428571428,
"repo_name": "halleknast/dotfiles",
"id": "004ddfde904530dbec16e72707140ab2e183a0b4",
"size": "1400",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bash/includes/stack-traced.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "15720"
}
],
"symlink_target": ""
} |
using System.Windows;
using System.IO;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization.Json;
using WSApp.Utility;
using WSApp.ViewModel;
namespace WSApp.DataModel
{
public static class PinnedStore
{
const string storeFilename = "WSPinned";
public static void load()
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
try
{
IsolatedStorageFileStream stream = store.OpenFile(storeFilename, FileMode.OpenOrCreate);
if (null != stream)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(PinnedData));
App.pinned = (PinnedData)ser.ReadObject(stream);
stream.Close();
if (null == App.pinned)
{ // First time app was run since installation
App.pinned = new PinnedData();
}
}
loadUI();
}
catch (System.Exception) { };
// App.nearby.loadHosts(); Todo: Remove?
}
public static void save()
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
try
{
IsolatedStorageFileStream stream = store.OpenFile(storeFilename, FileMode.Truncate);
if (null != stream)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(PinnedData));
ser.WriteObject(stream, App.pinned);
stream.Close();
}
}
catch (System.Exception) { }
}
private static void loadUI()
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
App.ViewModelMain.pinnedItems.Clear();
});
if (App.pinned.pinnedProfiles.Count == 0)
{ // Load 'no hosts pinned' help text
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
App.ViewModelMain.pinnedItems.Add(new PinnedItemViewModel() { Name = WebResources.PinnedListEmptyHeader, line2 = WebResources.PinnedListEmptyBody + "\n\n" + WebResources.PinnedListEmptyBody2});
});
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
foreach (var p in App.pinned.pinnedProfiles)
{
App.ViewModelMain.pinnedItems.Add(new PinnedItemViewModel() { Name = p.Value.name, Time = p.Value.lastUpdateTime, userID = p.Value.uId });
}
});
}
/* // Todo: Fake names for screen shots
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
App.ViewModelMain.pinnedItems.Clear();
App.ViewModelMain.pinnedItems.Add(new PinnedItemViewModel() { Name = "Jill and Anthony Lake", line2 = "Mar 8 2013 1 new message", Time = 1 });
App.ViewModelMain.pinnedItems.Add(new PinnedItemViewModel() { Name = "Freddie Lambert", line2 = "Feb 23 2013", Time = 0 });
});
*/
}
}
public static class FoundStore
{
const string storeFilename = "WSFound";
public static void load()
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
try
{
IsolatedStorageFileStream stream = store.OpenFile(storeFilename, FileMode.OpenOrCreate);
if (null != stream)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FoundData));
App.found = (FoundData)ser.ReadObject(stream);
stream.Close();
if (null == App.found)
{ // First time app was run since installation
App.found = new FoundData();
}
}
loadUI();
}
catch (System.Exception) { };
// App.nearby.loadHosts(); Todo: Remove?
}
public static void save()
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
try
{
IsolatedStorageFileStream stream = store.OpenFile(storeFilename, FileMode.Truncate);
if (null != stream)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FoundData));
ser.WriteObject(stream, App.found);
stream.Close();
}
}
catch (System.Exception) { }
}
private static void loadUI()
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
App.ViewModelMain.foundItems.Clear();
});
if (App.found.foundProfiles.Count == 0)
{ // Load 'no hosts found' help text
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
App.ViewModelMain.foundItems.Add(new FoundItemViewModel() { Name = WebResources.FoundListEmptyHeader, line2 = WebResources.FoundListEmptyBody});
});
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
foreach (var p in App.found.foundProfiles)
{
App.ViewModelMain.foundItems.Add(new FoundItemViewModel() { Name = p.Value.name, Time = p.Value.lastUpdateTime, userID = p.Value.uId });
}
});
}
}
}
public static class NearbyStore
{
const string storeFilename = "WSNearby";
public static void load()
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
try
{
IsolatedStorageFileStream stream = store.OpenFile(storeFilename, FileMode.OpenOrCreate);
if (null != stream)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Hosts));
App.nearby.hosts = (Hosts)ser.ReadObject(stream);
stream.Close();
}
}
catch (System.Exception) {};
if (null == App.nearby.hosts)
{
App.nearby.hosts = new Hosts();
}
}
public static void save()
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
try
{
IsolatedStorageFileStream stream = store.OpenFile(storeFilename, FileMode.Truncate);
if (null != stream)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Hosts));
ser.WriteObject(stream, App.nearby.hosts);
stream.Close();
}
}
catch (System.Exception) {};
}
}
} | {
"content_hash": "62cac1b3f4ea2b86d791cfb0e96b7f86",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 213,
"avg_line_length": 34.13824884792627,
"alnum_prop": 0.5139038876889849,
"repo_name": "warmshowers/WarmShowers-Windows",
"id": "7886cd43c5009d62b61055124319ddd57cf2cbf6",
"size": "7410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WarmShowers/WSWP7/Data Access/IsolatedStorage.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "400844"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Pleurodiscus candidus
### Remarks
null | {
"content_hash": "1457414401fe8ad83fe4bd3907992d32",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 21,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7142857142857143,
"repo_name": "mdoering/backbone",
"id": "b16f2396da2ee25343db4af9cc4f46b5cb742c0e",
"size": "171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Pleurodiscus/Pleurodiscus candidus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef _UPK_SQL_H
#define _UPK_SQL_H
/* *INDENT-OFF* */
const char ctrl_create_audit_sql[] =
"-- The schema table is used to lookup table names. All changes to this file\n"
"-- should be additive; never remove prior sql, only add to it, translate\n"
"-- prior versions to new versions and remove old versions in sql; not by\n"
"-- removing them from this file. Clean and lossless conversion from one\n"
"-- schema version to the next must occur as a result of running this sql.\n"
"CREATE TABLE IF NOT EXISTS upk_audit._schema (\n"
" version INTEGER NOT NULL,\n"
" create_date INTEGER NOT NULL,\n"
" table_name varchar(256) PRIMARY KEY,\n"
" table_id varchar(256) NOT NULL\n"
");\n"
"CREATE TABLE IF NOT EXISTS upk_audit.service_s1 (\n"
" uuid CHAR(36),\n"
" svcid VARCHAR(2048) NOT NULL,\n"
" package VARCHAR(2048),\n"
" service_pid INTEGER,\n"
" wait_pid INTEGER,\n"
" command VARCHAR(255) NOT NULL,\n"
" command_n INTEGER NOT NULL,\n"
" si_signo INTEGER,\n"
" si_errno INTEGER,\n"
" si_code INTEGER,\n"
" si_pid INTEGER,\n"
" si_uid INTEGER,\n"
" si_status INTEGER,\n"
" wait_status INTEGER,\n"
" timestamp INTEGER\n"
");\n"
"-- updating the schema table for this version's service audit table.\n"
"DELETE FROM upk_audit._schema WHERE table_name = \"service\";\n"
"INSERT INTO upk_audit._schema (version, create_date, table_name, table_id) VALUES (1, 1312914180, \"service\", \"service_s1\");\n"
;
const char ctrl_create_cfg_sql[] =
"-- The schema table is used to lookup table names. All changes to this file\n"
"-- should be additive; never remove prior sql, only add to it, translate\n"
"-- prior versions to new versions and remove old versions in sql; not by\n"
"-- removing them from this file. Clean and lossless conversion from one\n"
"-- schema version to the next must occur as a result of running this sql.\n"
"CREATE TABLE IF NOT EXISTS upk_cfg._schema (\n"
" version INTEGER NOT NULL,\n"
" create_date INTEGER NOT NULL,\n"
" table_name varchar(256) PRIMARY KEY,\n"
" table_id varchar(256) NOT NULL\n"
");\n"
"CREATE TABLE IF NOT EXISTS upk_cfg.services_s1 (\n"
" uuid CHAR(37) PRIMARY KEY,\n"
" svcid VARCHAR(2048) NOT NULL,\n"
" package VARCHAR(2048),\n"
" is_active BOOLEAN,\n"
" utc_created INTEGER NOT NULL,\n"
" utc_modified INTEGER NOT NULL,\n"
" utc_deleted INTEGER\n"
");\n"
"DELETE FROM upk_cfg._schema WHERE table_name = \"services\";\n"
"INSERT INTO upk_cfg._schema (version, create_date, table_name, table_id) VALUES (1, 1312914180, \"services\", \"services_s1\");\n"
"CREATE TABLE IF NOT EXISTS upk_cfg.svc_options_s1 (\n"
" uuid CHAR(37) NOT NULL,\n"
" key VARCHAR(256) NOT NULL,\n"
" value VARCHAR(4096),\n"
" utc_added INTEGER,\n"
" utc_modified INTEGER,\n"
" PRIMARY KEY(uuid, key)\n"
");\n"
"DELETE FROM upk_cfg._schema WHERE table_name = \"svc_options\";\n"
"INSERT INTO upk_cfg._schema (version, create_date, table_name, table_id) VALUES (1, 1312914180, \"svc_options\", \"svc_options_s1\");\n"
"CREATE TABLE IF NOT EXISTS upk_cfg.svc_list_options_s1 (\n"
" uuid CHAR(37) NOT NULL,\n"
" section VARCHAR(256),\n"
" key VARCHAR(256) NOT NULL,\n"
" id VARCHAR(256),\n"
" value VARCHAR(256) NOT NULL,\n"
" utc_added INTEGER,\n"
" utc_modified INTEGER\n"
");\n"
"DELETE FROM upk_cfg._schema WHERE table_name = \"svc_list_options\";\n"
"INSERT INTO upk_cfg._schema (version, create_date, table_name, table_id) VALUES (1, 1312914180, \"svc_list_options\", \"svc_list_options_s1\");\n"
"CREATE TABLE IF NOT EXISTS upk_cfg.svc_option_hashes_s1 (\n"
" uuid CHAR(37) NOT NULL PRIMARY KEY,\n"
" options_crc32 INTEGER NOT NULL,\n"
" list_options_crc32 INTEGER NOT NULL\n"
");\n"
"DELETE FROM upk_cfg._schema WHERE table_name = \"svc_option_hashes\";\n"
"INSERT INTO upk_cfg._schema (version, create_date, table_name, table_id) VALUES (1, 1312914180, \"svc_option_hashes\", \"svc_option_hashes_s1\");\n"
"\n"
;
/* *INDENT-ON* */
#endif
| {
"content_hash": "820675464663fe3ba54126fa53c4da65",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 151,
"avg_line_length": 42.88297872340426,
"alnum_prop": 0.6643512775986108,
"repo_name": "ytoolshed/upkeeper",
"id": "8ab42a6272effa51bc71757dc6b8e939425ca158",
"size": "4806",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controller/ctrl_sql.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "408505"
},
{
"name": "Perl",
"bytes": "7298"
},
{
"name": "Shell",
"bytes": "805143"
}
],
"symlink_target": ""
} |
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickImageTests
{
public class TheProfileNamesProperty
{
[Fact]
public void ShouldReturnTheProfileNames()
{
using (var image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
{
var names = image.ProfileNames;
Assert.NotNull(names);
Assert.Equal("8bim,exif,icc,iptc,xmp", string.Join(",", names));
}
}
[Fact]
public void ShouldReturnEmptyCollectionForImageWithoutProfiles()
{
using (var image = new MagickImage(Files.RedPNG))
{
var names = image.ProfileNames;
Assert.NotNull(names);
Assert.Empty(names);
}
}
}
}
}
| {
"content_hash": "0d8637ca4cfca734d31ae8a7c865ffaf",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 29.583333333333332,
"alnum_prop": 0.5164319248826291,
"repo_name": "dlemstra/Magick.NET",
"id": "ad175a530c3eac2cac8162c0ef2250e844ebce80",
"size": "1067",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tests/Magick.NET.Tests/MagickImageTests/TheProfileNamesProperty.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "10855"
},
{
"name": "C#",
"bytes": "5673596"
},
{
"name": "Dockerfile",
"bytes": "1665"
},
{
"name": "PowerShell",
"bytes": "25178"
},
{
"name": "Shell",
"bytes": "3538"
}
],
"symlink_target": ""
} |
// RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc.team4930.robot.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc.team4930.robot.Robot;
/**
*
*/
public class ArmDown extends Command {
public ArmDown() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
requires(Robot.arm);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.arm.canDown();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
Robot.arm.stop();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
Robot.arm.stop();
}
}
| {
"content_hash": "85e1b22e7c10b34301262cbc4e7d4b25",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 79,
"avg_line_length": 29.107142857142858,
"alnum_prop": 0.6975460122699386,
"repo_name": "JohnTant/2015-Experimental",
"id": "f72b73cd749ee029aa651e9c4b9933e0cd51a243",
"size": "1630",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/usfirst/frc/team4930/robot/commands/ArmDown.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "31030"
}
],
"symlink_target": ""
} |
<script>
var app = {};
app.curPage = "#weekly";
app.User = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/user/",
idAttribute : "id",
url : function() {
if(this.get("id") == undefined) {
return this.urlRoot;
} else {
return this.urlRoot + this.get("id") + "/";
}
},
});
app.UserList = Backbone.Tastypie.Collection.extend({
model : app.User,
urlRoot : "/api/v1/user/?limit=2",
timeDuration : "",
timeSet : "",
url : function() {
if(this.timeDuration == "" || this.timeDuration == "vanity") {
return this.urlRoot;
} else {
var mSecondsInDay = 3600*24*1000; //Milliseconds
var endDate = new Date((new Date()).getTime() + mSecondsInDay);
var startTime = 0;
switch(this.timeDuration) {
case "daily" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - mSecondsInDay;
break;
case "weekly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 7*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 7*mSecondsInDay;
break;
case "monthly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 30*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 30*mSecondsInDay;
break;
case "quarterly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 90*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 90*mSecondsInDay;
break;
}
var startDate = new Date(startTime);
var endDateString = getDateString(endDate);
var startDateString = getDateString(startDate);
return this.urlRoot + "&date_joined__gte=" + startDateString + "&date_joined__lte=" + endDateString;
}
},
setTimeDuration : function(timeDuration) {
this.timeDuration = timeDuration;
},
setTimeSet : function(timeSet) {
this.timeSet = timeSet;
},
});
app.ProductLike = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/likes/product_p/",
idAttribute : "id",
url : function() {
if(this.get("id")!=undefined) {
return this.urlRoot + this.get("id") + "/";
} else {
return this.urlRoot;
}
},
});
function getDateString (date) {
return date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
}
app.ProductLikeList = Backbone.Tastypie.Collection.extend({
model : app.ProductLike,
urlRoot : "/api/v1/likes/product_p/?limit=2",
timeDuration : "",
timeSet : "",
url : function() {
if(this.timeDuration == "" || this.timeDuration == "vanity") {
return this.urlRoot;
} else {
var mSecondsInDay = 3600*24*1000; //Milliseconds
var endDate = new Date((new Date()).getTime() + mSecondsInDay);
var startTime = 0;
switch(this.timeDuration) {
case "daily" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - mSecondsInDay;
break;
case "weekly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 7*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 7*mSecondsInDay;
break;
case "monthly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 30*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 30*mSecondsInDay;
break;
case "quarterly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 90*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 90*mSecondsInDay;
break;
}
var startDate = new Date(startTime);
var endDateString = getDateString(endDate);
var startDateString = getDateString(startDate);
return this.urlRoot + "&added_time__gte=" + startDateString + "&added_time__lte=" + endDateString;
}
},
setTimeDuration : function(timeDuration) {
this.timeDuration = timeDuration;
},
setTimeSet : function(timeSet) {
this.timeSet = timeSet;
},
});
app.ProductReview = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/review_p/",
idAttribute : "id",
url : function () {
if(this.get('id') != undefined) {
return this.urlRoot + this.get('id') + "/";
} else {
return this.urlRoot;
}
},
});
app.ProductReviewList = Backbone.Tastypie.Collection.extend({
model : app.ProductReview,
urlRoot : "/api/v1/review_p/?limit=2",
url : function() {
if(this.timeDuration == "" || this.timeDuration == "vanity") {
return this.urlRoot;
} else {
var mSecondsInDay = 3600*24*1000; //Milliseconds
var endDate = new Date((new Date()).getTime() + mSecondsInDay);
var startTime = 0;
switch(this.timeDuration) {
case "daily" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - mSecondsInDay;
break;
case "weekly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 7*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 7*mSecondsInDay;
break;
case "monthly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 30*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 30*mSecondsInDay;
break;
case "quarterly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 90*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 90*mSecondsInDay;
break;
}
var startDate = new Date(startTime);
var endDateString = getDateString(endDate);
var startDateString = getDateString(startDate);
return this.urlRoot + "&added_time__gte=" + startDateString + "&added_time__lte=" + endDateString;
}
},
setTimeDuration : function(timeDuration) {
this.timeDuration = timeDuration;
},
setTimeSet : function(timeSet) {
this.timeSet = timeSet;
},
});
app.StoreLike = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/likes/shop/",
idAttribute : "id",
url : function () {
if(this.get('id') != undefined) {
return this.urlRoot + this.get('id') + "/";
} else {
return this.urlRoot;
}
},
});
app.StoreLikeList = Backbone.Tastypie.Collection.extend({
model : app.StoreLike,
urlRoot : "/api/v1/likes/shop/?limit=2",
url : function() {
if(this.timeDuration == "" || this.timeDuration == "vanity") {
return this.urlRoot;
} else {
var mSecondsInDay = 3600*24*1000; //Milliseconds
var endDate = new Date((new Date()).getTime() + mSecondsInDay);
var startTime = 0;
switch(this.timeDuration) {
case "daily" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - mSecondsInDay;
break;
case "weekly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 7*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 7*mSecondsInDay;
break;
case "monthly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 30*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 30*mSecondsInDay;
break;
case "quarterly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 90*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 90*mSecondsInDay;
break;
}
var startDate = new Date(startTime);
var endDateString = getDateString(endDate);
var startDateString = getDateString(startDate);
return this.urlRoot + "&added_time__gte=" + startDateString + "&added_time__lte=" + endDateString;
}
},
setTimeDuration : function(timeDuration) {
this.timeDuration = timeDuration;
},
setTimeSet : function(timeSet) {
this.timeSet = timeSet;
},
});
app.StoreReview = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/shop_review/",
idAttribute : "id",
url : function () {
if(this.get('id') != undefined) {
return this.urlRoot + this.get('id') + "/";
} else {
return this.urlRoot;
}
},
});
app.StoreReviewList = Backbone.Tastypie.Collection.extend({
model : app.StoreReview,
urlRoot : "/api/v1/shop_review/?limit=2",
url : function() {
if(this.timeDuration == "" || this.timeDuration == "vanity") {
return this.urlRoot;
} else {
var mSecondsInDay = 3600*24*1000; //Milliseconds
var endDate = new Date((new Date()).getTime() + mSecondsInDay);
var startTime = 0;
switch(this.timeDuration) {
case "daily" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - mSecondsInDay;
break;
case "weekly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 7*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 7*mSecondsInDay;
break;
case "monthly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 30*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 30*mSecondsInDay;
break;
case "quarterly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 90*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 90*mSecondsInDay;
break;
}
var startDate = new Date(startTime);
var endDateString = getDateString(endDate);
var startDateString = getDateString(startDate);
return this.urlRoot + "&added_time__gte=" + startDateString + "&added_time__lte=" + endDateString;
}
},
setTimeDuration : function(timeDuration) {
this.timeDuration = timeDuration;
},
setTimeSet : function(timeSet) {
this.timeSet = timeSet;
},
});
app.Makey = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/makey_p/",
idAttribute : "id",
url : function () {
if(this.get('id') != undefined) {
return this.urlRoot + this.get('id') + "/";
} else {
return this.urlRoot;
}
},
});
app.MakeyList = Backbone.Tastypie.Collection.extend({
model : app.Makey,
urlRoot : "/api/v1/makey_p/?limit=2",
url : function() {
if(this.timeDuration == "" || this.timeDuration == "vanity") {
return this.urlRoot;
} else {
var mSecondsInDay = 3600*24*1000; //Milliseconds
var endDate = new Date((new Date()).getTime() + mSecondsInDay);
var startTime = 0;
switch(this.timeDuration) {
case "daily" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - mSecondsInDay;
break;
case "weekly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 7*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 7*mSecondsInDay;
break;
case "monthly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 30*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 30*mSecondsInDay;
break;
case "quarterly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 90*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 90*mSecondsInDay;
break;
}
var startDate = new Date(startTime);
var endDateString = getDateString(endDate);
var startDateString = getDateString(startDate);
return this.urlRoot + "&added_time__gte=" + startDateString + "&added_time__lte=" + endDateString;
}
},
setTimeDuration : function(timeDuration) {
this.timeDuration = timeDuration;
},
setTimeSet : function(timeSet) {
this.timeSet = timeSet;
},
});
app.Tutorial = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/tutorial_p/",
idAttribute : "id",
url : function () {
if(this.get('id') != undefined) {
return this.urlRoot + this.get('id') + "/";
} else {
return this.urlRoot;
}
},
});
app.TutorailList = Backbone.Tastypie.Collection.extend({
model : app.Tutorial,
urlRoot : "/api/v1/tutorial_p/?limit=2",
url : function() {
if(this.timeDuration == "" || this.timeDuration == "vanity") {
return this.urlRoot;
} else {
var mSecondsInDay = 3600*24*1000; //Milliseconds
var endDate = new Date((new Date()).getTime() + mSecondsInDay);
var startTime = 0;
switch(this.timeDuration) {
case "daily" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - mSecondsInDay;
break;
case "weekly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 7*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 7*mSecondsInDay;
break;
case "monthly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 30*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 30*mSecondsInDay;
break;
case "quarterly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 90*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 90*mSecondsInDay;
break;
}
var startDate = new Date(startTime);
var endDateString = getDateString(endDate);
var startDateString = getDateString(startDate);
return this.urlRoot + "&added_time__gte=" + startDateString + "&added_time__lte=" + endDateString;
}
},
setTimeDuration : function(timeDuration) {
this.timeDuration = timeDuration;
},
setTimeSet : function(timeSet) {
this.timeSet = timeSet;
},
});
app.StoreLinkClick = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/shop_url_clicks/",
idAttribute : "id",
url : function () {
if(this.get('id') != undefined) {
return this.urlRoot + this.get('id') + "/";
} else {
return this.urlRoot;
}
},
});
app.StoreLinkClickList = Backbone.Tastypie.Collection.extend({
model : app.StoreLinkClick,
urlRoot : "/api/v1/shop_url_clicks/?limit=2",
url : function() {
if(this.timeDuration == "" || this.timeDuration == "vanity") {
return this.urlRoot;
} else {
var mSecondsInDay = 3600*24*1000; //Milliseconds
var endDate = new Date((new Date()).getTime() + mSecondsInDay);
var startTime = 0;
switch(this.timeDuration) {
case "daily" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - mSecondsInDay;
break;
case "weekly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 7*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 7*mSecondsInDay;
break;
case "monthly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 30*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 30*mSecondsInDay;
break;
case "quarterly" :
if(this.timeSet == "previous") {
endDate = new Date(endDate.getTime() - 90*mSecondsInDay);
}
var endTime = endDate.getTime();
startTime = endTime - 90*mSecondsInDay;
break;
}
var startDate = new Date(startTime);
var endDateString = getDateString(endDate);
var startDateString = getDateString(startDate);
return this.urlRoot + "&added_time__gte=" + startDateString + "&added_time__lte=" + endDateString;
}
},
setTimeDuration : function(timeDuration) {
this.timeDuration = timeDuration;
},
setTimeSet : function(timeSet) {
this.timeSet = timeSet;
},
});
app.Store = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/shop/",
idAttribute : "id",
url : function () {
if(this.get('id') != undefined) {
return this.urlRoot + this.get('id') + "/";
} else {
return this.urlRoot;
}
},
});
app.StoreList = Backbone.Tastypie.Collection.extend({
model : app.Store,
urlRoot : "/api/v1/shop/?limit=2",
url : function() {
return this.urlRoot;
},
});
app.Product = Backbone.Tastypie.Model.extend({
urlRoot : "/api/v1/product_p/",
idAttribute : "id",
url : function () {
if(this.get('id') != undefined) {
return this.urlRoot + this.get('id') + "/";
} else {
return this.urlRoot;
}
},
});
app.ProductList = Backbone.Tastypie.Collection.extend({
model : app.Product,
urlRoot : "/api/v1/product_p/?limit=2",
url : function() {
return this.urlRoot;
},
});
app.initializeUser = function() {
var cur_fb_user = app.cur_fb_user;
if(cur_fb_user == undefined) {
if(!cur_user_details.id) {
alert('Please Login!');
return;
}
cur_fb_user = new app.User({'id' : cur_user_details.id});
cur_fb_user = cur_fb_user.fetch({
success : function(model, response) {
app.cur_fb_user = response;
},
});
}
};
app.ProductLikesView = Backbone.View.extend({
template : Handlebars.compile($('#product_likes').html()),
template_vanity : Handlebars.compile($('#total_product_likes').html()),
initialize : function(options) {
this.counter = 0;
this.mainEl = options.mainEl;
this.timeDuration = options.timeDuration;
this.initLikes();
},
initLikes : function() {
// this.total_likes = new app.ProductLikeList();
// this.total_likes.setTimeDuration("vanity");
this.current_likes = new app.ProductLikeList();
this.current_likes.setTimeDuration(this.timeDuration);
this.current_likes.setTimeSet("current");
this.current_likes.fetch();
this.previous_likes = new app.ProductLikeList();
this.previous_likes.setTimeDuration(this.timeDuration);
this.previous_likes.setTimeSet("previous");
var that = this;
// this.total_likes.fetch({
// success : function() {
// that.render();
// that.renderMain();
// },
// });
this.current_likes.fetch({
success : function() {
that.render();
that.renderMain();
},
});
this.previous_likes.fetch({
success : function() {
that.render();
that.renderMain();
},
});
},
renderMain : function() {
this.counter++;
// if(this.counter == 3) {
if(this.counter == 2) {
this.mainEl.append(this.output);
}
},
render : function() {
// var count_total = this.total_likes.meta.total_count;
var count_present = this.current_likes.meta.total_count;
var count_previous = this.previous_likes.meta.total_count;
var change_value = count_present-count_previous;
var change_percentage = (count_present-count_previous)/(count_previous)*100;
var change_class = "";
if(count_previous > count_present) {
change_class = "text-danger";
} else {
change_class = "text-success";
change_value = "+" + change_value.toString();
}
if(this.timeDuration == "vanity") {
this.output = this.template_vanity({
'value' : count_present,
});
} else {
this.output = this.template({
// 'value' : count_total,
'value' : count_present,
'change_percentage' : change_percentage,
'change_class' : change_class,
'change_value' : change_value,
});
}
return this;
},
});
app.ProductReviewsView = Backbone.View.extend({
template : Handlebars.compile($('#product_reviews').html()),
template_vanity : Handlebars.compile($('#total_product_reviews').html()),
initialize : function(options) {
this.counter = 0;
this.mainEl = options.mainEl;
this.timeDuration = options.timeDuration;
this.initReviews();
},
initReviews : function() {
// this.total_reviews = new app.ProductReviewList();
// this.total_reviews.setTimeDuration("vanity");
this.current_reviews = new app.ProductReviewList();
this.current_reviews.setTimeDuration(this.timeDuration);
this.current_reviews.setTimeSet("current");
this.previous_reviews = new app.ProductReviewList();
this.previous_reviews.setTimeDuration(this.timeDuration);
this.previous_reviews.setTimeSet("previous");
var that = this;
// this.total_reviews.fetch({
// success : function() {
// that.render();
// that.renderMain();
// },
// });
this.current_reviews.fetch({
success : function() {
that.render();
that.renderMain();
},
});
this.previous_reviews.fetch({
success : function() {
that.render();
that.renderMain();
},
});
},
renderMain : function() {
this.counter++;
// if(this.counter == 3) {
if(this.counter == 2) {
this.mainEl.append(this.output);
}
},
render : function() {
// var count_total = this.total_reviews.meta.total_count;
var count_present = this.current_reviews.meta.total_count;
var count_previous = this.previous_reviews.meta.total_count;
var change_value = count_present-count_previous;
var change_percentage = (count_present-count_previous)/(count_previous)*100;
var change_class = "";
if(count_previous > count_present) {
change_class = "text-danger";
} else {
change_class = "text-success";
change_value = "+" + change_value.toString();
}
if(this.timeDuration == 'vanity') {
this.output = this.template_vanity({
'value' : count_present,
});
} else {
this.output = this.template({
// 'value' : count_total,
'value' : count_present,
'change_percentage' : change_percentage,
'change_class' : change_class,
'change_value' : change_value,
});
}
return this;
},
});
app.StoreLikesView = Backbone.View.extend({
template : Handlebars.compile($('#store_likes').html()),
template_vanity : Handlebars.compile($('#total_store_likes').html()),
initialize : function(options) {
this.counter = 0;
this.mainEl = options.mainEl;
this.timeDuration = options.timeDuration;
this.initLikes();
},
initLikes : function() {
// this.total_likes = new app.StoreLikeList();
// this.total_likes.setTimeDuration("vanity");
this.current_likes = new app.StoreLikeList();
this.current_likes.setTimeDuration(this.timeDuration);
this.current_likes.setTimeSet("current");
this.previous_likes = new app.StoreLikeList();
this.previous_likes.setTimeDuration(this.timeDuration);
this.previous_likes.setTimeSet("previous");
var that = this;
// this.total_likes.fetch({
// success : function() {
// that.render();
// that.renderMain();
// },
// });
this.current_likes.fetch({
success : function() {
that.render();
that.renderMain();
},
});
this.previous_likes.fetch({
success : function() {
that.render();
that.renderMain();
},
});
},
renderMain : function() {
this.counter++;
// if(this.counter == 3) {
if(this.counter == 2) {
this.mainEl.append(this.output);
}
},
render : function() {
// var count_total = this.total_likes.meta.total_count;
var count_present = this.current_likes.meta.total_count;
var count_previous = this.previous_likes.meta.total_count;
var change_value = count_present-count_previous;
var change_percentage = (count_present-count_previous)/(count_previous)*100;
var change_class = "";
if(count_previous > count_present) {
change_class = "text-danger";
} else {
change_class = "text-success";
change_value = "+" + change_value.toString();
}
if(this.timeDuration == 'vanity') {
this.output = this.template_vanity({
'value' : count_present,
});
} else {
this.output = this.template({
// 'value' : count_total,
'value' : count_present,
'change_percentage' : change_percentage,
'change_class' : change_class,
'change_value' : change_value,
});
}
return this;
},
});
app.StoreReviewsView = Backbone.View.extend({
template : Handlebars.compile($('#store_reviews').html()),
template_vanity : Handlebars.compile($('#total_store_reviews').html()),
initialize : function(options) {
this.counter = 0;
this.mainEl = options.mainEl;
this.timeDuration = options.timeDuration;
this.initReviews();
},
initReviews : function() {
// this.total_reviews = new app.StoreReviewList();
// this.total_reviews.setTimeDuration("vanity");
this.current_reviews = new app.StoreReviewList();
this.current_reviews.setTimeDuration(this.timeDuration);
this.current_reviews.setTimeSet("current");
this.previous_reviews = new app.StoreReviewList();
this.previous_reviews.setTimeDuration(this.timeDuration);
this.previous_reviews.setTimeSet("previous");
var that = this;
// this.total_reviews.fetch({
// success : function() {
// that.render();
// that.renderMain();
// },
// });
this.current_reviews.fetch({
success : function() {
that.render();
that.renderMain();
},
});
this.previous_reviews.fetch({
success : function() {
that.render();
that.renderMain();
},
});
},
renderMain : function() {
this.counter++;
// if(this.counter == 3) {
if(this.counter == 2) {
this.mainEl.append(this.output);
}
},
render : function() {
// var count_total = this.total_reviews.meta.total_count;
var count_present = this.current_reviews.meta.total_count;
var count_previous = this.previous_reviews.meta.total_count;
var change_value = count_present-count_previous;
var change_percentage = (count_present-count_previous)/(count_previous)*100;
var change_class = "";
if(count_previous > count_present) {
change_class = "text-danger";
} else {
change_class = "text-success";
change_value = "+" + change_value.toString();
}
if(this.timeDuration == "vanity") {
this.output = this.template_vanity({
'value' : count_present,
});
} else {
this.output = this.template({
// 'value' : count_total,
'value' : count_present,
'change_percentage' : change_percentage,
'change_class' : change_class,
'change_value' : change_value,
});
}
return this;
},
});
app.MakeysView = Backbone.View.extend({
template : Handlebars.compile($('#new_makeys').html()),
template_vanity : Handlebars.compile($('#total_makeys').html()),
initialize : function(options) {
this.counter = 0;
this.mainEl = options.mainEl;
this.timeDuration = options.timeDuration;
this.initMakeys();
},
initMakeys : function() {
// this.total_makeys = new app.MakeyList();
// this.total_makeys.setTimeDuration("vanity");
this.current_makeys = new app.MakeyList();
this.current_makeys.setTimeDuration(this.timeDuration);
this.current_makeys.setTimeSet("current");
this.previous_makeys = new app.MakeyList();
this.previous_makeys.setTimeDuration(this.timeDuration);
this.previous_makeys.setTimeSet("previous");
var that = this;
// this.total_makeys.fetch({
// success : function() {
// that.render();
// that.renderMain();
// },
// });
this.current_makeys.fetch({
success : function() {
that.render();
that.renderMain();
},
});
this.previous_makeys.fetch({
success : function() {
that.render();
that.renderMain();
},
});
},
renderMain : function() {
this.counter++;
// if(this.counter == 3) {
if(this.counter == 2) {
this.mainEl.append(this.output);
}
},
render : function() {
// var count_total = this.total_makeys.meta.total_count;
var count_present = this.current_makeys.meta.total_count;
var count_previous = this.previous_makeys.meta.total_count;
var change_value = count_present-count_previous;
var change_percentage = (count_present-count_previous)/(count_previous)*100;
var change_class = "";
if(count_previous > count_present) {
change_class = "text-danger";
} else {
change_class = "text-success";
change_value = "+" + change_value.toString();
}
if(this.timeDuration == "vanity") {
this.output = this.template_vanity({
'value' : count_present,
});
} else {
this.output = this.template({
// 'value' : count_total,
'value' : count_present,
'change_percentage' : change_percentage,
'change_class' : change_class,
'change_value' : change_value,
});
}
return this;
},
});
app.TutorialsView = Backbone.View.extend({
template : Handlebars.compile($('#new_tutorials').html()),
template_vanity : Handlebars.compile($('#total_tutorials').html()),
initialize : function(options) {
this.counter = 0;
this.mainEl = options.mainEl;
this.timeDuration = options.timeDuration;
this.initTutorials();
},
initTutorials : function() {
// this.total_tutorials = new app.TutorailList();
// this.total_tutorials.setTimeDuration("vanity");
this.current_tutorials = new app.TutorailList();
this.current_tutorials.setTimeDuration(this.timeDuration);
this.current_tutorials.setTimeSet("current");
this.previous_tutorials = new app.TutorailList();
this.previous_tutorials.setTimeDuration(this.timeDuration);
this.previous_tutorials.setTimeSet("previous");
var that = this;
// this.total_tutorials.fetch({
// success : function() {
// that.render();
// that.renderMain();
// },
// });
this.current_tutorials.fetch({
success : function() {
that.render();
that.renderMain();
},
});
this.previous_tutorials.fetch({
success : function() {
that.render();
that.renderMain();
},
});
},
renderMain : function() {
this.counter++;
// if(this.counter == 3) {
if(this.counter == 2) {
this.mainEl.append(this.output);
}
},
render : function() {
// var count_total = this.total_tutorials.meta.total_count;
var count_present = this.current_tutorials.meta.total_count;
var count_previous = this.previous_tutorials.meta.total_count;
var change_value = count_present-count_previous;
var change_percentage = (count_present-count_previous)/(count_previous)*100;
var change_class = "";
if(count_previous > count_present) {
change_class = "text-danger";
} else {
change_class = "text-success";
change_value = "+" + change_value.toString();
}
if(this.timeDuration == "vanity") {
this.output = this.template_vanity({
'value' : count_present,
});
} else {
this.output = this.template({
// 'value' : count_total,
'value' : count_present,
'change_percentage' : change_percentage,
'change_class' : change_class,
'change_value' : change_value,
});
}
return this;
},
});
app.StoreLinkClicksView = Backbone.View.extend({
template : Handlebars.compile($('#store_link_clicks').html()),
template_vanity : Handlebars.compile($('#total_clicks').html()),
initialize : function(options) {
this.counter = 0;
this.mainEl = options.mainEl;
this.timeDuration = options.timeDuration;
this.initClicks();
},
initClicks : function() {
// this.total_clicks = new app.StoreLinkClickList();
// this.total_clicks.setTimeDuration("vanity");
this.current_clicks = new app.StoreLinkClickList();
this.current_clicks.setTimeDuration(this.timeDuration);
this.current_clicks.setTimeSet("current");
this.previous_clicks = new app.StoreLinkClickList();
this.previous_clicks.setTimeDuration(this.timeDuration);
this.previous_clicks.setTimeSet("previous");
var that = this;
// this.total_clicks.fetch({
// success : function() {
// that.render();
// that.renderMain();
// },
// });
this.current_clicks.fetch({
success : function() {
that.render();
that.renderMain();
},
});
this.previous_clicks.fetch({
success : function() {
that.render();
that.renderMain();
},
});
},
renderMain : function() {
this.counter++;
// if(this.counter == 3) {
if(this.counter == 2) {
this.mainEl.append(this.output);
}
},
render : function() {
// var count_total = this.total_clicks.meta.total_count;
var count_present = this.current_clicks.meta.total_count;
var count_previous = this.previous_clicks.meta.total_count;
var change_value = count_present-count_previous;
var change_percentage = (count_present-count_previous)/(count_previous)*100;
var change_class = "";
if(count_previous > count_present) {
change_class = "text-danger";
} else {
change_class = "text-success";
change_value = "+" + change_value.toString();
}
if(this.timeDuration == "vanity") {
this.output = this.template_vanity({
'value' : count_present,
});
} else {
this.output = this.template({
// 'value' : count_total,
'value' : count_present,
'change_percentage' : change_percentage,
'change_class' : change_class,
'change_value' : change_value,
});
}
return this;
},
});
app.NewUsersView = Backbone.View.extend({
template : Handlebars.compile($('#new_users').html()),
template_vanity : Handlebars.compile($('#total_users').html()),
initialize : function(options) {
this.counter = 0;
this.mainEl = options.mainEl;
this.timeDuration = options.timeDuration;
this.initUsers();
},
initUsers : function() {
// this.total_users = new app.UserList();
// this.total_users.setTimeDuration("vanity");
this.current_users = new app.UserList();
this.current_users.setTimeDuration(this.timeDuration);
this.current_users.setTimeSet("current");
this.previous_users = new app.UserList();
this.previous_users.setTimeDuration(this.timeDuration);
this.previous_users.setTimeSet("previous");
var that = this;
// this.total_users.fetch({
// success : function() {
// that.render();
// that.renderMain();
// },
// });
this.current_users.fetch({
success : function() {
that.render();
that.renderMain();
},
});
this.previous_users.fetch({
success : function() {
that.render();
that.renderMain();
},
});
},
renderMain : function() {
this.counter++;
// if(this.counter == 3) {
if(this.counter == 2) {
this.mainEl.append(this.output);
}
},
render : function() {
// var count_total = this.total_users.meta.total_count;
var count_present = this.current_users.meta.total_count;
var count_previous = this.previous_users.meta.total_count;
var change_value = count_present-count_previous;
var change_percentage = (count_present-count_previous)/(count_previous)*100;
var change_class = "";
if(count_previous > count_present) {
change_class = "text-danger";
} else {
change_class = "text-success";
change_value = "+" + change_value.toString();
}
if(this.timeDuration == "vanity") {
this.output = this.template_vanity({
'value' : count_present,
});
} else {
this.output = this.template({
// 'value' : count_total,
'value' : count_present,
'change_percentage' : change_percentage,
'change_class' : change_class,
'change_value' : change_value,
});
}
return this;
},
});
app.DailyView = Backbone.View.extend({
el : '#daily',
initialize : function() {
this.$el.append('<div class="row admin_row"></div>');
this.productLikesView = new app.ProductLikesView({
timeDuration : 'daily',
mainEl : this.$el.find('.admin_row').last(),
});
this.productReviewsView = new app.ProductReviewsView({
timeDuration : 'daily',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeLikesView = new app.StoreLikesView({
timeDuration : 'daily',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeReviewsView = new app.StoreReviewsView({
timeDuration : 'daily',
mainEl : this.$el.find('.admin_row').last(),
});
this.$el.append('<div class="row admin_row"></div>');
this.makeysView = new app.MakeysView({
timeDuration : 'daily',
mainEl : this.$el.find('.admin_row').last(),
});
this.tutorialsView = new app.TutorialsView({
timeDuration : 'daily',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeClicksView = new app.StoreLinkClicksView({
timeDuration : 'daily',
mainEl : this.$el.find('.admin_row').last(),
});
this.usersView = new app.NewUsersView({
timeDuration : 'daily',
mainEl : this.$el.find('.admin_row').last(),
});
},
});
app.WeeklyView = Backbone.View.extend({
el : '#weekly',
initialize : function() {
this.$el.append('<div class="row admin_row"></div>');
this.productLikesView = new app.ProductLikesView({
timeDuration : 'weekly',
mainEl : this.$el.find('.admin_row').last(),
});
this.productReviewsView = new app.ProductReviewsView({
timeDuration : 'weekly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeLikesView = new app.StoreLikesView({
timeDuration : 'weekly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeReviewsView = new app.StoreReviewsView({
timeDuration : 'weekly',
mainEl : this.$el.find('.admin_row').last(),
});
this.$el.append('<div class="row admin_row"></div>');
this.makeysView = new app.MakeysView({
timeDuration : 'weekly',
mainEl : this.$el.find('.admin_row').last(),
});
this.tutorialsView = new app.TutorialsView({
timeDuration : 'weekly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeClicksView = new app.StoreLinkClicksView({
timeDuration : 'weekly',
mainEl : this.$el.find('.admin_row').last(),
});
this.usersView = new app.NewUsersView({
timeDuration : 'weekly',
mainEl : this.$el.find('.admin_row').last(),
});
},
});
app.MonthlyView = Backbone.View.extend({
el : '#monthly',
initialize : function() {
this.$el.append('<div class="row admin_row"></div>');
this.productLikesView = new app.ProductLikesView({
timeDuration : 'monthly',
mainEl : this.$el.find('.admin_row').last(),
});
this.productReviewsView = new app.ProductReviewsView({
timeDuration : 'monthly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeLikesView = new app.StoreLikesView({
timeDuration : 'monthly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeReviewsView = new app.StoreReviewsView({
timeDuration : 'monthly',
mainEl : this.$el.find('.admin_row').last(),
});
this.$el.append('<div class="row admin_row"></div>');
this.makeysView = new app.MakeysView({
timeDuration : 'monthly',
mainEl : this.$el.find('.admin_row').last(),
});
this.tutorialsView = new app.TutorialsView({
timeDuration : 'monthly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeClicksView = new app.StoreLinkClicksView({
timeDuration : 'monthly',
mainEl : this.$el.find('.admin_row').last(),
});
this.usersView = new app.NewUsersView({
timeDuration : 'monthly',
mainEl : this.$el.find('.admin_row').last(),
});
},
});
app.QuarterlyView = Backbone.View.extend({
el : '#quarterly',
initialize : function() {
this.$el.append('<div class="row admin_row"></div>');
this.productLikesView = new app.ProductLikesView({
timeDuration : 'quarterly',
mainEl : this.$el.find('.admin_row').last(),
});
this.productReviewsView = new app.ProductReviewsView({
timeDuration : 'quarterly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeLikesView = new app.StoreLikesView({
timeDuration : 'quarterly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeReviewsView = new app.StoreReviewsView({
timeDuration : 'quarterly',
mainEl : this.$el.find('.admin_row').last(),
});
this.$el.append('<div class="row admin_row"></div>');
this.makeysView = new app.MakeysView({
timeDuration : 'quarterly',
mainEl : this.$el.find('.admin_row').last(),
});
this.tutorialsView = new app.TutorialsView({
timeDuration : 'quarterly',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeClicksView = new app.StoreLinkClicksView({
timeDuration : 'quarterly',
mainEl : this.$el.find('.admin_row').last(),
});
this.usersView = new app.NewUsersView({
timeDuration : 'quarterly',
mainEl : this.$el.find('.admin_row').last(),
});
},
});
app.VanityView = Backbone.View.extend({
el : '#vanity',
initialize : function() {
this.$el.append('<div class="row admin_row"></div>');
this.productLikesView = new app.ProductLikesView({
timeDuration : 'vanity',
mainEl : this.$el.find('.admin_row').last(),
});
this.productReviewsView = new app.ProductReviewsView({
timeDuration : 'vanity',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeLikesView = new app.StoreLikesView({
timeDuration : 'vanity',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeReviewsView = new app.StoreReviewsView({
timeDuration : 'vanity',
mainEl : this.$el.find('.admin_row').last(),
});
this.$el.append('<div class="row admin_row"></div>');
this.makeysView = new app.MakeysView({
timeDuration : 'vanity',
mainEl : this.$el.find('.admin_row').last(),
});
this.tutorialsView = new app.TutorialsView({
timeDuration : 'vanity',
mainEl : this.$el.find('.admin_row').last(),
});
this.storeClicksView = new app.StoreLinkClicksView({
timeDuration : 'vanity',
mainEl : this.$el.find('.admin_row').last(),
});
this.usersView = new app.NewUsersView({
timeDuration : 'vanity',
mainEl : this.$el.find('.admin_row').last(),
});
},
});
/* INITIALIZE */
app.initializeUser();
app.daily = new app.DailyView();
app.weekly = new app.WeeklyView();
app.monthly = new app.MonthlyView();
app.quarterly = new app.QuarterlyView();
app.vanity = new app.VanityView();
</script> | {
"content_hash": "736855763c129aa2630e1cb1c40b6844",
"timestamp": "",
"source": "github",
"line_count": 1626,
"max_line_length": 103,
"avg_line_length": 25.56088560885609,
"alnum_prop": 0.6361580289687695,
"repo_name": "Makeystreet/makeystreet",
"id": "dc1617691dbd8b96106c92631b44faef2705367c",
"size": "41562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "woot/apps/catalog/templates/catalog/bb/bb_stats_page_old.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1893401"
},
{
"name": "HTML",
"bytes": "2253311"
},
{
"name": "JavaScript",
"bytes": "1698946"
},
{
"name": "Python",
"bytes": "9010343"
}
],
"symlink_target": ""
} |
CHANGELOG
=========
2.1.0 (2014-10-29)
------------------
* Update ApiGen dependency to version that isn't broken on case sensitive
file systems.
* Added support for the GeoIP2 Anonymous IP database. The
`GeoIP2\Database\Reader` class now has an `anonymousIp` method which returns
a `GeoIP2\Model\AnonymousIp` object.
* Boolean attributes like those in the `GeoIP2\Record\Traits` class now return
`false` instead of `null` when they were not true.
2.0.0 (2014-09-22)
------------------
* First production release.
0.9.0 (2014-09-15)
------------------
* IMPORTANT: The deprecated `omni()` and `cityIspOrg()` methods have been
removed from `GeoIp2\WebService\Client`.
0.8.1 (2014-09-12)
------------------
* The check added to the `GeoIP2\Database\Reader` lookup methods in 0.8.0 did
not work with the GeoIP2 City Database Subset by Continent with World
Countries. This has been fixed. Fixes GitHub issue #23.
0.8.0 (2014-09-10)
------------------
* The `GeoIp2\Database\Reader` lookup methods (e.g., `city()`, `isp()`) now
throw a `BadMethodCallException` if they are used with a database that
does not match the method. In particular, doing a `city()` lookup on a
GeoIP2 Country database will result in an exception, and vice versa.
* A `metadata()` method has been added to the `GeoIP2\Database\Reader` class.
This returns a `MaxMind\Db\Reader\Metadata` class with information about the
database.
* The name attribute was missing from the RepresentedCountry class.
0.7.0 (2014-07-22)
------------------
* The web service client API has been updated for the v2.1 release of the web
service. In particular, the `cityIspOrg` and `omni` methods on
`GeoIp2\WebService\Client` should be considered deprecated. The `city`
method now provides all of the data formerly provided by `cityIspOrg`, and
the `omni` method has been replaced by the `insights` method.
* Support was added for GeoIP2 Connection Type, Domain and ISP databases.
0.6.3 (2014-05-12)
------------------
* With the previous Phar builds, some users received `phar error: invalid url
or non-existent phar` errors. The correct alias is now used for the Phar,
and this should no longer be an issue.
0.6.2 (2014-05-08)
------------------
* The Phar build was broken with Guzzle 3.9.0+. This has been fixed.
0.6.1 (2014-05-01)
------------------
* This API now officially supports HHVM.
* The `maxmind-db/reader` dependency was updated to a version that does not
require BC Math.
* The Composer compatibility autoload rules are now targeted more narrowly.
* A `box.json` file is included to build a Phar package.
0.6.0 (2014-02-19)
------------------
* This API is now licensed under the Apache License, Version 2.0.
* Model and record classes now implement `JsonSerializable`.
* `isset` now works with model and record classes.
0.5.0 (2013-10-21)
------------------
* Renamed $languages constructor parameters to $locales for both the Client
and Reader classes.
* Documentation and code clean-up (Ben Morel).
* Added the interface `GeoIp2\ProviderInterface`, which is implemented by both
`\GeoIp2\Database\Reader` and `\GeoIp2\WebService\Client`.
0.4.0 (2013-07-16)
------------------
* This is the first release with the GeoIP2 database reader. Please see the
`README.md` file and the `\GeoIp2\Database\Reader` class.
* The general exception classes were replaced with specific exception classes
representing particular types of errors, such as an authentication error.
0.3.0 (2013-07-12)
------------------
* In namespaces and class names, "GeoIP2" was renamed to "GeoIp2" to improve
consistency.
0.2.1 (2013-06-10)
------------------
* First official beta release.
* Documentation updates and corrections.
0.2.0 (2013-05-29)
------------------
* `GenericException` was renamed to `GeoIP2Exception`.
* We now support more languages. The new languages are de, es, fr, and pt-BR.
* The REST API now returns a record with data about your account. There is
a new `GeoIP\Records\MaxMind` class for this data.
* The `continentCode` attribute on `Continent` was renamed to `code`.
* Documentation updates.
0.1.1 (2013-05-14)
------------------
* Updated Guzzle version requirement.
* Fixed Composer example in README.md.
0.1.0 (2013-05-13)
------------------
* Initial release.
| {
"content_hash": "66bae3a567fd4e7964140ff1844ab65e",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 78,
"avg_line_length": 32.443609022556394,
"alnum_prop": 0.6878331402085748,
"repo_name": "janstk/boxJae",
"id": "4bf29fd4276f2fb91c79e7498936ebad5e8c373c",
"size": "4315",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bb-vendor/geoip2/geoip2/CHANGELOG.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "67"
},
{
"name": "CSS",
"bytes": "2854580"
},
{
"name": "HTML",
"bytes": "1494367"
},
{
"name": "JavaScript",
"bytes": "2883141"
},
{
"name": "Makefile",
"bytes": "983"
},
{
"name": "PHP",
"bytes": "2805675"
}
],
"symlink_target": ""
} |
<?php
namespace ApaiIO\Request\Soap;
use ApaiIO\Configuration\ConfigurationInterface;
use ApaiIO\Operations\OperationInterface;
use ApaiIO\Request\RequestInterface;
use ApaiIO\Request\Util;
/**
* Basic implementation of the soap request
*
* @see http://docs.aws.amazon.com/AWSECommerceService/2011-08-01/DG/MakingSOAPRequests.html
* @author Jan Eichhorn <exeu65@googlemail.com>
*/
class Request implements RequestInterface
{
/**
* The WSDL File
*
* @var string
*/
protected $webserviceWsdl = 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl';
/**
* The SOAP Endpoint
*
* @var string
*/
protected $webserviceEndpoint = 'https://webservices.amazon.%%COUNTRY%%/onca/soap?Service=AWSECommerceService';
/**
* @var ConfigurationInterface
*/
protected $configuration;
/**
* {@inheritdoc}
*/
public function setConfiguration(ConfigurationInterface $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function perform(OperationInterface $operation)
{
$requestParams = $this->buildRequestParams($operation);
$result = $this->performSoapRequest($operation, $requestParams);
return $result;
}
/**
* Provides some necessary soap headers
*
* @param OperationInterface $operation
*
* @return array Each element is a concrete SoapHeader object
*/
protected function buildSoapHeader(OperationInterface $operation)
{
$timeStamp = Util::getTimeStamp();
$signature = $this->buildSignature($operation->getName() . $timeStamp);
return array(
new \SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'AWSAccessKeyId',
$this->configuration->getAccessKey()
),
new \SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'Timestamp',
$timeStamp
),
new \SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'Signature',
$signature
)
);
}
/**
* Builds the request parameters depending on the operation
*
* @param OperationInterface $operation
*
* @return array
*/
protected function buildRequestParams(OperationInterface $operation)
{
$associateTag = array('AssociateTag' => $this->configuration->getAssociateTag());
return array_merge(
$associateTag,
array(
'AWSAccessKeyId' => $this->configuration->getAccessKey(),
'Request' => array_merge(
array(
'Operation' => $operation->getName()
),
$operation->getOperationParameter()
)
)
);
}
/**
* Performs the soaprequest
*
* @param OperationInterface $operation The operation
* @param array $params Requestparameters 'ParameterName' => 'ParameterValue'
*
* @return array The response as an array with stdClass objects
*/
protected function performSoapRequest(OperationInterface $operation, $params)
{
$soapClient = new \SoapClient(
$this->webserviceWsdl,
array('exceptions' => 1)
);
$soapClient->__setLocation(
str_replace(
'%%COUNTRY%%',
$this->configuration->getCountry(),
$this->webserviceEndpoint
)
);
$soapClient->__setSoapHeaders($this->buildSoapHeader($operation));
return $soapClient->__soapCall($operation->getName(), array($params));
}
/**
* Calculates the signature for the request
*
* @param string $request
*
* @return string
*/
protected function buildSignature($request)
{
return Util::buildSignature($request, $this->configuration->getSecretKey());
}
}
| {
"content_hash": "e687a6e966775bf8efa2d0a10450556d",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 115,
"avg_line_length": 27.32894736842105,
"alnum_prop": 0.5751083293211362,
"repo_name": "markdjames/bookmatchproject",
"id": "a637f434723be15fb8ee19dd7e8a3feeba37028b",
"size": "4769",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/ApaiIO/Request/Soap/Request.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6093"
},
{
"name": "JavaScript",
"bytes": "7201"
},
{
"name": "PHP",
"bytes": "171612"
}
],
"symlink_target": ""
} |
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
education, socio-economic status, nationality, personal appearance, race,
religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at seokju.me@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
| {
"content_hash": "59c4f8a1dee495392729bbe6e953140e",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 87,
"avg_line_length": 45.971014492753625,
"alnum_prop": 0.8221941992433796,
"repo_name": "seokju-na/geeks-diary",
"id": "301aca726c8bd6edff48115eaff50df53f95ca66",
"size": "3227",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CODE_OF_CONDUCT.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "107544"
},
{
"name": "HTML",
"bytes": "51765"
},
{
"name": "JavaScript",
"bytes": "4721"
},
{
"name": "TypeScript",
"bytes": "1224266"
}
],
"symlink_target": ""
} |
namespace dbus {
class Bus;
}
namespace ash {
// CryptohomePkcs11Client is used to communicate with the
// org.chromium.CryptohomePkcs11 interface within org.chromium.UserDataAuth
// service exposed by cryptohomed. All method should be called from the origin
// thread (UI thread) which initializes the DBusThreadManager instance.
class COMPONENT_EXPORT(USERDATAAUTH_CLIENT) CryptohomePkcs11Client {
public:
using Pkcs11IsTpmTokenReadyCallback = chromeos::DBusMethodCallback<
::user_data_auth::Pkcs11IsTpmTokenReadyReply>;
using Pkcs11GetTpmTokenInfoCallback = chromeos::DBusMethodCallback<
::user_data_auth::Pkcs11GetTpmTokenInfoReply>;
// Not copyable or movable.
CryptohomePkcs11Client(const CryptohomePkcs11Client&) = delete;
CryptohomePkcs11Client& operator=(const CryptohomePkcs11Client&) = delete;
// Creates and initializes the global instance. |bus| must not be null.
static void Initialize(dbus::Bus* bus);
// Creates and initializes a fake global instance if not already created.
static void InitializeFake();
// Destroys the global instance.
static void Shutdown();
// Returns the global instance which may be null if not initialized.
static CryptohomePkcs11Client* Get();
// Actual DBus Methods:
// Runs the callback as soon as the service becomes available.
virtual void WaitForServiceToBeAvailable(
chromeos::WaitForServiceToBeAvailableCallback callback) = 0;
// Checks if user's PKCS#11 token (chaps) is ready.
virtual void Pkcs11IsTpmTokenReady(
const ::user_data_auth::Pkcs11IsTpmTokenReadyRequest& request,
Pkcs11IsTpmTokenReadyCallback callback) = 0;
// Retrieves the information required to use user's PKCS#11 token.
virtual void Pkcs11GetTpmTokenInfo(
const ::user_data_auth::Pkcs11GetTpmTokenInfoRequest& request,
Pkcs11GetTpmTokenInfoCallback callback) = 0;
protected:
// Initialize/Shutdown should be used instead.
CryptohomePkcs11Client();
virtual ~CryptohomePkcs11Client();
};
} // namespace ash
// TODO(https://crbug.com/1164001): remove when the migration is finished.
namespace chromeos {
using ::ash::CryptohomePkcs11Client;
}
#endif // CHROMEOS_ASH_COMPONENTS_DBUS_USERDATAAUTH_CRYPTOHOME_PKCS11_CLIENT_H_
| {
"content_hash": "df0543f1a74123563f22a6ee590ab443",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 80,
"avg_line_length": 35.63492063492063,
"alnum_prop": 0.7692650334075724,
"repo_name": "chromium/chromium",
"id": "0c10e6d55078cdfcce5e694e990fa80c0f3aaf9a",
"size": "2834",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "chromeos/ash/components/dbus/userdataauth/cryptohome_pkcs11_client.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
raise "Missing parameter 'CRED_PATH'. Please read docs at #{__FILE__}" \
unless ENV.key?('CRED_PATH')
raise "Missing parameter 'PROJECT'. Please read docs at #{__FILE__}" \
unless ENV.key?('PROJECT')
# For more information on the gauth_credential parameters and providers please
# refer to its detailed documentation at:
# https://github.com/GoogleCloudPlatform/chef-google-auth
gauth_credential 'mycred' do
action :serviceaccount
path ENV['CRED_PATH'] # e.g. '/path/to/my_account.json'
scopes [
'https://www.googleapis.com/auth/sqlservice.admin'
]
end
gsql_tier 'D0' do
ram 134217728 # we'll confirm that tier has enough RAM for us
project ENV['PROJECT'] # ex: 'my-test-project'
credential 'mycred'
end
| {
"content_hash": "058e3fd970e88a4ed3972b25c743c102",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 78,
"avg_line_length": 34.666666666666664,
"alnum_prop": 0.7156593406593407,
"repo_name": "GoogleCloudPlatform/chef-google-sql",
"id": "45f8ddcb3556429a3eaae4a4fc0e1f61066152ed",
"size": "2488",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "recipes/examples~tier.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "437082"
}
],
"symlink_target": ""
} |
package samples;
import com.slack.api.app_backend.dialogs.response.Error;
import com.slack.api.app_backend.dialogs.response.Option;
import com.slack.api.bolt.App;
import com.slack.api.bolt.AppConfig;
import com.slack.api.methods.response.dialog.DialogOpenResponse;
import util.ResourceLoader;
import util.TestSlackAppServer;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class DialogSample {
static final List<Option> allOptions = Arrays.asList(
new Option("Product", "prd"),
new Option("Design", "des"),
new Option("Engineering", "eng"),
new Option("Sales", "sls"),
new Option("Marketing", "mrk")
);
public static void main(String[] args) throws Exception {
AppConfig config = ResourceLoader.loadAppConfig();
App app = new App(config);
app.command("/dialog", (req, ctx) -> {
// src/test/resources/dialogs/dialog.json
String dialog = ResourceLoader.load("dialogs/dialog.json");
DialogOpenResponse apiResponse = ctx.client().dialogOpen(r -> r
.triggerId(req.getPayload().getTriggerId())
.dialogAsString(dialog)
);
ctx.logger.info("dialog.open - {}", apiResponse);
if (apiResponse.isOk()) {
return ctx.ack();
} else {
return ctx.ackWithJson(apiResponse);
}
});
app.dialogSubmission("dialog-callback-id", (req, ctx) -> {
if (req.getPayload().getSubmission().get("comment").length() < 10) {
List<Error> errors = Arrays.asList(
new Error("comment", "must be longer than 10 characters"));
return ctx.ack(errors);
} else {
ctx.respond(r -> r.text("Thanks!!"));
return ctx.ack();
}
});
app.dialogSuggestion("dialog-callback-id", (req, ctx) -> {
String keyword = req.getPayload().getValue();
List<Option> options = allOptions.stream()
.filter(o -> o.getLabel().contains(keyword))
.collect(toList());
return ctx.ack(r -> r.options(options));
});
app.dialogCancellation("dialog-callback-id", (req, ctx) -> {
ctx.respond(r -> r.text("Next time :smile:"));
return ctx.ack();
});
TestSlackAppServer server = new TestSlackAppServer(app, "/dialog");
server.start();
}
}
| {
"content_hash": "e61aa428546dd9e82b5e6a0c0e70df08",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 83,
"avg_line_length": 35.465753424657535,
"alnum_prop": 0.5662417921977597,
"repo_name": "seratch/jslack",
"id": "f196b1f04534fc04eae52f5bb0177547eff185c9",
"size": "2589",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bolt-servlet/src/test/java/samples/DialogSample.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3120"
},
{
"name": "Dockerfile",
"bytes": "253"
},
{
"name": "Java",
"bytes": "2053529"
},
{
"name": "Kotlin",
"bytes": "26226"
},
{
"name": "Ruby",
"bytes": "3769"
},
{
"name": "Shell",
"bytes": "1133"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.