text:
Q: JS .load() not working inside a triple parameter url rewrite? im building a backoffice which has already this function working on single parameter url like example.com/backoffice/page
but on this page is not working the link is like this : example.com/backoffice/editassembly/2
This is the JS code of the page :
// When the document is ready set up our sortable with it's inherant function(s)
$("#todos").sortable({
    handle: "#handle",
    update: function() {
        var order = $('#todos').sortable('serialize');
        $("#info").load("../scripts/ficheiroassembleia.php?" + order);
    }
});

This code is completly correct and working on other pages, the thing is that the .load is not loading my script like it could not reach it.
The current module for the page im using is inside the folder "www/backoffice/modules/editassembly/" and the script is inside "www/scripts/"

A: I already found out the problem, it was due to fact that the include for header that contained all important js files was not loading corretly, path issue i had to make a call on the file itself since it was the only module using a tripple parameter.


text:
Q: Docker for dev and production Let's say I have some projects using Go and some Javascript Applications.
In development, I need to run those using go run or npm start.
In production, I need to run a compile version from my app go build or npm build.
Right now, I don't see how to use Docker for that: Should I create two containers: one for development (using npm start or go run) and one for production (it will build the app and serve it) ? It seems I will loose the benefits of using Docker if I choose this path.
EDIT1: One solution could be to use different command in production or development. But If my project takes 10 minutes to build, it will mean that everytime I deploy a container it will restart it's build which is not an acceptable solution.
How do you deal with those cases ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing the deserialised object from a different class I am using the following class to deserialise a JSON object:
 //Method to deserialize the response body
    public static responseResource deserialize(httpResponse res){
      return (responseResource)JSON.deserialize(res.getBody(),responseResource.class);
    }

I then want to access the returned deserialised object in a separate function and assign its elements to salesforce fields.
So, for example if one of the deserialised fields is 'Description', how do I access it in another class?
The question is about this part of the last class:
  string description = <the 'Description' field from the deserialise (res) object returned by 'responseResource Query' class I don't know how to describe in the script>

Let me use the following to explain further:
First, helper function:
public static responseResource APIQuery(string domain){
    httpResponse res = callout(domain);
    if ( res.getStatusCode() == 200 && string.isNotBlank(res.getBody())){
        return deserialize(res);
    }
    return null;
}

And the function to access the variable:
    @future (callout=true)
        public static void FutureCallBasicUpdater(string domain)
            {

string description = <the 'Description' field from the deserialise (res) object returned by 'responseResource APIQuery' class I don't know how to describe in the script>
            }

A: You access like any normal variable. "Utility" in this example is the name of the class that contains APIQuery.
@future (callout=true)
public static void FutureCallBasicUpdater(string domain) {
    Utility.responseResource res = Utility.APIQuery(domain);
    string description = res.Description;
}

Since you're trying to access the data across classes, the class and the Description value must be public:
public class resourceResponse {
    public String Description;
    // more attributes here, as needed
}


text:
Q: Activity not starting from Status Bar Notification I've found a lot of Stack Overflow posts about this issue but they all use the now deprecated Notification methods instead of using the Notification.Builder class.
I'm successfully creating status bar notifications, but when clicked nothing happens.  A warning in LogCat shows up:
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@412d6df0

Here is the code I'm using to build my Notification:
public class LunchNotificationBuilder {

private Notification notification;
public LunchNotificationBuilder(Lunch lunch, Context context) {
    Builder builder = new Builder(context);
    Calendar reminderTime = (Calendar)lunch.getReminderTime().clone();
    builder.setWhen(reminderTime.getTimeInMillis());
    builder.setTicker("Reminder for " + lunch.getTitle());
    builder.setContentTitle("LunchBunch Notification");
    builder.setContentText("Upcoming lunch at " + lunch.getTitle());
    builder.setSmallIcon(R.drawable.ic_launcher);
    Intent intent = new Intent(context, InviteDetails.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    builder.setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT));
    this.notification = builder.getNotification();
}

public Notification getNotification() {
    return this.notification;
}

}

The Lunch class is just a data structure I created, don't worry about that.
The Context being passed in is Application.getApplicationContext().
I'm setting the Intent.FLAG_ACTIVITY_NEW_TASK flag as suggested by the documentation, and the PendingIntent has the PendingIntent.FLAG_ONE_SHOT flag.
Another note: The activity I'm trying to launch (InviteDetails) works just fine when I explicitly call startActivity elsewhere in the code.  Something about this PendingIntent business isn't working.

A: Turns out I don't know how to use Android. I was clicking the status bar at the top, not dragging down to see the full notification before clicking. my code was working. doh!


text:
Q: Docker Jboss/wildfly: How to add datasources and MySQL connector I am learning Docker which is completely new to me. I already was able to create an jboss/wildfly image, and then i was able to start jboss with my application using this Dockerfile:
FROM jboss/wildfly

CMD ["/opt/jboss/wildfly/bin/standalone.sh", "-c", "standalone-full.xml", "-b", "0.0.0.0"]

ADD mywebapp-web/target/mywebapp-1.0.war /opt/jboss/wildfly/standalone/deployments/mywebapp-1.0.war

Now i would like to add support for a MySQL Database by adding a datasource to the standalone and the mysql connector. For that i am following this example:
https://github.com/arun-gupta/docker-images/tree/master/wildfly-mysql-javaee7
Following is my dockerfile and my execute.sh script
Dockerfile:
FROM jboss/wildfly:latest

ADD customization /opt/jboss/wildfly/customization/

CMD ["/opt/jboss/wildfly/customization/execute.sh"]

execute script code:
#!/bin/bash

# Usage: execute.sh [WildFly mode] [configuration file]
#
# The default mode is 'standalone' and default configuration is based on the
# mode. It can be 'standalone.xml' or 'domain.xml'.

echo "=> Executing Customization script"

JBOSS_HOME=/opt/jboss/wildfly
JBOSS_CLI=$JBOSS_HOME/bin/jboss-cli.sh
JBOSS_MODE=${1:-"standalone"}
JBOSS_CONFIG=${2:-"$JBOSS_MODE.xml"}

function wait_for_server() {
  until `$JBOSS_CLI -c ":read-attribute(name=server-state)" 2> /dev/null | grep -q running`; do
    sleep 1
  done
}

echo "=> Starting WildFly server"

echo "JBOSS_HOME  : " $JBOSS_HOME
echo "JBOSS_CLI   : " $JBOSS_CLI
echo "JBOSS_MODE  : " $JBOSS_MODE
echo "JBOSS_CONFIG: " $JBOSS_CONFIG

echo $JBOSS_HOME/bin/$JBOSS_MODE.sh -b 0.0.0.0 -c $JBOSS_CONFIG &
$JBOSS_HOME/bin/$JBOSS_MODE.sh -b 0.0.0.0 -c $JBOSS_CONFIG &

echo "=> Waiting for the server to boot"
wait_for_server

echo "=> Executing the commands"
$JBOSS_CLI -c --file=`dirname "$0"`/commands.cli

# Add MySQL module
module add --name=com.mysql --resources=/opt/jboss/wildfly/customization/mysql-connector-java-5.1.39-bin.jar --dependencies=javax.api,javax.transaction.api

# Add MySQL driver
/subsystem=datasources/jdbc-driver=mysql:add(driver-name=mysql,driver-module-name=com.mysql,driver-xa-datasource-class-name=com.mysql.jdbc.jdbc2.optional.MysqlXADataSource)

# Deploy the WAR
#cp /opt/jboss/wildfly/customization/leadservice-1.0.war $JBOSS_HOME/$JBOSS_MODE/deployments/leadservice-1.0.war

echo "=> Shutting down WildFly"
if [ "$JBOSS_MODE" = "standalone" ]; then
  $JBOSS_CLI -c ":shutdown"
else
  $JBOSS_CLI -c "/host=*:shutdown"
fi

echo "=> Restarting WildFly"
$JBOSS_HOME/bin/$JBOSS_MODE.sh -b 0.0.0.0 -c $JBOSS_CONFIG

But I get a error when i run the image complaining that a file or directory is not found:
Building Image
$ docker build -t mpssantos/leadservice:latest .
Sending build context to Docker daemon 19.37 MB

Step 1 : FROM jboss/wildfly:latest
 ---> b8279b641e82

Step 2 : ADD customization /opt/jboss/wildfly/customization/
 ---> aea03d4f2819

Removing intermediate container 0920e2cd97fd

Step 3 : CMD /opt/jboss/wildfly/customization/execute.sh
 ---> Running in 8a0dbcb01855
 ---> 10335320b89d

Removing intermediate container 8a0dbcb01855

Successfully built 10335320b89d

SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

Running image
$ docker run mpssantos/leadservice
no such file or directory
Error response from daemon: Cannot start container 5d3357ba17afa36e81d8794f2b0cd45cc00dde955b2b2054282c4ef17dd4f265: [8] System error: no such file or directory

Can someone let me know how can i access the filesystem so i can check which file or directory is complaining? Is there a better way to debug this?
I believe that is something related with the bash which is referred on first line of the script because the following echo is not printed
Thank you so much

I made it to ssh the container to check whats inside.
1) ssh to the docker machine: docker-machine ssh default
2) checked the container id with the command: docker ps -a
3) ssh to the container with the command: sudo docker exec -i -t 665b4a1e17b6 /bin/bash
4) i can check that the "/opt/jboss/wildfly/customization/" directory exists with the expected files
The customization dir have the following permissions and is listed like this:
drwxr-xr-x   2 root    root    4096 Jun 12 23:44 customization
drwxr-xr-x 10 jboss jboss   4096 Jun 14 00:15 standalone

and the files inside the customization dir
drwxr-xr-x  2 root  root    4096 Jun 12 23:44 .
drwxr-xr-x 12 jboss jboss   4096 Jun 14 00:15 ..
-rwxr-xr-x  1 root  root    1755 Jun 12 20:06 execute.sh
-rwxr-xr-x  1 root  root  989497 May  4 11:11 mysql-connector-java-5.1.39-bin.jar

if i try to execute the file i get this error
[jboss@d68190e4f0d8 customization]$ ./execute.sh
bash: ./execute.sh: /bin/bash^M: bad interpreter: No such file or directory

Does this bring light to anything?
Thank you so much again

A: I found the issue. The execute.sh file was with windows eof. I converted to UNIX And start to work.

A: I believe the execute.sh is not found. You can verify by running the following and finding the result is an empty directory:
docker run mpssantos/leadservice ls -al /opt/jboss/wildfly/customization/

