text:
Q: Update CCRC view via windows command line and integrate it in Jenkins I've been looking for a way to update my CCRC view via windows command line in a non-interactive way.
I'm using Jenkins and today there isn't a plugin for CCRC yet (https://issues.jenkins-ci.org/browse/JENKINS-5192), so I'm trying, as a first step, to auto update my CCRC view via batch script. I installed Managed Script Plugin (https://wiki.jenkins-ci.org/display/JENKINS/Managed+Script+Plugin) and wrote this simple script:
cd C:\Views\PathToMyViewVOB
rcleartool login -lname MyUser -server MyServer.com -password MyPass
rcleartool update

With this script, in the first execution, the login works correctly, but, I don't know why, Jenkins ignores the update command. In the following executions, it shows this error:
CRCLI2014E You have already logged on the server
"MyServer.com".
Build step 'Execute managed windows batch' marked build as failure
Finished: FAILURE

I've also tried with this other command, thinking that you can pass my credentials with any subcommands of rcleartool:
cd C:\Views\PathToMyViewVOB
rcleartool update -username MyUser -password MyPass -server MyServer.com

And this is the error now:
CRCLI2001E Unrecognized option: "-username".
Use: update [-print] [-ove/rwrite | -nove/rwrite | -ren/ame] [-pti/me][nombrep ...]
update -add/_loadrules [-print] [-ove/rwrite | -nove/rwrite | -ren/ame][-pti/me] nombrep [...]
Build step 'Execute managed windows batch' marked build as failure
Finished: FAILURE

I've thought in a script that checks if I'm already logged, if not, log in and then update, if yes, only update, and then go on with the compilation, but I don't know how to do that.
Is there any way to do what I want, auto update the CCRC? I can always do it manually, but...you know, it's better non-interactive.
Any suggestions, advice or idea will be helpful.

A: It depends on the version of ClearCase that you are using.
Before CC 8.0.1.9, there is this bug where, in non interactive mode, IBM ClearCase rcleartool waits on prompt for login when previous login failed, instead of reporting an error and not prompt the user.
As mentioned in this thread, you need to make sure CCSHARED & JAVA_HOME are properly in the rcleartool config.ini, as in here:
CCSHARED=C:\Program Files (x86)\IBM\IMShared
JAVA_HOME=C:\Program Files (x86)\Java\jre7

Those paths are example only, and might differ from your actual path.
The point is: they must be valid in the Jenkins job execution context (on the slave)
The OP Alavaros mentions in the comments:

only updating the version fixed the problem, now I do:

rcleartool update -lname MyUser -server MyServer -password MyPass

And works fine.

A: "rcleartool update" is ignored because rcleartool.bat itself is a batch file so u have to use "call rcleartool -params args" in each line in your batch file.


text:
Q: VB.net decrypt rinjdael-128 encrypted string I am writing a VB.Net app that reads and decrypts the response from a JSON web service. I have the secret passphrase and I am able to decrypt the encrypted string without a problem using online decryption tools and such. However, I have yet to be able to figure out how to write the code in VB.Net.
Below is an example of the encrypted string returned from the JSON web service:
[encoded data, 16088 characters]

Key:

d40da16b8bc6b5e33ef3ae5f704edb2b

I know that it is Rinjdael-128 encryption and that the string needs to be Base64 decoded. I just cant seem figure out the code to do it in VB.Net. I have tried a number of examples onlinethe likes, but nothing I do gets the expected result. The expected will be a JSON should be a JSON formatted string.
Here is my latest attempt that has failed miserably:
Dim rmt As RijndaelManaged = New RijndaelManaged()

   Using rmt
       rmt.KeySize = 128
       rmt.Mode = CipherMode.CBC
       rmt.Padding = PaddingMode.ISO10126

       Dim ciphertext() As Byte = Convert.FromBase64String(json)

       Dim plaintext() As Byte = rmt.CreateDecryptor(Convert.FromBase64String(key), System.Text.Encoding.ASCII.GetBytes(InitialVector)).TransformFinalBlock(ciphertext, 0, ciphertext.Length)

       Dim decryptedtext As String = System.Text.Encoding.UTF8.GetString(plaintext)
                        Console.WriteLine(decryptedtext)
   End Using

I would greatly appreciate any insight or help that anyone can offer.
Thanks

A: The answer is, as most of the time, not so much in the encryption as in the (character) encodings and knowing how the IV and padding is applied. If you correct the encoding of the key, the IV and use the correct padding, then the message should decrypt.
This answer more or less sums up the suggestions in the comments that managed to retrieve the plain text; most importantly the key was in hexadecimals instead of base64.

A: I built this dll a long time ago. It works for Rijndael decryption. I hope this solves your problem:
Imports Microsoft.VisualBasic
Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Imports Microsoft.Win32

Public Class GateKeeper

    Public Function Decipher(ByVal vstrStringToBeDecrypted As String, ByVal vstrDecryptionKey As String) As String

        Dim bytDataToBeDecrypted() As Byte
        Dim bytTemp() As Byte
        Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62}
        Dim objRijndaelManaged As New RijndaelManaged
        Dim objMemoryStream As MemoryStream
        Dim objCryptoStream As CryptoStream
        Dim bytDecryptionKey() As Byte

        Dim intLength As Integer
        Dim intRemaining As Integer
        Dim intCtr As Integer
        Dim strReturnString As String = String.Empty
        Dim achrCharacterArray() As Char
        Dim intIndex As Integer
        Dim StripNullCharactersFunc As New StringHandler

        bytDataToBeDecrypted = Convert.FromBase64String(vstrStringToBeDecrypted)

        intLength = Len(vstrDecryptionKey)

        If intLength >= 32 Then
            vstrDecryptionKey = Strings.Left(vstrDecryptionKey, 32)
        Else
            intLength = Len(vstrDecryptionKey)
            intRemaining = 32 - intLength
            vstrDecryptionKey = vstrDecryptionKey & Strings.StrDup(intRemaining, "X")
        End If

        bytDecryptionKey = Encoding.ASCII.GetBytes(vstrDecryptionKey.ToCharArray)

        ReDim bytTemp(bytDataToBeDecrypted.Length)

        objMemoryStream = New MemoryStream(bytDataToBeDecrypted)

        Try

            objCryptoStream = New CryptoStream(objMemoryStream, _
               objRijndaelManaged.CreateDecryptor(bytDecryptionKey, bytIV), _
               CryptoStreamMode.Read)

            objCryptoStream.Read(bytTemp, 0, bytTemp.Length)

            objCryptoStream.FlushFinalBlock()
            objMemoryStream.Close()
            objCryptoStream.Close()

        Catch

        End Try

        Return StripNullCharactersFunc.StripNullCharacters(Encoding.ASCII.GetString(bytTemp))

    End Function

End Class

Imports Microsoft.VisualBasic
Imports System.Text.RegularExpressions

Public Class StringHandler

    'lets get rid oof spaces
    Public Function StripNullCharacters(ByVal vstrStringWithNulls As String) As String
        'This function removes spaces from strings

        Dim intPosition As Integer
        Dim strStringWithOutNulls As String

        intPosition = 1
        strStringWithOutNulls = vstrStringWithNulls

        Do While intPosition > 0
            intPosition = InStr(intPosition, vstrStringWithNulls, vbNullChar)

            If intPosition > 0 Then
                strStringWithOutNulls = Left$(strStringWithOutNulls, intPosition - 1) & _
                                  Right$(strStringWithOutNulls, Len(strStringWithOutNulls) - intPosition)
            End If

            If intPosition > strStringWithOutNulls.Length Then
                Exit Do
            End If
        Loop

        Return strStringWithOutNulls

    End Function

End Class

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django filter queryset on "tuples" of values for multiple columns Say I have a model:
Class Person(models.Model):
    firstname = models.CharField()
    lastname = models.CharField()
    birthday = models.DateField()
    # etc...

and say I have a list of 2 first names: first_list = ['Bob', 'Rob'] And I have a list of 2 last names: last_list = ['Williams', 'Williamson'].  Then if I wanted to select everyone whose first name was in first_list I could run:
Person.objects.filter(firstname__in=first_list)

and if I wanted to select everyone whose last name was in last_list, I could do:
Person.objects.filter(lastname__in=last_list)

So far, so good.  If I want to run both of those restrictions at the same time, that's easy...
Person.objects.filter(firstname__in=first_list, lastname__in=last_list)

If I wanted to do the or style search instead of the and style search, I can do that with Q objects:
Person.objects.filter(Q(firstname__in=first_list) | Q(lastname__in=last_name))

But what I have in mind is something a bit more subtle.  What if I just want to return a queryset that returns specific combinations of first and last names?  I.e. I want to return the Person objects for which (Person.firstname, Person.lastname) is in zip(first_names, last_names).  I.e. I want to get back anyone named the Bob Williams or Rob Williamson (but not anyone named Bob Williamson or Rob Williams).
In my actual use case, first_list and last_list would both have ~100 elements.
At the moment, I need to solve this problem in a Django app.  But I am also curious about the best way to handle this in a more general SQL context.
Thanks!  (And please let me know if I can clarify anything.)

A: I don't see much solutions except for a big OR clause:
import operator
from itertools import izip
query = reduce(
    operator.or_,
    (Q(firstname=fn, lastname=ln) for fn, ln in izip(first_list, last_list))
    )

Person.objects.filter(query)

A: bruno's answer works, but it feels dirty to me - both on the Python level and on the SQL level (a large concatenation of ORs). In MySQL at least, you can use the following SQL syntax:
SELECT id FROM table WHERE (first_name, last_name) IN
       (('John','Doe'),('Jane','Smith'),('Bill','Clinton'))

Django's ORM doesn't provide a direct way to do this, so I use raw SQL:
User.objects.raw('SELECT * FROM table WHERE (first_name, last_name) IN %s',
      [ (('John','Doe'),('Jane','Smith'),('Bill','Clinton')) ])

(This is a list with one element, matching the single %s in the query. The element is an iterable of tuples, so the %s will be converted to an SQL list of tuples).
Notes:

*

*As I said, this works for MySQL. I'm not sure what other backends support this syntax.

*A bug in python-mysql, related to this behavior, was fixed in November 2013 / MySQLdb 1.2.4, so make sure your Python MySQLdb libraries aren't older than that.

A: Using python 3.5 version :
import operator
import functools

query = functools.reduce(
    operator.or_,
    (Q(firstname=fn, lastname=ln) for fn, ln in zip(first_list, last_list))
    )

Person.objects.filter(query)


