Q: XSLT 2.0 creating incremental footnote numbers in HTML output through multi-stage transformation This question builds on the responses to my original question, where it was suggested that I post a followup. This concerns attempting to integrate the XSL code from the previous post.
In the previous question I presented a simplified version of the TEI:XML document I am transforming into HTML using XSLT 2.0 (the full tei file and current xslt can be found here https://xsltfiddle.liberty-development.net/bdxtqT/6). This is a fuller view of the hierarchy, but not all details:
<tei>
 <teiHeader/>
 <text>
   <front/>

       <seg type="typefoo" corresp="#foo601" xml:id="foo361">
         <date type="deposition_date" when="1245">Idus
         marcii</date>In non hendrerit metus. Sed in posuere
         eros, sit amet pharetra lacus.</seg>
       <seg type="typefoo" xml:id="foo362">Nullam semper varius
         justo, vitae mollis turpis dapibus sit amet.
         Donec<note type="public_note">note content</note>
         rhoncus tempor urna sit amet imperdiet.</seg>
       <seg type="typefoo" xml:id="foo363">Integer
         id ante nunc. Curabitur at ligula sed arcu consequat
         gravida et id orci. Morbi quis porta dolor.</seg>
       <seg type="typefoo" corresp="#fooid2">Sed dictum<note
         type="public_note">note content 2</note> sem nec urna sodales
         cursus. Donec sit amet nibh tempor, congue ligula semper,
         rhoncus odio.</seg>

   <back>

       <seg>
       <seg>

       <seg>
       <seg>

   </back>
 </text>
<tei>

The desired HTML output is as follows. Incremental footnote numbers are created in  based on one of three conditions:

*

*date[@type="deposition_date"] (add footnote no.),

*seg[@type="typefoo"] (add footnote no.)

*note[@type="public_note"] (replace with footnote no.).
Desired output

Idus marcii1In non hendrerit metus. Sed in
       posuere eros, sit amet pharetra lacus.
2

Nullam semper varius justo, vitae mollis turpis
       dapibus sit amet. Donec3 rhoncus tempor
       urna sit amet imperdiet.

Integer id ante nunc. Curabitur at ligula sed
       arcu consequat gravida et id orci. Morbi quis porta
       dolor.

Sed dictum sem4 nec urna sodales cursus.
      Donec sit amet nibh tempor, congue ligula semper,
      rhoncus odio.
5

  [...]

1 1245

2 foo601

3 note here

4 note here

5 fooid2

The full XSLT transformation document is found at https://xsltfiddle.liberty-development.net/bdxtqT/6, where one can see the following problems:

*

*date[@type='deposition_date'] is being entirely replaced, instead receiving an added footnote marker

*seg[@type='dep_event' and @corresp] is not receiving an added footnote marker, but it appears in the
 at the bottom of the page.

The XSL file is too long and doesn't seem to paste here correctly. Interact with files here https://xsltfiddle.liberty-development.net/bdxtqT/6.
NB: I am restricted to XSLT 2.0 as this transformation is fired off inside eXist-DB with Xquery 3.1.
Thanks very much!

A: I think, unless you want to prefix all your paths in that template matching / with the variable I suggested to store the result of the marker insertion, one way to merge the existing code with my suggestion is to change the match from / to /* e.g. use
<xsl:template match="/*">

Latin

            <xsl:apply-templates select="//tei:body//tei:p"/>

English

            <xsl:apply-templates select="//tei:back//tei:p[@xml:lang='EN']"/>

            <xsl:if test="//tei:back//tei:p[@xml:lang='FR']">

French

                <xsl:apply-templates select="//tei:back//tei:p[@xml:lang='FR']"/>
            </xsl:if>

               <xsl:if test="$footnote-sources">

                     <xsl:apply-templates select="$footnote-sources" mode="build_footnotes"/>

               </xsl:if>

</xsl:template>

that would then mean that my suggestion to use
<xsl:template match="/">
    <xsl:apply-templates select="$fn-markers-added/node()"/>
</xsl:template>

can be kept and the XSLT processor would apply it.
There is however the use of that variable $footnote-sources at the end of the template, as far as I can see from the snippet its use on nodes from the original input document would not be affected by the introduction of a temporary result adding markers but somehow to me it would feel wrong to at that place keep processing the original input while the rest works on the temporary result so I would be inclined to change the variable declaration to
<xsl:variable name="footnote-sources" select="$fn-markers-added/tei:text//tei:seg//date[@type='deposition_date'] |
    $fn-markers-added/tei:text//tei:seg//note[@type='public_note'] | $fn-markers-added/tei:text//tei:seg[@corresp]"/>

With those two changes I think my suggestion in the previous answer should then be applied. Although now looking again at the posted source with a tei root element I wonder how a global variable having paths starting with tei:text would select anything but perhaps that is an omission in the sample.


Q: Nginx gives an Internal Server Error 500 after I have configured basic auth I am trying to do basic auth on Nginx. I have version 1.9.3 up and running on Ubuntu 14.04 and it works fine with a simple html file.
Here is the html file:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  "Some shoddy text"
</body>
</html>

And here is my nginx.conf file:
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    server {
        listen 80;
        server_name 192.168.1.30;
        location / {
            root /www;
            index index.html;
            auth_basic "Restricted";
            auth_basic_user_file /etc/users;
        }
    }
}

I used htpasswd to create two users in the "users" file under /etc (username "calvin" password "Calvin", and username "hobbes" password "Hobbes"). It's encrypted by looks like this:
calvin:$apr1$Q8LGMfGw$RbO.cG4R1riIfERU/175q0
hobbes:$apr1$M9KoUUhh$ayGd8bqqlN989ghWdTP4r/

All files belong to root:root. The server IP address is 192.168.1.30 and I am referencing that directly in the conf file.
It all works fine if I comment out the two auth lines and restart nginx, but if I uncomment them, then I do indeed get the username and password prompts when I try to load the site, but immediately thereafter get an Error 500 Internal Server error which seems to persist and I have to restart nginx.
Anybody can see what I'm doing wrong here? I had the same behaviour on the standard Ubuntu 14.04 apt-get version of Nginx (1.4.something) so I don't think it's the nginx version.

A: Not really an answer to your question as you are using MD5. However as this thread pops up when searching for the error, I am attaching this to it.
Similar errors happen when bcrypt is used to generate passwords for auth_basic:
htpasswd -B <file> <user> <pass>

Since bcrypt is not supported within auth_basic ATM, mysterious 500 errors can be found in nginx error.log, (usually found at /var/log/nginx/error.log), they look something like this:
*1 crypt_r() failed (22: Invalid argument), ...
At present the solution is to generate a new password using md5, which is the default anyway.
Edited to address md5 issues as brought up by @EricWolf in the comments:
md5 has its problems for sure, some context can be found in the following threads

*

*Is md5 considered insecure?

*Is md5 still considered secure for single use authentications?
Of the two, speed issue can be mitigated by using fail2ban, by banning on failed basic auth you'll make online brute forcing impractical (guide). You can also use long passwords to try and fortify a bit as suggested here.
Other than that it seems this is as good as it gets with nginx...

A: I was running Nginx in a Docker environment and I had the same issue. The reason was that some of the passwords were generated using bcrypt. I resolved it by using nginx:alpine.

A: Do you want a MORE secure password hash with nginx basic_auth? Do this:
echo "username:"$(mkpasswd -m sha-512) >> .htpasswd

SHA-512 is not considered nearly as good as bcrypt, but it's the best nginx supports at the moment.

A: I will just stick the htpassword file under "/etc/nginx" myself.
Assuming it is named htcontrol, then ...
sudo htpasswd -c /etc/nginx/htcontrol calvin
Follow the prompt for the password and the file will be in the correct place.
location / {
    ...

    auth_basic "Restricted";
    auth_basic_user_file htcontrol;
}

or auth_basic_user_file /etc/nginx/htcontrol; but the first variant works for me

A: I had goofed up when initially creating a user.  As a result, the htpasswd file looked like:
user:
user:$apr1$passwdhashpasswdhashpasswdhash...

After deleting the blank user, everything worked fine.

A: I just had the same problem - after checking log as suggested by @Drazen Urch I've discovered that the file had root:root permissions - after changing to forge:forge (I'm using Forge with Digital Ocean) - the problem went away.

A: Well, just use correct RFC 2307 syntax:
passwordvalue          = schemeprefix encryptedpassword
schemeprefix           = "{" scheme "}"
scheme                 = "crypt" / "md5" / "sha" / altscheme
altscheme              = "x-" keystring
encryptedpassword      = encrypted password

For example: sha1 for helloworld for admin will be

*

*admin:{SHA}at+xg6SiyUovktq1redipHiJpaE=
I had same error cause i wrote {SHA1} what against RFC syntax. When i fixed it - all worked like a charm. {sha} will not work too. Only correct {SHA}.

A: First, check out your nginx error logs:
tail -f /var/log/nginx/error.log

In my case, I found the error:
[crit] 18901#18901: *6847 open() "/root/temp/.htpasswd" failed (13: Permission denied),

The /root/temp directory is one of my test directories, and cannot be read by nginx. After change it to /etc/apache2/ (follow the official guide https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) everything works fine.
===
After executing the ps command we can see the nginx worker process maintained by the user www-data, I had tried to chown www-data:www-data /root/temp to make sure www-data can access this file, but it still not working. To be honest, I don't have a very deep understanding on Linux File Permissions, so I change it to /etc/apache2/ to fix this in the end. And after a test, you can put the .htpasswd file in other directories which in /etc (like /etc/nginx).

A: I too was facing the same problem while setting up authentication for kibana. Here is the error in my /var/log/nginx/error.log file

2020/04/13 13:43:08 [crit] 49662#49662: *152 crypt_r() failed (22:
  Invalid argument), client: 157.42.72.240, server: 168.61.168.150,
  request: “GET / HTTP/1.1”, host: “168.61.168.150”

I resolved this issue by adding authentication using this.
sudo sh -c "echo -n 'kibanaadmin:' >> /etc/nginx/htpasswd.users"
sudo sh -c "openssl passwd -apr1 >> /etc/nginx/htpasswd.users"

You can refer this post if you are trying to setup kibana and got this issue.
https://medium.com/@shubham.singh98/log-monitoring-with-elk-stack-c5de72f0a822?postPublishedType=repub

A: In my case, I was using plain text password by -p flag, and coincidentally my password start with $ character.
So I updated my password and thus the error was gone.
NB: Other people answer helped me a lot to figure out my problem. I am posting my solution here if anyone stuck in a rare case like me.

A: In my case, I had my auth_basic setup protecting an nginx location that was served by a proxy_pass configuration.
The configured proxy_pass location wasn't returning a successful HTTP200 response, which caused nginx to respond with an Internal Server Error after I had entered the correct username and password.
If you have a similar setup, ensure that the proxy_pass location protected by auth_basic is returning an HTTP200 response after you rule out username/password issues.


Q: Why does this LinkedList addLast implementation work? I am working on adding an item to the end of a linked list (this isn't homework...just an exercise for myself).
Here is the program:
public class CustomLinkedList {

    private static Node head = null;
    private int size = 0;

    public static void main(String[] args) {
        CustomLinkedList myList = new CustomLinkedList();
        myList.add(5);
        myList.add(9);
        myList.add(3);

        System.out.println("List Size: " + myList.size);
        myList.print();
    }

    private int size() {
        return this.size;
    }

    private void print() {
            Node temp = head;
           for (int i=0; i<=size-1;i++){
                System.out.print(temp.value + " ");
                temp = temp.next;
            }
        System.out.println();
    }

    private void add(int value) {
        if (head == null) {
            head = new Node();
            head.value = value;
            head.next = null;
            size++;
        } else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = new Node();
            (temp.next).value = value;
            size++;
        }
    }
}

Here is my Node class:
public class Node {
    public int value;
    public Node next;

    public int getValue(){
        return this.value;
    }
}

Here is what I think is happening:
1. I have an original/ongoing list starting with "head."
2. I want to add to that list.
3. To add to it, I need to find the end of it. I do that by creating a new node called temp (which is just a copy of the original list).
4. I traverse the copy (temp) until I reached the end.
5. Once I reach the end, I create a new node.
To me, this is where my code stops. Now, in my mind, I need to add code that says, "Alright, you have your new node, you know where it needs to go, so lets go through the real list and add it."
But I don't have that. According to my debugger (image below), the right thing is happening, but I don't see the magic that is adding the new node to the original list. How is this working?

Edit:
I did look at other implementations (like the one here); it looked very similar. However, I still couldn't find why it works without assigning temp to head (or to head.next). I get Linked Lists in theory I believe. I just don't understand why this bit works.

A: Your confusion is that temp is different to head. It's not.
They are both variables holding references to the same Node object. Changes made via either variable are reflected in the (same) object they reference. When you add a Node to temp, you add it to the real list.


Q: Setting fs.default.name in core-site.xml Sets HDFS to Safemode I installed the Cloudera CDH4 distribution on a single machine in pseudo-distributed mode and successfully tested that it was working correctly (e.g. can run MapReduce programs, insert data on the Hive server, etc.) However, if I chance the core-site.xml file to have fs.default.name set to machine name rather than localhost and restart the NameNode service, the HDFS enters safe-mode.
Before the change of fs.default.name, I ran the following to check the state of the HDFS:
$ hadoop dfsadmin -report
...
Configured Capacity: 18503614464 (17.23 GB)
Present Capacity: 13794557952 (12.85 GB)
DFS Remaining: 13790785536 (12.84 GB)
DFS Used: 3772416 (3.60 MB)
DFS Used%: 0.03%
Under replicated blocks: 2
Blocks with corrupt replicas: 0
Missing blocks: 0

Then I made the modification to core-site.xml (with the machine name being hadoop):
<property>
  <name>fs.default.name</name>
  <value>hdfs://hadoop:8020</value>
</property>

I restarted the service and reran the report.
$ sudo service hadoop-hdfs-namenode restart
$ hadoop dfsadmin -report
...
Safe mode is ON
Configured Capacity: 0 (0 B)
Present Capacity: 0 (0 B)
DFS Remaining: 0 (0 B)
DFS Used: 0 (0 B)
DFS Used%: NaN%
Under replicated blocks: 0
Blocks with corrupt replicas: 0
Missing blocks: 0

An interesting note is that I can still perform some HDFS commands. For example, I can run
$ hadoop fs -ls /tmp

However, if I try to read a file using hadoop fs -cat or try to place a file in the HDFS, I am told the NameNode is in safemode.
$ hadoop fs -put somefile .
put: Cannot create file/user/hadinstall/somefile._COPYING_. Name node is in safe mode.

The reason I need the fs.default.name to be set to the machine name is because I need to communicate with this machine on port 8020 (the default NameNode port). If fs.default.name is left to localhost, then the NameNode service will not listen to external connection requests.
I am at a loss as to why this is happening and would appreciate any help.

A: The issue stemmed from domain name resolution. The /etc/hosts file needed to be modified to point the IP address of the machine of the hadoop machine for both localhost and the fully qualified domain name.
192.168.0.201 hadoop.fully.qualified.domain.com localhost

A: Safemode is an HDFS state in which the file system is mounted read-only; no replication is performed, nor can files be created or deleted. Filesystem operations that access the filesystem metadata like 'ls' in you case will work.
The Namenode can be manually forced to leave safemode with this command( $ hadoop dfsadmin -safemode leave).Verify status of safemode with ( $ hadoop dfsadmin -safemode get)and then run dfsadmin report to see if it shows data.If after getting out of safe mode the report  still dose not show any data then i'm suspecting communication between namenode and datanode is not hapenning. Check namenode and datanode logs after this step.
The next steps could be to try restarting datanode process and last resort will be to format namenode which will result in loss of data.


Q: Checkbox styling Is there a way to style a checkbox and a label with border, so the user can see only the label (the checkbox is hidden), and when the user clicks on the label, the label will change the color of the background and the text? This click should also work as clicking on the checkbox.
If there is a way, how should I do this?
or
How to hide the checkbox and leave only the label do the work with changing colors?

A: Put them side to side (in html structure) and use the adjacent sibling selector +
Something like this
html
<input type="checkbox" id="box1" />
<label for="box1">checkbox #1</label>

css
input[type="checkbox"]{
    position:absolute;
    visibility:hidden;
    z-index:-1;
}
input[type="checkbox"]:checked + label{
    color:red;
}

you could style the label (2nd rule) as you want of course..
demo at http://jsfiddle.net/kb67J/1/


Q: Multiple Nuxt3 custom modules disable each other I developed 2 custom modules, let's say module1 and module2.
module1 uses addImports (to auto-import composable and utils) and module2 uses addComponent (to, obviously, auto-import some components) along a components list in directory ./runtime/components.
// module1
addImports([
  {
    from: resolve(runtimeDir, 'composables/useFoo'),
    name: 'useFoo',
    as: 'useFoo'
  }
]);

// module2
const components = fs.readdirSync(resolve('./runtime/components')).map((component: string) => {
  return component.split('.').slice(0,-1).join('.');
});
// components = [ 'Component1', 'Component2' ]
components.map((component: string) => {
  addComponent({
    name: component,
    filePath: resolve(`./runtime/components/${component}.vue`),
    global: true
  });
});

After publishing both and testing by installing them in a test Nuxt3 project, it appears that they work fine individualy, but as soon as I add both in nuxt.config.ts file's modules array, the first one in the array break the second one:
// In test project
// addCOmponents of module2 does not work
modules: [
  'module1',
  'module2'
]

// addImports of module1 does not work properly
modules: [
  'module2',
  'module1'
]

I have no idea what i can do or what I am doing wrong :/
Can someone help please ?


Q: How to count days between to dates So I would like to count how many days between two datepickers.
So I tried to make two array but it didnt work
any Ideas?
Here my date pickers

A: Convert your calendar string day, month, year to Date class.
More discussion here: Java string to date conversion
e.g.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d1, d2;

try {
    d1 = dateFormat.parse(year + "-" + month + "-" + day); //as per your example
    d2 = //do the same thing as above
    long days = getDifferenceDays(d1, d2);
}
catch (ParseException e) {
    e.printStackTrace();
}

public static long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}

A: Create a method getDates()
private static ArrayList<Date> getDates(String dateString1, String dateString2)
{
    ArrayList<Date> arrayofdates = new ArrayList<Date>();
    DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");

    Date date1 = null;
    Date date2 = null;

    try {
        date1 = df1 .parse(dateString1);
        date2 = df1 .parse(dateString2);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    Calendar calender1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calender1.setTime(date1);
    calender2.setTime(date2);

    while(!calender1.after(calender2))
    {
        arrayofdates.add(calender1.getTime());
        calender1.add(Calendar.DATE, 1);
    }
    return arrayofdates;
}

then pass the parameter in this method to get array of dates
As you are using DatePicker then
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
    ArrayList<Date> mBaseDateList = getDates(df1.format(cal1.time), df1.format(cal2.time))

A: Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    Date d1, d2;
     Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    for (int i = 0; i < n; i++) {
        try {
            d2 = sdf.parse(in.next());
            d1 = sdf.parse(in.next());
            long differene = (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24);
            System.out.println(Math.abs(differene));
        } catch (Exception e) {
        }
    }

A: public static int getDaysBetweenDates(Date fromDate, Date toDate) {
    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24)));
}


Q: Index keys of an object where the value satisfies a condition I'm trying to write a function that takes two objects and the name of a key that both objects contain, assuming the associated values are both arrays, and compares the length of the two arrays.
The general form of the function is this:
const compareByKeyLength = <T extends Record<string, unknown[]>, K extends keyof T>(
  a: T,
  b: T,
  key: K,
) => {
  return a[key].length < b[key].length ? 1 : -1;
};

However, I want to modify this so that T does not necessarily extend Record<string, unknown[]>. That is, it cannot be assumed that the T can be indexed by any arbitrary string to get an array. Some keys on the object will be other types. What I want is to limit the allowed values for K such that only the keys which are associated with array values can be given as input.
This is my best guess as to how to implement this, but as you can see, the compiler still doesn't accept that the values will be arrays:
// Find all keys in an object whose type is an array.
type ArrayKeys<O> = {
  [K in keyof O]: O[K] extends any[] ? K : never
}[keyof O];

// Example to test if `ArrayKeys` works.
const example = {
  foo: [1, 2, 3],
  bar: "bar",
  baz: ["one", "two", "three"],
};

// Evaluates to: "foo" | "baz"
type ExampleArrayKeys = ArrayKeys<typeof example>;

// Somehow `T[ArrayKeys<T>]` doesn't prove that the value accessed will be an array. Not sure why.
const compareByKeyLength = <T,>(
  a: T,
  b: T,
  key: ArrayKeys<T>,
) => {
  return a[key].length < b[key].length ? 1 : -1; // Error: Property 'length' does not exist on type 'T[ArrayKeys<T>]'.
};

TS Playground
My questions:

*

*What is the reason my attempt doesn't do what I want? Is it a limitation of the compiler to understand that T[ArrayKeys<T>] will always be an array? Or is that actually unsound and I'm just not seeing why?

*Is what I'm trying to do expressible in the type system, or do I need to use runtime checks to verify that the values are actually arrays?

A: Maybe this is what you need:
const compareByKeyLength = <
  A extends Record<Key, any[]>,
  B extends Record<Key, any[]>,
  Key extends keyof A & keyof B
>
(
  a: A,
  b: B,
  key: Key,
) => {
  return a[key].length < b[key].length ? 1 : -1;
};

compareByKeyLength({a: [], b: 123}, {a: [], c: 123}, "a")

I introduce the generic type Key which is both a keyof A and keyof B. Then I specify that the inputs a and b are of the generic types A and B which both have the key Key with an array type any[].
Playground


Q: How to style a photo gallery? I am looking for a method to design a photo gallary, I am currently using table but not sure if its a correct method to do it or not, also not sure about styling.
It has many images, upload is used to upload photos and message is used to show upload messages.
I just need to show the images and allow users to save images on the server, and show the messages, (uploaded / can not upload). I can show the images, save them and send the messages to the message section but not sure how to style it.
Another problem is that I need all images to be in the same size, as each is in different size now.
I need it to be the same on all browsers.

    upload photo btn
    message

    upload photo btn
    message

A: Semantically tables should be used for tabular data.
Check out the answer to this question for some options.
Depending on the age of the browsers you want to support, you could also consider using a flex box layout. Flex box is nice and easy to code but not fully supported in all browsers yet.

A: According to me this shouldn't be accomplished using tables, the better way to do is by using CSS3 column-count property, this way you can cut-split your content to whatever number of columns you want to, this way you don't have to use tables too..
Demo
Demo (Added -webkit support)
html, body {
    width: 100%;
    height: 100%;
}

.wrap {
    column-count: 3;
    -moz-column-count: 3;
    -webkit-column-count: 3;
}

.holder {
    border: 1px solid #f00;
}

img {
    max-width: 100%;
}

Note: column-count CSS3 property is not widely supported, but there
  are many polyfills available out, you can search online and use it for
  cross browser compatibility


Q: Unable to use DirectX.Capture library I am unable to use DirectX.Capture library because the following code from the example gave me errors:
Capture capture = new Capture(
    Filters.VideoInputDevices[0],
    Filters.AudioInputDevices[0]);

capture.Start();

capture.Stop();

An object reference is required for the non-static field, method, or
property 'DirectX.Capture.Filters.AudioInputDevices'
An object
reference is required for the non-static field, method, or property
'DirectX.Capture.Filters.VideoInputDevices'

Why? What am I doing wrong? How can I fix it?

A: The message is saying that the member AudioInputDevices and the member VideoInputDevices are not declared as static in the type DirectX.Capture.Filters, but you are using them as if they were static.
To reference a member that's not static, you need to instantiate that type, by calling the constructor (directly, or indirectly via some kind of factory method) of that type (DirectX.Capture.Filters).
In other words, you need something like this:
var filters = new DirectX.Capture.Filters(...);
var capture = new Capture(filters.VideoInputDevices[0], filters.AudioInputDevices[0]);


Q: Elasticsearch: Exact multiple match phrases on same field I want the following query to return results where exact phrases separated by OR match in a particular field.
{
  "query": {
    "nested": {
      "path": "positions",
      "query": {
        "bool": {
          "must": [
            {
              "query_string": {
                "default_field": "positions.companyname",
                "query": "microsoft OR gartner OR IBM"
              }
            },
            {
              "query_string": {
                "default_field": "positions.title",
                "query": "(Chief Information Security Officer) OR (Chief Digital Officer)"
              }
            }
          ]
        }
      },
      "inner_hits": {
        "highlight": {
          "fields": {
            "positions.title": {}
          }
        }
      }
    }
  }
}

The results should contain exact Chief Information Security Officer OR Chief Digital Officer,
but not Chief Digital Marketing Officer OR Chief Information Officer as it is currently being returned.
Also, the field may not necessarily have the exact phrase to be searched.
For example:
"CIO Chief Information Officer" -> FALSE
"Head at Digital - Chief Digital Officer" -> TRUE
"Former lead Chief Information Security Officer" -> TRUE
"Chief Information Officer" -> False
I guess the point I am trying to make is those phrases should always be next to each other(proximity).

A: For your use case I would suggest you to use match_phrase query inside a bool query's should clause.
Something like this should work:
GET stackoverflow/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "text": "Chief Information Security Officer"
          }
        },
        {
          "match_phrase": {
            "text": "Chief Digital Officer"
          }
        }
      ]
    }
  }
}

A: This query would do it.
{
  "query": {
    "nested": {
      "path": "positions",
      "query": {
        "bool": {
          "must": [
            {
              "query_string": {
                "default_field": "positions.companyname",
                "query": "microsoft OR gartner OR IBM"
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "match_phrase": {
                      "positions.title": "chief information security officer"
                    }
                  },
                  {
                    "match_phrase": {
                      "positions.title": "chief digital officer"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}

match_phrase makes sure that the exact phrase is being searched. To match multiple phrases on the same field, use bool operator with should condition.


Q: Which IDE should be used for Java Application development? I want to develop applications for Nokia Mobile. I googled and found that J2ME is the language in which app can be developed for the mobile phone.
Please suggest any IDE in which i can develop applications for Android, Blackberry, Nokia (platforms nokia commonly use) etc.
Is it possible to have a single IDE for all types of development described above?
I work on Microsoft.NET technology and am new to Java Development.

A: For Android I'd go with Eclipse see the following for the Android SDK and Eclipse setup

*

*Android SDK

*Eclipse Plugin for Android

*Blackberry

*Nokia S60

A: Have a look at Mobile Tools for Java. It is based on Eclipse and widely used among developers! You can add a large number of plugins to fulfill your needs if necessary.

A: I think there is two main used IDEs for Java. Eclipse and Netbeans. Since for Eclipse there is a better plugin for Android, I would recommend it if you want just use one.

A: There was an eclipse for J2ME (eclipse pulsar). But some people prefer NetBeans.
For Android, eclipse.
This question is not going to live much time, I think XD. Is the kind of 'better' question that gets closed.


Q: Displaying a confirmation message after doing a query with AJAX and PHP I am trying to call a function with Javascript, HTML, AJAX, and PHP.
I am still new to Javascript, AJAX, and PHP.
Background info: I am trying to add a new customer to my database but I am now trying to get a confirmation message on the same page without the page refreshing.
This is what I have:

Suggestions:

            <form action="return addCustomer(this.add_LN, this.add_FN, this.add_PN, this.add_DOB);">
                <input type="text" name="add_LN" id="add_LN" />

                <input type="text" name="add_FN" id="add_FN" />

                <input type="text" name="add_PN" id="add_PN" />

                <input type="text" name="add_DOB" id="add_DOB" />

                <input type="submit" name="add_Customer" id="add_Customer" value="Add Customer" />
            </form>

I get a "This link appears broken"
With:
http://127.0.0.1/cpsc471/return%20addCustomer(this.add_LN,%20this.add_FN,%20this.add_PN,%20this.add_DOB);?add_LN=ee&add_FN=123&add_PN=eee&add_DOB=eee&add_Customer=Add+Customer
in the url bar.
What am I doing wrong? :) I do not want the page to refresh. I am trying to just get the confirmation or non-confirmation to display.
Thanks again for all the help!

A: Your problem is here:
 <form action="return addCustomer(this.add_LN, this.add_FN, this.add_PN, this.add_DOB);">

You don't want the form action to be a javascript call, you need to do this onclick or something.
The arguments above by @thiefmaster and @martin are correct: using jquery is much simpler. You are right about the framework thing, but in this case you need to go and code for a lot of troubles (responses, when is there a successfull AJAX call, different browsers etc)

A: xmlhttp.onreadystatechange=function()
  {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
// put your codes here like
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

//  document.getElementById("show_label").innerHTML='text as you wish like updated enjoy';
}

}
And add a label with the id of show_label


Q: How to change the calendar table end date in power bi?
Here is my problem, I want to change the end date of my
calendar table based on what I have selected in the "Previous 12 Months Dates Table".
I used my "Previous 12 Months Dates Table" as a dropdown slicer filter and get the max date in that table and used it in my calendar table as my end date.
I tried a measure that returns the max date from my "Previous 12 Months Dates Table" and also I try to debug by displaying my measure value in the table chart and selecting a specific date in the dropdown slicer and it works fine.
But when I used that measure in my "Calendar Table" and try to debug it will return the default max date, not the date that I selected in my dropdown slicer.
Here is the behavior I wanted to achieve.
For example, if I select "EOMONTH" Jan 2022, it will return the previous 12 months' view from "EOMONTH" Jan 2022 and also it will calculate 12 months rolling average "EOMONTH" Jan 2022.
The previous 12 Months View and 12 months rolling average is working as I expected when I try to change the Calendar end date manually. that is why my only problem is how to change my calendar end date based on the selected date in the dropdown slicer.
Thanks in advance.


Q: How to resolve this deprected problem in OnActivityCreated? I am getting 'onActivityCreated(android.os.bundle)' is deprecated.
package example.com.fragmentrecycler;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 */
public class ListFrag extends Fragment {
    RecyclerView recyclerView;
    RecyclerView.Adapter myAdapter;
    RecyclerView.LayoutManager layoutManager;
    View view;

    public ListFrag() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_list, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    public void notifyDataChanged()
    {
        myAdapter.notifyDataSetChanged();
    }

}

This is that java file in which i am getting this error. This code is part of full project.I am not getting what wrong in my code.

A: onActivityCreated() is deprecated in API level 28.
There is no error shown because no error exists. Deprecated means that a newer or better method exists to handle stuff. So you need to change onActivityCreated() to onCreate(). But as I see you don't need to call this a second time if you already have a Fragment with onCreateView(). Keep your project clear and make a new .java file instead. Don't code everything in one single file.

*

*onCreate() is for Activity

*onCreateView() is for Fragment


Q: EventEmitter memory leak from function within socket.io handler I have a server that requires a dynamic value that's continuously updating from a spawned process. I tried to make a custom listener outside of the scope of the server because I was receiving potential memory leaks errors but I'm still receiving these messages after several connect/disconnects occur on the server. Why arn't the listeners that were added after the initial connect being removed during the disconnect event listener?
var express = require('express');
var http = require('http');
var spawn = require('child_process').spawn;
var util = require('util');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var sys = require('sys');

var app     = express(),
    server  = http.createServer(app),
    io      = require('socket.io').listen(server);

function Looper(req)  {
    this.req = req;
    EventEmitter.call(this);
}
sys.inherits(Looper, EventEmitter);

Looper.prototype.run = function() {
    var self = this;
    var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
    cmd.stdout.setEncoding('utf8');
    cmd.stdout.on('data', function(data) {
        self.emit('output',data);
    });
}

Looper.prototype.output = function(callback) {
    this.on('output', function(data) {
        return callback(data.trim());
    });
}

var looper = new Looper('blah');
looper.run();

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.send(
        "<script src='/socket.io/socket.io.js'></script>\n"+
        "<script>\n"+
        "\tvar socket=io.connect('http://127.0.0.1:3000');\n"+
        "\tsocket.on('stream', function(data) {\n"+
        "\t\tconsole.log(data);\n"+
        "\t});\n"+
        "</script>\n"
    );
});
server.listen(3000);