The reason for this is you are doing your build on a different (virtual) machine than your local system, so it's pulling the "customization" folder from that VM. I'd run the build within the VM and place the files you want to import on that VM where the build can find it.


text:
Q: Azure App Publishing - I think Javascript isn't enabled, but honestly I have no clue I've written and deployed a web form app (Visual Studio) and deployed it to my Azure platform which is running app services.
The problem is I think a Javascript setting isn't quit right as the login form isn't displaying correctly and the buttons don't fire any java functions.
Here's how the page looks when I view it while debugging in VS2017
It's basically 3 forms, but 2 are hidden (by depending on which button you click)
Debug Login
And here is what the page looks like when I view after publishing on the Azure platform. Any ideas what I need to change to always get it to display and behave the same as when run via localhost?
Azure Login
Update: These errors show under F12:
Javascript Error 1
Javascript Error 2


text:
Q: Is the continuous transformation of energy from one form to another one free? Or it consumes some quantity of who knows what? Sorry for the unclarity. I probably created some bias in your mind having tagged my question with energy-conservation and conservation-laws.
I simply consider that, relatively independently of matematical models, energy
is everyday changing its "form" both "spontaneously" or triggered by us
using our machines.
So I ask: why the universe seems to be designed in a way that it "seems"
free (at no cost) to change cinetic to thermal energy, for instance?
Why we do not need to pay a fee to move energy from "light" to heat?
Like exchanging currency without having to pay for that service.
I stress once again that I am not referring to the basic consideration of
losses. I do not discuss the conservation of energy itself.

A: We have losses in every transformation of energy. If I understood your question and what you meant by "free", transformation of energy is never "free".
E.g: When pushing forward a crate that is on the floor, not all that energy is transformed into movement, some of it is transformed in heat, because of friction.

A: "Consumes" is the wrong word to use, IMO. In any given Physical model, some quantities increase, some quantities decrease, some quantities stay the same. Some quantities change monotonically, some quantities oscillate.
The energy of a given model stays the same if the energy is a conserved quantity of the model dynamics, tautologically, or, slightly less tautologically, if the dynamics is time-translation invariant. The entropy of a model may increase, depending on whether the model satisfies the (usually rather vaguely stated) premises of Boltzmann's H-theorem, say, but the entropy is an extremely coarse-grained quantity that tells us practically nothing about the details of a dynamical state.
Now, you have also to consider what the relationship of whatever Physical model we use might be to the world. How accurate is the model? Does the accuracy (the definition of which is non-trivial) decrease monotonically, or does the accuracy oscillate or improve? If the model is not accurate, then it may be that there are better Physical models in which there is some new quantity that decreases over time. Then again, it may turn out that this better model has to be replaced in the future by another, still more accurate model that doesn't have that particular quantity in it at all.
Finally, it is a prejudice held by some that a perfect Physical model is around the corner, in terms of which we could definitely answer your Question; we could say precisely which quantities go down over time, which increase, which oscillate, ... . Then again, it is a prejudice held by others that every Physical model will always be an approximation, albeit the approximation may improve over time, in which case there cannot be a definite answer to your question. Now, find a way to definitely show that one or the other prejudice is correct.

A: No, the transformation of energy from one form to another is never free. You could say that it consumes some amount of work; or, more formally, that it increases the amount of entropy.
Most forms of energy are capable of doing some work. But low-grade heat is capable of doing very little work (for a given amount of energy). Other forms of energy are capable of doing more work. Kinetic energy is capable of doing lots of work. Turning it into low-grade heat, through friction, doesn't change the total amount of energy: the conversion can be (very very close to) 100%. But that will increase the amount of entropy in the system; the kinetic energy was able to do lots of work, and the low-grade heat will be capable of doing very little work.

A: Maybe the problem is that you are assuming some ideal process without losses that transforms for example heat energy into kinetic energy without increasing entropy, but that is not the case, as even an ideal combustion engine has a theoretical maximum performance. The decreased value if that is what you are looking for could be exergy, does that make sense?


text:
Q: Matching number with predifined patterns I have a problem that I have been thinking about for some time but failed to find the best solution.
The application is for a company that sells special phone numbers for different prices depending on the pattern of the number.
So the user has a stock of numbers. And defines patters using a some convention. For example:

*

*(ABCDEFG) represents a number with sequence such as (1234567, or
2345678, etc...).

*(ZYX-ZYXW) represents a number such as (654-6543).

When customer picks up a number, the number should be matched against the patter it matches, and when a pattern is matched, the number is charged with the price of the matched pattern.
My thoughts are focused on three possible solutions:

*

*I tried to think of regular expressions. But not sure if it can
work.

*Another solution would be looping over each possibility
for each patter and matching it against the purchased number. But I
am sure this is going to be too expensive performance wise.

*Finally I thought to save all possible numbers when user adds a
pattern so that when a clients wants to buy a new number, the
application doesn't search patter but search actual numbers. This
way the performance bottle neck would be when user adds a pattern
(which is much less frequent than a client picking a number).

Do you guys have any advice regarding which approach should I use? Any hint is much appreciated.
Edit:
I'm very happy for the replies I received. They are all enlightening, however non so far can solve my problem. The real world scenario will the have the following condition:

*

*Some patters will follow some kind of digits order (sequential or non-sequential), such as: ABCDEFG=1234567, or ACEGECA=2468642.

*Some patters will be based on repetition of numbers, such as: xyxyxyx=1919191, or xyxzxyx=2829282. I guess in a way we can include this condition to the one above.

*Some patterns will have hard-coded digit, like ABC0ABC, or 123xyxy

*There is no limit to pattern possibilities.

So far all proposed methods have a limitation in their own ways. I am still think of it, so please if you come up with any helpful hit, share it with me!

A: An idea. demo
$number = '987-9876';
$suffix = <<<'EOD'
0123456789 ABCDEFG 10 ABCABCD 15
9876543210 GFEDCBA 8 DCBDCBA 13
EOD;

$pattern = <<<'EOD'
~
\A (?<number>(\d{3})-?(\d{4})) \R
(?|
    \d*? # rectus
    (?|
        \2 \3 \d*
        [ ] (?<format> ABCDEFG ) [ ] (?<price>\d+)
      |
        (?=\3) \2 \d*
        (?> [ ] [A-Z]+ [ ] \d+)*? # other formats until the good one
        [ ] ( ABCABCD ) [ ] (\d+)
    )
  |
    .* \R \d*? # inversus
    (?|
        \2 \3 \d*
        [ ] ( GFEDCBA ) [ ] (\d+)
      |
        (?=\3) \2 \d*
        (?> [ ] [A-Z]+ [ ] \d+)*?
        [ ] ( DCBDCBA ) [ ] (\d+)
    )
)
~x
EOD;

if (preg_match($pattern, $number . PHP_EOL . $suffix, $m))
    echo 'number: ' . $m['number'] . PHP_EOL . 'format: ' . $m['format'] . PHP_EOL
       . 'price: ' . $m['price'];

Other approach (probably the most performant)
Special numbers are limited. You can produce and use a multidimensional array that contains all the special numbers, something like this:
$speNum = [
    'ABCDEFG' => [ '1234567', '2345678', '3456789' ],
    'GFEDCBA' => [ '9876543', '8765432', '7654321' ],
    'ABCABCD' => [ '1231234', '2342345' ...
];

$prices = [ 'ABCDEFG' => 10, 'ABCABCD' => 15, 'GFEDCBA' => 8 ...];

And with a simple foreach, test if the number is in the array:
foreach ($speNum as $format => $nums) {
    if (in_array($number, $nums)) {
        echo 'number: ' . $number . PHP_EOL . 'format: ' . $format . PHP_EOL
           . 'price: ' . $prices[$format];
        break;
    }
}

Note: for this second approach (an why not for the first too), remove the hyphen before. The main advantage of this approach is that you can easily extend it to other kind of patterns. Note that you can do the same with your database.

A: Use the following strategy:
pseudo code
String getPattern(String pn,int n)
    {

        int[] nums = new int[7];
        for (int i = 0; i < 7; i++)
            nums[i] = int.Parse(pn[i].ToString());
        Array.Sort(nums);
        String pat = pn;
        Char chr = 'A';
        for (int i = 0; i < 7; i++)
        {
            if (nums[i] != n)
            {
                pat = pat.Replace(nums[i].ToString(), chr.ToString());
                if ((i + 1) < 7)
                {
                    int shif = nums[i + 1] - nums[i];
                    chr = (Char)(Convert.ToUInt16(chr) + shif);
                }
            }

        }
        return pat;
    }

it worked for me with c# and it auto detect the pattern for entered number
also you can develop it to be more advanced (for example add zyx pattern detection)


text:
Q: SSRS Published report from MySQL DB shows blank/empty rows I have created a very simple report in Visual Studio (also tried it in Report Builder) that just returns 10 rows from a table in a MySQL (Not MSSQL) database. I changed the background and foreground color to make sure I could clearly see the rows in the report.
There are no parameters and it does not use a stored procedure. It's a straightforward SQL query:
select TASK_INSTANCE_ID, TASK_NAME, ASSIGNED_NAME, CREATED_DTTM
from task_instance where created_dttm > date_sub(now(), interval 1 day)
limit 10

Here's the result when previewing the report in Visual Studio. You can see that it is showing 10 rows of data.

I then publish that report to our SSRS server:

And when I view that report on the SSRS server I get 10 blank rows.

To confirm that I was actually seeing the rows and they were just blank, I changed the query to return just 5 rows. This shows that there are now only 5 blank rows, but with the defined background color.

For reference, I also created a simple report from an Oracle DB and published it to the same folder on the same SSRS server. This report works just fine.

So it appears to be something related to using a MySQL DB, but I have not been able to find anything that explains what I'm doing wrong. Any pointers/help will be greatly appreciated.
I then tried to add a couple new columns to the SQL query.

*

*I used the ROW_NUMBER function to get the rownum of each returned row

*I added a dummy column with a constant value for each row

Works fine in the Query Designer:

Works fine in the Preview:

Shows the new columns when published to SSRS, but still shows blank cells for the other columns:

A: If your problem is/was the same as mine then I think you will find that if you export your report to excel from the report-portal that all of the data that you expect to see is in fact present.
After some digging into the report properties and trying page width settings etc. I found that I had different values for the CanGrow property of the cells in the row and once I set them all to be the same -- True in my case -- then the report rendered as expected.
I am thinking that the reason that Excel showed the data is because it effectively ignores the CanGrow setting so having a mixture of them didn't matter.
I hope that this helps -- you or others who encounter it later -- as it was a really bizarre thing to encounter...


text:
Q: JqueryUI CDN works fine if my site is running on my local drive but won't load on my ipage host I am trying to use JqueryUI's accordion widget on my page, the widget works fine on my local drive.  However, when I uploaded my page on ipage host, the website won't load the JqueryUI.
Here is my CDN links to Jquery and JqueryUI:
<!-- jQuery library 1.1.2-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<!--JQUERY UI CDN-->
<link href="http://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.11.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

A: Not sure why you're loading jQuery twice. Try the following
<!-- always load CSS first -->
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/ui-lightness/jquery-ui.css">

<!-- jQuery library 1.11.2-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<!--JQUERY UI from Google CDN-->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>

I've removed the http: schemes from the URLs so they will load securely if your page is also secure.
You'll also notice I've used Google's CDN for all resources. You should be able to use jQuery's if you really want to though.

And as always, don't forget to upload all updated files to your webhost. I recommend rsync.

A: That is conflict, don't define same library. You have jquery minified (jquery.min.js) and you have jquery-1.11.2.js. Which one do you choose. and ensure jquery on the top of jquery ui, because jquery is dependency of jquery ui. I hope helpful.


text:
Q: int value to Hex and put it in int array i have this code
int[] i = new int[2]
i[0] = 0x13;
i[1] = 0x88;

here a value 5000 is converted to hex (1388) and put in an int array.
I want to make it so i can put in what i want with a int parameter. E.g. ``var represents decimal 6000 and it should convert it to hex (1770) and end up as
int[] i = new int[2]
i[0]= 0x17
i[1]= 0x70

in the array.

A: Try this
            UInt16 input = 0x7017;
            byte[] i = new byte[2];
            i[0] = (byte)(input & 0xff);
            i[1] = (byte)((input >> 8) & 0xff);


text:
Q: Benchmarking a simple spring application with JMH I am writing a simple jmh-demo program to see how to benchmark a spring program. Following the steps here, I start the benchmark with java -jar target/benchmarks.jar. It prints out the following and just stocks!
# JMH version: 1.21
# VM version: JDK 1.8.0_121, Java HotSpot(TM) 64-Bit Server VM, 25.121-b13
# VM invoker: C:\jdk1.8.0_121\jre\bin\java.exe
# VM options: <none>
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: MyBenchmark.testMethod

# Run progress: 0.00% complete, ETA 00:08:20
# Fork: 1 of 5
# Warmup Iteration   1: Do Setup
init context
DEBUG [MyBenchmark.testMethod-jmh-worker-1] (AbstractApplicationContext.java:594) - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1dba888f

Here is the code for the main class
public class MyBenchmark {
  @State(Scope.Thread)
  public static class MyState {
    @Setup(Level.Trial)
    public void doSetup() {
      System.out.println("Do Setup");
      if (context == null) {
        System.out.println("init context");
        context = new ClassPathXmlApplicationContext(
            "applicationContext.xml");
        System.out.println("after init");
      }
      System.out.println("Did Setup");
    }

    public ApplicationContext context;
    public int a = 1;
    public int b = 2;
  }

  @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MINUTES)
  public void testMethod(MyState state, Blackhole blackhole) {
    int sum1 = state.a + state.b;
    int sum2 = state.a + state.a + state.b + state.b;

    blackhole.consume(sum1);
    blackhole.consume(sum2);
  }
}

