I have a route with path("employee") that does simple POST and path("transaction") what it does is it tries to add data twice to the db. But i fail it by entering a column data more than 255 chars that has max length of 255 and i get the
ERROR: value too long for type character varying(255)
which is expected. But after the "transaction" post request, when i hit the "employee" post request. The data is added to the db but skipping the employeeID because previously i had hit post on "transaction".
Here is my route:-
path("transaction") {
post {
entity(as[String]) { data =>
complete {
controller.insertEmployeeTwice(data).map { res =>
HttpResponse(status = StatusCodes.OK, entity = HttpEntity(MediaTypes.`application/json`, compact(Extraction.decompose(res))))
}
}
}
}
}
Controller:-
def insertEmployeeTwice(data: String): Future[EmployeeResult] = {
val employee = data.parseJson.convertTo[Employee]
ImplEmployeeRepository.insertTwice(employee)
}
Repo:-
def insertTwice(row: Employee): Future[DbEmployee] = {
val userId = 10
val uuid = UUID.randomUUID().toString
val timeStamp = Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date()))
val saveData1 = DbEmployee(uuid, row.firstName, row.lastName, row.address, row.phoneNumber, row.age, timeStamp, userId)
val lengthLastName = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec"
val saveData2 = DbEmployee(uuid, row.firstName, lengthLastName, row.address, row.phoneNumber, row.age, timeStamp, userId)
insertTwoRows(saveData1, saveData2)
}
Base Repo:-
def insertTwoRows(r1: E, r2: E): Future[E] = {
db.run(insertTwoRowsQuery(r1, r2))
}
def insertTwoRowsQuery(row1: E, row2:E): DBIOAction[E, NoStream, Effect.Write with Effect.Transactional] = {
(for {
_ <- query returning query += row1
r <- query returning query += row2
} yield r).transactionally
}
Related
I'm currently using this function bellow to capture text after a certain keyword in a String of text :
static String? _getTextAfterKeyword({
required String inputtext,
required String keyword,
}) {
final indexKeyword = text.indexOf(keyword);
final indexAfter = indexKeyword + keyword.length;
if (indexKeyword == -1) {
return null;
} else {
return text.substring(indexAfter).trim();
}
}
Now I'm trying to capture a String of text in between two keywords - but what I've tried hasn't worked - 🙏
To illustrate this is what I need :
inputtext = "Lorem ipsum Lorem ipsum Lorem ipsum FIRSTKEYWORD - text I would like to return - SECONDKEYWORD Lorem ipsum Lorem ipsum Lorem ipsum"
the function would look something like this :
static String? _getTextInBetweenTwoKeywords({
required String inputtext,
required String firstKeyword,
required String SecondKeyword,
}) {
//Some Code
return the StringInBetweentheTwoKeywords;
}
``
Would something like this do the trick?
String capture(String first, String second, String input) {
int firstIndex = input.indexOf(first) + first.length;
int secondIndex = input.indexOf(second);
return input.substring(firstIndex, secondIndex);
}
void main() {
print(capture('FIRST', 'SECOND', 'AAAAAAA FIRST-what should print-SECOND BBBBBB')); // prints '-what should print-';
}
I'd like to convert a string to Date but I get this error when display date in Text :
Trying to read / from 2020-04-18 19:43:43.755927 at position 5
and this is the function
String get dateNote {
var d = DateFormat("yyyy/MM/dd", "en_US").parse(createdAt);
return d.toString();
}
final String date = '2020-04-18 19:43:43.755927';
String getFormattedDate(String date) {
var d = DateTime.parse(date);
return [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
][d.month - 1] +
" " + d.day.toString() +
"," +
d.year.toString();
}
print(getFormattedDate(date));
Output : Apr 18,2020
I found a short solution:
String get dateNote {
var date = DateTime.parse(createdAt);
var strDate = DateFormat("yyyy-MM-dd").format(date).toString();
return strDate;
}
I have one problem in Apache Spark GraphX, i tried to partition one graph with this method in the main:
graph.partitionBy(HDRF, 128)
HDRF is a method to do partitioning, I would like to print a val that is inside it, I tried to print but it does not print anything
/EDIT/
package app
import org.apache.spark.graphx._
import org.apache.spark._
import org.apache.spark.rdd.RDD
/**
* Main del sistema
*/
object Main{
def main(args: Array[String]) {
val sc = new SparkContext(new SparkConf().setMaster("local").setAppName("HDRF"))
// mostra solo i log in caso di errore
sc.setLogLevel("ERROR")
//modifico il file di testo preso in ingresso
val edges:RDD[Edge[String]]=
sc.textFile("data/u1.base").map{ line =>
val fields= line.split("\t")
Edge(fields(0).toLong,fields(1).toLong,fields(2))
}
val graph: Graph[Any,String] =Graph.fromEdges(edges,"defaultProperty")
graph.partitionBy(HDRF,128)
}
}
.
package app
import org.apache.spark.graphx._
import scala.collection.concurrent.TrieMap
object HDRF extends PartitionStrategy{
private var init=0; //lo puoi usare per controllare una fase di inizializzazione che viene eseguita solo la prima volta
private var partitionsLoad:Array[Long] = Array.empty[Long] //carico (numero di archi) di ogni partizione
private val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap() //lista di partizioni associate a ogni vertice
private val vertexIdEdges: TrieMap[Long, Long] = TrieMap() //grado di ogni vertice
private var edges = 0
private var sum :Long= 0
override def getPartition(src:VertexId,dst:VertexId,numParts:Int): PartitionID ={
var valoreMax:Long =Int.MaxValue
var partScarica:Int = -1
var c:Int = 0
if(init==0){
init=1
partitionsLoad=Array.fill[Long](numParts)(0)
}
//AGGIORNA IL GRADO CONOSCIUTO DEI VERTICI src E dst NELLA VARIABILE vertexIdEdges
vertexIdEdges(src)=vertexIdEdges(src)+1
vertexIdEdges(dst)=vertexIdEdges(dst)+1
sum=vertexIdEdges(src) + vertexIdEdges(dst)
//PARTIZIONA IL GRAFO
if((!vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst))){
//NESSUNO DEI DUE VERTICI E' STATO MAI INSERITO IN QUALCHE PARTIZIONE
//SCELGO LA PARTZIIONE PIU' SCARICA E LI ASSEGNO A QUELLA
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
valoreMax=partitionsLoad(c)
partScarica=c
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(src, dst))
}
return partScarica
}else if(((vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst)))||((!vertexIdListPartitions.contains(src))&&(vertexIdListPartitions.contains(dst)))){
//UNO SOLO DEI DUE VERTICI E' GIA' PRESENTE IN ALMENO UNA PARTIZIONE
if((vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst))){
//SI TRATTA DI src
//SCELGO LA PARTIZIONE PIU' SCARICA TRA QUELLE IN CUI E' PRESENTE src E CI REPLICO dst
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
if(vertexIdListPartitions(c).contains(src)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(dst))
}
}else{
//SI TRATTA DI dst
//SCELGO LA PARTZIIONE PIU' SCARICA TRA QUELLE IN CUI E' PRESENTE dst E CI REPLICO src
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
if(vertexIdListPartitions(c).contains(src)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(src))
}
}
}else if(!vertexIdListPartitions(src).intersect(vertexIdListPartitions(dst)).isEmpty){
//ENTRAMBI I VERTICI SONO PRESENTI IN DIVERSE PARTIZIONI ED ESISTE UNA INTERSEZIONE DEI SET NON NULLA (CIOE' ESISTE ALMENO UNA PARTIZIONE CHE LI CONTIENE ENTRAMBI)
//SCELGO NELL'INTERSEZIONE DEI SET LA PARTIZIONE PIU' SCARICA
while(c==numParts) {
if (partitionsLoad(c) < valoreMax) {
if (vertexIdListPartitions(c).contains(src) && vertexIdListPartitions(c).contains(dst)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c = c + 1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(src))
}
}else {
//ENTRAMBI I VERTICI SONO PRESENTI IN DIVERSE PARTIZIONI MA L'INTERSEZIONE DEI SET E' NULLA (CIOE' NON ESISTE ALCUNA PARTIZIONE CHE LI CONTIENE ENTRAMBI)
if((vertexIdEdges(src))>=(vertexIdEdges(dst))){
//SCELGO TRA LE PARTIZIONI A CUI E' ASSEGNATO dst QUELLA PIU' SCARICA E CI COPIO src
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
if(vertexIdListPartitions(c).contains(dst)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(src))
}
}else{
//SCELGO TRA LE PARTIZIONI A CUI E' ASSEGNATO src QUELLA PIU' SCARICA E CI COPIO dst
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
if(vertexIdListPartitions(c).contains(src)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(dst))
}
}
}
edges=edges+1
if(edges==80000) {
print(sum)
}
return partScarica
}
}
I need to print sum, but I don't understand why it does not appear.
partitionBy, like many Graph functions, is a lazily-evaluated operation that generates a new Graph object, but doesn't actually compute that Graph until it's necessary - i.e. until some action is performed on the result (e.g. counting, persisting, or collecting it).
Using a simpler example we can see that if we act on the result, these prints will be visible:
object SimpleExample extends PartitionStrategy {
override def getPartition(src: VertexId, dst: VertexId, numParts: PartitionID): PartitionID = {
println("partitioning!")
numParts
}
}
val result = graph.partitionBy(SimpleExample, 128) // nothing printed so far...
result.edges.count() // now that we act on the result,
// we see "paritioning!" printed (several times).
NOTE that printing from a PartitionStrategy (or any transformation function passed to Spark to be performed on an RDD, a Graph, or a Dataset) is not too helpful: these functions are executed on the worker nodes, hence these prints will be "scattered" in outputs of different processes on different machines, and would probably NOT be visible in the output of the driver application (your main function).
Here is my scala case class DateRange:
case class DateRange(startDT: DateTime, endDT: DateTime)
The sample input data (Joda):
val dt1 = DateTime.parse("2016-01-04T03:00:00.000Z") // dt1 will always the range start date time
val dt2 = DateTime.parse("2016-01-05T04:00:00.000Z") // dt2 will always the range end date time
val dr = DateRange(dt1, dt2) // container to hold the date ranges
val st = LocalTime.parse("13:00:00") // st will always the stoppage start time
val et = LocalTime.parse("02:00:00") // et will always the stoppage end time
I am trying to get the result as List[DateRange] excluding the stoppage timing intervals. The Date ranges and time ranges maybe anything.
Desired output for the above input data:
List(DateRange(2016-01-04T03:00:00.000Z,2016-01-04T13:00:00.000Z),DateRange(2016-01-05T02:00:00.000Z,2016-01-05T04:00:00.000Z))
I tried like this:
val result = if (st.isBefore(et)) {
if (dr.startDT.isBefore(dr.endDT) && st.isAfter(dr.startDT.toLocalTime)) {
DateRange(dr.startDT.withTime(st), dr.startDT.withTime(et))
} else if (dr.startDT.isBefore(dr.endDT) && st.isBefore(dr.startDT.toLocalTime)) {
DateRange(dr.endDT.withTime(st), dr.endDT.withTime(et))
} else {
DateRange(dr.startDT.withTime(st), dr.startDT.withTime(et))
}
}
else {
if (dr.startDT.isBefore(dr.endDT) && et.isBefore(dr.endDT.toLocalTime) && st.isBefore(dr.endDT.toLocalTime)) {
DateRange(dr.startDT.withTime(st), dr.endDT.withTime(23, 59, 59, 999))
} else if (dr.startDT.isBefore(dr.endDT) && et.isBefore(dr.endDT.toLocalTime) && st.isAfter(dr.endDT.toLocalTime)) {
DateRange(dr.startDT, dr.endDT.withTime(et))
} else if (dr.startDT.isBefore(dr.endDT) && et.isBefore(dr.endDT.toLocalTime) && st.isAfter(dr.endDT.toLocalTime)) {
DateRange(dr.startDT, dr.endDT.withTime(et))
} else {
DateRange(dr.startDT.withTime(st), dr.endDT.withTime(et))
}
Try This,
object Splitter extends App {
val shiftStartDate = DateTime.parse("2016-01-04T06:00:00.000")
val shiftEndDate = DateTime.parse("2016-01-04T16:00:00.000")
val st = LocalTime.parse("23:00:00")
val et = LocalTime.parse("08:00:00")
val stoppageStartDate = shiftStartDate.toLocalDate.toDateTime(st)
val StoppageEndDate = if(st.isBefore(et)){
shiftStartDate.toLocalDate.toDateTime(et)
}else{
shiftStartDate.toLocalDate.toDateTime(et).plusDays(1)
}
val result = if ((stoppageStartDate.isAfter(shiftStartDate) || stoppageStartDate.isEqual(shiftStartDate)) &&
(StoppageEndDate.isBefore(shiftEndDate) || StoppageEndDate.isEqual(shiftEndDate))) {
List(DateRange(shiftStartDate, stoppageStartDate), DateRange(StoppageEndDate, shiftEndDate))
} else if ((stoppageStartDate.isAfter(shiftStartDate) || stoppageStartDate.isEqual(shiftStartDate)) &&
StoppageEndDate.isAfter(shiftEndDate) && stoppageStartDate.isBefore(shiftEndDate)) {
List(DateRange(shiftStartDate, stoppageStartDate))
}
else if (stoppageStartDate.isBefore(shiftStartDate) && (StoppageEndDate.isBefore(shiftEndDate) ||
StoppageEndDate.isEqual(shiftEndDate)) && StoppageEndDate.isAfter(shiftStartDate)) {
List(DateRange(StoppageEndDate, shiftEndDate))
} else if (stoppageStartDate.isBefore(shiftStartDate) && StoppageEndDate.isAfter(shiftEndDate)) {
Nil
} else {
List(DateRange(shiftStartDate, shiftEndDate))
}
println(">>>> " + result.result.filterNot(x=>x.startTS==x.endTS))
}
What's wrong in my code ? I want to update or insert an Moteur object depending on url.
Thanks by advance.
/**
* #Route("/moteur/{moteurid}", name="moteur", requirements={"moteurid" = "\d+"}, defaults={"moteurid" = null})
* #Template()
*
* Cette page permet d'enregistrer de nouveaux moteurs (et de les éditer).
*/
public function moteurAction($moteurid)
{
$args=array();
$avertissement = null;
if (!$this->get('security.context')->isGranted('ROLE_ADMIN'))
{
$avertissement = "Vous n'avez pas le droit d'accéder à cet espace.";
return $this->redirect($this->generateUrl('index', array('avertissement' => $avertissement)));
}
$args['menu']['admin'] = 'selected';
$obj = null;
if ($moteurid == null)
{
$obj = new Moteur();
}
else
{
$obj = $this->getDoctrine()->getRepository('CreasixtineAFBundle:Moteur')->find($moteurid);
}
$form = $this->createForm(new FormMoteur(), $obj);
$args['form'] = $form->createView();
if ($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest());
if ($form->isValid())
{
$obj = $form->getData(); // Type Moteur()
$pn = $obj->getPnid();
$em = $this->getDoctrine()->getEntityManager();
if ($moteurid == null)
{
$em->persist($obj);
$avertissement = "Moteur créé !";
}
else
{
// Rien, le moteur sera mis à jour avec flush()
$avertissement = "Moteur mis à jour !";
}
foreach ($pn as $my_pn){$em->persist($my_pn);}
$em->flush();
return $this->redirect($this->generateUrl('admin', array('avertissement' => $avertissement)));
}
else
{
throw new Exception("Le formulaire n'est pas valide.");
}
}
$contenu = $this->rendu($args, "formulaire_moteur.html.twig");
return $contenu;
}
First, you don't need this line as PHP5 natively passes object by reference :
$obj = $form->getData(); // Type Moteur()
Then, your relation between Moteur and Pn is a bit confusing. You get a Pn with getPnid() but you get an object you wanna persist ?
Anyway, these Pn objects should be persisted before Moteur, so here is what I would write :
if ($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$pn = $obj->getPnid();
//Persist these related objects BEFORE Moteur
foreach ($pn as $my_pn)
{
$em->persist($my_pn);
}
if ($moteurid == null)
{
$em->persist($obj);
$avertissement = "Moteur créé !";
}
else
{
// Rien, le moteur sera mis à jour avec flush()
$avertissement = "Moteur mis à jour !";
}
$em->flush();
return $this->redirect($this->generateUrl('admin', array('avertissement' => $avertissement)));
}
else
{
throw new Exception("Le formulaire n'est pas valide.");
}