io.sockets.on('connection', function(webSocket) {
    looper.output(function(res) {
        webSocket.emit('stream',res);
    });

    webSocket.on('disconnect', function() {
        looper.removeListener('output',looper.output); // <- not remove listener added when connection was made
    });
});

A: You add(!) an extra callback function every time you call looper.output to the event 'output'. I don't know what you want to achieve, but to get this call only once use this.once('output', ...) or move the callback setting to the object or remove the old function first...


Q: R segfaults when starting R by opening a source file My R.app (R version 3.3.2, R.app GUI 1.68 (7288) x86_64-apple-darwin13.4.0) on macOS Sierra is odd.
When I start R.app by clicking the app icon, I have no problems.
But if I start R.app by double-clicking a source file (e.g., test.R) in Finder.app or if I type open test.R in Terminal.app, I get a segfault error ("memory not mapped").
 *** caught segfault ***
address 0x18, cause 'memory not mapped'

Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace
>
Selection:

It is OK if R.app is already running when test.R is opened.
When R.app segfaults, I am sometimes lucky to have control and can close the app normally. But at other times, R.app halts with the spinning wheel appearing, and I have to Force-Quit the app. After I force-quit R.app, the next time I start R.app, I am permanently stuck (with R.app halting trying to open test.R as soon as I restart R.app), in which case I solve the problem by starting R from Terminal by typing /Applications/R.app/Contents/MacOS/R.
What would be the problem?