What is the problem and what should I do?

A: I skipped working with the jar file and just simply added a main method to run the benchmark:
public static void main(String... args) throws RunnerException {//just run (not debug) it
  Options opt = new OptionsBuilder()
      .include(MyBenchmark.class.getSimpleName())
      .build();
  Collection<RunResult> runResults = new Runner(opt).run();
  for (RunResult runResult : runResults) {
    System.out.println(runResult);
  }
}


text:
Q: How do I ignore an alert using selenium + chrome webdriver + python? I need to ignore the alert raised by Chrome Webdriver:
Alert Screenshot
I am trying using: browser.switch_to.alert.accept but it is not working.
I already set up the option as:
chrome_options = Options()
chrome_options.add_argument("--disable-notifications")

But I believe the alert is not a notification object.
Thank you for your help!

A: Have you tried this.
chrome_options = Options()
chrome_options.add_argument("--disable-popup-blocking")

A: While your original post mentioned that you couldn't get the alert code to work, the accepted answer didn't work for me. Looking at the documentation, I successfully used:
 alert = browser.switch_to.alert
 alert.accept()

A: This way helped me to handle the alert boxes and save the screenshot of the URL.
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
alert.accept();
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "C:\\Images";
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
driver.close();


text:
Q: acessing innerHTML text node inside a block of HTML I'm trying to access the 12:00 number in this huge span of HTML.  It's in the
. I tried using getElementById().innerHTML of the div, and then console log with a function that fires on click of the element, gives me nothing, no error either

function minusMinute() {
  time = window.document.getElementById('gameClock').innerHTML;
  console.log(time);
}

minusMinute = window.document.getElementById('minusMinute');

minusMinute.addEventListener('click', minusMinute, false);

        12:00

A: You have multiple issues there:

*

*You've declared a function called minusMinute, but you've also declared a variable called minusMinute, and assigning to it overwrites the function. So your
minusMinute.addEventListener('click', minusMinute, false);

line is hooking up the element as a click handler.

*Your HTML also has onclick="minusMinute". If minusMinute were a function, that wouldn't do anything, because the function the browser creates to wrap your code there will just refer to minusMinute but not call it. onXyz attribute handlers should contain function calls (e.g., onclick="minusMinute()"), but if you're using addEventListener, you don't need the onclick attribute at all.

*While it's true that the 12:00 is inside an element with id="gameClock", there a lot else in there as well. But helpfully it's all on its own inside the span with id="gameTime".
Here's a fixed version with minimal changes:

function minusMinute(){
  var time = window.document.getElementById('gameTime').innerHTML;
  console.log(time);
}

window.document.getElementById('minusMinute').addEventListener('click', minusMinute, false);

        minusMinuteIsHere12:00

Changes:

*

*I don't declare a minusMinute variable and assign to it, so the minusMinute function doesn't get overwritten.

*I removed the onclick attribute

*I used gameTime rather than gameClock

*Just for the purposes of the snippet, I put some text inside the minusMinute element, since the snippet doesn't have your CSS and so there's no icon to click.

Side note: There's no need for window.document, just use document. window is a global variable (pointing to the global object, where most global variables are available as properties), and document is a global variable, so... I mean, you could also do window.window.document, or window.window.window.document. :-)

A: Like mplungjan already mentioned, you should make sure the element is there when you try to get it's content (either by including the javascript at the end or using the onload function).
another problem that you also had is you used the same name for global variable minusMinute and the function name minusMinute so that would produce you the also give you an error.

A: You firstly need to do this when the Dom elements exist, for example onload :
window.onload=function() {
  var minusMinute = window.document.getElementById('minusMinute');
  minusMinute.addEventListener('click', minusMinute, false);
}

or simpler and more compatible - I assume you want gameTime instead of gameClock
window.onload=function() {
  document.getElementById('minusMinute').onclick=function() {
    var time = document.getElementById('gameTime').innerHTML;
    console.log(time);
  }
}

The above anonymous function also solves a name clash between your function and object.
You also have some weird onclicks in the html that needs to be removed,
Lastly addEventListener is not compatible with all browsers.
Here is my code with your cleaned up HTML - I had to add some content to minusMinute to see it

window.onload = function() {
  document.getElementById('minusMinute').onclick = function() {
    var time = document.getElementById('gameTime').textContent;
    console.log(time);
  }
}

        <<
        >>
        12:00


text:
Q: How to deal with changes to ios 13 fonts? I'm developing my first pet-project app. It's almost ready for release, but the recent ios 13 release has changed all the fonts. I can see there was an issue filed on Github (https://github.com/flutter/flutter/issues/43998).
My code is pretty standard:
Widget build(BuildContext context) {
  return Text(
    'Find out which bins to put out and when your collection day is',
    style: TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: 16.0,
    ),
    textAlign: TextAlign.center,
  );
}

But the results are like this: https://imgur.com/a/u2Esgym
How are people dealing with this?

A: So, it looks like there is another Github issue to address this
https://github.com/flutter/flutter/issues/49492


text:
Q: Best practice in declaring events in C# I know the following two methods work, but I wonder if one is better in terms of performance / maintenance / whatever.
The short way:
  public event EventHandler MyEvent;

The long way:
  private EventHandler _myEvent;
  public event EventHandler MyEvent
  {
     add { _myEvent += value; }
     remove { _myEvent -= value; }
  }

The long way seems similar to encapsulating members with properties, which is indeed a good practice. But does this apply to event handlers?

A: The first way does exactly the same underneath with creating private EventHandler with the name MyEvent. When it's accessed within the class event handler is returned (i.e. no problem with calling delegate) when it's called outside of class (myClassInstance.MyEvent += SomeHandler/myClassInstance.MyEvent -= SomeHandler) Add/Remove methods are called respectively. And these methods are the same (except they add thread-safety) as those you've written in the second way.
So why do you want to write more code when you actually don't need it?

A: In this case, the argument of "good practice" is a little tricker; the first is a "field-like event"; you note:

The long way seems similar to encapsulating members with properties,

but: this is encapsulated (behind add/remove) either way; so by comparison to properties, it is really the difference between:
public int Foo {get;set;}

and
private int foo;
public int Foo {
    get { return foo; }
    set { foo = value; }
}

In which case I would say "use the first one unless you have an actual reason not to" - it is still hidden behind accessors. Additionally, it is important to note that your second example is not what a field-like event (the first example) expands to : the compiler adds thread-safety into the mix. So: I would say use the first sample:
public event EventHandler MyEvent;

Note that the "how" for the thread-safety depends on which compiler version (and indeed, which specification) you use. In recent Microsoft C# compilers, it does this with Interlocked operations (CompareExchange etc), so it does not require a dedicated private synchronization object.

A: To check what Marc Gravel mean i tried the following code:
public event EventHandler MyEventShortWay;

private EventHandler _myEvent;
public event EventHandler MyEventLongWay
{
    add { _myEvent += value; }
    remove { _myEvent -= value; }
}

I was surprised by what was generated (I edited the decompiled variable name) :
private EventHandler _myEventShortWay;