text:
Q: Error when trying to start python.exe from C# I am trying to execute a python script from C#. I found a way to accomplish this in another post at the following link: run a python script from c#. However, I am getting an error when the process arrives to the using (Process process = Process.Start(start)) line. Here is the code that I am implementing:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RunPy
{
    class Program
    {
        static void Main(string[] args)
        {
            // As an example, cmd would be @C:/Python26/python.exe and args would be C://Python26//test.py 100
            String cmd = "@C:/Program Files (x86)/Python27/python.exe";
            String argss = "C:/My_Python_lib/happyBirthday.py 'joe'";
            // Console.Write(argss); this line is just to test the output of the above argss
            // Console.ReadLine(); this line goes with the above line to prevent the window from closing so fast
            run_cmd(cmd, argss);
            //ProcessStartInfo startInfo = new ProcessStartInfo();
            //startInfo.FileName = cmd;
            //Process.Start(cmd);

        }
        private static void run_cmd(string cmd, string args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = cmd;
            start.Arguments = args;
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    Console.Write(result);
                }
            }
        }
    }
}

Here is the error that I am getting back:

An unhandled exception of type 'System.ComponentModel.Win32Exception'
  occurred in System.dll

Any help would be appreciated. Thanks!

A: You're initializing your cmd variable incorrectly. The "@" should precede the quotation mark (i.e. @"C:/..."). Of course, using forward slashes instead of backslashes negates the need for the verbatim string anyway so you can omit the "@" altogether.
String cmd = "C:/Program Files (x86)/Python27/python.exe";

A: try it
string cmd = @"C:\Program Files (x86)\Python27\python.exe";

or
string cmd = @"C:\PROGRA~1\Python27\python.exe";

A: read and load python exe into memory first.
var assembly = Assembly.GetExecutingAssembly();
var resourcePath = assembly.GetManifestResourceNames().Single(str => str.EndsWith("python.exe"));
FileStream outputFileStream = new FileStream(Path.Combine(Directory.GetCurrentDirectory(), resourcePath), FileMode.OpenOrCreate, FileAccess.ReadWrite);
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
{
    if (stream != null)
    {
        stream.CopyTo(outputFileStream);
        stream.Close();
    }
    outputFileStream.Close();
}


text:
Q: Как разместить виджет/кнопку/текст PySimpleGUI в заданных координатах Я не знаю как это сделать без Tkinter. Нашел только как это сделать в Tkinter
b = tk.Button(self.YoureName,text='Button')
b.place(x=120,y=62)

Если можете дайте хорошую документацию на PySimpleGUI/Tkinter

A:
Если можете дайте хорошую документацию на

PySimpleGUI - https://pysimplegui.readthedocs.io/en/latest/
Там есть пример, как разместить окно window2 относительно окна window1:
window2.move(window1.current_location()[0], window1.current_location()[1] + 220)

TkInter. "Программирование GUI на Python". Светлана Шапошникова
https://younglinux.info/tkinter/course
Рекомендую скачать в виде PDF - там с исходами.


text:
Q: maven-assembly-plugin I'm trying to add a classpath to the jar generated by the maven-assembly-plugin. The assembly bulids, except the manifest has no classpath. Below is my configuration. Any help would be appreciated. Thanks!
<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <executions>
    <execution>
      <id>make-assembly</id>
      <phase>package</phase>
      <goals>
        <goal>assembly</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <descriptors>
      <descriptor>assembly/package.xml</descriptor>
    </descriptors>
    <archive>
      <manifest>
        <mainClass>mymain.Main</mainClass>
        <addClasspath>true</addClasspath>
      </manifest>
    </archive>
  </configuration>
</plugin>

A: I see you are using a custom assembly descriptor. But the plugin's documentation page has this to say about the <archive> element:

At this point, only the jar assembly format supports the <archive> configuration element.  By definition, directory-based assembly mojos - assembly:directory, assembly:directory-inline, and assembly:directory-single - do not produce a jar-format archive, and therefore do not support the <archive> element.

A: It doesn't add classpath but adds main-class because there is a bug http://jira.codehaus.org/browse/MASSEMBLY-334


text:
Q: How autostart python script in RaspBerry Pi 3 (Raspbian (Debian))? The problem is that I can not find the way for a Application.py file to auto-execute when the system starts. I have tried several ways; crontab, init.d, rc.local. And the sh script is executed, the problem is that the line where it is: sudo /usr/lib/python3 /home/pi/file.py, nothing happens. I know that the sh is executed, because I create a test1.log file and it is always created when starting.
On the other hand, if I manually execute sudo /etc/init.d/startApp start, everything runs normally and when you put sudo /etc/init.d/inicioApp stop the process stops. Next I leave the file /etc/init.d/startApp, to see if someone can help me, remember that Raspbian is running on a Raspberry Pi 3 Model B V1.2.
The /etc/init.d/startApp file:
#! /bin/sh
# /etc/init.d/startApp

### BEGIN INIT INFO
# Provides: startApp
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start Application
# Description: Start Application.py automatically.
### END INIT INFO

case "$1" in
 start)
  echo "Start Application.py"
  echo "startApp is running" >> /home/pi/test1.log
  sudo /usr/bin/python3 /home/pi/Application.py
  ;;

 stop)
  echo "Stop Application.py"
  /usr/bin/python3 -kill :1
  ;;

 *)
  echo "Usage: /etc/init.d/startApp {start|stop}"
  exit 1
  ;;
esac

exit 0

The /home/pi/Application.py file:
from PIL import Image, ImageTk
import sys

try:
    import tkinter as tk  # Python 3
except ImportError:
    import Tkinter as tk  # Python 2

import RPi.GPIO as GPIO

GPIO_present = True
GPIO_PULSE = 4
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(GPIO_PULSE, GPIO.IN, GPIO.PUD_UP)

class Application(tk.Frame):
    DELAY = 100  # ms
    IMG_DELAY = 200
    POST_DELAY = 2000

    def __init__(self, master=None):
        super().__init__(master)
        print("executed")
        self.pack()
        self.w, self.h = self.winfo_screenwidth(), self.winfo_screenheight()
        self.img_name = "/home/pi/pattern.png"
        self.control = 0
        self.create_widgets()
        self.flag = False
        self.after(self.DELAY, self.check_signal)
        root.bind('<Escape>', self.quitApp)

    def load_image(self, filename):

        try:
            pil_img = Image.open(filename)
            img_width, img_height = pil_img.size

            if img_width > self.w or img_height > self.h:  # Too big?
                size = (int(self.w), int(self.h))
                pil_img = pil_img.resize(size)
                ratio = min(self.w / img_width, self.h / img_height)
                img_width, img_height = int(img_width * ratio), int(img_height * ratio)
                pil_img = pil_img.resize((img_width, img_height), Image.ANTIALIAS)  # Resize.
            self.control = 0
            img = ImageTk.PhotoImage(pil_img)  # Convert to tkinter PhotoImage.
            return img

        except FileNotFoundError:
            self.control = 1

    def quitApp(self, a):
        root.destroy()

    def create_widgets(self):
        file = open("testfile.txt", "w")

        file.write("Se ejecuto.py")

        file.close()
        self.canvas = tk.Canvas(root, width=self.w, height=self.h, background='black')
        self.canvas.pack()

        self.pattern_img = self.load_image(self.img_name)
        if self.control == 1:
            sys.exit()
            root.destroy()

        self.image_id = self.canvas.create_image(self.w / 2, self.h / 2, image=None)

    def show_image(self):
        self.cur_img = self.pattern_img
        self.after(self.IMG_DELAY)
        self.canvas.itemconfigure(self.image_id, image=self.cur_img)
        self.update()
        self.after(self.POST_DELAY)
        self.canvas.delete(self.image_id)
        self.image_id = self.canvas.create_image(self.w / 2, self.h / 2, image=None)

    def check_signal(self):

        if GPIO_present:
            self.flag = not GPIO.input(GPIO_PULSE)

        if self.flag:
            self.show_image()
            self.flag = False  # Reset

        root.after(self.DELAY, self.check_signal)  # Check again after delay.

if __name__ == '__main__':
    root = tk.Tk()
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.wm_attributes('-fullscreen', 'true')
    root.focus_set()

app = Application(root)

app.mainloop()

Many thanks in advance!!!

A: I assume you are running raspbian isn't it?
Since Debian 7 (raspbian is based on Debian) the default init system is systemd, nonetheless there is compatibility with the old known systemv, so you can still use the /etc/init.d/youscript approach but please make sure to:

*

*Grant execution permissions for your init.d script startApp

*Choose which runlevels do you want the startApp to be executed, i.e 5,3, etc you can find your default runlevel with:

sudo runlevel

*