Q: Compare md5 after tftp transfer Because I use the tftp command to transfer an important file, I would like to compare md5 in order to valid the transfer.
Note : The file has been already transfered in the the example below
int main(int argc, char *argv[])
{
    FILE *input_md5_fd;
    FILE *md5_fd;
    size_t md5_length;
    size_t nbr_items;
    char *input_md5 = NULL;
    char *file_md5 = NULL;
    int ret;

    chdir("/tmp");

    system("tftp -g -r INPUT_MD5 192.168.0.1");
    input_md5_fd = fopen("INPUT_MD5", "r");
    if (input_md5_fd != NULL)
    {
       fprintf(stdout,"MD5 transfered\n");
       fseek(input_md5_fd,0L,SEEK_END);
       md5_length = ftell(md5_fd);
       input_md5 = malloc(md5_length + 1);
       fseek(input_md5_fd,0L,SEEK_SET);
       nbr_items = fread(input_md5, 1, md5_length, input_md5_fd);
       input_md5[nbr_items] = 0;
       fprintf(stdout, "length = %lu B\n",md5_length);
       fprintf(stdout, "contains %s\n", input_md5);
       fclose(input_md5_fd);
    }
    else
    {
       return -1;
    }

    system("md5sum IMPORTANT_FILE > /tmp/file_md5.txt");

    md5_fd = fopen("file_md5.txt", "r");
    if (md5_fd != NULL)
    {
       file_md5 = malloc(md5_length +1);
       rewind(md5_fd);
       nbr_items = fread(file_md5, 1, md5_length, md5_fd);
       file_md5[nbr_items] = 0;
       fprintf(stdout, "contains %s\n", file_md5);
       fclose(md5_fd);
    }
    else
    {
       return -1;
    }

    printf("file_md5 = %s\n", file_md5);
    printf("input_md5 = %s\n", input_md5);
    ret = strncmp(file_md5, input_md5, md5_length);
    printf("ret = %d\n", ret);

    free(input_md5);
    free(file_md5);

}