public event EventHandler MyEventShortWay
    {
        add
        {
            EventHandler handler2;
            EventHandler myEventShortWay = this._myEventShortWay;
            do
            {
                handler2 = myEventShortWay;
                EventHandler handler3 = (EventHandler)Delegate.Combine(handler2, value);
                myEventShortWay = Interlocked.CompareExchange<EventHandler>(ref this._myEventShortWay, handler3, handler2);
            }
            while (myEventShortWay != handler2);
        }
        remove
        {
            EventHandler handler2;
            EventHandler myEventShortWay = this._myEventShortWay;
            do
            {
                handler2 = myEventShortWay;
                EventHandler handler3 = (EventHandler)Delegate.Remove(handler2, value);
                myEventShortWay = Interlocked.CompareExchange<EventHandler>(ref this._myEventShortWay, handler3, handler2);
            }
            while (myEventShortWay != handler2);
        }
    }

    private EventHandler _myEvent;

    public event EventHandler MyEventLongWay
    {
        add
        {
            this._myEvent = (EventHandler) Delegate.Combine(this._myEvent, value);
        }
        remove
        {
            this._myEvent = (EventHandler)Delegate.Remove(this._myEvent, value);
        }

    }


text:
Q: Write elements of a map to a CSV correctly in a simplified way in Java 8 I have a countries Map with the following design:
England=24
Spain=21
Italy=10
etc

Then, I have a different citiesMap with the following design:
London=10
Manchester=5
Madrid=7
Barcelona=4
Roma=3
etc

Currently, I am printing these results on screen:
    System.out.println("\nCountries:");
    Map<String, Long> countryMap = countTotalResults(orderDataList, OrderData::getCountry);
    writeResultInCsv(countryMap);
    countryMap.entrySet().stream().forEach(System.out::println);

System.out.println("\nCities:\n");
    Map<String, Long> citiesMap = countTotalResults(orderDataList, OrderData::getCity);
    writeResultInCsv(citiesMap);
    citiesMap.entrySet().stream().forEach(System.out::println);

I want to write each line of my 2 maps in the same CSV file. I have the following code:
public void writeResultInCsv(Map<String, Long> resultMap) throws Exception {
    File csvOutputFile = new File(RUTA_FICHERO_RESULTADO);
    try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
        resultMap.entrySet().stream()
                .map(this::convertToCSV)
                .forEach(pw::println);
    }
}

public String convertToCSV(String[] data) {
    return Stream.of(data)
            .map(this::escapeSpecialCharacters)
            .collect(Collectors.joining("="));
}

public String escapeSpecialCharacters(String data) {
    String escapedData = data.replaceAll("\\R", " ");
    if (data.contains(",") || data.contains("\"") || data.contains("'")) {
        data = data.replace("\"", "\"\"");
        escapedData = "\"" + data + "\"";
    }
    return escapedData;
}

But I get compilation error in writeResultInCsv method, in the following line:
.map(this::convertToCSV)
This is the compilation error I get:
reason: Incompatible types: Entry is not convertible to String[]
How can I indicate the following result in a CSV file in Java 8 in a simplified way?
This is the result and design that I want my CSV file to have:
Countries:
England=24
Spain=21
Italy=10
etc

Cities:
London=10
Manchester=5
Madrid=7
Barcelona=4
Roma=3
etc

A: Your resultMap.entrySet() is a Set<Map.Entry<String, Long>>. You then turn that into a Stream<Map.Entry<String, Long>>, and then run .map on this. Thus, the mapper you provide there needs to map objects of type Map.Entry<String, Long> to whatever you like. but you pass the convertToCSV method to it, which maps string arrays.
Your code tries to join on comma (Collectors.joining(",")), but your desired output contains zero commas.
It feels like one of two things is going on:

*

*you copy/pasted this code from someplace or it was provided to you and you have no idea what any of it does. I would advise tearing this code into pieces: Take each individual piece, experiment with it until you understand it, then put it back together again and now you know what you're looking at. At that point you would know that having Collectors.joining(",") in this makes no sense whatsoever, and that you're trying to map an entry of String, Long using a mapping function that maps string arrays - which obviously doesn't work.

*You would know all this stuff but you haven't bothered to actually look at your code. That seems a bit surprising, so I don't think this is it. But if it is - the code you have is so unrelated to the job you want to do, that you might as well remove your code entirely and turn this question into: "I have this. I want this. How do I do it?"
NB: A text file listing key=value pairs is not usually called a CSV file.


text:
Q: How to assign the User Id to Foreign Key type Users struct {
    Id       int `orm:"pk;auto"`
    Username string
    Password string
    Salt     string
    Email    string `orm:"unique"`
}

type Post struct {
    Id          int    `orm:"pk;auto"`
    Users       *Users `orm:"rel(fk)"`
    Author      string
    Title       string    `form:"title,text,Title:" valid:"MinSize(5); MaxSize(20)"`
    Description string    `form:textarea`
    Date        time.Time `orm:"auto_now_add;type(datetime)"`
}

I am trying to assign value to Users as it is the foreign key. I want to assign the user id who is logged in. How to assign the user id from Users struct to user id in Post struct which is foreign key.
o := orm.NewOrm()
o.Using("default")
post := models.Post{}
users := models.Users{}

if this.Ctx.Input.Method() == "POST" {
    inputs := this.Input()

    post.Author = sess.(string)
    post.Title = inputs.Get("title")
    post.Description = inputs.Get("description")
    post.Date = time.Now()
}

A: First, answering your question:
post.Date = time.Now()
// This is your last line
// Up until now all good
post.Users = &users // Actually the naming is bad, should be post.User = user
o.Insert(users) // First create user
o.Insert(post) // Then insert post

This is very similar to the basic example BeeGo ORM provides: https://beego.me/docs/mvc/model/orm.md
In real world, you'll notice that most of the time you have a user, and you only want to create it once. So you'll switch first Insert to ReadOrCreate: https://beego.me/docs/mvc/model/object.md#readorcreate
Having said that, from my experience, using MVC and ORM frameworks with Go is a bad idea.


text:
Q: strtok disappearing when returning -1 So I'm writing code to put strings into arrays and it's working perfectly, however I want it to terminate the reading of the strings when I hit a ## in the file. I'm running a loop and parsing the strings line by line. Within my string parser I put a loop to check for the ##. It's at the very end of my parser function and it goes:
for (i = 0; i < strlen(line)); i++)
{
    if ((buffer[i] == '#') && (buffer[i+1] == '#'))
    {
        return -1;
    }
}

The problem is that when it hits the line with the ## at the end it doesn't parse the string into my array. It seems like it's just ignoring the code before this loop.
As additional information I'm using strtok to put the tokens in positions in my char* array before this for loop.
EDIT: Here's my parseString function:
int parseString(char* line, char*** inString)
{
    char* buffer;
    int Token, i;

    buffer = (char*) malloc(strlen(line) * sizeof(char));
    strcpy(buffer,line);
    (*inString) = (char**) malloc(MAX_TOKS * sizeof(char**));

    Token = 0;
    (*inString)[Token++] = strtok(buffer, DELIMITERS);

    while ((((*inString)[token] = strtok(NULL, DELIMITERS)) != NULL) && (Token < MAX_TOKS))
        Token++;

    for(i=0; i<strlen(line); i++)
    {
        if ((buffer[i] == '#') && (buffer[i+1] == '#'))
        {
            return -1;
        }
    }
    return Token;
}

A: First of all, you are reading out of bounds on an array, because array[-1] is not good. Secondly, use a variable to hold the string length, as the way you do it causes the for loop to re-evaluate strlen(line) for each iteration.
Now, for your problem, it seems like you're putting it before the code that adds it to an array. If you could give us a bit more code, that would help.

A: Insufficient buffer allocation
// buffer = (char*) malloc(strlen(line) * sizeof(char));
buffer = malloc(strlen(line) + 1);  // +1 for the \0
strcpy(buffer,line);

Memory Leak
The allocated 'buffer' may be lost.  The *inString array_ have a pointer to the beginning of 'buffer', allowing it to be freed in the calling routine, but that is iffy.  Suggest using first element of *inString to save that buffer explicitly.
Algorithm hole
(*inString)[token-1] == NULL should be asserted before for().
O(n*n) via strlen()
Suggestion:
// for(i=0; i<strlen(line); i++)
int length = strlen(line); // `length` should be used in `malloc()` too.
for(i=0; i<length; i++)

OP's early edit approach was almost OK
Just needed to start indexing at 1, rather than 0.  No need to test every index i of line, but (length-1).  So (i = 1; i<length; i++) or (i = 0; i<length-1; i++).
// for (i = 0; i < strlen(line)); i++) {
int length = strlen(line);
for (i = 1; i<length; i++) { // start at 1
  if ((buffer[i-1] == '#') && (buffer[i] == '#')) {
    return -1;
  }
}

For better assistance, recommend OP provide sample line, line with the ## at the end, MAX_TOKS and DELIMITERS.


text:
Q: VSCode App Service Deploy Failed 2gb zip file limit Deploying Flask app using VSCode App Service fails.  The zip file is 2.2 gb - too large.
What procedure can I use to deploy large projects?
Can I upload the project in 2 or more steps ?
https://learn.microsoft.com/en-us/azure/app-service/deploy-zip
Created new web app "mysite": https://mysite.azurewebsites.net
mysite: Starting deployment...
mysite: Creating zip package...
mysite: Zip package size: 2.22 GB
mysite: Fetching changes.
mysite: Cleaning up temp folders from previous zip deployments and extracting pushed zip file /tmp/zipdeploy/b02a0e95-4e86-4bcc-a71f-9997355a55fb.zip (54.56 MB) to /tmp/zipdeploy/extracted
mysite: Offset to Central Directory cannot be held in an Int64.
mysite: Deployment failed.

A: As I mentioned in your post here "The zip file limit of 2048MB (2GB) can't be increased in App service. This is by the design and is not a limitation of Kudu but of IIS since the request goes through the Frontends. When the integrated pipeline is used, we go through webengine code (webengine4!MgdGetRequestBasics) which doesn't support more than 2 GB content-length."


text:
Q: Disqus Dynamic Variables in RoR Working through a RoR blog website tutorial, but I got stuck at adding Disqus. It doesn't like how I'm writing my dynamic variables. Still pretty new to all of this.

Please enable JavaScript to view the comments powered by Disqus.

Update
I noticed that my url is not displaying properly. Inspecting the disqus javascript revealed:
var disqus_config = function () {
this.page.url = '/posts/5'; //This should be a complete url
this.page.identifier = '5';
this.page.title = 'Article 5';
};

A: this.page.url = '<%= url_for(only_path: false) %>';