*Use update-rc.d to put your script in the boot startup for the default runlevel (that way you don't have to worry about if the default is the /etc/rc5.d or /etc/rc2.d it does it for you )

update-rc.d script-name default

*

*(Optional if not using update-rc.d) Create a soft link and point it to the right runlevel directory /etc/rcX.d but mind the name!, is important that will have an 'S' for start and a number like '99' as you want it to be executed at the very end of the runlevel start sequence, i.e:

ln -s /etc/init.d/startApp /etc/rc5.d/S99startApp


text:
Q: Manually invoke lambda with s3 event in java Have a lambda which implements
RequestHandler<S3Event, Void>
and has handler as such Void handleRequest(S3Event event, Context context) {log.info(" Event => " + event)....}
S3Event here is of type com.amazonaws.services.lambda.runtime.events.S3Event;
Trying to manually invoke the lambda without uploading any data to s3. So using LambdaInvokerFactory to create lambda client and lambda interface as:
public interface Lambdas {

        @LambdaFunction(functionName = "Foo)
        Void bar(S3Event event);
    }

Manually created S3EventNotification.S3EventNotificationRecord ( of type com.amazonaws.services.lambda.runtime.events.S3EventNotification)  with this reference. Logging locally the S3Event after creation prints as such :
{
    "Records": [
        {
            "records": [
                {
                    "awsRegion": "us-west-2",
                    "eventName": "ObjectCreated:Put",
                    "eventSource": "aws:s3",
                    "eventTime": {
                        "era": 1,
                        "dayOfYear": 71,
                        "year": 2021,
                        "dayOfMonth": 12,
                        "dayOfWeek": 5,
                        "weekyear": 2021,
                        "weekOfWeekyear": 10,
                        "monthOfYear": 3,
                        "millisOfDay": 0,
                        "yearOfCentury": 21,
                        "centuryOfEra": 20,
                        "millisOfSecond": 0,
                        "yearOfEra": 2021,
                        "secondOfMinute": 0,
                        "secondOfDay": 0,
                        "minuteOfHour": 0,
                        "minuteOfDay": 0,
                        "hourOfDay": 0,
                        "millis": 1615536000000,
                        "zone": {
                            "fixed": false,
                            "uncachedZone": {
                                "fixed": false,
                                "cachable": true,
                                "id": "America/Los_Angeles"
                            },
                            "id": "America/Los_Angeles"
                        },
                        "chronology": {
                            "zone": {
                                "fixed": false,
                                "uncachedZone": {
                                    "fixed": false,
                                    "cachable": true,
                                    "id": "America/Los_Angeles"
                                },
                                "id": "America/Los_Angeles"
                            }
                        },
                        "afterNow": false,
                        "beforeNow": true,
                        "equalNow": false
                    },
                    "eventVersion": "2.0",
                    "requestParameters": {
                        "sourceIPAddress": "127.0.0.1"
                    },
                    "responseElements": {
                        "xAmzId2": "Foo",
                        "xAmzRequestId": "Bar"
                    },
                    "s3": {
                        "configurationId": "Foo",
                        "bucket": {
                            "name": "Foo",
                            "ownerIdentity": {
                                "principalId": "arn:aws:iam::Foo"
                            },
                            "arn": "arn:aws:s3::Foo"
                        },
                        "object": {
                            "key": "FooBar.txt",
                            "size": 10,
                            "eTag": "Foo",
                            "versionId": "Foo",
                            "sequencer": "Foo",
                            "urlDecodedKey": "FooBar.txt",
                            "sizeAsLong": 10
                        },
                        "s3SchemaVersion": "1.0"
                    },
                    "userIdentity": {
                        "principalId": "arn:aws:iam::Foo"
                    }
                }
            ]
        }
    ]
}

But upon invoking bar(S3Event), it invokes the lambda but logs show it as empty:
Event => {[]}

Things I tried

*

*Change the interface's input to Void bar(Map<String, Object> event)
and invoked lambda as such bar(ImmutableMap.of("Records", event.getRecords())
It invokes the lambda but following err:

An error occurred during JSON parsing: java.lang.RuntimeException
java.lang.RuntimeException: An error occurred during JSON parsing
Caused by: lambdainternal.util.ReflectUtil$ReflectException: java.lang.reflect.InvocationTargetException
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
Caused by: java.lang.IllegalArgumentException: Invalid format: "{"year":2021,"dayOfYear":71,"equ..."
    at org.joda.time.format.DateTimeFormatter.parseDateTime(Unknown Source)
    at org.joda.time.DateTime.parse(Unknown Source)
    at org.joda.time.DateTime.parse(Unknown Source)
    at com.amazonaws.services.s3.event.S3EventNotification$S3EventNotificationRecord.<init>(S3EventNotification.java:386)
    at com.amazonaws.services.s3.event.S3EventNotification$S3EventNotificationRecord.<init>(S3EventNotification.java:355)
    ... 4 more

This is how records are been created :
return new S3EventNotification.S3EventNotificationRecord(
            region,
            EVENT_NAME,
            EVENT_SOURCE,
            DateTime.now().toString(),
            EVENT_VERSION,
            new S3EventNotification.RequestParametersEntity(SOURCE_IP_ADDRESS),
            new S3EventNotification.ResponseElementsEntity(
                RandomStringUtils.randomAlphanumeric(SIZE),
                RandomStringUtils.randomAlphanumeric(SIZE)
            ),
            s3Entity,
            getUserIdentityEntity(accountId)

Not sure what is going wrong here ?

A: Format of S3 event source to lambda is documented here
It is an object with array of Records
So, it should be below, we don't need a second layer of records array.
{
  "Records": [
    {
      "eventVersion": "2.1",
      "eventSource": "aws:s3",
      "awsRegion": "us-east-2",
      "eventTime": "2019-09-03T19:37:27.192Z",
      "eventName": "ObjectCreated:Put",
      "userIdentity": {
        "principalId": "AWS:AIDAINPONIXQXHT3IKHL2"
      },
      "requestParameters": {
        "sourceIPAddress": "205.255.255.255"
      },
      "responseElements": {
        "x-amz-request-id": "D82B88E5F771F645",
        "x-amz-id-2": "vlR7PnpV2Ce81l0PRw6jlUpck7Jo5ZsQjryTjKlc5aLWGVHPZLj5NeC6qMa0emYBDXOo6QBU0Wo="
      },
      "s3": {
        "s3SchemaVersion": "1.0",
        "configurationId": "828aa6fc-f7b5-4305-8584-487c791949c1",
        "bucket": {
          "name": "lambda-artifacts-deafc19498e3f2df",
          "ownerIdentity": {
            "principalId": "A3I5XTEXAMAI3E"
          },
          "arn": "arn:aws:s3:::lambda-artifacts-deafc19498e3f2df"
        },
        "object": {
          "key": "b21b84d653bb07b05b1e6b33684dc11b",
          "size": 1305107,
          "eTag": "b21b84d653bb07b05b1e6b33684dc11b",
          "sequencer": "0C0F6F405D6ED209E1"
        }
      }
    }
  ]
}

A: Couple things here,

*

*As Balu Vyamajala mentioned to match the records format.

*Was using 3.5 as dependency which created eventTime field as an object instead of string which threw com.amazonaws.services.lambda.invoke.LambdaFunctionException: Invalid format: "{"year":2019,"dayOfYear":246,"eq... upon invoking lambda. Using 2.8
created eventTime:2019-09-03T19:37:27.192Z which solved the issue.

the current interface.
@LambdaFunction(functionName = Foo)
        Void Bar(S3Event payload);

However, S3EventNotificationRecord constructor is deprecated. You can create json doc in such format and use S3EventNotification.parseJson to get the records.

A: When unit testing Lambda functions in Java I recommend to use the aws-lambda-java-tests module for JUnit.
Lambda has specific serialization logic which it implements which your own test code might not.
By using this testing library you will use the same serialisation logic as Lambda.


text:
Q: Add math verification to jquery validate form I have a contact form where I am trying to add a simple captcha of adding two numbers together and to also display the successMessage div when the form is sent. My form looks like this;
<form method="post" action="" id="contact">

Message sent

* Your Name
<input name="name" type="text" id="name" size="30" value="" />

* Email
<input name="email" type="text" id="email" size="30" value="" />

* Phone Number
<input name="phone" type="text" id="phone" size="30" value="" />

* Your Comments
<textarea name="comments" cols="26" rows="8" id="comments"></textarea>

*Are You Human?

3 + 1 =
<input name="verify" type="text" id="verify" size="6" value="" />

<input name="contactus" type="submit" class="submit" id="contactus" value="Submit" />

</form>

You can see that I have tried using the addMethod to verify that someone enters 4 into the verify field, but it's not validating the field.
I would be grateful if someone can help me out to get that to work and to also display a global success message when the form submits.
Thank you.

A: You specified the method, but you did not use it. Here is the simple fix in Javascript.

*

*updated the error message so it is "{0} + {1}".

*called verify method for verify field. I may use different names or may get confused between field and custom method.

A: Just letting everyone know that you need to parse the Integer because the value is a string. You're doing an equality so they both need to be integers.
Just wrap the 'value' with parseInt like this:
return this.optional(element) || parseInt(value, 10) == params[0] + params[1];


text:
Q: Windows account has been hijacked by my girlfriend As title says, my Windows account has been hijacked.
My girlfriend, logged me out of Hotmail on Chrome, and the logged into her Hotmail on Chrome last night.
Today, The only user account on the PC is hers!
I couldn't log on!
I have got her to unlock it a few hours later.
All my shortcuts, folders, files etc. Logged under her email/Windows account!
I created a second account, my email back on the PC and it creates a new entire profile! clean of everything that was mine.
How do I reclaim my actual account. Aka swap the email back somehow??

A: To recover your account.
A question to ponder. Whos computer is this? If it's yours, then your default folder may have been hijacked. If it's your GF's computer then it was really never yours and you should have sync'd your account in the following manner.
Sync your account:
url, chrome://settings/  Sign In: Sign into your "gmail" account here. Sign In: Advanced snyc settings... make sure bookmarks is checked and all other sync's desired. - This will ensure that any future updates will update your specific account.
If that doesn't fix it you can copy the default folder manually.
Two ways:
Way 1) Log into your girlfriends account, with her permission of course. Export the bookmarks: Bookmark Manager (Cntrl+Shift+O), Organized Menu, Export. Import bookmarks to your account: In your account. Log in. Import bookmarks is in the same method as export above, but instead import from the saved location.
Way 2) Assuming you only have one profile, the default file. Before copying, copy a backup of any profiles in this directory: C:\Users\your_profile_name\AppData\Local\Google\Chrome\User Data Before copying, copy a backup of the default provile in this directory: C:\Users\your_profile_name\AppData\Local\Google\Chrome\User Data\Default
You may have to copy the profile folder of your girlfriends account into your default, or visa versa. That's why creating a backup is important above as to not lose anything.
Preventitive measures: Sharing, via Create users: On your PC, or laptop. Go the the control panel. User Accounts. Create new user login. You should log into the computer with your login credentials and your GF with her own credentials. This way your files are yours, and her's are hers.

Win7
  http://www.bleepingcomputer.com/tutorials/create-new-user-account-in-windows-vista-7/
Win10
  https://support.microsoft.com/en-us/instantanswers/5de907f1-f8ba-4fd9-a89d-efd23fee918c/create-a-local-user-account-in-windows-10

A: It seems like my computer account was set as local in the user settings. When she logged into hotmail on chrome, she somehow accepted permissions for the pc to become linked to her email. So it replaced my username and password with her email and password.
To fix it, go on the user settings, and change it back to local.
You can then retype your desired username and password.


text:
Q: how to do vi style navigation in rail console How can I do VI style navigation in rails console?
In my .bash_profile i do set -o vi and then in my terminals I enjoy vi style navigation.
I can do dd to delete a line, cmd+$ to jump to end of line, etc etc.
I want to get the same thing in rails console?

A: You need to set the editing-mode to vi.
The easiest way to do that is simply creating the file .inputrc in your home folder and add the mode:
$ echo "set editing-mode vi" >> ~/.inputrc
And voilá!

A: I had the same issue although using inputrc didn't work. The reason it didn't work though is because I was using zsh as my shell.  Zsh does NOT use inputrc for setting the input mode. Hence if you want to use vi editing mode in rails console and you're using zsh as your shell do the following:
Add the following to your ~/.zshrc
bindkey -v

References:

*

*https://wiki.archlinux.org/index.php/Zsh#Key_bindings

*http://zsh.sourceforge.net/Guide/zshguide04.html

A: just wanted to point out that there is a gem called
rb-readline
this gem breaks rails console's ability to work in vi mode
(my project had bundled it because this gem was once necessary for byebug to work)


text:
Q: Minidom (XML Parsing) with Python - dont want geting any childs child nodes I'm using Minidom (Python XML Parser)
Example:
> <layer1>
>   <layer2>
>     <element>1</element>
>     <if>
>       <element>2</element>
>     </if>
>     <element>3</element>
>   <layer2>
> </layer1>

I'm using the ".getElementsByTagName" in the < layer2 > and get every < element >< /element > within the one in the < if >< /if > braces, is there a easy way to just grap the one in the < layer2 >: < element >1< /element >< element >3< /element > ?
I searched through the minidom Documentation and found nothing but this:

Document.getElementsByTagName(tagName)
      Search for all descendants (direct children, children's children, etc.) with a particular element type name.

Hope someone can help me with this

A: Every Element has a childNodes property that has all of that element's (direct) children. Iterating over those, then checking every child to see if it is one of the elements you're looking for, should do what you want.
for child in layer2_element.childNodes:
    if child.tagName == 'element':
        ...  # do something with `child`


text:
Q: Ruby on Rails options_for_select onchange to call a Javascript function? How do you setup a select element to change the maximum value of a number field element on a change of value?
I want to change the max value of the passenger number field when the flight ID is changed.
This is my code so far. As you can see, I added the onchange at the end of the select layout.

    <%= form.label :flight_id %>
    <%= form.select :flight_id, options_for_select(Flight.all.map {|flight| [flight.name, flight.id]}, form.object.id), onchange: 'getMaxCapacity()' %>

    <% qty = @reservation.passengers %>
    <%= form.label :passengers %>
    <%= form.number_field :passengers, :id => 'passengers', min: 1, onchange: "calculateTotalPrice()", oninput: "calculateTotalPrice()" %>

My Javascript function getMaxCapacity() never gets entered. In the function I am setting the max value of the 'passengers' number field to the capacity variable.

A: The signature of the FormBuilder#select looks like this:
select(method, choices = nil, options = {}, html_options = {}, &block)

This means html_options are the fourth parameter. Because you do not have any options for the select method you need to pass an empty hash as a third parameter.
<%= form.select(
      :flight_id,
      options_for_select(Flight.all.map {|flight| [flight.name, flight.id]}, form.object.id),
      {},                                 # empty options
      onchange: 'getMaxCapacity()' %>.    # here the HTML options


text:
Q: Cannot get customer session in Controller I am just trying to get the customer session in my custom controller class and it always returns NULL.
What is wrong with Magento? It doesn't work as expected, I am spending days not minutes for a small changes...
Here is my custom controller class.
class Referral extends \Magento\Customer\Controller\AbstractAccount {

    protected $customerRepository;

    protected $dataObjectHelper;
    protected $session;
    protected $resultPageFactory;

    public function __construct(
        Context $context,
        \Magento\Customer\Model\Session $customerSession,
        PageFactory $resultPageFactory,
        CustomerRepositoryInterface $customerRepository,
        DataObjectHelper $dataObjectHelper
    ) {
        $this->session            = $customerSession;
        $this->resultPageFactory  = $resultPageFactory;
        $this->customerRepository = $customerRepository;
        $this->dataObjectHelper   = $dataObjectHelper;
        parent::__construct( $context );
    }

    public function execute() {
        $resultPage = $this->resultPageFactory->create();

        $block = $resultPage->getLayout()->getBlock( 'customer_account_dashboard_referral_edit' );
        if ( $block ) {
            $block->setRefererUrl( $this->_redirect->getRefererUrl() );
        }

        $data = $this->session->getCustomerFormData(true);
        $customerId = $this->session->getCustomerId();
        var_dump($customerId);
        exit;

        $customerDataObject = $this->customerRepository->getById( $customerId );
        if ( ! empty( $data ) ) {
            $this->dataObjectHelper->populateWithArray(
                $customerDataObject,
                $data,
                \Magento\Customer\Api\Data\CustomerInterface::class
            );
        }
        $resultPage->getConfig()->getTitle()->set( __( 'Referral Settings' ) );

        return $resultPage;
    }
}

In that case it returns NULL, I have found only one way to get real id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->create("Magento\Customer\Model\Session");

In this case it works, and I can get customer id, but why??? What is the purpose of all these dependency injections and other features, it even doesn't work in a simple case...
Please explain what is wrong ?

A: I think you need  do it :
PS: "purpose of all these dependency injections" use Factory ."
Example :
...
protected $sessionFactory;
...
public function __construct(
        ...
        \Magento\Customer\Model\SessionFactory $sessionFactory,
       ...
    ) {
        $this->sessionFactory = $sessionFactory;
        ...
    }

    public function execute() {

        ...
        $sessionModel = $this->sessionFactory->create();
        $customerId = $sessionModel->getCustomer()->getId();
        ...


text:
Q: libjingle talk_base::AsyncSocket() connect failed for Android due to access denied? I am using the AsyncSocket source code from libjingle to connect to a server.  I am using the same source code in an iPhone App and the connection is fine, but on the Android phone, I get access denied error when creating a socket.
This is the function that fails at s_ = ::socket(family, type, 0).
    // Creates the underlying OS socket (same as the "socket" function).
  virtual bool Create(int family, int type) {
    Close();
    s_ = ::socket(family, type, 0);
    udp_ = (SOCK_DGRAM == type);
    UpdateLastError();
    if (udp_)
      enabled_events_ = DE_READ | DE_WRITE;
    return s_ != INVALID_SOCKET;
  }

The family value is 2 and type is 1.  S_ gets a return value of -1 with errno of 13.  I looked up Linux error code and it's access denied.  Do you know if there is any special setting in Android that I need to set?  Any help would be appreciated.

A: Permissions?
Specifically : <uses-permission android:name="android.permission.INTERNET" />


text:
Q: Can I use macros while defining postfix template? I assume it's possible, cause there is 'foo'.var and it expands to $foo = 'var';, so there has to be some way.
What i'm trying to do is to create a template that does the following:
FooBar.new -> $fooBar = new FooBar();.
The best what I had by far is:
$$$EXPR$ = new $EXPR$();, which behaves like this:
FooBar.new -> $FooBar = new FooBar();.
It's almost what I want, but the variable name is capitalized. I've tried with suggestVariableName taken from Template Macros, but I guess it only works inside live templates or I don't know how to use it for postfix completion.
UPDATE
I've found a really cool plugin, which does what I need. Kudos to the author!


text:
Q: Where should I ask about a text font used somewhere? Is there any SE site where I can ask users tell me/help me find what the font used in some media (movie, picture, whatever) is? If so, which one?

A: Graphic Design has a font-identification tag; read its guidance. It suggests trying automatic font recognition tools like WhatTheFont first.
Graphic Design's help center and the tag info link to this meta question about font identification questions: What are the requirements for font identification questions?.
To summarize: you need to show your efforts (e.g. with the tools from the tag guidance), give as much details as possible about the font (source, screenshot, etc.), and make your question title specific.


text:
Q: Using Drag and Drop method I have a Web-table that has Row and Column. Some Row has 8 cells some has 10, 14, and 20, 4,2. Some Row has no data, some row has few. First I have to identify there is at least 6 or 8 source object(balls) is present (imagine they are connected each other so one drag will pull all of them) in a row for drag  and then need to identify Row (target object) where empty cells is present(at least 6 to 8 or more) to drop the balls(data).and then do drag and drop.
First I tried to use object SPY to get the record in object repository then write the script
Browser("...").Page("...").WebTable("...")

I tried so many way like x,y combination for drag and drop also tried as WeElement none of them is worked out.
Can someone help me?


text:
Q: java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds i like to get the duration between to datetime values in minutes.
public long datetimeDiffInMinutes(String dateStop, String dateStart) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate firstDate = LocalDate.parse(dateStart, formatter);
        LocalDate secondDate = LocalDate.parse(dateStop, formatter);
        Duration d1 = Duration.between(firstDate, secondDate);
        long min = d1.toMinutes();

        return min;
    }

There will be thrown an exception: java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds
But i dont use "Seconds" in this function. This line throws the exception: Duration d1 = Duration.between(firstDate, secondDate);

A: The documentation for the method you're calling (Duration.between(Temporal, Temporal)) states:

The specified temporal objects must support the SECONDS unit. For full accuracy, either the NANOS unit or the NANO_OF_SECOND field should be supported.

But LocalDate.isSupported is documented with:

If the unit is a ChronoUnit then the query is implemented here. The supported units are: DAYS, WEEKS, MONTHS, YEARS, DECADES, CENTURIES, MILLENNIA, ERAS
All other ChronoUnit instances will return false.

So no, LocalDate doesn't support seconds, which is required for the method you're calling.
It may be worth considering that a Duration is intended to be an elapsed time - a fixed number of seconds etc. The elapsed time between two dates may depend on the time zone involved - because a day doesn't always have 24 hours when there are time zones involved.
If you're happy assuming a 24-hour day, you could use Duration.ofDays(DAYS.between(firstDate, secondDate)).

A: You specify your dates with time information. That makes LocalDate a suboptimal choice. LocalDateTime is a better option. That already lets you create a duration.
Results may be off because of DST. Adding the right time zone should solve that:
ZoneId zone = ZoneId.systemDefault(); // or an explicit one
ZonedDateTime firstDateTime = LocalDateTime.parse(dateStart, formatter).atZone(zone);
ZonedDateTime secondDateTime = LocalDateTime.parse(dateStop, formatter).atZone(zone);
Duration d1 = Duration.between(firstDateTime, secondDateTime);
long min = d1.toMinutes();

A: For differences between dates, Period is a better representation.
Because your format string contains time, however, it looks like you want to be parsing to LocalDateTime instead of LocalDate. This way, the minutes (and seconds) you care about are not discarded:
private static final DateTimeFormatter parser =
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

public long datetimeDiffInMinutes(String dateStop, String dateStart) {
    LocalDateTime firstDate = parser.parse(dateStart, LocalDateTime::from);
    LocalDateTime secondDate = parser.parse(dateStop, LocalDateTime::from);
    return firstDate.until(secondDate, ChronoUnit.MINUTES);
}

Note that because you don't have information about the time zone and any daylight-saving transitions that may occur, the results might not match what people expect in every case. You should clarify the use case, and get more information about the zone if necessary.


text:
Q: Angular Open Div Below Current Row I'm using Angular JS and need to open a div of related content (with the class of .info-bg )under the selected element row. So if I click row 1 it opens the hidden div under row 1. If I click row 2 content it appears under row 2. I am however at a bit of a loss as to the best way to accomplish this, any help would be appreciated. Here is a CodePen of what I have done thus far.
My HTML:

  <input type="text" id="query" data-ng-model="query"/>

{{i.name}}

{{i.cat}}

    Name:

    Index:

        Category:

{{i.name}}

{{i.cat}}

MY JS:
angular.module('app', ['ngAnimate'])

.controller('starWarsCtrl', function ($scope) {
  $scope.data = [
    {"name": "Obi-Wan Kenobi",
     "index":88,
      "cat": "jedi"},
    {"name": "Yoda",
     "index":69,
      "cat":"jedi"},
    {"name": "Lando",
     "index":31,
      "cat": "smuggler"},
    {"name": "Han Solo",
     "index":90,
      "cat": "smuggler"},
    {"name": "Darth Vader",
     "index":98,
      "cat": "sith"},
    {"name": "Jar-Jar Binks",
     "index":80,
      "cat": "alien"},
    {"name": "Mace Windu",
     "index":45,
      "cat": "jedi"},
    {"name": "Chewy",
     "index":76,
      "cat": "smuggler"}
  ];

  $scope.select = function (item) {
    $scope.selectedItem = item;
  }
})

A: I think the 'best' way here is to add a second hidden div underneath the second set of items. This isn't very DRY, so instead you might consider adding a custom directive instead - this will allow you to create multiple sets with corresponding hidden divs in a DRY manner.
See the following AngularJS documentation for writing your own directives: https://docs.angularjs.org/guide/directive
So imagine you created a directive called filtered-set, and attached it to your module:
.directive('filtered-set', function() {
  return {
    templateUrl: 'filered-set.html'
  };
});

And then create filtered-set.html template with:

{{i.name}}

{{i.cat}}

    Name:

    Index:

      Category:

And then use the following in your HTML, replacing the two repetitions of the items/info HTML in your original code:
<filtered-set items="data | filter : {cat: 'jedi'} : true | filter:query |orderBy: orderList"></filtered-set>


text:
Q: JRockit full memory dump I suspect that my application have a memory leak. I have GC logs and when I look at them I see that memory usage is about 9-10GB. Then I try to dump memory to the file, the file size is about 5GB.
The question is why dump has not got 9GB in size, but only 5GB? How can I force jrcmd to dump full memory?
Command that I use:
jrcmd 11906 hprofdump filename=/path_to_dump/dump.hprof

JVM:
Java(TM) Platform, Standard Edition for Business (build 1.5.0_28-b04)
Oracle JRockit(R) (build R28.1.3-11-141760-1.5.0_28-20110301-1432-linux-x86_64, compiled mode)

Update:
The problem is that due to GC logs memory is never freed up to level that is below 9GB. JDK tool truncated dump to 5GB. Why?

A: I assume JRockit behaves similar to HotSpot: if your live data set is only 5 GB then the dump also only 5 GB. I assume only 5 GB of your 9-10 are live.

A: What does your GC  log look like?
BTW, have you tried the JRockit Mission Control tool called Memleak? It can be useful for finding memory leaks.


text:
Q: Posting nested form data as JSON array of objects I have a form, part of which is dynamic (using jinja templates). For example, when it renders, the number of fruits is unknown. Let's say I have the below form inputs:
<input type="text" name="{{ fruit1 }} name" value="apple">
<input type="text" name="{{ fruit1 }} size" value="5">
<input type="text" name="{{ fruit1 }} color" value="red">

<input type="text" name="{{ fruit2 }} name" value="banana">
<input type="text" name="{{ fruit2 }} size" value="7">
<input type="text" name="{{ fruit2 }} color" value="yellow">

I'd like to be able to post to Flask via AJAX the form input in the following JSON structure:
{
    "fruit": [{
        "id": "fruit1"
        "name": "apple",
        "size": "5",
        "color": "red"
    }, {
        "id": "fruit2"
        "name": "banana",
        "size": "7",
        "color": "yellow"
    }]
}

Outside of manually shaping the data using javascript, is there a more elegant way to do this--perhaps using nested inputs in some manner?


text:
Q: Float keeps overlapping adjacent block I've got a block that contains text, with an icon to the left of this text. When the block only contains one line of text, the icon is higher than the text block. If the next text block has the same structure, the icons will overlap each other. I'm trying to avoid that. I tried using clear="both" -but apparently that only applies to the left/right side of the float, not to the top or bottom.
How can I avoid my icons overlapping each other?
<fo:block clear="both" start-indent="0mm" border="1pt solid black">
    <fo:float float="left" clear="both" >
        <fo:block-container position="absolute"  left="5mm" width="10mm" height="12mm" clear="both">
            <fo:block>
                <fo:external-graphic src="Icon.pdf"  width="10mm" height="10mm" content-width="scale-to-fit"/>
            </fo:block>
        </fo:block-container>
    </fo:float>

    <fo:block margin-left="25mm" clear="both">
        <fo:block>
            <xsl:text>text is inserted here</xsl:text>
        </fo:block>
    </fo:block>
</fo:block>
<fo:block clear="both" start-indent="0mm" border="1pt solid black">
    <fo:float float="left" clear="both" >
        <fo:block-container position="absolute"  left="5mm" width="10mm" height="12mm" clear="both">
            <fo:block>
                <fo:external-graphic src="Icon.pdf"  width="10mm" height="10mm" content-width="scale-to-fit"/>
            </fo:block>
        </fo:block-container>
    </fo:float>

    <fo:block margin-left="25mm" clear="both">
        <fo:block>
            <xsl:text>text is inserted here</xsl:text>
        </fo:block>
    </fo:block>
</fo:block>

A: If your want to avoid icon image overlap, it is not a good idea to use fo:block-container with @position="absolute" because it generates area class "xsl:absolute" which does not affect the main text flow thus @clear attribute is not effective.
If the requirements are:

*

*To place the icon image left of the text.

*Avoid image overlap between same sequence of icon image and text.

It is better to use more simple fo:list-block formatting object and locate icon image to fo:list-item-label and locate text into fo:list-item-body/fo:block.
Here is sample implementation based above:
<fo:list-block provisional-distance-between-starts="25mm" provisional-label-separation="1mm">
    <fo:list-item relative-align="before" border="1pt solid black" space-before="1mm">
        <fo:list-item-label end-indent="label-end()">
            <fo:block>
                <fo:external-graphic src="icon.png"  width="10mm" height="10mm" content-width="scale-to-fit"/>
            </fo:block>
        </fo:list-item-label>
        <fo:list-item-body  start-indent="body-start()">
            <fo:block>text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here text is inserted here</fo:block>
        </fo:list-item-body>
    </fo:list-item>
    <fo:list-item relative-align="before" border="1pt solid black" space-before="1mm">
        <fo:list-item-label end-indent="label-end()">
            <fo:block start-indent="0mm">
                <fo:external-graphic src="icon.png"  width="10mm" height="10mm" content-width="scale-to-fit"/>
            </fo:block>
        </fo:list-item-label>
        <fo:list-item-body start-indent="body-start()">
            <fo:block>text is inserted here text is inserted here</fo:block>
        </fo:list-item-body>
    </fo:list-item>
    <fo:list-item relative-align="before" border="1pt solid black" space-before="1mm">
        <fo:list-item-label end-indent="label-end()">
            <fo:block start-indent="0mm">
                <fo:external-graphic src="icon.png"  width="10mm" height="10mm" content-width="scale-to-fit"/>
            </fo:block>
        </fo:list-item-label>
        <fo:list-item-body start-indent="body-start()">
            <fo:block>text is inserted here text is inserted here</fo:block>
        </fo:list-item-body>
    </fo:list-item>
</fo:list-block>

The formatting result:


text:
Q: initlocation not working in postgresql I am using postgresql 9.2 on a RHEL 6.5 machine and would like to set up a database in a non-standard location as it is filling up the root partition. The instructions tell me to use the initlocation command from the command line but I get the error 'command not found' on using it. I have searched for it in case it is a shell script but cannot find it anywhere.
How do I run this command? thanks for any help.

A: Right, so you want to leave the existing installation where it is and create a new database in a directory that has more space.
First, a disclaimer, I haven't done exactly this before, but, I have a 9.4b2 installation here on my home computer and I did walk through these steps to verify that is seems to work :-)
@Mike Sherrill 'Cat Recall' has a pretty good write up on database storage (Where does PostgreSQL store the database?). I don't think it specifically answers your question, but it does have all of the information necessary to figure it out.
In your case, you will want to use tablespaces.  First, create a new tablespace in the postgres installation.  I will use my machine as an example.  The first thing I would do is identify where the new database will reside.  A directory name, and it has to be empty.  For me, I'll create an empty directory in my home directory (I have to do it as the root user) with the shell commands:
mkdir /home/gfausak/pg_tablespace
chown postgres /home/gfausak/pg_tablespace
chgrp postgres /home/gfausak/pg_tablespace
chmod 700 /home/gfausak/pg_tablespace

Then I log in to psql as the postgres user.  Like:
psql -Upostgres

Your incantation might be different. When you get to the prompt just verify where your current database(s) are via:
postgres=# show data_directory;
    data_directory
-----------------------
 /var/local/pgsql/data
(1 row)

Now, create your new tablespace.
postgres=# create tablespace newspace location '/home/gfausak/pg_tablespace';
CREATE TABLESPACE

The docs for this command can be views here: http://www.postgresql.org/docs/9.2/static/manage-ag-tablespaces.html
Once created it can be used for a variety of different objects.  In your case, createdb, can be done from the command line or from the postgres psql prompt.  I'll create a test database in that tablespace:
postgres=# create database newdb with tablespace = newspace;
CREATE DATABASE

Just for grins, open it and create a table:
postgres=# \c newdb
You are now connected to database "newdb" as user "postgres".
newdb=# create table testme (t text);
CREATE TABLE
newdb=#

If I go back to my home directory and take a peek in that newly created directory I'll see some postgres files:
ls /home/gfausak/pg_tablespace
PG_9.4_201407151

Anything you create in the newdb database will go in to the new directory unless you override the creation of it.  There is a default_tablespace variable.  As long as it is blank, the default is to put objects in the current database.  Same goes for another setting temp_tablespace.  The default for both of these is blank, meaning the current database.
You can even create objects in your old database in the new tablespace by specifying the tablespace when you create the table.
-g

A: Try this.

vi /etc/init.d/postgresql-XX

Change this variable with:
PGDATA=/var/lib/pgsql/$PGMAJORVERSION/data
PGLOG=/var/lib/pgsql/$PGMAJORVERSION/pgstartup.log

on:
PGDATA=/new_pgdata/pgsql/${PGMAJORVERSION}/data
PGLOG=/new_pgdata/pgsql/${PGMAJORVERSION}/pgstartup.log

than:
mkdir -p /new_pgdata/pgsql/XX/data/
chown -R postgres:postgres /pgdata/pgsql

/etc/init.d/postgresql-XX initdb -D /new_pgdata/pgsql/XX/data/

Where XX is equal to 9.2


text:
Q: HTML page quote outer jquery file does not work I make a html page in eclipse, but it does not work when I quote the outer jquery file.
Below is my code:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../css/layout.css">
<link rel="stylesheet" type="text/css" href="../css/flexigrid.css">

<title>Insert title here</title>

        jnoifsf
        nifs
        nofsfsa

        mflsf
        noijfs
        mifsf

The annotated code of line 12 can work.

A: It should be:
$('#data').css("display", "block");

Or even easier:
$('#data').show();


text:
Q: How can I add an ICS meeting automatically to the Organizer's calendar? Our java application generates ICalendar files using ical4j, and sends them out to users as part of an HTML e-mail notification. A couple of users (the Organizers of the meeting) report that the the "Accept", "Reject", etc. buttons for the meeting are grayed out, and unclickable. The meeting is not added to the Organizer's calendar.
How can I force the meeting to be added for the Organizer?
I configured the server temporarily to send the .ics file as an attachment (instead of inline), so that I could run it through a web-based ICalendar validator. The validator gave me a warning that the Version property was supposed to be the first property, but didn't find any other problems.
The ICalendar works normally for every user except the organizer.
I was able to reproduce the issue on my own Outlook account. I noticed that if I send the meeting notice through a gmail mail server, it works normally; but, when it comes from our internal Outlook server, it doesn't get added to the calendar.
A message is shown underneath the grayed-out meeting controls: "As the meeting organizer, you do not need to respond to this meeting."
Example ICalendar file generated by our system:
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//MyCompany//Product//EN
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
DTSTAMP:20101202T210423Z
UID:77B17E9B-BE02-476E-816B-ED9558EE7D2A
DTSTART:20101230T133000
DTEND:20101230T143000
SUMMARY:Review Meeting for A1 CI Review #123456
LOCATION:BLDG - 123
CREATED:20101202T210423Z
LAST-MODIFIED:20101202T210423Z
TZID:America/New_York
ORGANIZER;CN="ORGANIZER, THE";SENT-BY="mailto:noemail@mycompany.com":mailto:myemail@mycompany.com
ATTENDEE;ROLE=REQ-PARTICIPANT;CN="ATTENDEE, SOME":mailto:noemail@mycompany.com

END:VEVENT
END:VCALENDAR

Edit:
I tried adding the meeting organizer as an "Optional to" participant. No dice; same behavior.
Edited the question again to reflect my progress on the issue.

A: It looks like this issue might be solvable by applying a HotFix to Outlook.

*

*Description of the Outlook 2007 post-Service Pack 1 hotfix package: January 28, 2008
It seems it could be related to setting ExtractOrganizedMeetings in the registry.  Worth a try.
See:

*

*You cannot accept an invitation that
is in a third-party calendar format
in Outlook 2007

*As the meeting organizer, you cannot
accept a meeting request in Outlook
2007 if you used a public Calendar
for the meeting that you created

A: Add an ORGANIZER to the ICS file. Apparently Outlook 2007 assumes the organizer is the current user whereas previous versions did not.


text:
Q: Using PETSc under Cygwin I'm trying to get PETSc running under Cygwin on my Windows machine to test parallel code. Unfortunately there's a problem where Cygwin is importing elements from my Windows path of the form:
C:\Program Files (x86)\...

And the problem is that the PETSc and MPI compilers are falling on their faces because they don't invoke cygpath to fix the " " characters. So, I need help with one of three things:

*

*How to get Cygwin to not load the Windows path

*

*I put it on its own partition and am trying to use only native Cygwin compilers so it could, hopefully, live without knowing much about Windows.

*Rewrite my PATH variable to escape all the " " characters by replacing them with "\ "
I know this:
       echo $PATH | sed 's/ /\\ /g'

Does exactly what I need, but I can't get it to execute as an "export PATH=" command in .bashrc. I've tried:
export PATH='echo $PATH | sed '"'"'s/ /\\ /g'"'"' '

Which just breaks my Cygwin session to the point that I need to repair .bashrc in Notepad++ to boot again
export PATH="echo $PATH | sed 's/ /\\ /g'"

Which just prepends "echo " and appends " | sed 's/\ /g" to PATH.
export PATH='echo $PATH | sed "s/ /\\ /g"'

Which replaces my entire path with just "echo $PATH | sed "/\ /g"

*Something I haven't thought of at all.

Any help would be greatly appreciated.

A: How to get Cygwin to not load the Windows path
For the bash shell this can be done by making some small changes to ~/.bash_profile.
I like to have complete control over the PATH in Cygwin bash, so I added the following code to my ~/.bash_profile
# Build up the path using the directories in ~/.path_elements
unset PATH
while read line; do
  PATH="${PATH}$line";
done < ~/.path_elements

# Add current directory to path
export PATH=".:${PATH}"

Notes:

*

*unset PATH removes any PATH already configured by the Cygwin startup
code.

*The while loop reads in path elements from a file in my home directory (~/.path_elements) to build up my preferred PATH

*Finally we add the current directory . to the PATH and export it.

*Adding the current directory to the PATH could be considered as a security risk since built in commands could be replaced by commands located in the current directory. Please bear that in mind if you choose to use my code.
The contents of my ~/.path_elements are as follows. Modify and season to your taste to add extra elements to the path.
/home/DavidPostill/bin:
/usr/local/bin:
/usr/bin:
/c/Windows/system32:
/c/Windows

Result:
DavidPostill@Hal /f/test
$ echo $PATH
.:/home/DavidPostill/bin:/usr/local/bin:/usr/bin:/c/Windows/system32:/c/Windows


text:
Q: Correct status code to return when API calls a 3rd party API and that call fails I am developing a Web API which, as one of its functions, sends out SMSes. So when the consuming front-end requests the API to send out an SMS, the API in turn calls another API (from a 3rd party SMS service provider) and sends the SMS.
If the SMS fails to send for whatever reason (i.e. the SMS service provider tells my API that the SMS couldn't go through), what status code should my API return?
EDIT:
500 Internal Server Error doesn't seem right as there is no issue on the server. The SMS service provider simply couldnt send out the SMS (perhaps because the client has run out of credits, or the cellphone number is wrong
)


text:
Q: Sorting List of Arrays by different elements using Java 8 lambdas If I have a List<String[]> in which each String[] is as follows: {FirstName, LastName, Income, City} how would I go about using Java 8 lambdas to sort the List by a certain value such as income or first name?

A: Here's a couple examples.  Replace x in the first two examples below with the index of the field you'd like to use for sorting.
Collections.sort(personList, (p1, p2) -> p1[x].compareTo(p2[x]));

or
personList.sort((p1, p2) -> p1[x].compareTo(p2[x]);

Also, I agree with @Robin Topper's comment.  If lambdas are required (and you wanted to sort by first name), you could use:
Collections.sort(personList, (p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()));

or
personList.sort((p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()));

Also consider using the comparable implementation from Robin's comment and a data-structure allowing sorting.

A: If you can rely on the order in this array, then as simple as:
List<String[]> list = Arrays.asList(new String[] { "eugene", "test", "300", "LA" },
                              new String[] { "hunter", "test2", "25", "CA" });

 List<String[]> sorted = list.stream()
            .sorted(Comparator.comparingLong(s -> Long.parseLong(s[2])))
            .collect(Collectors.toList());

    sorted.forEach(s -> System.out.println(Arrays.toString(s)));

But the general advice to create an Object from those fields is much better.


text:
Q: text below an image HTML I am having a difficult problem which I can't solve properly. I am trying to design a web page. I came up with a problem and I can't find the solution. I have two pics in my web page. I want them to be in the center of the page. It is quite diffcult to set the image float left and then right and then bottom. That is too difficult for me. and then my second problem is I want a text below my image.
But I can't do that because it is difficult to set the text position like "left:20x: "right:20px; and blah blah.

A: Set the positions of the images to relative style="position:relative;" then use right and left to move them from side to side (top and bottom to move them up and down). You can also put your text in a < div > and move it separately.
If after this you are still unsure, please enter your code and I'll examine it to make any modifications required.
EDIT: Here's an example of the CSS code I'm suggestions you use, in case you didn't understand what I meant:
style="position:relative;left:10px;top:35px;" Put this in the img tag and it would alter the position of your image by 10 pixels to the right and 35 pixels downwards.


text:
Q: Bi-directional communication between Google Assistant and my App Firstly, I will note my observations of how other apps use Google Assistant (GA) with their android apps installed on local devices:
When you use apps like WhatsApp & Telegram (with a locally installed version on your device), it allows you to send a message via GA.
You're able to do the following:

*

*Select a desired contact (from what looks like the device's phone book)

*Add a text message and send it.

From my research I have come across these posts which suggest how they possibly achieve this:

*

*https://github.com/iNPUTmice/Conversations/issues/2655

*https://developer.android.com/reference/android/provider/ContactsContract.Intents.html#ACTION_VOICE_SEND_MESSAGE_TO_CONTACTS

*http://aivc.mobi/en/questions/view/8/whatsapp-message

*https://github.com/GigaDroid/Decompiled-Whatsapp/blob/master/AndroidManifest.xml

*https://github.com/DrKLO/Telegram/blob/master/TMessagesProj/src/main/AndroidManifest.xml
I chatted to @prisoner and he indicated that in this case GA is handing off the responsibility to the local app to complete the request. Which sort of makes sense based on the links I found.
In my case, I'm integrating my android application with Google Assistant and DialogFlow.
Thus far, I've managed to setup intents and fulfilment in DialogFlow which can be trigged by GA on a device.
I have a few questions regarding other functionality I'd like to achieve. Should I:

*

*Either use GA and my local app to complete requests?

*Or use GA, DialogFlow and my server (using a web-hook) to complete my requests?

To be able to achieve either of the two points above, I need to answer the below questions, assuming i'm using Actions-on-Google:

*

*Is it possible to achieve bi-directional communication between my local app and GA?

*Is there a mechanism I can use to expose data within my local app to GA? E.g. a list that will be displayed within GA which the user can interact with.

*Or rather should I authenticate my user using (Google Sign-in & OAuth) and fetch my data from the server (using a web-hook) through GA and DialogFlow?

A: According to Reddit user fleker2 bi-directional communication between Google Assistant and the app is only possible using App Actions:

For communication between a local app and the Assistant, you can look
  at using App Actions. Note that the capabilities are within a few
  domains, and not generally applicable.
  If you are asking whether to use a local app versus Dialogflow, consider your audience. A webhook and server would work on more surfaces like a Google Home or smart display.
You cannot have arbitrary communication between Assistant and a local
  app. If an app action doesn't work, you'll need a way to route webhook
  behavior to your app or service in a custom way.

Unfortunately App Actions are not mature enough for our use case.


text:
Q: If matter and antimatter were produced equally during the big bang, where is the rest of the antimatter? As far as my understanding goes, during the 'Big Bang' equal amounts of matter and antimatter (matter's oppositely charged twin) were produced, and the physical matter that remains within this universe is what's left over from the equilibrium of matter and antimatter canceling one another out following the Big Bang. If matter and antimatter truly do cancel one another out (are transformed into pure energy) upon contact, than:
a) why is there still matter in existence?
b) if matter is still in existence then doesn't that mean that somewhere within the universe there is an equal amount of antimatter?

A: The link Kyle gives in  his comment expands enough on the reasons
a) why is there still matter in existence?.
That there exists matter as we know it is an experimental observation that has to be taken into account in any theoretical formulation.
The existence of matter and antimatter is an experimental observation in the elementary particles data in our labs. The theories developed to describe the data are dominated by the CPT theorem :

CPT symmetry is a fundamental symmetry of physical laws under the simultaneous transformations of charge conjugation (C), parity transformation (P), and time reversal (T). CPT is the only combination of C, P and T that's observed to be an exact symmetry of nature at the fundamental level. The CPT theorem says that CPT symmetry holds for all physical phenomena, or more precisely, that any Lorentz invariant local quantum field theory with a Hermitian Hamiltonian must have CPT symmetry

Within this theory CP transformations turn particles into antiparticles.  There exist CP violation processes in the data,   but the size is not enough to explain the predominance of matter in our observable universe. Other arguments are brought forth as in the link above.
The CP violation  subject is still a matter of research, experimentally and theoretically.

b) if matter is still in existence then doesn't that mean that somewhere within the universe there is an equal amount of antimatter?

All the observational data from astrophysics lead to the conclusion that in the observable universe matter dominates by orders of magnitude.
1) a probe was just landed on a comet , no  explosion
2) cosmic rays from sun and the galaxy are predominantly matter
3)there is no dominant signal in cosmic gamma rays of electron positron annihilation that would happen in the boundary of galaxies and clusters of galaxies if they were composed of different matter content.
So it is an observational fact that the observable universe is dominated by matter, and the explanation is a matter of research still.