Output :
MD5 transfered
length = 33 B
contains a95ef51ec6b1b06f61c97559ddf4868f

contains a95ef51ec6b1b06f61c97559ddf4868f
file_md5 = a95ef51ec6b1b06f61c97559ddf4868f
input_md5 = a95ef51ec6b1b06f61c97559ddf4868f

ret = 22

The input files contain :
# cat /tmp/INPUT_MD5
a95ef51ec6b1b06f61c97559ddf4868f

 # cat /tmp/file_md5
a95ef51ec6b1b06f61c97559ddf4868f  XXX_XX-XXXX-XX-DD.DDD-DD.DDD.DD.bin

X being char and D decimal values.
Why ret is not equal to 0 ? In addition, I don't know from where 34 comes from
EDIT :
CODE HAS BEEN UPDATED, problem came from md5_length definition. long type has been exchanged to size_t

A: You risk printing out and comparing garbage since you don't ensure the strings are nul terminated.
You need to do
 fread(file_md5, 1, md5_length, md5_fd);
 file_md5[md5_length] = 0;

And similar for input_md5. Or to do it properly, use the return value of fread() to add the nul terminator in the proper place, check if fread() fails, Check how much it returned.
If you also place your debug output inside quotes, it'll also be easier to spot unwanted whitespace or unprintable characters:
fprintf(stdout, "contains '%s'\n", input_md5);


Q: ocaml mutual recursion error I am new to Ocaml and want help with recursive function defined on a recursive data type. I have defined a data type as follows
    type 'a slist = S of 'a sexp list
    and
    'a sexp = Symbol of 'a | L of 'a slist

The function(subst) I'm writing checks for a symbol a in the defined slist and substitutes it by b. For ex subst 1 10 S[ 1; 4; S[L[3; 1;]; 3];] returns S[10; 4; S[L[S[3; 10;]]; 3;]
. My code is as follows
    let rec subst a b sl = match sl with
    S s -> match s with
          [] -> []
          | p :: q -> match p with
                Symbol sym -> if sym = a then S[b] :: (**subst** a b S[q]) else
                                 S[p] :: (subst a b S[q])
                L l -> (subst a b l) :: (subst a b S[q])
    | L lis -> subst a b lis;;

I am getting the error :
This function is applied to too many arguments; Maybe you forgot a ';'
Please help

A: Your type can be defined in a simpler way, you don't need slist:
type 'a sexp = Symbol of 'a | L of 'a sexp list

Your problem is that subst a b S[q] is read as subst a b S [q], that is the function subst applied to 4 arguments. You must write subst a b (S[q]) instead.


Q: Teradata CASE WHEN attribute IN ( Select... from)
I have selected a bunch of IDs and I try to use CASE WHEN to get a column when the IDs which I really want to select are in the IDs I selected earlier.
But it shows Select Failed .3771:Illegal expression in WHEN clause of Case expression.
Any suggestion to get it right?
Please help.
p.s my goal is to select the IDs shown for the first time.


Q: Type mismatch java.io.Serializable and GenTraversableOnce I'm trying to get a parser to take a sequence of colon-seperated words and convert them into an array.
Here's an SSCCE.
import util.parsing.combinator._

class Element {

  def getSuper() = "TODO"

}

class Comp extends RegexParsers with PackratParsers {
  lazy val element: PackratParser[Element] = (
    "foo") ^^ {
    s => new Element
  }

  lazy val list: PackratParser[Array[Element]] = (
    (element ~ ";" ~ list) |
    element ~ ";") ^^
  {
    case a ~ ";" ~ b => Array(a) ++ b
    case a ~ ";" => Array(a)
  }
}

object Compiler extends Comp {
  def main(args: Array[String]) = {
    println(parseAll(list, "foo; foo; foo;"))
  }
}

It's not working and it's not compiling, if it was I wouldn't be asking about it. This is the error message I'm getting. Is there a way to convert from Serializable to GenTraversableOnce?
~/Documents/Git/Workspace/Uncool/Scales$ scalac stov.scala
stov.scala:19: error: type mismatch;
 found   : java.io.Serializable
 required: scala.collection.GenTraversableOnce[?]
    case a ~ ";" ~ b => Array(a) ++ b
                                                    ^
one error found

A: My suspicion goes on the | combinator.
The type of (element ~ ";" ~ list) is ~[~[Element, String], Array[Element]] and the type of element ~ ";" is ~[Element, String].
Thus when applying the | combinator on these parsers, it returns a Parser[U] where U is a supertype of T ([U >: T]).
Here the type of T is ~[~[Element, String], Array[Element]] and the type of U is ~[Element, String].
So the most specific type between Array[Element] and String is Serializable.
Between ~[Element, String] and Element its Object. That's why the type of | is ~[Serializable, Object].
So when applying the map operation, you need to provide a function ~[Serializable, Object] => U where U is Array[Element] in your case since the return type of your function is PackratParser[Array[Element]].
Now the only possible match is:
case obj ~ ser => //do what you want