text:
Q: How to update fields in cassandra frozen UDT column? I am aware of fact that fields in frozen UDT column is not possible and entire records needs to update , in that case does it imply update on frozen UDT column is not possible and if there is scenario of field update of frozen UDT column , in that case one has to insert new record and delete older one ?

A: You are correct that you cannot update individual fields of a frozen UDT column but you can update the whole column value. You do not need to delete the previous record. It's fine to update the fields directly. Let me illustrate with an example I created on Astra.
Here is a user-defined type that stores a user's address:
CREATE TYPE address (
  number int,
  street text,
  city text,
  zip int
)

and here is the definition for the table of users:
CREATE TABLE users (
  name text PRIMARY KEY,
  address frozen<address>
)

In this table, there is one user with their address stored as:
cqlsh> SELECT * FROM users ;

 name  | address
-------+----------------------------------------------------------------
 alice | {number: 100, street: 'Main Rd', city: 'Melbourne', zip: 3000}

Let's say that the street number is incorrect. If we try to update just the street number field with:
cqlsh> UPDATE users SET address = {number: 456} WHERE name = 'alice';

We'll end up with an address that only has the street number and nothing else:
cqlsh> SELECT * FROM users ;

 name  | address
-------+----------------------------------------------------
 alice | {number: 456, street: null, city: null, zip: null}

This is because the whole value (not just the street number field) got overwritten by the update. The correct way to update the street number is to explicitly set a value for all the fields of the address with:
cqlsh> UPDATE users SET address = {number: 456, street: 'Main Rd', city: 'Melbourne', zip: 3000} WHERE name = 'alice';

so we end up with:
cqlsh> SELECT * FROM users ;

 name  | address
-------+----------------------------------------------------------------
 alice | {number: 456, street: 'Main Rd', city: 'Melbourne', zip: 3000}

Cheers!

A: You can update column that is frozen UDT, but you'll need to insert all values for fields inside that UDT.  So you can just do normal update of that column only
UPDATE table SET udt_col = new_value WHERE pk = ....

without need to delete something first, etc.
Basically, frozen value is just blob obtained by serializing UDT or collection, and stored as one cell inside row and having the single timestamp.  That's different from the non-frozen value, where different pieces of UDT/collection could be stored in different places, and having different timestamps.


text:
Q: can't access to properties and events of my custom control inherited from ToolStripControlHost in designer I'm looking to make a custom ContextMenu item which is composed of simply a FlowLayoutPanel containing a Label and a ComboBox. I want to be able to access the properties and events of my custom control at design-time in the designer of visual studio 2013. I want to be able to use my custom control in a MenuStrip, in a ToolStripMenuItem or in a ContextMenu. My actual problem is that everything is working fine if I insert the control directly in a MenuStrip but  I can't access the property window of my control when it is in a ToolStripMenuItem or in a ContextMenu. The property window is all white and the control is glitchy in the designer.
So Here is my code(I didn't implement any properties nor any events yet but I should have access to inherited properties and events in property window anyway. In fact, I do when I insert the control in a MenuStrip but not in the other two.)
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace CustomControlLib
{
    [ToolStripItemDesignerAvailabilityAttribute(ToolStripItemDesignerAvailability.MenuStrip        | ToolStripItemDesignerAvailability.ToolStrip |    ToolStripItemDesignerAvailability.ContextMenuStrip)]
    public class LblCboxStripControl : ToolStripControlHost
    {
        private Label controlName;
        private ComboBox controlComboBox;
        private FlowLayoutPanel controlPanel;

        public LblCboxStripControl()
            : base(CreateControlInstance())
        {
            controlPanel = (FlowLayoutPanel)base.Control;
            controlPanel.AutoSize = true;
            controlPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            controlPanel.BackColor = Color.Transparent;

            controlName = new Label();
            controlName.BackColor = Color.Transparent;
            controlName.AutoSize = true;
            controlName.Dock = DockStyle.None;
            controlName.Text = "Control name";

            controlComboBox = new ComboBox();

            controlPanel.Controls.Add(controlName);
            controlPanel.Controls.Add(controlComboBox);
        }

        public static FlowLayoutPanel CreateControlInstance()
        {
            FlowLayoutPanel flp = new FlowLayoutPanel();
            return flp;
        }
    }
}

I've seen a similar post here:
 .NET Custom Control (ToolStripControlHost) Wreaks Havoc on the Designer
but the only solution there is to create a class which inherits form ToolStripControlHost and provides a constructor without arguments doesn't solve my problem at all. I also tried creating new empty projects, restarting VS and putting the class inside the form project or in an extern library doesn't solve it either. I'd also add that there is nothing unusual in the Form.designer file.


text:
Q: Interpretation of residual variance and corrleation in factor analysis
Hi!
The above image is from "Latent Variable Models" by Loehlin and Beaujean (p.146).
It's a four group-model, with male idential twins, female idential twins, male fraternal twins, and female fraternal twins.
The latent variable Num1 refers to the numerical ability of "twin 1", and Num2 belongs to "twin 2."
The same goes for the manifest variables.
The four group only differ in their covariance between Num1 and Num2 (for identital twins it's 1, and fraternal twins it's 0.5).
The both latent variables are standardized.
Also, corresponding residual covariances were considered to be equal (for example, the cov between Ad and Mu is same for both of the twins).
Given the model above, the authors created the following table.

First, the "Other shared variance - cross-twin within-trait residual correlation" for the Addition in the third column is defined as follow.
$r$ is the residual variance of both Ad1 and Ad2.
$s$ is the residual covariance between Ad1 and Ad2.
$vAD$ is the variance of both Ad1 and Ad2, defined as $a^2 + r$.
And its "Other shared variance - cross-twin within-trait residual correlation" is
$$\frac{s}{\sqrt{vAD}*\sqrt{vAD}} = 0.147$$
What is it? I'm lost here.
But I know that it is not the residual correlation between Ad1 and Ad2.
Because the residual correlation between Ad1 and Ad2 should be defined as follow.
$$\frac{s}{\sqrt{r}*\sqrt{r}}$$
Why divide the residual covariance between Ad1 and Ad2 by standard deviation of Ad1 and Ad2, not their residual sd?
Also, For the residual correlation part for Ad-Mu, the followings were calculated.
"other shared correlation---cross-person cross-trait residual covariance" (when $e1$ is the residual covariance b/t Ad1-Mu2 and Ad2-Mu1)
$$AD.MU.cpct = \frac{e1}{\sqrt{vAD}*\sqrt{vMU}} = 0.059$$
"environmental contributions to correlations--within-person cross-trait residual correlation" (when $d$ is the residual covariance b/t Ad1-Mu1 and Ad2-Mu2)
$$AD.MU.wpct = \frac{d}{\sqrt{vAD}*\sqrt{vMU}} = 0.144$$
And the "residual correlations" are calculated as follow.
$$rAD.MU = AD.MU.wpct - AD.MU.cpct = 0.087$$
I have no idea what they are too.
Also Why the last three components together equal the phenotypic correlation (0.55 + 0.06 + 0.09 = 0.7)?
This model has been killing me for days.
I would really appreciate any help!


text:
Q: How to resize the window without hiding controls How can I resize a windows form without hiding controls that are positioned outside the form's new size?

A: Check out the .Anchor property of the buttons you want to avoid hiding. The anchor property can be set such that the placment of the buttons is alwas relative to one or more edges of the form. This way, when the form is resized, the buttons location is "anchored" to (for example) the Bottom and right edges of the form.
This will not prevent the user from making the form smaller than the minimum space required by the buttons, but I believe you can also set a minimum size property for the form.

A: set the anchor property of your buttons or items in form.
If still you have issues, put the buttons or controls to pannel or groupbox and dock the buttons to parent container. Then apply anchor property for controller.

A: I Have found the similar issue and what i tried is to put all the buttons in a TableLayoutPanel and set the Anchor property of the buttons that way i am able to resize the button corresponding to the size of the form.
If any body has a better idea kindly suggest........


text:
Q: Getting app:drawableEndCompat instead of android:drawableEnd warning for Lollipop API 21 devices AS 4.0.1
Use app:drawableEndCompat instead of android:drawableEnd warning on API 21 and above
 <TextView
        android:id="@+id/tvCheckStock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableEnd="@drawable/ic_pin_drop
        android:gravity="center_vertical"/>

The ic_pin_drop is a SVG (Vector Drawable) that was created using Android Studio File | New | Vector Asset | Configure Vector Assert
In my Build.gradle file I have the following configuration:
minSdkVersion 21
targetSdkVersion 29
vectorDrawables.useSupportLibrary true

As the min is API 21 which is Lollipop I was thinking that vector drawables are supported out of the box and we can use the DrawableEnd, DrawableStart etc without the compat versions?
I was thinking that the compat versions were for pre 21 API level. Kitkat and below. And as I am not targeting that minimum I am not sure why I am getting that warning.
This would result in a cash on those devices less than 21 if the compat version is not used.
Many thanks for any suggestions.

A: Vector drawables are supported since API 21 but new features are added over time, even to vector drawables. It may be a good idea to use AppCompat and not worry about that.
Tinting compound drawables on TextViews was added in API 23. The suggestion is pushing you towards the compat variant, where the feature is backported.

*

*app:drawable*Compat

*app:drawableTint and app:drawableTintMode
If you don't use compound drawable tinting you may be fine with the platform version of the attributes.

*

*android:drawable*

*android:drawableTint and android:drawableTintMode (added in API 23)

A: The primary motive behind this warning is to make your VectorDrawables look same on all devices by making them backward compatible.
By using "Compat", you would be ensuring that using your vector asset would not crash your app for devices below API 21(Lollipop). In short, using drawableEndCompat would allow anyone to use the same features of drawableEnd on older APIs(<21).
Now you would be thinking that what should I choose:
If you are using drawableEndCompat, it would work as you expect in every device. Devices with API more than 21 would internally unwrap them as normal drawableEnd as far as I know.
If you choose to use drawableEnd, it will be working for API 21 and above only.
If you think that I don't need any Compat Support : You may increase your application's minimum SDK from current value to atleast 21. Then you can use keyword drawableEnd peacefully without any warning.
Also, you may opt to create different layout file for different APIs under which in layout file for below API 21, use drawableEndCompat and for API 21 and above use drawableEnd. In my opinion, you can also check whether you can use both attributes at same place. I feel like that they can work together as well.
If you are not supporting devices below API 21, there is no problem: You should have no issues/warning. Also, one more thing I need to tell you - Android Studio sometimes throw warnings or bugs; even if you are right. In that case, if you feel that you were correct, you should try invalidate/restart option after clicking File option in Menu Bar. I would also suggest to try restarting your system to everyone who are using system for long durations or always keeping it on sleep mode.
So, for a TextView, you should use app:drawableEndCompat (or start, top, bottom) instead of app:drawableEnd


text:
Q: I'm trying to compare a string but when I have the user input a string it doesn't let them     System.out.println( "Great! Now select the type of measurement this is so we can convert!");
    System.out.println( "G = Gallons" );
    System.out.println( "I = Inches" );
    System.out.println( "P = Pound" );
    System.out.println( "M = Mile" );
    String userType = input.nextLine();

I enter a number, and then when I should be entering the measurement type (as shown above) it automatically skips to the if statement that is after this. Nothing I've tried has worked. Can anyone help?

A: You must
input.nextLine();

after your read in number part when you go from reading in a number from scanner to a string
I hope this works and helps you in the future.

A: Use BufferedReader Class
Try the following code:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println( "Great! Now select the type of measurement this is so we can convert!");
  System.out.println( "G = Gallons" );
  System.out.println( "I = Inches" );
  System.out.println( "P = Pound" );
  System.out.println( "M = Mile" );
  String userType = br.readLine();

Import required is:
import java.io.*;

You can campare two string by using String functions
Example:
if(String1.equals(String2)){
//Both the strings are equal
}
else{
//Both string are not equal
}

You can even use "campareTo" function.


text:
Q: delete polictDef in ApiMan via GUI I have added Policy Definition wrongly instead adding it as custom Plugin.
  "id": "test-policy",
  "policyImpl": "plugin:${project.groupId}:${project.artifactId}:${project.version}:${project.packaging}/io.apiman.plugins.test.TestPolicy",
  "name": "Test Policy Plugin",
  "description": "Test policy plugin",
  "icon": "lock",
  "templates": [],
  "formType": "JsonSchema",
  "form": "schemas/test-policyDef.schema",
  "deleted": false
}