text:
Q: client constantly reconnecting My .net application which connects to signalr hub is constantly reconnecting.
This problem only occurs on certain other corporate networks which makes me believe something is being blocked.
I've tried to use the jabbr.net website from the same network and this doesn't work either (in chrome).
How can i trace/fix this issue?

A: I think you're experiencing this issue https://github.com/SignalR/SignalR/pull/1553. We're working on a fix for it. The issue happens when the server sent events request times out but the actual http requests is still going. What then happens is that the longpolling transport and server sent events http requests fight for the connection.
To workaround this you can specify the LongPollingTransport specifically. We'll look at fixing this for the next release.

A: For your server, in your web.config's system.diagnostics section add:
<sharedListeners>
  <add name="SignalR"
       type="System.Diagnostics.TextWriterTraceListener"
       initializeData="signalr.log.txt" />
</sharedListeners>

For your client (I'm assuming .net C#), its logging is via Debug.Writes. Also, I'd recommend hooking into the Error handler for your connection.
If your using a JS client you can turn logging on via
// Non dynamically made connection
connection.logging = true;
// Dynamically made connection
$.connection.hub.logging = true

Hope this helps!


text:
Q: Multiple modals on webpage I have a problem with modals. I want to make many modals for example 2 modals. First modal works correctly but second isn't opening.

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}