Now you see that the pattern you're trying to match in your map is fundamentally wrong. Even if you return an empty array (just so that it compiles), you'll see that it leads to a match error at runtime.

That said, what I suggest is first to map separately each combinator:
lazy val list: PackratParser[Array[Element]] =
    (element ~ ";" ~ list) ^^ {case a ~ ";" ~ b => Array(a) ++ b} |
    (element ~ ";") ^^ {case a ~ ";" => Array(a)}

But the pattern you are looking for is already implemented using the rep combinator (you could also take a look at repsep but you'd need to handle the last ; separately):
lazy val list: PackratParser[Array[Element]] = rep(element <~ ";") ^^ (_.toArray)


Q: how to display javascript validation message on html popup Want to display javascript validation messages inside an html popup window which would be a seperate html page.currently it is displayed on the same page from where it has been called.

 $("#getStarted").val('Try xxxx for Free');
 $('#message1').text('User ' + emailID + ' already exists.');
 $("#stRegister").val("");
 document.getElementById("stRegister").focus();
<input name="stRegister" id="stRegister" type="email" class="registerinput" placeholder="Enter your business email ID" onkeypress="$('#message1').text('');">

A: var window = window.open(url, windowName, [windowFeatures]);  moidify the dom on the window object.

A: Not sure if you can do it in a separate window. However, for validation you can use the window.confirm function natively build into the browsers. Here is an example:

// window.confirm returns a boolean based on the user action
let validate = window.confirm('Do you want to continue?');

if (validate) {
  console.log('validated');
} else {
  console.log('not validated');
}

A: You can use in your script something like:
window.alert("what you want here");


Q: Can we use class transitions in jQuery like with CSS3? Do any of you know the answer to the following problem. It's driving me crazy that I cannot find a solution.
I want to animate in jQuery by adding/replacing a class and transitioning between the two, NOT by using inline styling.
This is exactly how CSS3 transition works, and its really great and allows for quick prototyping. But I want to do it in jQuery because I want it to be normalised across all browsers.
I've used jQuery animate for a long time, but I've only used it to add inline-styling. This gets really messy to manage and means I can't have the end result written in CSS and separate the presentation layer from the logic.
Consider the following example. In CSS3 if I want to animate a div height by changing the height of a div I can do this:

*

*A div has a class .object which has an initial height of 100px.

*An event runs, and the div now has the classes .object and .active.

*With the .active class, the CSS now sets the height to 150px

*Using CSS3 transition, I can allow a smooth transition between the two over 2 seconds with easing.

If i want to do the same thing in jQuery:

*

*A div has a class .object which has an initial height of 100px.

*An event runs, and I use .animate to animate the height of the object to 150px

*As a result of this, the CSS now sets the height to 150px using inline styling

*Using parameters I can set the speed in ms with easing.

You may be aware of jQuery UI which allows transition on toggleClass and switchClass:
http://jqueryui.com/demos/toggleClass/
However, annoyingly it won't work for the example above because it only works if the initial class has no specific height set. To test this, inspect the element in the demo and give it a height and watch the demo break.
Hopefully someone can help me with this

A: You could try DOM Mutation Events, which are dispatched eg. when a property of an element is changed.
There are plugins for jQuery, which mimes the behavior of event mutation (although I haven't tried any of those).
But feel free to google about mutation events in jQuery and that should probably help you.

A: You can do it with http://jqueryui.com/demos/switchClass/
(i made a similar question few weeks a go can a .classA styles to .classB styles be animated easly? )


Q: Where to find the size of SQL Server data types I am trying to calculate the size of my database. I will have a table with 3 columns (id, int, money) I will have 26 million rows with all columns being occupied. How big will my database be? Also, where can I find the size of all SQL Server data types?

A: T-SQL has a function for that: DATALENGTH for all SQL Server versions.
Example:
DECLARE @lat DECIMAL(10, 7) = 3.14151415141514151415;

SELECT @lat, DATALENGTH(@lat);

Result:
3.1415142 and 5 (because DECIMAL(10,7) uses 5 bytes to be stored).
Documentation: https://learn.microsoft.com/en-us/sql/t-sql/functions/datalength-transact-sql?view=sql-server-ver15
For example, I have a table called Applications with these columns: (id VARCHAR(32), debug BIT, connectionString VARCHAR(2048), firebaseKey VARCHAR(4096)). As we know, VARCHAR doesn't allocate all the space (just what you need, so 'A' is 1 byte in VARCHAR).
These queries:
SELECT
  SUM(DATALENGTH(id)) AS idSize,
  SUM(DATALENGTH(debug)) AS debugSize,
  SUM(DATALENGTH(connectionString)) AS connectionStringSize,
  SUM(DATALENGTH(firebaseKey)) AS firebaseKeySize
FROM Applications;

SELECT
  SUM(
    DATALENGTH(id) +
    DATALENGTH(debug) +
    DATALENGTH(connectionString) +
    DATALENGTH(firebaseKey)
  ) AS totalSize
FROM Applications;

will return my data size (in my case, with my rows, is 8, 2, 366, 4698 (total: 5074). There are 2 rows in that table.
Notice that this does NOT represent the total size of my database (there are pages, descriptors, indexes, etc. involved.)*
MSSQL has internal stored procedures to tell you the exactly size of your database in disk:

*

*EXEC sp_spaceused; for all database;

*EXEC sp_spaceused N'schema.TableName'; for a specific table;

*EXEC sp_helpdb N'DatabaseName'; if you want details from each file.

A: Your can use below query :
SELECT * FROM sys.types

result of above query is below :
name                 system_type_id user_type_id schema_id principal_id max_length precision scale collation_name    is_nullable is_user_defined is_assembly_type default_object_id rule_object_id is_table_type
-------------------- -------------- ------------ --------- ------------ ---------- --------- ----- ----------------- ----------- --------------- ---------------- ----------------- -------------- -------------
image                34             34           4         NULL         16         0         0     NULL              1           0               0                0                 0              0
text                 35             35           4         NULL         16         0         0     Persian_100_CI_AI 1           0               0                0                 0              0
uniqueidentifier     36             36           4         NULL         16         0         0     NULL              1           0               0                0                 0              0
date                 40             40           4         NULL         3          10        0     NULL              1           0               0                0                 0              0
time                 41             41           4         NULL         5          16        7     NULL              1           0               0                0                 0              0
datetime2            42             42           4         NULL         8          27        7     NULL              1           0               0                0                 0              0
datetimeoffset       43             43           4         NULL         10         34        7     NULL              1           0               0                0                 0              0
tinyint              48             48           4         NULL         1          3         0     NULL              1           0               0                0                 0              0
smallint             52             52           4         NULL         2          5         0     NULL              1           0               0                0                 0              0
int                  56             56           4         NULL         4          10        0     NULL              1           0               0                0                 0              0
smalldatetime        58             58           4         NULL         4          16        0     NULL              1           0               0                0                 0              0
real                 59             59           4         NULL         4          24        0     NULL              1           0               0                0                 0              0
money                60             60           4         NULL         8          19        4     NULL              1           0               0                0                 0              0
datetime             61             61           4         NULL         8          23        3     NULL              1           0               0                0                 0              0
float                62             62           4         NULL         8          53        0     NULL              1           0               0                0                 0              0
sql_variant          98             98           4         NULL         8016       0         0     NULL              1           0               0                0                 0              0
ntext                99             99           4         NULL         16         0         0     Persian_100_CI_AI 1           0               0                0                 0              0
bit                  104            104          4         NULL         1          1         0     NULL              1           0               0                0                 0              0
decimal              106            106          4         NULL         17         38        38    NULL              1           0               0                0                 0              0
numeric              108            108          4         NULL         17         38        38    NULL              1           0               0                0                 0              0
smallmoney           122            122          4         NULL         4          10        4     NULL              1           0               0                0                 0              0
bigint               127            127          4         NULL         8          19        0     NULL              1           0               0                0                 0              0
hierarchyid          240            128          4         NULL         892        0         0     NULL              1           0               1                0                 0              0
geometry             240            129          4         NULL         -1         0         0     NULL              1           0               1                0                 0              0
geography            240            130          4         NULL         -1         0         0     NULL              1           0               1                0                 0              0
varbinary            165            165          4         NULL         8000       0         0     NULL              1           0               0                0                 0              0
varchar              167            167          4         NULL         8000       0         0     Persian_100_CI_AI 1           0               0                0                 0              0
binary               173            173          4         NULL         8000       0         0     NULL              1           0               0                0                 0              0
char                 175            175          4         NULL         8000       0         0     Persian_100_CI_AI 1           0               0                0                 0              0
timestamp            189            189          4         NULL         8          0         0     NULL              0           0               0                0                 0              0
nvarchar             231            231          4         NULL         8000       0         0     Persian_100_CI_AI 1           0               0                0                 0              0
nchar                239            239          4         NULL         8000       0         0     Persian_100_CI_AI 1           0               0                0                 0              0
xml                  241            241          4         NULL         -1         0         0     NULL              1           0               0                0                 0              0
sysname              231            256          4         NULL         256        0         0     Persian_100_CI_AI 0           0               0                0                 0              0
CalculatedCreditInfo 243            257          9         NULL         -1         0         0     NULL              0           1               0                0                 0              1
udt_QoutaDetail      243            258          21        NULL         -1         0         0     NULL              0           1               0                0                 0              1
BeforeUpdate         243            259          22        NULL         -1         0         0     NULL              0           1               0                0                 0              1
udt_StoreInventory   243            260          26        NULL         -1         0         0     NULL              0           1               0                0                 0              1
udt_WKFHistory       243            261          32        NULL         -1         0         0     NULL              0           1               0                0                 0              1
IDTable              243            262          1         NULL         -1         0         0     NULL

you can use max_length for size of each data type.

A: http://msdn.microsoft.com/en-us/library/ms187752.aspx
Money : 8 bytes
int : 4 bytes
id  - depends on what you mean.

A: If the table specified in the where clause contains a nvarchar, this query will give you how many characters there are for that column correctly!
This detects if the column is "wide" and essentially divides by 2. More broad than just nvarchar.
SELECT c.name, (CASE WHEN LEFT(ts.name, 1) = 'n' AND ts.[precision] = 0 AND ts.[scale] = 0 THEN c.max_length / ts.[bytes] ELSE c.max_length END) AS [length]
FROM sys.columns AS c
    INNER JOIN sys.tables AS t
        ON t.object_id = c.object_ID
    INNER JOIN
    (
        SELECT *, (CASE WHEN [bits] = -1 THEN -1 ELSE ([bits] + 7) / 8 END) AS [bytes]
        FROM (
            SELECT *, (CASE WHEN max_length >= 256 THEN (CASE WHEN LEFT(name, 1) = 'n' AND [precision] = 0 AND [scale] = 0 THEN 16 ELSE 8 END) ELSE max_length END) AS [bits]
            FROM sys.types AS iits
        ) AS its
    ) AS ts
        ON ts.user_type_id = c.user_type_id
WHERE t.name LIKE 'tb_tablename' -- LIKE is case insensitive

Of course, you can just divide max_length on sys.columns by 2 if you know the column is an nvarchar. This is more for discovering table schema in a way that seems better for if new sql data types are introduced in the future. And you so-choose to upgrade to it. Pretty small edge case.

Please edit and correct this answer if you find an edge case where
  bytes and bits are incorrect.

Details:
-- ([bits] + 7) / 8 means round up
--
-- Proof:
--   o  (1 bit + 7 = 8) / 8 = 1 byte used
--   o  ((8 + 8 + 1 = 17 bytes) + 7 = 24) / 8 = 3 byes used
--   o  ((8 + 8 + 7 = 23 bytes) + 7 = 30) / 8 = 3.75 = integer division removes decimal = 3
SELECT *, (CASE WHEN [bits] = -1 THEN -1 ELSE ([bits] + 7) / 8 END) AS [bytes]
FROM (
    SELECT *, (CASE WHEN max_length >= 256 THEN (CASE WHEN LEFT(name, 1) = 'n' AND [precision] = 0 AND [scale] = 0 THEN 16 ELSE 8 END) ELSE max_length END) AS [bits]
    FROM sys.types AS its
) AS ts

If someone knows that SQL Server stores the bit and byte sizes for each data type. Or a better way to get sys.columns size, please leave a comment!


Q: Why is my java animation taking up my entire CPU I made a program to display interference patterns for light waves. I did this by using the paint method on a JPanel to draw 2 sources and then drawing concentric circles around them. This would be double slit interference, so I allowed one of the sources to move around to experiment with the slit width.
The problem is that when I run this, my computer says it is using 80% of my CPU! There's really not much to it. Circle in the middle, circles around it, and it moves. My code follows.
main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class main {
static final int UP = -1;
static final int DOWN = 1;
static final int RIGHT = 1;
static final int LEFT = -1;
static final int NOMOVEMENT = 0;

static int verticalMovement = NOMOVEMENT;
static int horizontalMovement = NOMOVEMENT;
public static void main(String[] args) {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    Point s1 = new Point((int)(screenSize.getWidth()/3), 50);
    Point s2 = new Point((int)(2*screenSize.getWidth()/3), 50);

    JFrame frame = new JFrame("Physics Frame");
    frame.setPreferredSize(screenSize);

    PhysicsPane pane = new PhysicsPane(screenSize, 15, s1, s2);
    pane.setPreferredSize(screenSize);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(pane);
    frame.pack();

    Timer time = new Timer(1000 / 20, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            switch (verticalMovement){
                case UP:
                    s2.changeY(UP);
                    break;
                case DOWN:
                    s2.changeY(DOWN);
                    break;
                default:
                    break;
            }
            switch (horizontalMovement){
                case RIGHT:
                    s2.changeX(RIGHT);
                    break;
                case LEFT:
                    s2.changeX(LEFT);
                    break;
                default:
                    break;
            }
            pane.repaint();
        }
    });

    frame.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==37){
                horizontalMovement = LEFT;
            } else if (e.getKeyCode()==38){
                verticalMovement = UP;
            } else if (e.getKeyCode()==39){
                horizontalMovement = RIGHT;
            } else if (e.getKeyCode()==40){
                verticalMovement = DOWN;
            }

            if(e.getKeyChar()=='a'){
                pane.setWaveLength(2);
            }
            if(e.getKeyChar()=='s'){
                pane.setWaveLength(-2);
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            switch (e.getKeyCode()){
                case 37:
                    horizontalMovement = NOMOVEMENT;
                    break;
                case 38:
                    verticalMovement = NOMOVEMENT;
                    break;
                case 39:
                    horizontalMovement = NOMOVEMENT;
                    break;
                case 40:
                    verticalMovement = NOMOVEMENT;
                    break;
            }
        }
    });
    frame.setVisible(true);
    time.start();

}
}