Now if I try to add the plugin, it complains that the plugin with name already exist. There is only option to update policy and if i try to set "deleted": true. It does not update at all as I can see the configuration remains unchanged.
How can I delete this policy definition and install it as plugin. I think I can change to new "id" and add it as plugin. Is it possible ? But is there no way to delete the policy directly ?
EDIT : I can add it as plugin with new "id" as it the primary key in ES registry. But still cannot find a way to delete it. Where are the policydefs stored in the system? Can we delete using ES query?


text:
Q: TimerTrigger Schedules and code execution time What happens if a function gets invoked by a TimerTigger every 5 minutes and for some reasons the code takes more than 5 minutes to complete?

*

*Does this result in my function running twice at the same time?

*Or does the interval start when the triggered code execution is completed?

I could not find an answer myself in the docs.
I have to ensure that my function is running always as singleton.
Thanks,
Alex

A: If your function execution takes longer than the timer interval, another execution won't be triggered until after the current invocation completes. The next execution is scheduled after the execution completes. You can see this in the code here. You can prove this to yourself by trying a simple local example - create a function that runs every 5 seconds, and put a sleep in there for a minute. You won't see another function start until the first finishes.
As far as running singleton, the above shows that only a single function invocation runs at a given time on the same instance (VM). The SDK further ensures that no other functions are running across scaled out instances. You can read more about that here. To see this in action, you can simulate by starting two instances of your console app locally - one will run the schedule the other will not. However, if you kill the one running the schedule, the other one will pick it up after a short time (within a minute).


text:
Q: Cannot set default gateway to specific LAN Recently, I am trying to add a default gateway to my ubuntu machine to be able to send/receive packets from an another LAN through the router. However, everything I do the result is the following:
    vag@ubuntu:~$ route -n
    Kernel IP routing table
    Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
    192.168.141.0   0.0.0.0         255.255.255.0   U     1      0        0 eth0
    x.y.z.w         0.0.0.0         255.255.0.0     U     1000   0        0 eth0
    0.0.0.0         192.168.141.2   0.0.0.0         UG    0      0        0 eth0

What I am trying to do (at least I think) is to create a line with the given information
    192.168.20.0    192.168.1.254   255.255.255.0  xx     xxx xxxx        xxxx

I don't want to have connection on the internet and this is what I think 0.0.0.0 Destination and gateway represent in the above table. I want just to connect to the LAN.
Any ideas?

A: The command you have to run is:
sudo route add -net 192.168.20.0 netmask 255.255.255.0 gw 192.168.1.254


text:
Q: Sprockets syntax error with capistrano deployment I am using Rails 5.2.2 and ruby 2.3.1p112. I am deploying my rails application to the server using capistrano. I have these gems.
gem "capistrano", "~> 3.10", require: false
gem "capistrano-rails", "~> 1.4", require: false
gem 'capistrano-rvm'
gem 'capistrano3-puma', github: "seuros/capistrano-puma"
gem 'capistrano-bundler', require: false

During deployment, when capistrano executes:
deploy:assets:backup_manifest

I get the following error:
Capistrano Log:
02:04 deploy:assets:backup_manifest
      01 mkdir -p /home/developer/clapp/releases/20181207075748/assets_manifest_backup
      01 /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
    ✔ 01 developer@142.93.105.197 1.537s
      02 cp /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory  /home/developer/clapp/releases/20181207075748…
      02 /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
      02 bash: -c: line 0: syntax error near unexpected token `('
      02 bash: -c: line 0: `cd /home/developer/clapp/releases/20181207075748 && /usr/bin/env cp /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change loca…