/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

.video-container {
    position:relative;
    padding-bottom:56.25%;
    padding-top:30px;
    height:0;
    overflow:hidden;
}

.video-container iframe, .video-container object, .video-container embed {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}

    ×

Header

                ×

Header

I want to make many modals working correctly! Look, second modal doesn't open. Any solutions? Please easy solutions, I don't want to change much my code.


text:
Q: Using a gtable object with gganimate I'm producing a gif with gganimate, and I'd like to make some tweaks to the plot format that can only be accomplished by converting a ggplot object to a gtable. For instance, I'd like to change the position of the plot title so that it always appears in the far left corner of the plot.
Here's an example of what the plot tweak would look like:
library(ggplot2)
library(gganimate)
library(dplyr)

# Helper function to position plot title all the way to left of plot
align_titles_left <- function(p, newpage = TRUE) {
  p_built <- invisible(ggplot2::ggplot_build(p))
  gt <- invisible(ggplot2::ggplot_gtable(p_built))

  gt$layout[which(gt$layout$name == "title"), c("l", "r")] <- c(2, max(gt$layout$r))
  gt$layout[which(gt$layout$name == "subtitle"), c("l", "r")] <- c(2, max(gt$layout$r))

  # Prints the plot to the current graphical device
  # and invisibly return the object
  gridExtra::grid.arrange(gt, newpage = newpage)
  invisible(gt)
}