Panel class. If there's an inefficiency with the drawing method, it would be here.
import javax.swing.*;
import java.awt.*;

public class PhysicsPane extends JPanel {
private Dimension size;
private Point[] pointArray = new Point[2];
private double waveLength;
public PhysicsPane(Dimension size, double wavelength, Point source1, Point source2) {
    this.size = size;
    pointArray[0] = source1;
    pointArray[1] = source2;
    setPreferredSize(size);
    this.waveLength = wavelength;
}

@Override
public void paintComponent(Graphics g){
    for (int i = 0; i < 2; i++) {
        g.setColor(Color.black);
        double x = this.pointArray[i].getX();
        double y = this.pointArray[i].getY();
        g.fillOval((int)x, (int)y, 2, 2);
        for (int j = (int)waveLength; j < 1500; j+=waveLength) {
            g.setColor(Color.red);
            g.drawOval((int)x-(j/2+1), (int)y-(j/2+1), 2 + j, 2 + j);
        }
    }
}

public void setWaveLength(double increment){
    this.waveLength+=increment;
}
}

Point Class: Really just puts x and y coordinates into one construct. Not important particularly
public class Point {
private double x;
private double y;

public Point(double x, double y) {
    this.x = x;
    this.y = y;
}

public double getX() {
    return x;
}

public void setX(double x) {
    this.x = x;
}

public double getY() {
    return y;
}

public void setY(double y) {
    this.y = y;
}

public void changeX(double dX){
    this.x+=dX;
}

public void changeY(double dY){
    this.y+=dY;
}
}

So what is wrong with my program? Why is such a simple animation consuming so much of my processor?
UPDATED CODE SECTION:
@Override
public void paintComponent(Graphics g){
    BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
    Graphics graphics = bi.getGraphics();
    for (int i = 0; i < 2; i++) {
        graphics.setColor(Color.black);
        double x = this.pointArray[i].getX();
        double y = this.pointArray[i].getY();
        graphics.fillOval((int)x, (int)y, 2, 2);
        for (int j = (int)waveLength; j < 1500; j+=waveLength) {
            graphics.setColor(Color.red);
            graphics.drawOval((int)x-(j/2+1), (int)y-(j/2+1), 2 + j, 2 + j);
        }
    }
    g.drawImage(bi, 0, 0, new ImageObserver() {
        @Override
        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
            return false;
        }
    });
}

A: The improvement that I recommend is removal of unnecessary tasks being performed, notably how your code updates the pane being drawn on, even when there aren't changes.
The following update reduced CPU usage from 12% to 0% (static frame):
Timer time = new Timer(1000 / 20, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {

        boolean refresh = false;

        switch (verticalMovement) {
        case UP:
            s2.changeY(UP);
            refresh = true;
            break;
        case DOWN:
            s2.changeY(DOWN);
            refresh = true;
            break;
        default:
            break;
        }

        switch (horizontalMovement) {
        case RIGHT:
            s2.changeX(RIGHT);
            refresh = true;
            break;
        case LEFT:
            s2.changeX(LEFT);
            refresh = true;
            break;
        default:
            break;
        }

        if (refresh == true) {
            pane.repaint();
        }
    }
});