(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as developer@142.93.105.197: cp exit status: 1
cp stdout: /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `cd /home/developer/clapp/releases/20181207075748 && /usr/bin/env cp /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory  /home/developer/clapp/releases/20181207075748/public/assets/.sprockets-manifest-4b7cb236de58906a848ecfd6888fa29f.json /home/developer/clapp/releases/20181207075748/assets_manifest_backup'
cp stderr: Nothing written

Caused by:
SSHKit::Command::Failed: cp exit status: 1
cp stdout: /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `cd /home/developer/clapp/releases/20181207075748 && /usr/bin/env cp /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory  /home/developer/clapp/releases/20181207075748/public/assets/.sprockets-manifest-4b7cb236de58906a848ecfd6888fa29f.json /home/developer/clapp/releases/20181207075748/assets_manifest_backup'
cp stderr: Nothing written

Tasks: TOP => deploy:assets:backup_manifest
(See full trace by running task with --trace)
The deploy has failed with an error: Exception while executing as developer@142.93.105.197: cp exit status: 1
cp stdout: /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `cd /home/developer/clapp/releases/20181207075748 && /usr/bin/env cp /etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory  /home/developer/clapp/releases/20181207075748/public/assets/.sprockets-manifest-4b7cb236de58906a848ecfd6888fa29f.json /home/developer/clapp/releases/20181207075748/assets_manifest_backup'
cp stderr: Nothing written

** DEPLOY FAILED
** Refer to log/capistrano.log for details. Here are the last 20 lines:

Can someone suggest what change I need to make for a successful deployment?
UPDATE:
deploy.rb
lock "~> 3.11.0"

set :application, "myapp"
set :repo_url, "git@bitbucket.org:selise07/myapp.git"
set :branch, 'feature/push'
set :deploy_to, '/home/developer/myapp'
set :pty, true
set :default_shell, '/bin/bash -l'
set :linked_files, %w[config/secrets.yml config/database.yml .env]

set :linked_dirs, %w[bin log tmp/pids tmp/cache tmp/sockets vendor/bundle
public/default public/files]
set :keep_releases, 5

set :rvm_type, :user                     # Defaults to: :auto
set :rvm_ruby_version, 'ruby-2.3.1'      # Defaults to: 'default'
append :rbenv_map_bins, 'puma', 'pumactl'

set :puma_rackup, -> { File.join(current_path, 'config.ru') }
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"    #accept array
for multi-bind
set :puma_conf, "#{shared_path}/puma.rb"
set :puma_access_log, "#{shared_path}/log/puma_error.log"
set :puma_error_log, "#{shared_path}/log/puma_access.log"
set :puma_role, :app
set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))
set :puma_threads, [0, 8]
set :puma_workers, 0
set :puma_worker_timeout, nil
set :puma_init_active_record, true
set :puma_preload_app, false

namespace :deploy do

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      # Here we can do anything such as:
      # within release_path do
      #   execute :rake, 'cache:clear'
      # end
    end
  end
end


text:
Q: cassandra data model for web logging Been playing around with Cassandra and I am trying to evaluate what would be the best data model for storing things like views or hits for unique page id's? Would it best to have a single column family per pageid, or 1 Super-column (logs) with columns pageid? Each page has a unique id, then would like to store date and some other metrics on the view.
I am just not sure which solution handles better scalability, lots of column family OR 1 giant super-column?
page-92838 { date:sept 2, browser:IE }
page-22939 { date:sept 2, browser:IE5 }
OR
logs {
   page-92838 {
      date:sept 2,
      browser:IE
   }
   page-22939 {
      date:sept 2,
      browser:IE5
   }
}
And secondly, how to handle lots of different date: entries for page-92838?

A: You don't need a column-family per pageid.
One solution is to have a row for each page, keyed on the pageid.
You could then have a column for each page-view or hit, keyed and sorted on time-UUID (assuming having the views in time-sorted order would be useful) or other unique, always-increasing counter. Note that all Cassandra columns are time-stamped anyway, so you would have a precise timestamp 'for free' regardless of what other time- or date- stamps you use. Using a precise time-UUID as the key also solves the problem of storing many hits on the same date.
The value of each column could then be a textual value or JSON document containing any other metadata you want to store (such as browser).
page-12345 -> {timeuuid1:metadata1}{timeuuid2:metadata2}{timeuuid3:metadata3}...
page-12346 -> ...

A: With cassandra, it is best to start with what queries you need to do, and model your schema to support those queries.
Assuming you want to query hits on a page, and hits by browser, you can have a counter column for each page like,
stats { #cf
    page-id { #key
        hits : # counter column for hits
        browser-ie : #counts of views with ie
        browser-firefox : ....
    }
}

If you need to do time based queries, look at how twitters rainbird denormalizes as it writes to cassandra.


text:
Q: Manipulation with GIS content on the web using the WebGL I have task to create program for manipulation with 3d content on the web. When I said 3d content i mean
on 3d map (witch i have and it is something like *.sdm) which i should load into browser and work some basic operation with it (rotate screen, change camera etc...).
Because i am totaly n00b i want to ask a couple of questions:
 1. How to load maps into browser. Just for notice that my map have sdm extension. Is this possible?
 2. What i should use for represent 3d content. I am thinking of GLGE framework for webGL, if it is possible of course
What should be the most painless and the most effective way to do this? Maybe i was totally wrong when choose webGL?

A: Programs that use WebGL aren't mature enough to do what you want. Within the next few years, when GIS applications start popping up it may be possible, but not now.
Also, keep in mind that WebGL is what gives you access to a low-level graphics library. It does not directly have anything to do with GIS data.
You may want to take a look at OpenLayers (2d, javascript based) or WorldWind-Java (3d, jogl/java based). Both of these programs can display map information in a browser.
http://openlayers.org/
http://worldwind.arc.nasa.gov/java/


text:
Q: ValueError: The `batch_size` argument must not be specified for the given input type I have created dummy data for an autoencoder model using tf.data.dataset. I am using tensorflow-1.15.x, keras 2.3.1 and numpy 1.19.5 for running on my GPU.
N = 5000
H = 128
W = 128
C = 2

train_data = np.random.randn(N,H,W,C)

train_data = tf.convert_to_tensor(train_data)

test_data = np.random.randn(500,H,W,C)

test_data = tf.convert_to_tensor(test_data)

batch_size = 1

train_dataset = tf.data.Dataset.from_tensor_slices((train_data, train_data))
train_dataset = train_dataset.batch(batch_size, drop_remainder=True)

test_dataset = tf.data.Dataset.from_tensor_slices((test_data, test_data))
test_dataset = test_dataset.batch(batch_size, drop_remainder=True)

But while fitting this data on the model, I get the following error -
epochs = 5

rms = RMSprop(learning_rate=0.00002,
              rho=0.9,
              epsilon=1e-07)

model.compile(loss='mean_squared_error', optimizer=rms, metrics=['mean_squared_error'])

callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3)

logs = "logs/"

tboard_callback = tf.keras.callbacks.TensorBoard(log_dir = logs,
                                                 histogram_freq = 1)

history = model.fit(train_dataset, epochs=epochs, batch_size=batch_size, callbacks=[callback, tboard_callback],
                    validation_data=test_dataset)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-25-47134a802115> in <module>()
     15
     16 history = model.fit(train_dataset, epochs=epochs, batch_size=batch_size, callbacks=[callback, tboard_callback],
---> 17                     validation_data=test_dataset)

2 frames
/tensorflow-1.15.2/python3.7/tensorflow_core/python/keras/engine/training.py in _validate_or_infer_batch_size(self, batch_size, steps, x)
   1813             'The `batch_size` argument must not be specified for the given '
   1814             'input type. Received input: {}, batch_size: {}'.format(
-> 1815                 x, batch_size))
   1816       return
   1817

ValueError: The `batch_size` argument must not be specified for the given input type. Received input: <DatasetV1Adapter shapes: ((1, 128, 128, 2), (1, 128, 128, 2)), types: (tf.float64, tf.float64)>, batch_size: 1

Answers to other questions on this error suggest batching both train and validation datasets, but I have batched both already. What could be causing this error? Thanks.

A: Remove the batch_size in model.fit()
history = model.fit(train_dataset, epochs=epochs, callbacks=[callback, tboard_callback],validation_data=test_dataset)


text:
Q: Change printer properties from command line Please help, how can I change printer properties - font selection - code page from command line. Thanks

A: As far as I know it is not possible to change printer settings from the command line.
However, what is possible is to change the default printer from the command line. You can set up multiple copies of the same printer driver, with different settings. Then you can select the setting you want with the command
RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /y /n "printer"

In this command, change "printer" to the name of the printer you want (keep the quotes).
Rob Van der Woude has a great webpage with more information on command line printer control


text:
Q: How to use linked-in j library to get current user details I am using linked-in j library.
I am able to connect with linked-in but when i go for details for the profile of current user then i get whole Person object but this object only contain the values of first name, last name and headline.And other values are null.
But when i go to my linked-in public profile their i can see the skills, college etc.
My application have full access.

A: I think you never set ProfileField's in enum
Please try like this,
  Set<ProfileField> propertiesToFetch = EnumSet.of(ProfileField.ID,
            ProfileField.FIRST_NAME, ProfileField.LAST_NAME,
            ProfileField.HEADLINE, ProfileField.PICTURE_URL,
            ProfileField.DATE_OF_BIRTH, ProfileField.PHONE_NUMBERS,
            ProfileField.MAIN_ADDRESS, ProfileField.INDUSTRY,
            ProfileField.EDUCATIONS, ProfileField.LANGUAGES_LANGUAGE_NAME,
            ProfileField.SKILLS_SKILL_NAME,
            ProfileField.CERTIFICATIONS_NAME, ProfileField.POSITIONS_TITLE,
            ProfileField.POSITIONS_COMPANY_NAME,
            ProfileField.POSITIONS_COMPANY);
    Person profile = client.getProfileForCurrentUser(propertiesToFetch);


text:
Q: Converting M4A file into Raw data I am trying to read the raw values of a sound file. I am pretty new to IOS development. I am ultimately trying to take a fast fourier transform of the audio file. The output of the data looks like a sound wave, but when I take the fft of a beep sound provided hereenter link description here I do not get an obvious frequency from the fft, which leads me to believe I am not getting the real raw data. I have constructed the following code using a combination of several stack overflow posts. Am I reading the file incorrectly?
class AudioAnalyzer {
init(file_path: NSURL) {
    var assetOptions = [
        AVURLAssetPreferPreciseDurationAndTimingKey : 1,
        AVFormatIDKey : kAudioFormatLinearPCM
    ]
    println(file_path)
    var videoAsset=AVURLAsset(URL: file_path, options: assetOptions)
    var error:NSError?

    var videoAssetReader=AVAssetReader(asset: videoAsset, error: &error)

    if error != nil
    {
        println(error)
    }

    var tracksArray=videoAsset?.tracksWithMediaType(AVMediaTypeAudio)
    var videotrack = tracksArray?[0] as! AVAssetTrack
    var fps = videotrack.nominalFrameRate

    var videoTrackOutput=AVAssetReaderTrackOutput(track:videotrack as AVAssetTrack , outputSettings: nil)

    if videoAssetReader.canAddOutput(videoTrackOutput)
    {
        videoAssetReader.addOutput(videoTrackOutput)
        videoAssetReader.startReading()
    }

    if videoAssetReader.status == AVAssetReaderStatus.Reading {

        var sampleBuffer  = videoTrackOutput.copyNextSampleBuffer()
        var audioBuffer = CMSampleBufferGetDataBuffer(sampleBuffer)
        let samplesInBuffer = CMSampleBufferGetNumSamples(sampleBuffer)
        var currentZ = Double(samplesInBuffer)

        let buffer: CMBlockBufferRef = CMSampleBufferGetDataBuffer(sampleBuffer)

        var lengthAtOffset: size_t = 0
        var totalLength: size_t = 0
        var data: UnsafeMutablePointer<Int8> = nil
        var output:  Array<Float> = [];
        if( CMBlockBufferGetDataPointer( buffer, 0, &lengthAtOffset, &totalLength, &data ) != noErr ) {
            println("some sort of error happened")
        } else {
            for i in stride(from: 0, to: totalLength, by: 2) {
                var myint = Int16(data[i]) << 8 | Int16(data[i+1])
                var myFloat = Float(myint)
                output.append(myFloat);
            }
            println(output)
        }
    }
}
}

A: Your AVAssetReaderTrackOutput is giving you raw packet data. For LPCM output, pass in some outputSettings:
var settings = [NSObject : AnyObject]()
settings[AVFormatIDKey] = kAudioFormatLinearPCM
settings[AVLinearPCMBitDepthKey] = 16
settings[AVLinearPCMIsFloatKey] = false

var videoTrackOutput=AVAssetReaderTrackOutput(track:videotrack as AVAssetTrack , outputSettings: settings)

p.s. I'd feel much better if you renamed videoTrackOutput to audioTrackOutput.


text:
Q: When should I use the C++ fixed-width integer types and how do they impact performance? Normally I imagine most people would use int for everything and ocassionally they would use unsigned int when needed. Every now and then you might use a short int, maybe for network traffic or something.
But lately I have started to use std::size_t for indexing into STL containers (as I should), and then I started to find a use for std::uint8_t when creating a struct of four 8-bit colour values (RGBA), rather than a char, simply because it makes more sense to me (it's a number, not a character type, and not a 8-bit value, it's a 8-bit number from 0-255).
Then while doing some network programming I found that I wanted to make sure certain values being passed were 16-bits. And according to https://en.cppreference.com/w/cpp/language/types I can't assume a short int is 16 bits, only that it's at least 16 bits. So I found a use for std::int16_t.
This led me to gradually start using a fixed-width type everywhere. Which caused me to really think about what I needed, how much range I needed etc, whether it would fall into negative values or not.
So now, I have almost zero occurences of int in my code.
There's three reasons in my head for this:

*

*It makes my intent clear to someone else (i.e., I don't expect the number to be larger than this or it won't be negative)

*Code is more portable. If I want a 16bit integer type, it will be 16 bit on every compiler

*Saves memory. Though I imagine on a modern PC this is largely unimportant.

But I'm concerned that this is reducing performance as your usual consumer-grade CPU would operate on a native width type like a std::int32_t better.
So, when should I use the fixed-width types, and how do they impact performance?

A: You should use int when writing portable code (unless the integer size is constrained by external factors (e.g. protocol parsing), because this will allow machines to use the integer size that is preferred (optimal) on that machine.
There are a number of microprocessors in use whose register size is 16 bits for example;  the compiler headers they provide set sizeof(int) to 2.   Using e.g. int32_t on these machines for arithmetic would generate a lot of extra instructions.
However: For indexing,  using int is a bad idea: size_t is preferable, even if you're guaranteed not to overflow the index by using int.  This is because the value may need to be converted to the index register size (e.g. 64 bits for size_t vs 32 bits for int).  This can be costly in inner loops.


text:
Q: Pt to sp conversion issue I have a photoshop maket with 300ppi and 1080 x 1920 pixels size.
Our designer uses 10pt font size. I converted it to 23sp and used in my app.
I tested on a Nexus 5 emulator (1080 x 1920 and ~445 ppi) and text much more bigger than on maket.
Where is my mistake?

A: You may need to use a scaleable type of dp/sp. This repo is a very nice way to support mutliple screens without actually writing for each screen size. https://github.com/intuit/sdp/tree/master/sdp-android/src/main/res
All you have to do to use it if for example you are in an xml file, do this like so:
android:layout_width="@dimen/_100sdp"

This effectively makes the widget you set the width to be consistent on all device screens. I hope this helps.


text:
Q: Current Url is not correct for google calendar api When I sent an authsub request, google says the url is not correct.
I'm suspecting this is because I have a subdomain in my url.
The url that sends the request is http://admin.domain.com/test.php
In php, I put this line of code in the $next variable : '
http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

When I echo it, it shows the proper url but google tells me this :
The page you have requested cannot be displayed. Another site was
requesting access to your Google Account, but sent a malformed
request. Please contact the site that you were trying to use when you
received this message to inform them of the error. A detailed error
message follows:

The page you have requested cannot be displayed. Another site was requesting access to your Google Account, but sent a malformed request. Please contact the site that you were trying to use when you received this message to inform them of the error.
A detailed error message follows:  The site "http://domain.com" has not been registered.

Where is my problem ?
Thanks,
Etienne NOEL
EDIT1:
Here's my code: I followed all the instructions and the error still remains:
session_start();

require_once 'lib/Zend/Loader.php';
set_include_path($_SERVER['DOCUMENT_ROOT'].'/lib/');

    Zend_Loader::loadClass('Zend_Gdata');
    Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
    Zend_Loader::loadClass('Zend_Gdata_Calendar');
    Zend_Loader::loadClass('Zend_Http_Client');
    Zend_Loader::loadClass('Zend_Gdata_Query');
    Zend_Loader::loadClass('Zend_Gdata_AuthSub');

$my_calendar = 'http://www.google.com/calendar/feeds/default/private/full';

if (!isset($_SESSION['cal_token'])) {
    if (isset($_GET['token'])) {
        // You can convert the single-use token to a session token.
        $session_token =
            Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
        // Store the session token in our session.
        $_SESSION['cal_token'] = $session_token;
    } else {
        // Display link to generate single-use token
        $googleUri = Zend_Gdata_AuthSub::getAuthSubTokenUri(
            'http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'],
            $my_calendar, 0, 1);
        echo "Click here " .
             "to authorize this application.";
        exit();
    }
}

// Create an authenticated HTTP Client to talk to Google.
$client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['cal_token']);

// Create a Gdata object using the authenticated Http Client
$cal = new Zend_Gdata_Calendar($client);


text:
Q: Simple way to query which monitor is currently focused I'm wondering if there is a tool which can query which monitor is currently focused.
I'd like to have a script which changes the wallpaper on the monitor I am currently on (using xwallpaper). From what I understand, both the monitor number or the monitor name (i.e. HDMI1, eDP1) could be useful to achieve my goal.
Ultimately, the chosen wallpaper for the current monitor would be copied using a name which has this structure: wall-HDMI1.png or wall-eDP1.png
There is a partial solution where the accepted answer suggests guessing the current monitor using the mouse's position using xdotool. This seems finicky at best. Especially on a laptop that could be connected to multiple monitors using multiple different layouts.

A: If you want to know what the current primary monitor is, that's easy:
$ xrandr | grep primary
DP-2 connected primary 2560x1440+0+0 (normal left inverted right x axis y axis) 597mm x 336mm

or
$ xrandr | awk '/ primary / {print $1}'
DP-2

If you want to know which monitor the mouse pointer is currently on, that's a little more difficult.  First you have to find out where the mouse-pointer is (e.g. with xdotool) and then you have to compare the mouse's X,Y co-ordinates to the starting and ending X & Y co-ordinates of each screen (e.g. with xrandr).
The following perl script uses xrandr and xdotool to do exactly that.
#!/usr/bin/perl

use strict;

my %M;    # hash to hold keys from 'xdotool getmouselocation --shell'
my $pipe; # file handle for the pipes we're going to open

# get the current cursor location into $M{X} and $M{Y}
open($pipe, "-|", qw(xdotool getmouselocation --shell)) ||
    die "couldn't open pipe from xdotool: $!\n";

while(<$pipe>) {
  chomp;
  my($key, $val) = split /=/;
  $M{$key} = $val;
};
close($pipe);

# compare mouse location to monitor co-ordinates
open($pipe, "-|", "xrandr") ||
    die "couldn't open pipe from xrandr: $!\n";

while(<$pipe>) {
  my ($display, $width, $height, $x_offset, $y_offset);

  next unless m/ connected /;
  my @F = split;
  $display = $F[0];

  # co-ordinates are on fourth field (F[3]) on the primary display
  # or on third field (F[2]) on non-primary displays. Perl arrays
  # start from zero, not one (same as in bash).
  if ($F[2] eq "primary") {
    ($width, $height, $x_offset, $y_offset) = split /[x+]/, $F[3];
  } else {
    ($width, $height, $x_offset, $y_offset) = split /[x+]/, $F[2];
  };

  if ($M{X} >= $x_offset && $M{X} <= $width + $x_offset &&
      $M{Y} >= $y_offset && $M{Y} <= $height + $y_offset) {
    print "$display\n";
    last;
  };
};
close($pipe);

Save this as, e.g., ./get-focused-monitor.pl, make it executable with chmod +x get-focused-monitor.pl, and run it.  It will tell you which monitor the mouse pointer is currently hovering over.
$ ./get-focused-monitor.pl
DP-2

Run it as watch -n 0.1 ./get-focused-monitor.pl and thrill to the excitement of seeing the display name changing as you move the mouse from one display to another.  I did that for tens of seconds and the excitement never varied. It was almost too much.

BTW, I currently have two 1440p monitors connected. A 27" monitor in landscape mode ("DP-2", the primary), and a 24" monitor pivoted to portrait mode("DP-0").   The xrandr output that this script parses on my system looks like this:
$ xrandr | grep \\bconnected
DP-0 connected 1440x2560+2560+0 left (normal left inverted right x axis y axis) 527mm x 296mm
DP-2 connected primary 2560x1440+0+0 (normal left inverted right x axis y axis) 597mm x 336mm

split /[x+]/ in the script splits the third or fourth field into an array of four integers using x or + as the delimiter: width, height, x offset, and y offset.    See perldoc -f split for info on how perl's split() function works.

PS: Why perl?  Because perl's easier - parsing text in while-read loops in shell sucks, and doing calculations in shell sucks at least as much, I don't want to deal with the usual shell white-space and quoting and word-splitting issues, or the extra-ordinarily ugly shell syntax for arrays.  And shell isn't the only language that can pipe data to or from external programs. Most languages commonly used on unix & linux can do that.
Doing it in shell is not particularly difficult, just clumsy and awkward.  Feel free to re-implement the algorithm in bash if you want, it's the method that's important, not the language.
BTW, the easiest way to do it in shell would be to run something like (xdotool getmouselocation --shell; xrandr) | awk '...' and have awk parse the different kinds of input from the two programs. or use perl instead of awk.  Also worth noting is that like shell and perl, awk can also run external programs and process their output.
There's a little more setup work in perl (explicitly opening pipes), but that's boilerplate stuff. The rest of the code is much easier than in shell.
I could have used back-ticks or qx() (see perldoc -f qx) to do command substitution like in shell instead of using open() (see perldoc -f open).  For example:
#!/usr/bin/perl

foreach (qx(xdotool getmouselocation --shell)) {
  m/^([^=]+)=(.*)$/;
  $M{$1} = $2;
};

foreach (qx(xrandr)) {
  next unless m/connected/;
  ($d, $w, $h, $xo, $yo) = m/^([^\s]+) .* (\d+)x(\d+)\+(\d+)\+(\d+)/;

  if ($M{X} >= $xo && $M{X} <= $w + $xo &&
      $M{Y} >= $yo && $M{Y} <= $h + $yo) {
    print "$d\n";
    last;
  }
}

This produces exactly the same output as the first script, but uses perl-style command substitution instead of explicitly open()-ing pipes.  It also uses regular expression capture groups to extract the data instead of split().
BTW, perl has an extremely useful function called map.  See perfoc -f map for details (and see also perldoc -f grep for a similarly useful built-in).  It's an amazingly useful and versatile tool - one of the simplest things you can use it for is to do things like replace the first foreach loop with:
foreach (qx(xdotool getmouselocation --shell)) {
  map { $M{$1} = $2 } m/^([^=]+)=(.*)$/;
};

or even:
map { $M{$1} = $2 } m/^([^=]+)=(.*)$/ foreach (qx(xdotool getmouselocation --shell));

Both versions are basically the same: map { CODE BLOCK } ARRAY - and the array can be a variable that already exists, or an anonymous array, generated on-the-fly in whatever manner suits you at them time.
Regexes return an array when called in list context (the match or matches). In the examples above, the regex match operator (m/PATTERN/) is being applied to each element of a foreach loop which is, in turn, iterating through elements of an array (the array in this case being the output of xdotool getmouselocation --shell, one line per array element).
There are other ways that map can be used.  Depending on how you call it, it can return a scalar value, an array, or a hash which can be assigned to variables or consumed by other functions.
Also BTW, foreach and for are synonyms in perl.  Anywhere I've written foreach, you can replace it with for.   for/foreach can be used to iterate over an array (list) as I've used it above, and it can also be used like a C-style for ($i = 1; $i < 10; $i++) loop.
There are probably perl modules for querying X directly to get the information needed about the displays and the mouse pointer, but it would have taken me longer to find them and read their docs than to just use the existing xdotool and xrandr tools.


text:
Q: Is there a JavaScript (or jQuery) shortcut for "function(){return false;}"? To prevent actions from happening, I frequently type
function(){return false;}

Is there a shortcut?

A: You could declare a named function like this:
function always_false() { return false; }

then use always_false() wherever you would have previously created the anonymous function.

A: I often have a "no op" function defined at the top of my common js file:
function nop() { return false }

I use it whenever I need a "do nothing" or a "cancel event" handler (eg div.oncontextmenu = nop). In IE this has the added benefit that memory does not leak when creating similar [anonymous] functions on the fly and assigning them to event handlers. At least that's what IE Drip tells me.

A: The shortcut(ECMAScript 2015):
_ => false

Or, simply press 5 keys:
_=>!1

But I'd rather recommend you to use the below for non-jQuery Event handlers.
event => event.preventDefault()

A: You can cancel an event default action by using the preventDefault method:
$("form").bind("submit", function(event){
  event.preventDefault();
});

A: Do you really think that's too much typing?
Why not have a global variable named f set to false, and use function() {return f;}

A: Just set the event handler to null. This is cleaner than assigning to a "return false" function IMO because it removes the event handler altogether.
myButton.onclick = null;