# Create an example plot
static_plot <- iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width,
             color = Species)) +
  geom_point() +
  labs(title = "This title should appear in the far left.")

# Print the static plot using the adjustment function
align_titles_left(static_plot)

How can I use this function with gganimate?
Here's some example gganimate code to turn the plot in this example into an animation.
# Produce the animated plot
static_plot +
  transition_states(Species,
                    transition_length = 3,
                    state_length = 1)

A: Here's the result. Explanation below:

Any hacking with grobs should done after the individual frames of the animated plot have been created, but before they get drawn on the relevant graphics device. This window occurs in the plot_frame function of gganimate:::Scene.
We can define our own version of Scene that inherits from the original, but uses a modified plot_frame function with the grob hack lines inserted:
Scene2 <- ggproto(
  "Scene2",
  gganimate:::Scene,
  plot_frame = function(self, plot, i, newpage = is.null(vp),
                        vp = NULL, widths = NULL, heights = NULL, ...) {
    plot <- self$get_frame(plot, i)
    plot <- ggplot_gtable(plot)

    # insert changes here
    plot$layout[which(plot$layout$name == "title"), c("l", "r")] <- c(2, max(plot$layout$r))
    plot$layout[which(plot$layout$name == "subtitle"), c("l", "r")] <- c(2, max(plot$layout$r))

    if (!is.null(widths)) plot$widths <- widths
    if (!is.null(heights)) plot$heights <- heights
    if (newpage) grid::grid.newpage()
    grDevices::recordGraphics(
      requireNamespace("gganimate", quietly = TRUE),
      list(),
      getNamespace("gganimate")
    )
    if (is.null(vp)) {
      grid::grid.draw(plot)
    } else {
      if (is.character(vp)) seekViewport(vp)
      else pushViewport(vp)
      grid::grid.draw(plot)
      upViewport()
    }
    invisible(NULL)
  })