Q: Use RankX function to calculate date rank per Fiscal Year per Entity ID I would like to use the RankX function (to use the Dense feature for ties) in order to rank the dates in a table per two columns: Fiscal Year and Entity ID.
(I guess it may be easier to concatenate the two columns and just sort by that but I'm having issues with my formula still)
Below is my sample data:

My invalid dax formula which returns all 1's is:
Fiscal Purchase Index =
VAR a = 'Purchases'[Purchase_Date]
VAR b = 'Purchases'[Entity_ID]
var c = 'Purchases'[FISCAL_YEAR]
RETURN
    CALCULATE (
        RANKX ('Purchases', a,,1,Dense ),
        FILTER (all('Purchases'),
            'Purchases'[Entity_ID] = b &&
            'Purchases'[FISCAL_YEAR] = c
        )
    )

Any help in fixing the rank formula would be very much appreciated.
Thank you

A: Use the following dax formula:
Fiscal Purchase Index =

VAR __entity = 'Purchases'[Entity ID]
var __year = 'Purchases'[FISCAL YEAR]
var __table = FILTER ( all('Purchases'), 'Purchases'[Entity ID] = __entity && 'Purchases'[FISCAL YEAR] = __year )

var __result =
RANKX(__table, Purchases[Date] ,, 1, Dense)

RETURN __result

Hope it helps.


Q: Rails ActiveRecord: List parent category and sub category from self-join table I want to return a list like the one below. All category records which have a parent. Displaying parent name and category name.
I'm using a self-join (self-associated?) model 'category' in which categories can be parents of other categories.
It works with the pure SQL just below, but how can I do it with ActiveRecord?
> sql="select p.name parent, s.name category from categories s join categories p on s.parent_id=p.id"
> ActiveRecord::Base.connection.execute(sql)

   (0.4ms)  select p.name parent, s.name category from categories s join categories p on s.parent_id=p.id
=>
[{"parent"=>"Income", "category"=>"Available next month"},
 {"parent"=>"Income", "category"=>"Available this month"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Fuel"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Groceries"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Restaurants"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Entertainment"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Household & Cleaning"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Clothing"},
 {"parent"=>"1. Everyday Expenses", "category"=>"MISC"},
 {"parent"=>"2. Monthly Expenses", "category"=>"Phone"},
 {"parent"=>"2. Monthly Expenses", "category"=>"Rent"},
 {"parent"=>"2. Monthly Expenses", "category"=>"Internet & Utilities"},
 {"parent"=>"2. Monthly Expenses", "category"=>"News Subscriptions"},
 {"parent"=>"2. Monthly Expenses", "category"=>"Car Registration"}]

I've been trying several queries. This appears to replicate my SQL closest, but returns nothing usable.
> Category.select('parents_categories.name as parent, categories.name as category').joins(:parent)

  Category Load (0.7ms)  SELECT parents_categories.name as parent, categories.name as category FROM "categories" INNER JOIN "categories" "parents_categories" ON "parents_categories"."id" = "categories"."parent_id"
=>
[#<Category:0x000055fefee12af0 id: nil>,
 #<Category:0x000055fefee12a28 id: nil>,
 #<Category:0x000055fefee12960 id: nil>,
 #<Category:0x000055fefee12898 id: nil>,
...

This was my other try, but I'm struggling with the syntax, and it just ignores the :parent['name'] phrase
> Category.select(:parent['name'],:name).joins(:parent).first

  Category Load (0.2ms)  SELECT "categories"."name" FROM "categories" INNER JOIN "categories" "parents_categories" ON "parents_categories"."id" = "categories"."parent_id" ORDER BY "categories"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<Category:0x000055feff38cd78 id: nil, name: "Available next month">

Schema
  create_table "categories", force: :cascade do |t|
    t.string "name", null: false
    t.integer "parent_id"
    ...
  end

Model
class Category < ApplicationRecord
  belongs_to :parent, class_name: "Category", optional: true
  has_many :subcategories, class_name: "Category", foreign_key: :parent_id
...
end

I can't find a matching example from the Rails guide here: https://guides.rubyonrails.org/active_record_querying.html
And stackoverflow questions like this (Unable to join self-joins tables in Rails) are close but not getting me across the finish line
UPDATE: I've found a convoluted answer from this website: https://medium.com/@swapnilggourshete/rails-includes-vs-joins-9bf3a8ada00
> c = Category.where.not(parent: nil).includes(:parent)
> c_data = [ ]
> c.each do |c|
      c_data << {
         parent: c.parent.name,
         category: c.name
      }
  end

[{:parent=>"Income", :category=>"Available next month"},
 {:parent=>"Income", :category=>"Available this month"},
 {:parent=>"1. Everyday Expenses", :category=>"Fuel"},
 {:parent=>"1. Everyday Expenses", :category=>"Groceries"},
 {:parent=>"1. Everyday Expenses", :category=>"Restaurants"},...]

But there must be a better way.

A: You are really close my friend. Just a little tweak and you will get what you are looking for
Category.select('parents_categories.name as parent_category, categories.name as category').joins(:parent).as_json(except: :id)

Note if you have belongs_to :parent, parent cannot be named as selected key so we need to change it to parent_category


Q: Rails initial page load extremely slow I've got a rails app in development mode (3.1.12 ruby 1.9.2) running on a windows server via fastcgi (with heliconzoo).
If i wait a certain amount of time from page load to page load, it takes 4-6 seconds to load the page. Afterwards it's loading with normal speed independent on which computer and in every browser.
Does the app/service shutdown if nobody visits the page within a while?
What can I do to prevent this behaviour?
e: For the first entry of today the development.log says it took 500ms to load the page which is 10 times faster...But it took 5s to load actually...


Q: Core Data table to NSArray I have the following Array which retrieved from the Core Data  :
NSArray *dataArray = [context executeFetchRequest:request error:&error];

so I wrote this code to get each row data individually to send it to REST API:
for (NSString *str in dataArray) {

        NSString *name =[dataArray valueForKey:@"name"];
        NSString *dob = [dataArray valueForKey:@"dob"];
        int gender =[[dataArray valueForKey:@"gender"]integerValue];
        NSString *childId =[dataArray valueForKey:@"id"];

         int response = [network sendName:name withDateOfBirth:dob andGender:gender forID:childId];

        if (response == 200) {
            // [self performSelectorOnMainThread:@selector(postSuccess) withObject:nil waitUntilDone:YES];
            NSLog(@"Success");

        }
    }

but it's not working, because I couldn't know how data is stored in each index in the array!!
Please help, and if I am not doing this correctly please tell me a better way to do it.
Thanks.

A: NSString *name =[dataArray valueForKey:@"name"];

This doesn't do what you think it'll do. valueForKey:, when sent to an array, returns an array of the values corresponding to the given key for all the items in the array. So, that line will assign an array of the "name" values for all the items in dataArray despite the fact that you declared name as a NSString. Same goes for the subsequent lines.
What you probably want instead is:
for (NSManagedObject *item in dataArray) {
    NSString *name = [item valueForKey:@"name"];
    ...

Better, if you have a NSManagedObject subclass -- let's call it Person representing the entity you're requesting, you can say:
for (Person *person in dataArray) {
    NSString *name = person.name;
    ...

which leads to an even simpler version:
for (Person *person in dataArray) {
    int response = [network sendName:person.name
                     withDateOfBirth:person.dob
                           andGender:person.gender
                               forID:person.id];

although I'd change the name of that method to leave out the conjunctions and prepositions. -sendName:dateOfBirth:gender:id: is enough, you don't need the "with", "and", and "for."


Q: actionListener associated with an h:commandLink/h:commandButton is not invoked I have a 2 forms that contain 4 buttons with each button having a an actionListener property set to call a single method in a request scoped bean. This method checks to determine what button is performing the action and then does a few things based on that information (Create, Read, Update, or Delete). The problem is that, out of these four buttons, three work. The last (update) button isn't calling the action.
This question helped a little bit as, after reading it, I managed to get the fourth button to work once (breakpoints and variable watching determined that) -- but then I stopped the program, made a small change because the page failed to not render a portion of the page (dependent of the 'editing' variable), watched it fail again, and then forgot what I did to make it work. I've determined that the problem is not nested forms, that I'm importing the right event class, that there are no validation errors, that there are no iterating tags, that the buttons are rendering and are not disabled, or any of the other points mentioned in @BalusC 's answer to that question except one -- when I use a <h:commandLink>, JS is rendered on the page that returns false although changing to a <h:commandButton> still fails to invoke the actionListener. But what's weird is that the one time is worked and the action was invoked I was using a <h:commandLink>.
Does anyone see what I'm doing wrong?
Form 1 (create; works):

    <h:head></h:head>

    <h:body>
        <ui:composition template="../../template.xhtml">
            <ui:define name="top">
                New Location View
            </ui:define>

            <ui:define name="left"></ui:define>

            <ui:define name="content">
                <f:view>
                    <h:form>

<h:outputText value="Create a Location"/>

                        <h:panelGrid columns="2">
                            <h:outputLabel for="locationName" value="Name:"/>
                            <h:inputText id="locationName" value="#{locationBean.locationName}"/>
                            <h:outputLabel for="locationDesc" value="Description:"/>
                            <h:inputText id="locationDesc" value="#{locationBean.locationDescription}"/>
                            <h:commandButton value="Add Location" id="createact" actionListener="#{locationBean.doAction}"/>
                        </h:panelGrid>
                    </h:form>
                </f:view>
            </ui:define>
        </ui:composition>
    </h:body>

Form 2 (Read (a details button clicked from a listing page which redirects to this one) works, Update; doesn't work, Delete; works):

    <h:head>

    </h:head>
    <h:body>
        <ui:composition template="../../../template.xhtml">
            <ui:define name="top">
                Location Details View
            </ui:define>

            <ui:define name="left">

            </ui:define>

            <ui:define name="content">
                <c:set var="location" value="#{locationBean.l}"/>

                <h:form>
                    <h:panelGrid columns="2" rendered="#{not locationBean.editing}" >
                        <h:outputLabel value="Name:"/>
                        <h:outputText  id="nameout" value="#{location.locationname}"/>
                        <h:outputLabel value="Description:" />
                        <h:outputText  id="descout" value="#{location.description}"/>
                        <h:commandButton id="delact"  actionListener="#{locationBean.doAction}" value="Delete"/>
                        <h:commandButton id="editact"  actionListener="#{locationBean.doAction}" value="Edit"/>
                    </h:panelGrid>
                    <h:panelGrid columns="2" rendered="#{locationBean.editing}">
                        <h:outputLabel value="Name:" />
                        <h:inputText   id="namein" value="#{location.locationname}" required="true" requiredMessage="There must be a name."/>
                        <h:outputLabel value="Description:" />
                        <h:inputText  id="descin" value="#{location.description}" required="true" requiredMessage="There must be a description."/>
                        <h:commandLink id="cancelact" actionListener="#{locationBean.doAction}" value="Cancel"/>
                        <h:commandLink id="saveact" actionListener="#{locationBean.doAction}" value="Save"/>
                    </h:panelGrid>
                    <h:inputHidden value="#{location.identifier}" id="viewid" />
                    <c:catch var="error">
                        <h:outputLabel value="#{error.message}" />
                    </c:catch>
                </h:form>
                <h:outputText value="will also show location hours and days open and employees at this location."/>
            </ui:define>
        </ui:composition>
    </h:body>

doAction method (called from all four buttons):
public void doAction(ActionEvent e) {
    String callingID = e.getComponent().getId();
    try {
        if (callingID.isEmpty()) {//id is empty
            FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
                    "What are you doing wrong? Actions must have a valid id.",
                    "Empty Strings are not a valid id."));
        } else if (callingID.endsWith("delact")) {//component id is delete
            this.l = lsb.getLocationToView();
            lsb.delete(l);
            FacesContext.getCurrentInstance().getExternalContext().redirect("/EmployeeScheduler-war/webpages/view/locations.xhtml");
        } else if (callingID.endsWith("editact")) {//component id is edit
            this.editing = true;
            this.l = lsb.getLocationToView();
        } else if (callingID.endsWith("saveact")) {//component id is save, usually after an edit action
            this.editing = false;
            lsb.edit(l);
        } else if (callingID.endsWith("cancelact")) {//component id is cancel. usuallys after edit action
            this.editing = false;
        } else if (callingID.endsWith("createact")) {//component id is create. always create a new location
            FacesContext.getCurrentInstance().getExternalContext().redirect("/EmployeeScheduler-war/webpages/view/locations.xhtml");
            lsb.create(l);
        } else if (callingID.endsWith("detailsact")) {//component id is details. alwas from list view
            this.l = lsb.getLocationToView();
        } else {
            FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
                    "What are you doing wrong? Actions must have a valid id.",
                    callingID + " is not not valid."));
        }
        //catch any failures
    } catch (RollbackFailureException ex) {
        FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
                "An error occured trying to rollback the deletion of the location: " + ex.getMessage(),
                "Details: " + ex.getCause().getMessage()));
    } catch (Exception ex) {
        FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
                "An error occured trying to delete the location: " + ex.getMessage(),
                "Details: " + (ex.getCause() == null ? "none" : ex.getCause().getMessage())));
    }
}