Thereafter, we have to replace Scene with our version Scene2 in the animation process. I've listed two approaches below:

*

*Define a separate animation function, animate2, plus intermediate functions as required to use Scene2 instead of Scene. This is safer, in my opinion, as it doesn't change anything in the gganimate package. However, it does involve more code, & could potentially break in the future if the function definitions change at the source.

*Over-write existing functions in the gganimate package for this session (based on the answer here). This requires manual effort each session, but the actual code changes required are very small, & probably won't break as easily. However, it also carries the risk of confusing the user, since the same function could lead to different results, depending on whether it's called before or after the change.
Approach 1
Define functions:
library(magrittr)

create_scene2 <- function(transition, view, shadow, ease, transmuters, nframes) {
  if (is.null(nframes)) nframes <- 100
  ggproto(NULL, Scene2, transition = transition,
          view = view, shadow = shadow, ease = ease,
          transmuters = transmuters, nframes = nframes)
}

ggplot_build2 <- gganimate:::ggplot_build.gganim
body(ggplot_build2) <- body(ggplot_build2) %>%
  as.list() %>%
  inset2(4,
         quote(scene <- create_scene2(plot$transition, plot$view, plot$shadow,
                                      plot$ease, plot$transmuters, plot$nframes))) %>%
  as.call()

prerender2 <- gganimate:::prerender
body(prerender2) <- body(prerender2) %>%
  as.list() %>%
  inset2(3,
         quote(ggplot_build2(plot))) %>%
  as.call()

animate2 <- gganimate:::animate.gganim
body(animate2) <- body(animate2) %>%
  as.list() %>%
  inset2(7,
         quote(plot <- prerender2(plot, nframes_total))) %>%
  as.call()

Usage:
animate2(static_plot +
           transition_states(Species,
                             transition_length = 3,
                             state_length = 1))

Approach 2
Run trace(gganimate:::create_scene, edit=TRUE) in console, & change Scene to Scene2 in the popup edit window.
Usage:
animate(static_plot +
          transition_states(Species,
                            transition_length = 3,
                            state_length = 1))

(Results from both approaches are the same.)


text:
Q: how can I do the action based on user input in python I have this code
phrase = input("Enter your message: ")

if 'hello' in phrase:
  print('Hello, Human')
if 'what is your favorite color' in phrase:
  print("It's blue")
else:
  print('unavailable')

how can it reply based on user like if he say hello and then what is your favorite color it will reply hello then it's blue like below:
Enter your message: hello, what is your favorite color
Hello, Human
It's blue

and that's okay but what if I want to automatically change like if he say what is your favorite color and then hello it will reply it's blue and then hello so the output should like this:
Enter your message: what is your favorite color, hello
It's blue
Hello, Human

but not like this:
Enter your message: what is your favorite color, hello
Hello, Human
It's blue

A: Your question is a bit too unspecific.. please specify it a bit more.
For the favorite color, since the user might ask something like "what's your favorite color", your program won't respond with blue because it's different from "what is your favorite color", so just have the program check for "favorite color".
phrase = input("Enter your message: ")

if 'hello' in phrase:
  print('Hello, Human')
elif 'favorite color' in phrase:
  print("It's blue")
else:
  print('unavailable')

A: phrase = input("Enter your message: ")

if 'hello' in phrase:
  print('Hello, Human')
  phrase1 = input('Enter your message: ')
  if phrase1 == 'what is your favorite color':
    print('its blue')
elif 'what is your favorite color' in phrase:
  print("It's blue")
  phrase2 = input('Enter your message: ')
  if phrase2 == 'hello':
    print('hello human')