Template file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Employee Scheduler</title>
        <link href="resources/styles/main.css" rel="stylesheet" type="text/css"/>
        <ui:insert name="head"/>
    </h:head>

    <h:body style="margin-right:15%;margin-left:15%">

                    Welcome to the BMS Employee Scheduler

                    <h:form id="loginForm">
                        <h:panelGrid columns="2" cellspacing="2px" style="text-align: right">
                            <h:outputLabel for="usernameInput">
                                Username
                            </h:outputLabel>
                            <h:inputText disabled="#{login.loginDisabled}" id="usernameInput" value="#{login.username}"
                                         required="true" />
                            <h:outputLabel for="passwordInput">
                                Password
                            </h:outputLabel>
                            <h:inputSecret disabled="#{login.loginDisabled}" id="passwordInput" value="#{login.password}"
                                           required="true" />
                        <h:commandButton disabled="#{login.loginDisabled}" value="Login" action="#{login.login}" style="float: right"/>
                        </h:panelGrid>
                    </h:form>

                <ui:insert name="top"/>

                    <h:panelGrid columns="1" style="text-align: left">
                        <h:outputLink value="./index.xhtml" >Home</h:outputLink>
                        <h:outputLink value="./webpages/view/users.xhtml">Users</h:outputLink>
                        <h:outputLink value="./webpages/view/locations.xhtml">Locations</h:outputLink>
                        <ui:insert name="left" />
                    </h:panelGrid>

                    <ui:insert name="content" />

    </h:body>


Q: JavaScript document.write is not working Sorry if this seems dumb, i'm new to JavaScript.
This is in menu.js:
document.write("Home");
document.write("News");
document.write("About us");

This is in index.html:

When I load index.html, nothing comes up...

A: The problem is your quotes, you're using " both to delimit your new elements and to set their href attribute, change your code to:
document.write("Home");
document.write("News");
document.write("About us");

Or:
document.write('Home');
document.write('News');
document.write('About us');

Combining single (') and double (") quotes. You could also escape your internal quotes (document.write("Home");
BUT it'd be better to use a single call to document.write(), like this:
document.write('Home'
    + 'News'
    + 'About us');

A: You're not escaping the quotes in your strings.  It should be:
document.write("Home");

Otherwise, JavaScript thinks the string ends after href= and the rest of the line does not follow valid JavaScript syntax.
As @Felix mentioned, the JavaScript debugger tools will be extremely helpful in letting you know what's going on.


Q: turn bootstrap button into link with javascript and ajax I have a bootstrap button, that i have embedded into a form. The form requests a php file with ajax. But i Cant get the button to work like a link?
The html code is for the bootstrap button is :
Login

and the js is :

A: So do I get that correct that the link is supposed to send the form? That will not work, as a link on its own is not able to trigger a submit. You need an input of type submit.
<input type="submit" class="btn btn-success" value="Login">


Q: Dynamically updating string from one div to another I have a list of divs that contain a string in h3 format. Upon clicking these divs (they are all the same class) a screen is displayed (part of the same html doc) containing some sliders for user input.
Is there a way to make it so that when the screen is displayed it contains the string of whatever div was clicked? In other words, if the user taps/clicks the "Push Ups" card, I would like the div "#info" to update to shoe "push Ups", if the user selects "Iquats" I would like "#info" to show "Squats" ec.
I can't think of a way to do this without using JSON or some sort of server magic. CODE!
HTML:

Select Exercise

Push Ups

Dips

Burpees

Plank

Sit Ups

Leg Ups

Russian Twists

Back Raises

Time:

      <output id="timeValue">60 sec.</output>
      <input type="range" id="determineTime" step="10" value="60" min="0" max="180" />

Rest Time:

      <output id="restValue">10 sec.</output>
      <input type="range" id="determineRest" step="10" value="10" min="0" max="180" />

Add Break

JavaScript (jQuery)
  $(".exercise").click(function()
  {
    $("#specifier").css("display", "block");
    $(".backButton").css("display", "none");
  });

Thanks for any help and ideas given!

A: It would be preferable to create the elements programatically.
var arrExercises = ['Push Ups', 'Dips', 'Burpees'];//add all exercises here
arrExercises.forEach(function(exercise, i){
    var $exercise = $('
', {id:'div-excercise-'+i, "class":'exercise'});//create the exercise element
    //give the on click handler to the exercise
    $exercise.on('click', function(e){
        $("#specifier").css("display", "block");
        $(".backButton").css("display", "none");
        $("#info").text(exercise);//set the info to the exercise text
    });
    $('#exerciseContainer').append($exercise);//append this exercise to the container
});

A: If I understand you correctly, you can get the clicked element text by using $(this).text() inside the click event.

$(function() {
  $('.exercise').click(function() {
    $('#info').text($(this).text());
  });
});

Select Exercise

Push Ups

Dips

Burpees

Plank

Sit Ups

Leg Ups

Russian Twists

Back Raises

Time:

      <output id="timeValue">60 sec.</output>
      <input type="range" id="determineTime" step="10" value="60" min="0" max="180" />

Rest Time:

      <output id="restValue">10 sec.</output>
      <input type="range" id="determineRest" step="10" value="10" min="0" max="180" />

Add Break


Q: How to push into an existing session array , key and value in laravel With php I used
if (!isset($_SESSION['cart']) || !isset($_SESSION['cart'][$product])) {
    $_SESSION['cart'][$product] = 0;
    $_SESSION['cart'][$product] = $_SESSION['cart'][$product] + $product_quantity;

}else{
    $_SESSION['cart'][$product] = $_SESSION['cart'][$product] + $product_quantity;
}

I tried with put() but it's not working, cause every time I try to insert a new value it replace the first one
session()->put('cart',[request('variant_id') => request('quantity')]);

With push() I put inside the array cart another array with key and value
session()->push('cart',[request('variant_id') => request('quantity')]);

Is there a way to insert into session array with key and value cause right now I can't figure it out how to do it


Q: How to Display plain text of api result ( noob question ) I am completely new to api.
I want to display the plain text response of the output of this:
https://vurl.com/api.php?url=https://google.com
to my webpage html but it's not working.
My code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

$url = urlencode('https://google.com');
$api_url = 'vurl.com/api.php?url='.$url;
$arr_output = json_decode(file_get_contents($api_url), true);
document.write($arr_output);
</script>

Thanks

A: Not really sure why you're mixing javascript with your php code. Nevertheless, this is the approach you should follow:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

<?php
$url = urlencode("https://google.com");
$api_url = "vurl.com/api.php?url=".$url;
$arr_output = json_decode(file_get_contents($api_url), true);

echo $arr_output;
?>

</script>


Q: overlaying a div over three floats I need a bit of help overlaying a
 over 3 other
 elements which are styled float:left in their own container.
It looks like this now (http://i.imgur.com/2xk4tax.jpg) and i would like the text to overlay on top of the three floated colorlines.
Here's my hmtl/css any help would be appreciated.
HTML

hi

CSS
#introtextcontainer {
    margin: 0px auto 0px auto;
    width: 500px;
    height: 100px ;
    text-align:center;
    font-color: black;
    float:middle;
}

#linecontainer {
    margin: 0px auto 0px auto;
    width: 500px;
    height: 3000px ;
}

#line1 {
    width:160px;
    height:2000px;
    background-color: #00A7B0;
    float:left;
}

#line2 {
    width:160px;
    height:2000px;
    background-color: #D1DE3E;
    float:left;
}

#line3{
    width:160px;
    height:2000px;
    background-color: #DE006B;
    float:left;
}

A: By just adding position:absolute and width:100% to your introtextcontainer container it seems to work:
#introtextcontainer {
    margin: 0px auto 0px auto;
    height: 100px;
    text-align:center;
    font-color: black;
    position:absolute;
    width:100%;
}

jsFiddle example
Note that there is no such float:middle; property (left or right only).

A: You could also position:absolute the #linecontainer to slide up behind the text (I also centered it with left:50%; margin-left:- 0.5 * width ). You might have to give the text a position:relative; z-index:1; to force it on top.
#introtextcontainer {
    margin: 0px auto 0px auto;
    height: 100px;
    text-align:center;
    font-color: black;
    position:relative;
    width:100%;
    z-index:1;
}
#linecontainer {
    margin: 0 0 0 -250px;
    width: 500px;
    height: 3000px;
    position:absolute;
    top:0;
    left:50%;
}

Or even better, use a gradient generator, remove the 3 divs and make the bars a background: http://www.colorzilla.com/gradient-editor/
#introtextcontainer {
    margin: 0px auto 0px auto;
    height: 100px;
    text-align:center;
    font-color: black;
    position:absolute;
    width:100%;
    background: rgb(0,167,176); /* Old browsers */
    /* IE9 SVG, needs conditional override of 'filter' to 'none' */
    background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIzMyUiIHN0b3AtY29sb3I9IiMwMGE3YjAiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIzMyUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIzNCUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSI2NiUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSI2NiUiIHN0b3AtY29sb3I9IiNkZTAwNmIiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
    background: -moz-linear-gradient(left,  rgba(0,167,176,1) 33%, rgba(209,222,62,1) 33%, rgba(209,222,62,1) 34%, rgba(209,222,62,1) 66%, rgba(222,0,107,1) 66%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, right top, color-stop(33%,rgba(0,167,176,1)), color-stop(33%,rgba(209,222,62,1)), color-stop(34%,rgba(209,222,62,1)), color-stop(66%,rgba(209,222,62,1)), color-stop(66%,rgba(222,0,107,1))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(left,  rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(left,  rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* Opera 11.10+ */
    background: -ms-linear-gradient(left,  rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* IE10+ */
    background: linear-gradient(to right,  rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00a7b0', endColorstr='#de006b',GradientType=1 ); /* IE6-8 */

}