else:
  print('unavailable')


text:
Q: SOAP-ERROR: Parsing WSDL: Couldn't load from : Start tag expected, '<' not found I recently updated my module to open cart 2.x from 1.5. I was using webservice in my module and it was working fine in 1.5 version. But when i updated to 2.x iam getting this error.
SOAP-ERROR: Parsing WSDL: Couldn't load from** 'https://abc.xyz.com/EndiciaParamWebService?wsdl' : **Start tag expected, '<' not found

I am calling my soap client like this.
$proxy = new SoapClient("http://hxlabelserver-heurixtics.rhcloud.com/EndiciaParamWebService?wsdl");

A: May be i am too late to answer this...but still add here so that someone can take help of it.
I also had this issue and i was left with two options:
1>openSSL was off
2>PHP version got mismatched
openssl was on for me...so then started playing with different version of php
And got it solved when reached php version 5.6
So i suggest you also can try with different version and could possibly match the good php version for your solution.


text:
Q: Example with camera glm / OpenGL immediate mode I can't get the camera transforms to work with glm...
Probably just a silly thing I missed but I just can't find it... help?
  glViewport(0, 0, m_width, m_height);
  glClearColor(0.5f, 0.5f, 1.0f, 1);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  float fovy = 60.0f;
  float aspect = m_width / float(m_height);
  float znear = 0.1f;
  float zfar = 100.0f;
  glm::mat4 Mp = glm::perspective(fovy, aspect, znear, zfar);
  glMultMatrixf(&Mp[0][0]);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glm::vec3 eye = glm::vec3(5, 5, 5);
  glm::vec3 lookat = glm::vec3(0, 0, 0);
  glm::vec3 up = glm::vec3(0, 1, 0);
  glm::mat4 M = glm::lookAt(eye, lookat, up);
  glMultMatrixf(&M[0][0]);

  glBegin(GL_TRIANGLES);
  glColor3f(1, 1, 1);
  glVertex3f(-10,-10,-10);
  glVertex3f(10,-10,-10);
  glVertex3f(10, 10,-10);

  glColor3f(1, 1, 0);
  glVertex3f(-10,-10,-10);
  glVertex3f(10, 10,-10);
  glVertex3f(-10, 10,-10);
  glEnd();

This gives the following output:
m_width = 1024, m_heigth = 768

A: Compared to gluPerspective, the unit of the angle argument of glm::perspective is Radian. Use glm::radians o convert from degrees to radians:
glm::perspective(fovy, aspect, znear, zfar);
glm::perspective(glm::radians(fovy), aspect, znear, zfar);

Instead of glLoadIdentity followed by glMultMatrixf you can use glLoadMatrixf.
In addition, you can use glm::value_ptr to get a pointer to the matrix fields:
float fovy = 60.0f;
float aspect = m_width / float(m_height);
float znear = 0.1f;
float zfar = 100.0f;
glm::mat4 Mp = glm::perspective(glm::radians(fovy), aspect, znear, zfar);

glMatrixMode(GL_PROJECTION);
glLoadMatrixf(glm::value_ptr(Mp));

glm::vec3 eye = glm::vec3(5, 5, 5);
glm::vec3 lookat = glm::vec3(0, 0, 0);
glm::vec3 up = glm::vec3(0, 1, 0);
glm::mat4 M = glm::lookAt(eye, lookat, up);

glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(glm::value_ptr(M));


text:
Q: how to add a new paypal sdk to file autoload.php of another paypal sdk that already exist in php i already installed adaptivepayments-sdk-php in my project and it have own file autoload.php and directory composer. composer directory have these following files : autoload_classmap.php,autoload_namespaces.php,autoload_psr4.php,autoload_real.php,ClassLoader.php and also a json file installed.json.
now i want to add a new sdk adaptiveaccounts-sdk-php in project and also want both sdk should have same file autoload.php.
so please guide me how to do it.
Note:- i already downloaded zip file of adaptiveaccounts-sdk-php

A: since you already have a composer.json, open it and add this
"autoload":{
   "psr-4":{
       "namespace\\to\\root\\of\\sdk":"path/to/root/of/sdk"
       "namespace\\to\\root\\of\\sdk2":"path/to/root/of/sdk2"
   }
}

Run composer updateafter that


text:
Q: Passphrase Key-based authenication with net-sftp in Ruby Based on question Key based authenication with net-sftp in Ruby, I can SFTP with key-based authentication using the following:
Net::SFTP.start(host, "user", keys:['~/.ssh/my_key']) do |sftp|
   sftp.upload! "/local/file.tgz", "/remote/file.tgz"
end

But I can't get this to work for keys that require a passphrase -- I just get prompted for the user login on that host. Am I missing something to pass in that would let me enter the passphrase for my key? Or do I need to just stick with ssh-agent for this?

A: There's the passphrase option:

the passphrase to use when loading a private key (default
        is nil, for no passphrase)

If you do not specify the passphrase, you should get asked for one, unless you used the non_interactive option:

set to true if your app is non interactive and prefers
         authentication failure vs password prompt
non interactive applications should set it to true
         to prefer failing a password/etc auth methods vs asking for password


text:
Q: Show that the metrices are not strongly equivalent We have the following metrices \begin{align*}&d_1(x,y)=|x-y| \\ &d_2(x,y)=\left |\frac{1}{x}-\frac{1}{y}\right |=\frac{|x-y|}{|xy|}\end{align*} Iwant to show that these are not strongly equivalent.
To get an inequality with $d_1$ and $d_2$ it depends on the value of $|xy|$ if it is less or greater than $1$.
Does it follow from that that the two metrices are not strongly equivalent?

A: Hint: $d_1$ and $d_2$ are strongly equivalent if and only if there exist constants $k>0$ and $K>0$ such that
$$
kd_1(x,y)\le d_2(x,y)\le Kd_1(x,y)\qquad\text{for all $x,y$.}\tag{*}
$$
In particular (*) implies that
$$
\sup_{x,y} \frac{d_1(x,y)}{d_2(x,y)}
$$
must be finite.


text:
Q: Html arrow characters aligned to bottom of font, how align to mid of font? I want to use the following html charactes:
A←↞⇽
However, as you can see, the arrows are aligned bottom of the font's vertical center-line. Is there a way to "lift them" up to the vertical center of the font?


text:
Q: What should I call a balance sheet that doesn't balance? One of the fundamental accounting/financial statements is the balance sheet. A balance sheet is balanced because the total assets of a company equal their liabilities plus owners' equity. However, what should a balance sheet that doesn't balance be called? Would that be an imbalance sheet, unbalance sheet, unbalanced sheet, or something else?

A: To be a hair more serious, one might say that the balance sheet has a "discrepancy":

a difference between two things that should be the same

A: You can use the expression "unbalanced balance sheet."
M-W defines unbalanced as:

c : not adjusted so as to make credits equal to debits - an unbalanced account.

The are numerous usage examples of unbalanced used referring to a balance sheet such as:

How to Review an Unbalanced Balance Sheet. (smallbusiness.chron.com
5 Reasons Why Your Balance Sheet Is Unbalanced. (atsaccountinginc.com)
Unbalanced Balance Sheet & Trial Balance.
  (community.myob.com)

A: It seems silly to have to say this, but you should call it what it is: an unbalanced balance sheet. And, clearly, given the definition of balance sheet, there can only be an unbalanced balance sheet if there is an error of some kind in the balance sheet: an error in the total assets of the company, the company's liabilities, the owners' equity, and whatever other pluses and minuses come into play. As @Greybeard has indicated in his comment, you could avoid the existence of an imbalance by including in the balance sheet an unaccountable deficit (or surplus) line. That would result in a balanced balance sheet in all cases, i.e., a balance sheet that actually balances. At the same time, it would indicate the existence of a problem (if the unaccountable deficit or surplus were significant) while shedding no light on the origin of the problem.


text:
Q: On topology of p-adic numbers. This may be a stupid question.But I am stuck with it.Is Q_p(the p-adic) connected under the usual topology?I was confounded with this problem while trying to construct a counter-example related to my master's thesis.

A: Any non-empty open can be written as a disjoint union of opens ; for example
$\mathbb{Z}_p=\cup(a+p\mathbb{Z}_p)$ where $a$ runs through $\{0...(p-1)\}$. Those spaces are said totally disconnected.


text:
Q: Node - How to reconstruct full stack trace for Promise rejection I've stumbled upon an issue similar to the one discussed in this question but does not seem to be the same. I have a function returning a promise and rejecting (in case of errors) after a while (it's doing an HTTP call, so it takes some time). While the request is flying around the internet Node takes care of other instructions, when the request is received and the error thrown the stack trace begins from processTicksAndRejections (as it would for any async operations, I guess). This is a problem as I no longer have a record of where the function was called from.
So I tried the following approach, the normal code would be
const fetch = require('node-fetch');

function myFunction() {
  return new Promise(async (resolve, reject) => {
    fetch('https://www.google.com').then(() => {
      return reject(new Error('Whoops!'));
    });
  });
}

myFunction().catch(console.log);

which prints out
Error: Whoops!
    at /home/dami/projects/testing/stack.js:8:21
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

The idea is to concatenate the old stack trace like
function myFunction() {
  const stack = (new Error()).stack;

  return new Promise(async (resolve, reject) => {
    fetch('https://www.google.com').then(() => {
      const error = new Error('Test');
      error.stack += stack;
      reject(error);
    });
  });
}

myFunction().catch(console.log);

which prints
Error: Test
    at /home/dami/projects/testing/stack.js:8:21
    at processTicksAndRejections (internal/process/task_queues.js:95:5)Error
    at myFunction (/home/dami/projects/testing/stack.js:4:18)
    at a (/home/dami/projects/testing/stack.js:16:3)
    at Object.<anonymous> (/home/dami/projects/testing/stack.js:19:1)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47

However, this does not seem the best (and most neat) solution to me, as at this point I have two 'sources' of the trace (one being the normal Node process at run_main_module, the other at processTicksAndRejections).
So the final question, is there a best practice approach to this problem?  I've tried using async/await and keeping the rejection at the top level of myFunction, but it will always be picked up by processTicksAndRejections because of its async nature. Thanks!

A: I would use an async function here exactly for the reason of preserving the stack trace:
async function myFunction() {
    await fetch('https://www.google.com');
    throw new Error('Whoops!');
}

async function foo() {
    await myFunction();
}

async function bar() {
    await foo();
}

bar().catch(console.log);

Don't be bothered by the process.processTicksAndRejections entry in the stack trace. As long as async/await are used consistently, the whole call chain should be logged with the exception.