text:
Q: Java - how to reference a resource file from Java class I want to reference a resource file, which is a keystore file, inside a Java test class. This property is normally loaded from a properties file which points to the JDK running either locally or remotely.
When Maven executes a build as part of my deploy process it is first built on a build server. I want to be able place the keystore file on the classpath so i dont have to put a hard dependency on the build server (whereby i would place the keystore on the build server)
When i wire up the unit test locally it works fine with this configuration however this path fails when i execute the build on the build server. Can anyone shed some light on why this is failing? and what i can do to resolve? I think i know the why but clarification would be great.
Current configuration
<bean id="httpClient"
    class="myapp.HTTPClient">
    <property name="trustStoreLocation" value="..\\mywebapp\\target\\test-classes\\truststore" />
    <property name="trustStorePass" value="mypass" />
</bean>

A: For resource files, I prefer following the standard directory structure for Maven. Please read (http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html) for more reference. Placing a file like (.cfg or .jks or .properties) in src/test/resources and src/main/resources automatically makes the available in the class path upon build. Further, it give you the ability to isolate your test and main resource files.
For example, my pom.xml looks like this:
<build>
    <finalName>${project.artifactId}</finalName>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
        <resource>
            <directory>src/main/config</directory>
        </resource>
         <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/main/config</directory>
        </testResource>
         <testResource>
            <directory>src/main/resources</directory>
        </testResource>
    </testResources>

    <!-- Other pom.xml stuff -->

</build>

Now, a simple way to verify if your file has been copied properly is to tabulate the jar and check for the file you want.
mvn build

Then do:
jar -tf target/<your project jar>.jar | grep "<file name you want to verify>"


text:
Q: Avro schema evolution throwing EOFException while deserializing I have a no-sql db where I am storing serialized avro objects. I use sbt-avro plugin to generate java classes specifically addSbtPlugin("com.cavorite" % "sbt-avro-1-8" % "1.1.5"). Now I want to add new fields to the schema and also want backward compatibility with the data already present. But deserialization of old data using new schema is throwing java.io.EOFException
Old Schema:
{
  "name": "DNode",
  "namespace": "my.model",
  "type": "record",
  "fields": [
    {"name": "prev", "type": ["null", "string"]},
    {"name": "next", "type": ["null", "string"]}
  ]
}

New Schema:
{
  "name": "DNode",
  "namespace": "my.model",
  "type": "record",
  "fields": [
    {"name": "prev", "type": ["null", "string"]},
    {"name": "next", "type": ["null", "string"]},
    {"name": "size", "type": ["null", "long"], "default": null}
  ]
}

Deserialization code
  def deserialize(bytes: Array[Byte]) = {
    val reader = new SpecificDatumReader[DNode](classOf[DNode])
    val decoder = DecoderFactory.get().binaryDecoder(bytes, null)
    reader.read(null, decoder)
  }

Throws
java.io.EOFException
    at org.apache.avro.io.BinaryDecoder.ensureBounds(BinaryDecoder.java:473)
    at org.apache.avro.io.BinaryDecoder.readInt(BinaryDecoder.java:128)
    at org.apache.avro.io.BinaryDecoder.readIndex(BinaryDecoder.java:423)
    at org.apache.avro.io.ResolvingDecoder.doAction(ResolvingDecoder.java:290)
    at org.apache.avro.io.parsing.Parser.advance(Parser.java:88)
    at org.apache.avro.io.ResolvingDecoder.readIndex(ResolvingDecoder.java:267)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:179)
    at org.apache.avro.specific.SpecificDatumReader.readField(SpecificDatumReader.java:116)
    at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:222)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:175)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:145)
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Supernova Emoji library integration with socket.io chat app in Android I am making chat app in android through socket.io which includes recylerview/adapter & model class. I have also successfully added emoji library separately but i want to add emoji library & recyclerview on same activity. Can you guide me about how can I do it on same page(activity). Responses will be highly appreciated.
I am following these guides.
https://github.com/hani-momanii/SuperNova-Emoji
https://dev.to/medaymentn/creating-a-realtime-chat-app-with-android--nodejs-and-socketio-4o55

A:
Layout File for your Chat View

<?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/contentRoot1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorchatbg"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/contentRoot"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/layout_header"
                android:layout_width="match_parent"
                android:layout_height="?android:attr/actionBarSize"
                android:layout_alignParentTop="true"
                android:background="@color/voilacabs">

                <RelativeLayout
                    android:id="@+id/layout_back_arrow"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:paddingLeft="@dimen/margin_15"
                    android:paddingRight="@dimen/margin_15">

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:src="@drawable/back_arrow" />

                </RelativeLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="@dimen/margin_10"
                    android:layout_toRightOf="@+id/layout_back_arrow"
                    android:gravity="center_vertical"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/txt_username"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Username"
                        android:textColor="@color/white"
                        android:textSize="16dp" />

                    <TextView
                        android:id="@+id/txt_typing"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Typing..."
                        android:textColor="@color/white"
                        android:textSize="16dp"
                        android:visibility="gone" />
                </LinearLayout>

            </RelativeLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/messageRecyclerView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scrollbars="none" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="4dp"
                    android:layout_gravity="bottom"
                    android:background="@drawable/shadow_top" />
            </FrameLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#fff"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:padding="2dp">

                <ImageView
                    android:id="@+id/buttonEmoji"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentLeft="true"
                    android:padding="8dp"
                    android:src="@drawable/chat_smilly" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/buttonEmoji"
                    android:layout_weight="1">

                    <hani.momanii.supernova_emoji_library.Helper.EmojiconEditText
                        android:id="@+id/editTextMessage"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        app:emojiconSize="28sp" />

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/lauout"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_toRightOf="@+id/editTextMessage"
                    android:orientation="horizontal">

                    <ImageView
                        android:id="@+id/buttonMessage"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:padding="8dp"
                        android:src="@drawable/chat_send" />
                </LinearLayout>

            </LinearLayout>

        </LinearLayout>

        </LinearLayout>

    </android.support.design.widget.CoordinatorLayout>

Your Activity Code is like

private EmojIconActions emojIcon;

edMessage = (EmojiconEditText) findViewById(R.id.editTextMessage);
btEmoji = (ImageView) findViewById(R.id.buttonEmoji);

emojIcon = new EmojIconActions(this, contentRoot, edMessage, btEmoji);
                emojIcon.ShowEmojIcon();


text:
Q: returning address in C Why this code is giving unexpected output.
int * func(int *xp)
{
    int y = 10 + *xp;
    return (&y);
}
void main()
{
    int x = 10;
    int *xp = func(&x);
    printf("%d\n", x);
    printf("%d\n", *xp);
}

expected output:
10
20

Real Output:
10
1074194112

A: Because y goes out of scope when function returns. Remember, y was declared on the stack. This is an undefined behavior.

A: < real_life_example >
Imagine you put an apple on the table. You then write down it's position on a piece of paper.
Later, someone comes and takes the apple. The position on the piece of paper now makes no sense.
< /real_life_example >

A: You are returning a pointer to a variable (y) that goes out of scope the moment you leave func. This is undefined behaviour.
It is not entirely clear what you're trying to achieve, but there are several ways to fix this:

*

*return the int by value;

*modify *xp in place and don't return anything;

*take an additional int* parameter and store the result in there (again returning void);

*allocate memory on the heap using malloc or new and return that (the caller would be responsible for correctly freeing that memory).

It is impossible to say which of the above are applicable to your problem without knowing the broader context.
Lastly, main() should return int (thanks @pmg for spotting this). This is not related to the problem you're having but is worthing pointing out.

A: Returning the address of a local variable and then derefencing it causes undefined behavior.
Since the printf calls use the same memory (stack) region that func uses, they overwrite the stack frame of func with their own internal variables and function arguments.
To solve this problem, allocate memory on the heap with malloc:
int* func (int *xp) {
  int* res = malloc(sizeof(int));
  if (!res) {
    perror('Cannot allocate memory in func');
    exit(1);
  }
  *res = 10 + *xp;
  return res;
}

Don't forget to free it:
int main(void) {
    int x = 10;
    int *xp = func(&x);
    printf("%d\n", x);
    printf("%d\n", *xp);
    free(xp);
    return 0;
}

A: func should look like this:
// C++
int* func(int* xp)
{
    int* y = new int;
    *y = 10 + *xp;
    return y;
}

A: As everyone mentioned already, you are trying to return the address of a temporary variable.  What nobody has mentioned is the easiest solution.  Cast the variable as static inside the function.  This makes it remain in memory for the entirety of the program.
int * func(int *xp)
{
    static int y;
    y = 10 + *xp;
    return (&y);
}
void main()
{
    int x = 10;
    int *xp = func(&x);
    printf("%d\n", x);
    printf("%d\n", *xp);
}

This works as expected.  Of course there are better ways to go about this, but this is the simplest solution if you indeed want to declare a variable inside the scope of a function, and return it's address.  Keep in mind, every time this function is called, it modifies y, it doesn't give you a copy.


text:
Q: Postfix email server sending in junk folder I'm trying to configure a mail server with Ubuntu 14.04 (Postfix+ dovecot, hostname=idcmail.idc.healthcare) but my emails are being received in recipient's spam folders. I know there are many answers to this question but I have tried almost everything according to answers to no avail. I've done following steps

*

*PTR record is set for domain

*SPF record is set in DNS

*DKIM is configured

*IP address is checked for black list via spamhaus but it is also clear.

*Abuse address is configured at abuse.net

The email headers I am receiving in my Gmail email box says that my SPF and DKIM is passed. Below is the header
    Delivered-To: umair.naqvi73@gmail.com
Received: by 10.79.72.1 with SMTP id v1csp1761228iva;
        Sun, 13 Mar 2016 04:34:08 -0700 (PDT)
X-Received: by 10.98.34.205 with SMTP id p74mr21651199pfj.93.1457868848225;
        Sun, 13 Mar 2016 04:34:08 -0700 (PDT)
Return-Path: <bobby@idc.healthcare>
Received: from idcmail.idc.healthcare (115-186-155-204.nayatel.pk. [115.186.155.204])
        by mx.google.com with ESMTPS id l9si8897121pfb.158.2016.03.13.04.34.07
        for <umair.naqvi73@gmail.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Sun, 13 Mar 2016 04:34:07 -0700 (PDT)
Received-SPF: pass (google.com: domain of bobby@idc.healthcare designates 115.186.155.204 as permitted sender) client-ip=115.186.155.204;
Authentication-Results: mx.google.com;
       spf=pass (google.com: domain of bobby@idc.healthcare designates 115.186.155.204 as permitted sender) smtp.mailfrom=bobby@idc.healthcare;
       dkim=pass header.i=@idc.healthcare
Received: from [192.168.8.4] (unknown [39.47.91.89])
    (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits))
    (No client certificate requested)
    by idcmail.idc.healthcare (Postfix) with ESMTPSA id D3C1C80D36;
    Sun, 13 Mar 2016 04:33:30 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple; d=idc.healthcare;
    s=dkim; t=1457868812;
    bh=6imp6PpJMW+8Q5OtYGkLm8HP7ihBSc3AC9SAqXIvKYc=;
    h=To:Cc:From:Subject:Date:From;
    b=XaNuuKJ5/rdtcvDuTZKCaNUfluHOFeJgn7m2O6KfZ2gfEI7/ztVMd61b3Bvx3WUZO
     zbLc8vt4UMaaWe5C4c5DqikNjqJ3VSmFqkzFdeS2pkv9e3F+n7LZ+wnINjAUHWFJsU
     bfiq7KpVI9MWveOCAuTbsg4DLluxTBhNrYGvGykY=
To: ab.sattar@idc.net.pk
Cc: rizwanuppal@hotmail.com, doctoruppal@hotmail.com, rizwanuppal@idc.net.pk,
 arfan.qadir@live.com, umair.naqvi73@gmail.com, umair@acetechnologies.biz
From: bobby <bobby@idc.healthcare>
Subject: Email server
Message-ID: <56E55008.1040309@idc.healthcare>
Date: Sun, 13 Mar 2016 16:33:28 +0500
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101
 Thunderbird/38.6.0
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="------------010202010701020208060102"

This is a multi-part message in MIME format.
--------------010202010701020208060102
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit

Dig command returns with following details
; <<>> DiG 9.9.5-3ubuntu0.8-Ubuntu <<>> idc.healthcare
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37910
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;idc.healthcare.                        IN      A

;; ANSWER SECTION:
idc.healthcare.         583     IN      A       115.186.155.204

;; Query time: 2 msec
;; SERVER: 192.168.1.4#53(192.168.1.4)
;; WHEN: Mon Mar 21 09:40:41 PKT 2016
;; MSG SIZE  rcvd: 59

MX record test returns following details from MX record Tester
I also tried to test my email for spam using different free services but somehow my email does not delivered to the temporary email addresses provided by these services, however, for gmail, yahoo, hotmail it is working. One of the returned messages to one such service is
Reporting-MTA: dns; idcmail.idc.healthcare
X-Postfix-Queue-ID: 2B41380CF5
X-Postfix-Sender: rfc822; bobby@idc.healthcare
Arrival-Date: Sun, 13 Mar 2016 15:25:24 +0500 (PKT)

Final-Recipient: rfc822; web-Y8ogB7@mail-tester.com
Original-Recipient: rfc822;web-Y8ogB7@mail-tester.com
Action: failed
Status: 4.4.1
Diagnostic-Code: X-Postfix; connect to mail-tester.com[94.23.206.89]:25:
    Connection timed out

Here my server can ping the IP mentioned in the returned email header i.e. 94.23.206.89.
My current MX record entries are below and i am receiving emails
10  @   @   1 Hour
30  smtp    @   1 Hour
0   smtp.idcmail    @   1 Hour

Previously i tried with following MX records from which i was receiving emails too
10  @   @   1 Hour
30  @   smtp    1 Hour
0   @   smtp.idcmail    1 Hour

There must be something i am missing. Any help would be highly appreciated.
UPDATE: After configuring DKIM, SPF and IP not in black list what else could have been done to avoid emails going in spam. It is a test server and no lists have been sent to audience.
Update: My reverse DNS is also ok but why am i not able to send to testing services such as mail-tester.com etc but i can send to gmail, yahoo or hotmail (though in spam). It always has a timeout message in logs but i can ping to these address successfully.
    Mar 24 19:58:36 idcmail postfix/qmgr[987]: D059481247: from=<bobby@idc.healthcare>, size=755, nrcpt=1 (queue active)
Mar 24 19:59:06 idcmail postfix/smtp[1796]: connect to mail.isnotspam.com[74.208.174.205]:25: Connection timed out
Mar 24 19:59:36 idcmail postfix/smtp[1796]: connect to mx01.1and1.com[74.208.5.21]:25: Connection timed out
Mar 24 20:00:06 idcmail postfix/smtp[1796]: connect to mx00.1and1.com[74.208.5.3]:25: Connection timed out
Mar 24 20:00:06 idcmail postfix/smtp[1796]: D059481247: to=<ins-f1vtzbop@isnotspam.com>, relay=none, delay=696, delays=606/0.02/90/0, dsn=4.4.1, status=deferred (connect to mx00.1and1.com[74.208.5.3]:25: Connection timed out)
Mar 24 20:03:36 idcmail postfix/qmgr[987]: 12D2A81258: from=<bobby@idc.healthcare>, size=755, nrcpt=1 (queue active)
Mar 24 20:04:06 idcmail postfix/smtp[1799]: connect to mail-tester.com[94.23.206.89]:25: Connection timed out
Mar 24 20:04:06 idcmail postfix/smtp[1799]: 12D2A81258: to=<web-BqH7aD@mail-tester.com>, relay=none, delay=531, delays=501/0.02/30/0, dsn=4.4.1, status=deferred (connect to mail-tester.com[94.23.206.89]:25: Connection timed out)

A: your reverse dns for your MX is mismarch. I check via mxtoolbox. I attach the screen capture.enter image description here


text:
Q: How to make 2 websites to speak to each other I'm have 2 websites hosted on localhost with different ports and I'm trying to make first one only to send data and second one only to receive that data. Earlier, I made that happens with only one website. User could login, and logged users could change data and that data would be emitted to all other users. Users which aren't logged could just view page. But there were so many problems. Taking that a part would fix some problems. I'm trying to do all this without back-end experience and knowledge just watching some videos and pasting code, and I'm sorry about that, I know this is wrong. I figured out some things but I can't make it work. So here is my terrible code:
This is node.js code for website which will send data
var express = require("express");

var app = express();
var server = app.listen(3000);
app.use(express.static('public'));
var socket = require("socket.io");
var io = socket(server);
io.sockets.on('connection', newConnection);

function newConnection(socket)
{
  console.log('Connection: ' + socket.id);
  socket.on('data', dataMsg);
  function dataMsg(data)
  {
    socket.broadcast.emit('data', data);
  }
}

This is javascript code for website which will send data which works fine
Btw functions press1(), press2() etc. are called from html by clicking certain buttons
let ps = 2.5;
let bl = 3.5;
const socket = io('http://localhost:3000');
function update(data)
{
  buttons[0].time = data.btn11;
  buttons[0].price = data.btn12;
  buttons[1].time = data.btn21;
  buttons[1].price = data.btn22;
  buttons[2].time = data.btn31;
  buttons[2].price = data.btn32;
  buttons[3].time = data.btn41;
  buttons[3].price = data.btn42;
}

let buttons = [];
buttons[0] = new Button(ps);
buttons[1] = new Button(ps);
buttons[2] = new Button(ps);
buttons[3] = new Button(bl);

let arr = [];
arr[0] = [document.getElementById("prviprvi"), document.getElementById('prvidrugi')];
arr[1] = [document.getElementById('drugiprvi'), document.getElementById('drugidrugi')];
arr[2] = [document.getElementById('treciprvi'), document.getElementById('trecidrugi')];
arr[3] = [document.getElementById('cetvrtiprvi'), document.getElementById('cetvrtidrugi')];

var tempD = setInterval( () => {
  var data = {
    btn11 : buttons[0].time,
    btn12 : buttons[0].price,
    btn21 : buttons[1].time,
    btn22 : buttons[1].price,
    btn31 : buttons[2].time,
    btn32 : buttons[2].price,
    btn41 : buttons[3].time,
    btn42 : buttons[3].price
  }
  socket.emit("data", data);
  for(var i = 0; i < 4; i++)
  {
    buttons[i].update();
    buttons[i].show(arr[i][0], arr[i][1]);
  }
},100);

function press1()
{
  buttons[0].press();
}

function press2()
{
  buttons[1].press();
}

function press3()
{
  buttons[2].press();
}

function press4()
{
  buttons[3].press();
}

function Button(tempD1)
{
  this.val = tempD1;
  this.pressed = false;
  this.startingTime = Date.now();
  this.endingTime = Date.now();
  this.hours = 0;
  this.min = 0;
  this.sec = 0;
  this.price = 0;
  this.time = "0:0:0";

  this.show = function(span1, span2)
  {
    span1.innerHTML = this.time;
    span2.innerHTML = this.price + " Din";
  }

  this.update = function()
  {
    if(this.pressed)
    {
      this.endingTime = Date.now();
      this.tempD = this.endingTime - this.startingTime;
      this.sec = parseInt((this.tempD / 1000) % 60);
      this.min = parseInt(((this.tempD / 1000) / 60) % 60);
      this.hours = parseInt((((this.tempD / 1000) / 60) / 60) % 24);
      this.time = this.hours + ":" + this.min + ":" + this.sec;
      this.price = this.hours * 60 * this.val + this.min * this.val;
    }
  }

  this.press = function()
  {
    if(this.pressed == false)
    {
      this.startingTime = Date.now();
      this.pressed = true;
    }
    else
    {
      this.pressed = false;
    }
  }
}

This is node.js for website which receiving data
  var express = require("express");

    var app = express();
    var server = app.listen(3001);
    app.use(express.static('public'));
    var socket = require("socket.io");
    var io = socket('localhost:3000');
    io.sockets.on('connection', newConnection);

    function newConnection(socket)
    {
      console.log('Connection: ' + socket.id);
      socket.on('data', dataMsg);
      function dataMsg(data)
      {
        socket.broadcast.emit('data', data);
      }
    }

This is javascript code for website which receiving data
let ps = 2.5;
let bl = 3.5;
const socket = io('http://localhost:3000');
socket.on('data', update);
function update(data)
{
  buttons[0].time = data.btn11;
  buttons[0].price = data.btn12;
  buttons[1].time = data.btn21;
  buttons[1].price = data.btn22;
  buttons[2].time = data.btn31;
  buttons[2].price = data.btn32;
  buttons[3].time = data.btn41;
  buttons[3].price = data.btn42;
}

var tempD = setInterval( () => {
  for(var i = 0; i < 4; i++)
    buttons[i].show(arr[i][0], arr[i][1]);
}
let buttons = [];
buttons[0] = new Button(ps);
buttons[1] = new Button(ps);
buttons[2] = new Button(ps);
buttons[3] = new Button(bl);

let arr = [];
arr[0] = [document.getElementById("prviprvi"), document.getElementById('prvidrugi')];
arr[1] = [document.getElementById('drugiprvi'), document.getElementById('drugidrugi')];
arr[2] = [document.getElementById('treciprvi'), document.getElementById('trecidrugi')];
arr[3] = [document.getElementById('cetvrtiprvi'), document.getElementById('cetvrtidrugi')];

function Button(tempD1)
{
  this.val = tempD1;
  this.pressed = false;
  this.startingTime = Date.now();
  this.endingTime = Date.now();
  this.hours = 0;
  this.min = 0;
  this.sec = 0;
  this.price = 0;
  this.time = "0:0:0";

  this.show = function(span1, span2)
  {
    span1.innerHTML = this.time;
    span2.innerHTML = this.price + " Din";
  }

  this.update = function()
  {
    if(this.pressed)
    {
      this.endingTime = Date.now();
      this.tempD = this.endingTime - this.startingTime;
      this.sec = parseInt((this.tempD / 1000) % 60);
      this.min = parseInt(((this.tempD / 1000) / 60) % 60);
      this.hours = parseInt((((this.tempD / 1000) / 60) / 60) % 24);
      this.time = this.hours + ":" + this.min + ":" + this.sec;
      this.price = this.hours * 60 * this.val + this.min * this.val;
    }
  }

  this.press = function()
  {
    if(this.pressed == false)
    {
      this.startingTime = Date.now();
      this.pressed = true;
    }
    else
    {
      this.pressed = false;
    }
  }
}

Asking this may be too much but I will do it anyway:
How to allow access to the one which sends data with just the right password.
When user go to website he will be asked for password and if he type right one, he will be forwarded further. I did it last time in javascript but anyone could just go to inspect elements and see password
Thank you!


text:
Q: Ошибка You have an error in your SQL syntax Здесь была огромная простыня кода и скриншот, которые не имеют никакого отношения к SQL-ошибке. Из-за этого собственно ошибки были не видны. Проблемный код и текст ошибки оставлены (@Khvorostin)
<?php

  $pos = mysql_query( "SELECT `признак_посещения`
                        WHERE 'фио_студента' == $stud_array[$f]
                          AND 'имя_работы'   == $work_array[$t] ")
         or die( mysql_error() );
?>

выдает
> You have an error in your SQL syntax;
> check the manual that corresponds to
> your MySQL server version for the
> right syntax to use near 'where
> 'фио_студента'==Исаев Алексей and
> 'имя_раб' at line 1

A: 'фио_студента'==Исаев Алексей

*

*не ==, а =

*текст не закавычен

Общее замечание. Не стыдно такой говнокод показывать?

*

*echo где не надо, дикая смесь HTML, PHP и SQL

*несколько запросов к БД в рамках одной страницы, SQL-запросы в цикле

*SQL-запросы типа SELECT * FROM

*бардак в оформлении - кривые отступы, отстутствие единства в оформлении кода: первый запрос вынесен в отдельую переменную, три другие - нет

*Кое-как составленные таблицы, потерянные теги <tr>, незакртые теги, вложенные таблицы там, где это не нужно.

все это, как минимум, неуважение к тем, кто видит ваш код.
Попробуйте сделать так:

*

*Единственный запрос к БД.

*Обработка данных, результаты складываются в массив.

*Вывод результатов. Максимум HTML, минимум PHP (только foreach..., никаких echo)

A: Формально говоря, такое будет работать.
Но любой человек, знакомый с базами данных, будет плеваться на этот код: обращение к базе данных стоит «дорого» (то есть, забирает много времени и ресурсов системы). Поэтому лучше сделать один запрос, который выдаст вам сразу все нужные данные, и потом уж разобрать его в ваши структуры данных.


text:
Q: Generate coefficient array from general formula of linear equation system This is a problem coming out in the implementation of finite difference method (FDM).
Here is a toy example. Suppose we want to solve the boundary value problem (BVP)
$$y''(x)=\sin(x),\ y(0)=0,\ y(1)=0$$
eq = y''[x] == Sin[x];
bc = {y[0] == 0, y[1] == 0};

with FDM, then we can program as follows. First, write down the corresponding difference formula:
Clear@dx;
generalformula = (y[x + dx] - 2 y[x] + y[x - dx])/dx^2 == Sin[x];

Then define the grid size and generate difference equations at every grid point:
points = 25; domain = {0, 1};
dx = Subtract @@ domain/(1 - points);
var = Table[y[x], {x, ##, dx}] & @@ domain;
differenceeq = Table[generalformula, {x, domain[[1]] + dx, domain[[-1]] - dx, dx}]~Join~bc;

Finally solve the difference equations with e.g. NSolve:
solrule = NSolve[differenceeq, var][[1]]; // AbsoluteTiming
(* {0.00462427, Null} *)

BTW, a comparision with the analytic solution:
asol = DSolveValue[{eq, bc}, y, x]
Plot[asol[x], {x, ##}, PlotRange -> All]~Show~
   ListPlot[solrule[[All, -1]], DataRange -> {##}] & @@ domain

Alternatively, we can extract the coefficient array from differenceeq and solve it with LinearSolve, as illustrated in the document of CoefficientArrays. This approach is faster than the one using NSolve:
{barray, marray} = CoefficientArrays[differenceeq, var]; // AbsoluteTiming
(* {0.000614324, Null} *)
sol = LinearSolve[marray // N, -barray]; // AbsoluteTiming
(* {0.000488251, Null} *)

However, this isn't the end. As already mentioned, we've generated difference equation at every grid point and then extract the coefficient array from the symbolic system in the code above. This procedure can be rather memory-demanding and slow when points is large. Is it possible to generate barray and marray directly from generalformula and bc programatically, in a memory-conserving and not-that-slow way?

If the toy example above is too simple to illustrate the underlying problem, the following is a more complicated one attempting to solve the problem mentioned here:
r = .8; glass = (1.45)^2; air = 1.; k = (2 π)/1.55;
n2 = Function[{x, y}, #] &@If[x^2 + y^2 <= r^2, glass, air];
ClearAll[fw, bw, delta]
SetAttributes[#, HoldAll] & /@ {fw, bw};

fw@D[expr_, x_] :=
 With[{Δ = delta@ToString@x},
  Subtract @@ (expr /. {{x -> x + Δ}, {x -> x}})/Δ]
bw@D[expr_, x_] :=
 With[{Δ = delta@ToString@x},
  Subtract @@ (expr /. {{x -> x}, {x -> x - Δ}})/Δ]

delta[a_ + b_] := delta@a + delta@b
delta[k_. delta[_]] := 0
grad = Function[expr, fw@D[expr, #] & /@ {x, y}];
div = Function[expr, Total@MapThread[bw@D@## &, {expr, {x, y}}]];
elst = e[#][x, y] & /@ Range[2];
discretelhs =
  With[{n2 = n2[x, y]},
   div@grad@elst + (n2 k^2) elst - grad[div@elst - 1/n2 div[n2 elst]]] // FullSimplify;
points = 100; L = 2; domain = {-L, L}; grid = Array[# &, points, domain];
del = #[[2 ;; -2]] &;
delta["x"] = delta["y"] = -Subtract @@ domain/(points - 1);
vare = Outer[e[#][#2, #3] &, Range@2, del@grid, del@grid, 1] // Flatten;
discretelhslst =
   Flatten@Transpose[
     Table[discretelhs, {x, del@grid}, {y, del@grid}], {2, 3, 1}]; // AbsoluteTiming
{barray2, marray2} = CoefficientArrays[discretelhslst, vare]; // AbsoluteTiming
{val, vec} =
   Eigensystem[marray2, -6,
    Method -> {"Arnoldi", "Shift" -> k^2 glass}]; // AbsoluteTiming
mat = ArrayReshape[#, {2, points - 2, points - 2}] & /@ vec;
MapThread[ArrayPlot[#[[1]], PlotLabel -> Sqrt@#2, PlotRange -> All,
   ColorFunction -> "AvocadoColors"] &, {mat, val}]

ByteCount[marray2]/1024^2. "MB"
(* 1.60567 "MB" *)

ByteCount[discretelhslst]/1024^2. "MB"
(* 44.9877 "MB" *)

The corresponding problem is, how to arrive at marray2 from discretelhs without generating discretelhslst, in an efficient enough way?

A: To compare code @xzczd and @b3m2a1, I took a simplified version of the 2D operator from the topic here and 300x300 cells. I simplified code @xzczd  a little, so it works 3 times faster. Code  @b3m2a1, on the contrary, I complicated a little, so that it works 30 times faster. As a result, they now work equally fast and produce the same output.
Code @xzczd
r = .8; glass = (1.45)^2; air = 1.; k = (2 \[Pi])/1.55;
n2[x_, y_] := If[x^2 + y^2 <= r^2, glass, air];
ClearAll[fw, bw, delta]
SetAttributes[#, HoldAll] & /@ {fw, bw};

fw@D[expr_, x_] :=
 With[{\[CapitalDelta] = delta@ToString@x},
  Subtract @@ (expr /. {{x -> x + \[CapitalDelta]}, {x ->
         x}})/\[CapitalDelta]]
bw@D[expr_, x_] :=
 With[{\[CapitalDelta] = delta@ToString@x},
  Subtract @@ (expr /. {{x -> x}, {x ->
         x - \[CapitalDelta]}})/\[CapitalDelta]]

delta[a_ + b_] := delta@a + delta@b
delta[k_. delta[_]] := 0
grad = Function[expr, fw@D[expr, #] & /@ {x, y}];
div = Function[expr, Total@MapThread[bw@D@## &, {expr, {x, y}}]];
elst = e[#][x, y] & /@ Range[1];
discretelhs =
  With[{n2 = n2[x, y]}, div@grad@elst + (k^2*n2 ) elst] //
   FullSimplify;
points = 302; L = 2; domain = {-L, L}; grid =
 Array[# &, points, domain];
del = #[[2 ;; -2]] &;
delta["x"] = delta["y"] = -Subtract @@ domain/(points - 1);
vare = Outer[e[#][#2, #3] &, Range@1, del@grid, del@grid, 1] //
   Flatten;
discretelhslst =
   Flatten@Transpose[
     Module[{e}, e[i_][L | -L, _] = e[i_][_, L | -L] = 0.;
      Table[discretelhs, {x, del@grid}, {y, del@grid}]], {2, 3,
      1}]; // AbsoluteTiming
{barray2, marray2} =
   CoefficientArrays[discretelhslst, vare]; // AbsoluteTiming
{val, vec} =
   Eigensystem[marray2, -4,
    Method -> {"Arnoldi", "Shift" -> k^2 glass}]; // AbsoluteTiming
mat = ArrayReshape[#, {2, points - 2, points - 2}] & /@ vec;
MapThread[
 ArrayPlot[#[[1]], PlotLabel -> Sqrt@#2, PlotRange -> All,
   ColorFunction -> "AvocadoColors"] &, {mat, val}]

Code  @b3m2a1
fdmWeightDataND~SetAttributes~HoldAll;
fdmWeightDataND[a_, dep_Symbol, indeps : {__Symbol},
   hs : {__Symbol}] :=
  Block[{dep},
   Block[indeps,
    Block[hs,
     Module[{weights, order, denomWeight, denom, num, powed, pows,
       minpow, pts, x}, denom = Denominator[a];
      (*assumes the mesh spacing is in there at different powers*)
      order = Exponent[denom, #] & /@ hs;
      (*pull the power on the mesh spacing*)
      denomWeight = If[order > 0, Coefficient[denom, hs^order], denom];
      num = Numerator[a];
      {powed, pows} =
       Reap[num /.
         dep[args___]?(Not@*FreeQ[Alternatives @@ indeps]) :>
          dep @@ Sow[MapThread[Coefficient[#, #2] &, {{args}, hs}]]];
      minpow = Min[pows];
      weights =
       AssociationThread[pows[[1]],
        Map[Coefficient[powed /. (dep @@ #) -> x, x] &, pows[[1]]]];
      <|"Weights" -> weights, "Orders" -> order|>]]]];

FDM2D[weightData_, {hx_, hy_}, {nptsx_, nptsy_}] :=
 Module[{xps, yps, weights = weightData["Weights"],
   orders = weightData["Orders"]},
  xps = Length@DeleteDuplicates@Keys[weights][[All, 1]];
  yps = Length@Sort@DeleteDuplicates@Keys[weights][[All, 2]];
  SparseArray[
    Flatten@KeyValueMap[
      With[{ix = #[[1]], iy = #[[2]], v = #2},
        Map[Band[
            If[ix >= 0, {1, 1 + ix}, {1 - ix, 1}] + {#, #} +
             If[iy >= 0, {0, iy*nptsx}, {-iy*nptsx, 0}], {nptsx*nptsy,
              nptsx*nptsx}, {nptsx, nptsx}] -> v &,
         Range[nptsx - Abs[ix]] - 1]] &, weights], {nptsx*nptsy,
     nptsx*nptsx}]/(Times @@ ({hx, hy}^orders))]

ClearAll[fw, bw, delta]
SetAttributes[#, HoldAll] & /@ {fw, bw};

fw@D[expr_, x_] :=
 With[{\[CapitalDelta] = delta@ToString@x},
  Subtract @@ (expr /. {{x -> x + \[CapitalDelta]}, {x ->
         x}})/\[CapitalDelta]]
bw@D[expr_, x_] :=
 With[{\[CapitalDelta] = delta@ToString@x},
  Subtract @@ (expr /. {{x -> x}, {x ->
         x - \[CapitalDelta]}})/\[CapitalDelta]]

delta[a_ + b_] := delta@a + delta@b
delta[k_. delta[_]] := 0
grad = Function[expr, fw@D[expr, #] & /@ {x, y}];
div = Function[expr, Total@MapThread[bw@D@## &, {expr, {x, y}}]];
elst = e[#][x, y] & /@ Range[1];
baseDiscreteLHS = Together[div@grad@elst];
prepped = (baseDiscreteLHS[[1]]) //. {e[1] -> e1, delta["y"] -> dy,
    delta["x"] -> dx};
weightsE1 = {fdmWeightDataND[prepped, e1, {x, y}, {dx, dy}]};
mate1 = Block[{sp1, spRules, points = 300, dx, dy},
    dx = 4./(points + 1); dy = 4./(points + 1);
    sp1 = FDM2D[#, {dx, dy}, {points, points}] & /@ weightsE1 // Total;
    spRules =
     MapThread[# -> With[{x = #[[1]]*dx, y = #[[2]]*dy}, #2] &, {sp1[
        "NonzeroPositions"], sp1["NonzeroValues"]}];
    SparseArray[spRules, Dimensions[sp1]]]; // AbsoluteTiming
r = .8; glass = (1.45)^2; air = 1.; k = (2 \[Pi])/1.55;
n2[x_, y_] := If[x^2 + y^2 <= r^2, glass, air]; discretelhs =
 With[{n2 = n2[x, y]}, (k^2*n2) elst];
points1 = 302; L = 2; domain = {-L, L}; grid =
 Array[# &, points1, domain];
del = #[[2 ;; -2]] &;
delta["x"] = delta["y"] = -Subtract @@ domain/(points1 - 1);
vare = Outer[e[#][#2, #3] &, Range@1, del@grid, del@grid, 1] //
   Flatten;
discretelhslst =
  Flatten@Transpose[
    Module[{e}, e[i_][L | -L, _] = e[i_][_, L | -L] = 0.;
     Table[discretelhs, {x, del@grid}, {y, del@grid}]], {2, 3, 1}];
{barray2, marray2} =
   CoefficientArrays[discretelhslst, vare]; // AbsoluteTiming
points = 300; {val, vec} =
  Eigensystem[mate1 + marray2, -4,
   Method -> {"Arnoldi", "Shift" -> k^2*glass}]; // AbsoluteTiming
mat = ArrayReshape[#, {2, points, points}] & /@ vec;
MapThread[
 ArrayPlot[#[[1]], PlotLabel -> Sqrt[#2], PlotRange -> All,
   ColorFunction -> "AvocadoColors"] &, {mat, val}]

Finally, compare with my method that I suggested for this problem here using FEM:
<< NDSolve`FEM`
r = 0.8; ne = 4;
reg = ImplicitRegion[-2 <= x <= 2 && -2 <= y <= 2, {x, y}];
mesh = ToElementMesh[reg,
   MeshRefinementFunction ->
    Function[{vertices, area},
     area > 0.0004 (1 + 9 Norm[Mean[vertices]])]];

glass = 1.45; air = 1.; k0 = (2 \[Pi])/1.55; b = I*Sqrt[glass]*k0*1.37;
n[R_] := If[R <= r, glass^2, air^2]*k0^2

helm = -Laplacian[u[x, y], {x, y}] - (b^2 + n[Sqrt[x^2 + y^2]])*
    u[x, y];
boundary = DirichletCondition[u[x, y] == 0, True];

{vals, funs} =
     NDEigensystem[{helm, boundary}, u[x, y], {x, y} \[Element] mesh,
    ne]; // AbsoluteTiming
Table[DensityPlot[Im[funs[[i]]], {x, y} \[Element] mesh,
  PlotRange -> All,
    PlotLabel -> Im[Sqrt[vals[[i]] + b^2]], Mesh -> None,
  ColorFunction -> "AvocadoColors", Frame -> True, Axes -> False,
  FrameTicks -> None], {i, Length[vals]}]

Comparing the data in Figure 1-3, we find that there is an eigenvalue match in methods FDM and FEM. The small difference can be explained by the difference in the number of cells.

A: I'd like to add my incomplete answer. I call it incomplete because a general-purposed function hasn't been created (yet), but I do find a general strategy for handling the problem.
The idea is simple: generate coefficient array of general difference formula with CoefficientArray first, then generate the complete array using the general coefficients.
I'll solve the 2D problem in the question for illustration. delta, discretelhs etc. are the same as in the question.
sfx = Rescale[#, {x, x + delta@"x"}, {nx, nx + 1}] &;
sfy = Rescale[#, {y, y + delta@"y"}, {ny, ny + 1}] &;
rule = e[i_][x_, y_] :> {i, sfx@x // Simplify, sfy@y // Simplify};
varegeneral = Union@Cases[discretelhs, e[_][__], Infinity];
index = {i, nx, ny, ##} & @@@ (varegeneral /. rule);
coelst = Last@CoefficientArrays[discretelhs, varegeneral];
marrayfast =
   Flatten[SparseArray[
      Flatten[#,
          3] &@(Unevaluated@
            Compile[{},
             Table[term, {i, 2}, {nx, 2, pts - 1}, {ny, 2, pts - 1}]] /. {term -> index,
            pts -> points})[] -> (Flatten[#,
           3] &@(Unevaluated@
             Compile[{}, Table[lst[[i]], {i, 2}, {x, dgrid}, {y, dgrid}]] /. {dgrid ->
              del@grid,
             lst -> (Normal@coelst /. {HoldPattern@glass -> glass,
                 HoldPattern@air -> air})})[]), {2, points, points, 2, points,
       points}][[All, 2 ;; -2, 2 ;; -2, All, 2 ;; -2, 2 ;; -2]], {{1, 2, 3}, {4, 5,
      6}}]; // AbsoluteTiming

MaxMemoryUsed[]/1024^2. MB

marrayfast == marray2
(* True *)

{val, vec} =
   Eigensystem[marrayfast, -6,
    Method -> {"Arnoldi", "Shift" -> k^2 glass}]; // AbsoluteTiming

MaxMemoryUsed[]/1024^2. MB

mat = ArrayReshape[#, {2, points - 2, points - 2}] & /@ vec;
MapThread[ArrayPlot[#[[1]], PlotLabel -> Sqrt@#2, PlotRange -> All,
   ColorFunction -> "AvocadoColors"] &, {mat, val}]

When points = 500, it only takes 5.63068 seconds to generate marrayfast, while 53.4027 + 19.1697 to generate marray2.
Memory usage is also reduced, but the real bottleneck seems to be Eigensystem, so perhaps it's not a big deal.

A: Partial ND
It's possible to again extract all this weight data and stuff in the higher dimensional cases using effectively the same procedure as for the 1D:
fdmWeightDataND~SetAttributes~HoldAll;
fdmWeightDataND[a_, dep_Symbol, indeps : {__Symbol}, hs : {__Symbol}] :=

  Block[{dep}, Block[indeps, Block[hs,
     Module[{weights, order, denomWeight, denom, num, powed, pows, minpow,
       pts, x}, denom = Denominator[a];
      (*assumes the mesh spacing is in there at different powers*)

      order = Exponent[denom, #] & /@ hs;
      (*pull the power on the mesh spacing*)

      denomWeight = If[order > 0, Coefficient[denom, hs^order], denom];
      num = Numerator[a];
      {powed, pows} =
       Reap[
        num /.
         dep[args___]?(Not@*FreeQ[Alternatives @@ indeps]) :>
          dep @@
           Sow[
            MapThread[
             Coefficient[#, #2] &,
             {
              {args},
              hs
              }
             ]
            ]
        ];
      minpow = Min[pows];
      weights =
       AssociationThread[
        pows[[1]],
        Map[Coefficient[powed /. (dep @@ #) -> x, x] &, pows[[1]]]
        ];
      <|
       "Weights" -> weights,
       "Orders" -> order
       |>
      ]
     ]
    ]
   ];

This is less automate-able, though, since you need to specify what your f, independent variables, and mesh spacings are. Also without knowing how you'd like to flatten your nD tensor of grid points it's impossible to automatically build the FD matrix. But at a minimum I can give you weights and indices for the weights:
(*didn't want to Wikipedia the nine-point stencil so most of this is fake*)

simpleFormula = (
    f[x - xh, y] + f[x + xh, y] +
     f[x, y - yh] + f[x, y + yh] - 4 f[x, y] +
     1/2 f[x + xh, y - yh] + 1/2 f[x - xh, y - yh] +
     1/2 f[x + xh, y + yh] + 1/2 f[x - xh, y + yh]
    )/(xh^2*yh^2);

weights2D = fdmWeightDataND[simpleFormula, f, {x, y}, {xh, yh}]

<|"Weights" -> <|{0, 0} -> -4, {0, -1} -> 1, {0, 1} -> 1, {-1, 0} ->
    1, {-1, -1} -> 1/2, {-1, 1} -> 1/2, {1, 0} -> 1, {1, -1} -> 1/2, {1, 1} ->
     1/2|>, "Orders" -> {2, 2}|>

Basically now you'd pick how to order your grid points and build a matrix from that. Here's one way to do this based on having the second index be the slowest moving (note that I'm only like 50% confident I built this correctly):
FDM2D[weightData_, {hx_, hy_}, {nptsx_, nptsy_}] :=

 Module[{xps, yps, weights = weightData["Weights"],
   orders = weightData["Orders"]},
  xps = Length@DeleteDuplicates@Keys[weights][[All, 1]];
  yps = Length@Sort@DeleteDuplicates@ Keys[weights][[All, 2]];
  SparseArray[
    Flatten@
     KeyValueMap[
      With[{ix = #[[1]], iy = #[[2]], v = #2},
        Map[
         Band[
            If[ix >= 0, {1, 1 + ix}, {1 - ix, 1}] + {#, #} +
             If[iy >= 0, {0, iy*nptsx}, {-iy*nptsx, 0}],
            {nptsx*nptsy, nptsx*nptsx},
            {nptsx, nptsx}
            ] -> v &,
         Range[nptsx - Abs[ix]] - 1
         ]
        ] &,
      weights
      ],
    {nptsx*nptsy, nptsx*nptsx}
    ]/(Times @@ ({hx, hy}^orders))
  ]

Here's what that outputs:
FDM2D[weights2D, {1, 1}, {5, 5}] // MatrixPlot

In the case of no coupling across degrees of freedom this looks correct I believe... (but can't be sure since I usually do my Laplacian via a Kronecker sum):
laplacian = (
    f[x - xh, y] + f[x + xh, y] +
     f[x, y - yh] + f[x, y + yh] - 4 f[x, y]
    )/(xh^2*yh^2);

FDM2D[fdmWeightDataND[laplacian, f, {x, y}, {xh, yh}], {1, 1}, {10,
   10}] // MatrixPlot

Full Thing for 1D
Here's a method that automates this extraction for 1D FDM stuff:
fdmWeightData~SetAttributes~HoldAll;
fdmWeightData[Equal[a_, b_], dep : {__Symbol}, indep : {__Symbol}] :=
  fdmWeightData[a, dep, indep];
fdmWeightData[a_, dep_Symbol, indep_Symbol, h_Symbol] :=

  Block[{dep, indep, h},
   Module[{weights, order,
     denomWeight, denom,
      num, powed, pows,
     minpow, pts
     },
    denom = Denominator[a];
    (* assumes the mesh spacing is in there *)

    order = Exponent[denom, h];
    (* pull the power on the mesh spacing *)

    denomWeight = Coefficient[ denom, h^order];
    num = Numerator[a];
    {powed, pows} =
     Reap[
      num /.
       dep[expr_?(Not@*FreeQ[indep])] :>
        dep[Sow@Coefficient[expr, h]]
      ];
    minpow = Min[pows];
    powed = powed /. dep[n_] :> dep^(n - minpow);
    weights = (CoefficientList[powed, dep])/denomWeight;
    pts = Exponent[powed, dep, List] + minpow;
    <|
     "Weights" -> weights,
     "Points" -> pts,
     "Order" -> order
     |>
    ]
   ];
fdmWeightData[Equal[expr_, b_]] :=
  fdmWeightData[expr];
fdmWeightData[expr_] :=
  Module[
   {
    vars = Variables[expr],
    dep,
    indep,
    h
    },
   h = FirstCase[vars, _Symbol];
   {dep, indep} =
    Replace[
     FirstCase[vars, a_Symbol[b_Symbol] :> {a, b}, None],
     None :>
      a_Symbol[e_] :> FirstCase[e, Except[h, _Symbol], None, Infinity]
     ] ;
   With[
    {dep = dep, indep = indep, h = h},
    fdmWeightData[expr, dep, indep, h]
    ]
   ];

fdmWeightData[(y[x + dx] - 2 y[x] + y[x - dx])/dx^2 == Sin[x]]

<|"Weights" -> {1, -2, 1}, "Points" -> {-1, 0, 1}, "Order" -> 2|>

Here's a helper on that:
fdmMat[weights_List, pts_List, order_List, h_, n_] :=
  SparseArray[
   MapThread[
    If[# >= 0,
      Band[{1, # + 1}] -> #2,
      Band[{-# + 1, 1}] -> #2
      ] &,
    {pts, weights/(h^order)}
    ],
   {n, n}
   ];
fdmMat[a_Association, h_, n_] :=

  fdmMat[Sequence @@ Lookup[a, {"Weights", "Points", "Order"}], h, n];
fdmMat[a_Association _, n_] :=
  fdmMat[a, 1, n];
FDMMatrix[a_Association][n_, h_: 1] :=
  fdmMat[a, h, n];
FDMMatrix[expr : Except[_Pattern | _Association]] :=

 FDMMatrix[fdmWeightData[expr]]
FDMMatrix[expr_, dep_, indep_, h_] :=

 FDMMatrix[fdmWeightData[expr, dep, indep, h]]

fdmat = FDMMatrix[(y[x + dx] - 2 y[x] + y[x - dx])/dx^2]

FDMMatrix[<|"Weights" -> {1, -2, 1}, "Points" -> {-1, 0, 1}, "Order" -> 2|>]

Then we can make the matrix fast:
fdmat[100] // MatrixPlot

Doing the nD extension will take a bit of thought, though.
Partial Solution to Actual Problem
I'm not sure how your actual problem works, but here's a way we can try to build an FD matrix for it using this stuff. The main thing we'll do is break it down into portions with the same dx and dy terms after doing some symbolic pre-simplification. Here's my new setup (same as yours but entirely symbolic):
Clear[r, glass, air, k]
n2 = (Function[{x, y}, #] &@(Simplify`PWToUnitStep@
      PiecewiseExpand@If[x^2 + y^2 <= r^2, glass, air]));
ClearAll[fw, bw, delta]
SetAttributes[#, HoldAll] & /@ {fw, bw};

fw@D[expr_, x_] :=
 With[{\[CapitalDelta] = delta@ToString@x},
  Subtract @@ (expr /. {{x -> x + \[CapitalDelta]}, {x -> x}})/\[CapitalDelta]]
bw@D[expr_, x_] :=
 With[{\[CapitalDelta] = delta@ToString@x},
  Subtract @@ (expr /. {{x -> x}, {x -> x - \[CapitalDelta]}})/\[CapitalDelta]]

delta[a_ + b_] := delta@a + delta@b
delta[k_. delta[_]] := 0
grad = Function[expr, fw@D[expr, #] & /@ {x, y}];
div = Function[expr, Total@MapThread[bw@D@## &, {expr, {x, y}}]];
elst = e[#][x, y] & /@ Range[2];
baseDiscreteLHS =
  With[{n2 = n2[x, y]},
   div@grad@elst + (n2 k^2) elst - grad[div@elst - 1/n2 div[n2 elst]]];

Now I'll prep this stuff so it's in a form my code can use cleanly:
prepped =
  (baseDiscreteLHS[[1]]) //. {
     e[1] -> e1,
     e[2] -> e2,
     delta["y"] -> dy,
     delta["x"] -> dx,
     UnitStep[r^2 - x^2 - y^2] -> usxy,
     UnitStep[r^2 - x^2 - (-dy + y)^2] -> usxdy,
     UnitStep[r^2 - (dx + x)^2 - y^2] -> usdxy,
     UnitStep[r^2 - (dx + x)^2 - (-dy + y)^2] -> usdxdy,
     UnitStep[r^2 - (-dx + x)^2 - y^2] -> usdxmdy
     } // FullSimplify;

Now I'll use this stuff to pull the FD weights just for e1 from the first of the two equations provided:
weightsE1 =
  {
   fdmWeightDataND[prepped[[1]], e1, {x, y}, {dx, dy}],
   fdmWeightDataND[prepped[[2]], e1, {x, y}, {dx, dy}],
   fdmWeightDataND[prepped[[3]], e1, {x, y}, {dx, dy}],
   fdmWeightDataND[prepped[[4]], e1, {x, y}, {dx, dy}],
   fdmWeightDataND[
    Simplify[Collect[prepped[[6]] // Expand, dx][[1]]],
    e1,
    {x, y},
    {dx, dy}
    ],
   fdmWeightDataND[
    Simplify[Collect[prepped[[8]] // Expand, dx][[1]]],
    e1,
    {x, y},
    {dx, dy}
    ]
   };

Then I'll build all the matrices, add them together, and numericize everything:
mate1 =
 Block[
  {
   r = .8, glass = (1.45)^2, air = 1., k = (2 \[Pi])/1.55,
   sp1, spRules, points = 25,
   dx, dy
   },
  dx = 1./points; dy = 1/points;
  sp1 = FDM2D[#, {dx, dy}, {points, points}] & /@ weightsE1 // Total;
  spRules =
   MapThread[
    # ->
      With[{x = #[[1]]*dx, y = #[[2]]*dy},
       #2 /.
        {
         usxy -> UnitStep[r^2 - x^2 - y^2],
         usxdy -> UnitStep[r^2 - x^2 - (-dy + y)^2],
         usdxy -> UnitStep[r^2 - (dx + x)^2 - y^2],
         usdxdy -> UnitStep[r^2 - (dx + x)^2 - (-dy + y)^2],
         usdxmdy -> UnitStep[r^2 - (-dx + x)^2 - y^2]
         }
       ] &,
    {
     sp1["NonzeroPositions"],
     sp1["NonzeroValues"]
     }
    ];
  SparseArray[spRules, Dimensions[sp1]]
  ]

Finally we can solve this using your same Eigensystem code:
Block[{r = .8, glass = (1.45)^2, air = 1., k = (2 \[Pi])/1.55, points = 25},
  {val, vec} =
   Eigensystem[mate1, -6, Method -> {"Arnoldi", "Shift" -> k^2 glass}
    ];
  mat = ArrayReshape[#, {2, points - 2, points - 2}] & /@ vec;
  MapThread[
   ArrayPlot[#[[1]], PlotLabel -> Sqrt@#2, PlotRange -> All,
     ColorFunction -> "AvocadoColors"] &,
   {mat, val}
   ]
  ] // AbsoluteTiming

The results are meaningless since I just randomly took part of the problem, but this entire procedure was fast and not memory intensive at all.


text:
Q: Select from database based on multiple occurrences in junction table Could you help me with finding the right way of selecting from database some data – based on multiple occurrence in junction table?
Im using Sequelize ORM, but plain SQL also would be ok. Query should be dynamic – based on users input. Although, even static solution would be very helpful at this point.
I will use some example to better describe problem which im facing here:
I have two tables – lets say one for orders, and second for products (Order, Product).
Every order can contain multiple products, every product can be related with multiple orders. I made in sequelize Many to Many relationshop between those tables using order_product (OrderProduct) as junction table (which contains some additional fields other then IDs of order and product – e.g. amount of product):
Order.belongsToMany(Product, { through: OrderProduct });
Product.belongsToMany(Order, { through: OrderProduct });

My question is – how can i get from database all orders wchich contains – for example – product of ID = 1, AND product of ID = 2, AND product of ID = 3?
What will be most elegant solution using Sequelize or plain SQL?
I experiment with include statment in Sequelize, but i failed at using this correctly in this case.
On the other hand many 'EXISTS' statement in plain SQL (one after another) would be probably far too expensive?
Thanks!

A: In SQL, you would have a bridging table called something like OrderProducts.  Then you can use aggregation and having:
select op.orderId
from orderProducts op
where op.productId in (1, 2, 3)
group by op.orderId
having count(*) = 3;  -- number of product

If a product can be in an order multiple times, then use:
having count(distinct op.productId) = 3


text:
Q: My modal content does't show until i inspect the browser Modal without inspecting

Modal After inspect the browser window

A: Its working fine in codepen link: https://codepen.io/kalaiselvan/pen/POKyKw

 $('#exampleModal').on('show.bs.modal', function(e) {
      $(window).resize();
      $(window).resize();
    });
    $('#lightSlider').lightSlider({
      gallery: true,
      item: 1,
      loop: true,
      slideMargin: 0,
      thumbItem: 9
    });
 .demo {
      width: 450px;
    }

    ul {
      list-style: none outside none;
      padding-left: 0;
      margin-bottom: 0;
    }

    li {
      display: block;
      float: left;
      margin-right: 6px;
      cursor: pointer;
    }

    img {
      display: block;
      height: auto;
      max-width: 100%;
    }
 <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/lightslider/1.1.3/css/lightslider.min.css" rel="stylesheet" />

    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
      Launch demo modal
    </button>

Modal title

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
            </button>

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>


text:
Q: Applying functions to multiple lists I'm trying to run some basic statistics (and deeper ones later) on a data frame that has categorical variables for sales.  In addition to sales, it tracks things like area (where the merchant is located), the day of the week, the time of the day (Lunch, After Work, etc), and various other things.
Here is a small, random subset of the data: (Note that this is a basic representation- the actual data frame has 38 columns- I just took most of the non-applicable ones out)
    structure(list(dayofweek = structure(c(4L, 7L, 3L, 7L, 3L, 2L,
2L, 7L, 3L, 3L, 2L, 7L, 5L, 5L, 2L, 5L, 1L, 3L, 7L, 3L, 4L, 1L,
3L, 5L, 7L), .Label = c("Friday", "Monday", "Saturday", "Sunday",
    "Thursday", "Tuesday", "Wednesday"), class = "factor"), timeofday = structure(c(6L,
4L, 5L, 5L, 2L, 6L, 6L, 5L, 6L, 3L, 6L, 3L, 5L, 4L, 1L, 3L, 5L,
6L, 5L, 4L, 6L, 6L, 3L, 2L, 5L), .Label = c("After Work", "Early AM",
     "Evening", "Late AM", "Lunch", "MidAfternoon", "Overnight"), class = "factor"),
 area = c(6L, 4L, 4L, 5L, 5L, 1L, 4L, 2L, 3L, 2L, 7L, 3L,
 7L, 5L, 7L, 4L, 1L, 4L, 1L, 4L, 5L, 7L, 1L, 3L, 7L), totsales = c(40,
 6, 5, 10, 1, 0, 0, 3, 5, 3, 10, 30, 2, 1, 2, 22, 8, 1, 1,
 5, 11, 20, 0, 1, 5)), .Names = c("dayofweek", "timeofday",
     "area", "totsales"), class = "data.frame", row.names = c(192278L,
     140773L, 121051L, 157984L, 154299L, 258034L, 108031L, 43760L,
     78005L, 42103L, 95603L, 98431L, 30252L, 165303L, 40713L, 108252L,
     304549L, 137041L, 268473L, 124599L, 161253L, 12897L, 240815L,
     89439L, 21032L))

The first thing I am doing is trying to get the mean and median sales in each area and at each time of day.  I would like to have R go through a list of each and return all the values.  I tried this:
vallist<-list(a= c("Early AM", "Late AM", "Lunch", "MidAfternoon", "After Work",
         "Evening", "Overnight"),
          b= c(1,2,3,4,5,6,7))

sapply(vallist[['b']], function(x)
    mapply(function(a,b) mean(data$totsales[which(data$timeofday==a & data$area==b)]),
          vallist[['a']], vallist[['b']])
 )

But, it only applies the mean to each timeofday segment in area 1, not each time of day segment in areas 1-7.  So, my results look like this:
                  [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
Early AM      9.192847  9.192847  9.192847  9.192847  9.192847  9.192847  9.192847
Late AM       8.020678  8.020678  8.020678  8.020678  8.020678  8.020678  8.020678
Lunch        10.096277 10.096277 10.096277 10.096277 10.096277 10.096277 10.096277
MidAfternoon 11.503961 11.503961 11.503961 11.503961 11.503961 11.503961 11.503961
After Work    8.206124  8.206124  8.206124  8.206124  8.206124  8.206124  8.206124
Evening      11.457599 11.457599 11.457599 11.457599 11.457599 11.457599 11.457599
Overnight    11.415667 11.415667 11.415667 11.415667 11.415667 11.415667 11.415667

which are the correct answers for Area 1, but you can see they are the same values for each area.  How do I get R to apply the function to multiple lists and return all the combinations of values?
The next steps will be to apply medians, and to evaluate at district levels and for different weekdays, but I assume the same idea will apply to all of the different combinations.

A: For this particular case you can reproduce your result with:
library(reshape2)
dcast(data[-1], timeofday ~ area, fun.aggregate=mean, fill=0)

which produces:
     timeofday   1 2  3    4  5  6    7
1   After Work 0.0 0  0  0.0  0  0  2.0
2     Early AM 0.0 0  1  0.0  1  0  0.0
3      Evening 0.0 3 30 22.0  0  0  0.0
4      Late AM 0.0 0  0  5.5  1  0  0.0
5        Lunch 4.5 3  0  5.0 10  0  3.5
6 MidAfternoon 0.0 0  5  0.5 11 40 15.0

I'm pretty sure the discrepancy from your result is due to the data you posted being as subset of the whole.

A: Converting my comment to an answer....
It seems like you might be interested in aggregate (though there are many ways to aggregate data in R).
out <- aggregate(totsales ~ timeofday + area, data, mean)
out
#       timeofday area totsales
# 1       Evening    1      0.0
# 2         Lunch    1      4.5
# 3  MidAfternoon    1      0.0
# 4       Evening    2      3.0
# 5         Lunch    2      3.0
# 6      Early AM    3      1.0
# 7       Evening    3     30.0
# 8  MidAfternoon    3      5.0
# 9       Evening    4     22.0
# 10      Late AM    4      5.5
# 11        Lunch    4      5.0
# 12 MidAfternoon    4      0.5
# 13     Early AM    5      1.0
# 14      Late AM    5      1.0
# 15        Lunch    5     10.0
# 16 MidAfternoon    5     11.0
# 17 MidAfternoon    6     40.0
# 18   After Work    7      2.0
# 19        Lunch    7      3.5
# 20 MidAfternoon    7     15.0

If you want to go from there to a wide format, you can then use reshape (like: reshape(out, direction = "wide", idvar="timeofday", timevar="area")).


text:
Q: How to display associated objects from database using rails after a doing filter firstly i do a filter for my object Folder , after having the result of this filter i get the objects @folders.
i can display all attributes of the table Folder but i don't know how to display otehr information existing in ther table who is associated to the table folder Folder.
this is my model :
Folder model :
class Folder < ActiveRecord::Base
  paginates_per 15
  default_scope { order('folders.created_at desc') }
  .....
  has_one :technical_detail, class_name: 'Folders::TechnicalDetail', foreign_key: 'folder_id', dependent: :destroy, inverse_of: :folder
DechnicalDetail model :
class Folders::TechnicalDetail < ActiveRecord::Base
  belongs_to :folder, class_name: '::Folder', inverse_of: :technical_detail
so the related object to Folder is Technical detalis , how to display attribute from technicaldetails table after doing a filter
the colntroller of the filter : `  def search
    params[:search] ||= {}
if params[:search][:created_at_start].present? && params[:search][:created_at_end].present?
  @folders = ::Folder.filter(params[:search]).where('created_at BETWEEN ? AND ?', params[:search][:created_at_start], params[:search][:created_at_end]).where(town_id: permitted_towns)
else
  @folders = ::Folder.filter(params[:search]).where(town_id: permitted_towns)
end

end`
the filter is working good and i have the object folder as a result, now how can i display technicaldetails information , i display data in a table

A: when you get @folders it's meaning collection of folders (couple of records) you must select one record of @folders first then you can display attributes for other related tables
here is the sample
@first_folder = @folders.first
@first_folder.technical_detail.attribute_name

or you can loop it
@folders.each do |folder|
  if folder.technical_detail
    folder.technical_detail.attribute_name
  end
end

your can check it first before print the attribute, the if statement above if folder.technical_detail meaning it's checking whether technical_detail is nil / not if not then it will continue print the attribute_name, but if it nil it will skip the record


text:
Q: Is it possible to have a multilanguage Environnement in SQL Server 2008 ide is it possible to install another interface language to SQL Server 2008 Management Studio?
Im not talking about programming language but changing the interface language from English to French (or others). In Visual Studio, i can do it by installing the english and the french version of the product and then, in the option of Visual Studio, i can go to the Environnement Language and change from English to French.
Can i do the same with SQL Server 2008 Management Studio?

A: No.
[BTW, what other language did you have in mind?  If you want to use LINQ to query, download LINQPad]


text:
Q: is there any way to import NULLS to mySQL inside of single quotes? I'm using VBA that encloses every field with single quotes in order to import into mySQL and noticed that every variation I tried on NULL for numeric data types imported as 0.  If I drop the backticks the nulls import fine, so I think my question boils down to this: if there any way to indicate NULL data inside of single quotes in a mySQL import?
this website shows a bunch of examples, but nothing inside of single quotes.
thanks!

A: If the string inside the single quotes is escaped, too, then there is no way of making it NULL. That would negate the purpose of quotes+escaping.
If it is not escaped, you could "break out" of the single quotes with a single quote. For example if you store the string '/0+' it will become ''/0+'' (say: empty string divided by zero plus empty string) which is NULL because anything divided by zero is NULL.


text:
Q: How to use R to reshape multiple rows to separate columns - long to wide? I have the following df,
ID  event   eventdate1     date2       date3        date4     date5  index1   index2   index3
1   before               1/22/2020
1   now                              10/20/2017   10/25/2017
1   later   03/02/2020                                                  0         1        0
1   tomo    05/05/2020                                                  0         0        0

I would like to reshape this to wide and the expected output is,
ID    date2     eventdate1      date3      date4       date5   index1   index2   index3
1   1/22/2020   05/05/2020   10/20/2017   10/25/2017             0         0        0

The eventdate1 is related to event.

eventdate1 will  always print the last date, i.e for tomo.

It's the same for index1, index2 and index3. All the other dates will have just one date in column.

date5 is empty and i hope to keep it empty

I hope to use reshape but any other method would work too.

A: With dplyr you can try :
library(dplyr)

df %>%
  group_by(ID) %>%
  summarise(across(eventdate1:index3, ~{
                  x <- .[.!='']
                  if(length(x)) last(x) else ''
                  })) -> result

result

#     ID eventdate1 date2     date3      date4      date5 index1 index2 index3
#  <int> <chr>      <chr>     <chr>      <chr>      <chr> <chr>  <chr>  <chr>
#1     1 05/05/2020 1/22/2020 10/20/2017 10/25/2017 ""    0      0      0

For older version of dplyr use :
df %>%
  group_by(ID) %>%
  summarise_at(vars(eventdate1:index3), ~{
    x <- .[.!='']
    if(length(x)) last(x) else ''
  }) -> result

data
df <- structure(list(ID = c(1L, 1L, 1L, 1L), event = c("before", "now",
"later", "tomo"), eventdate1 = c("", "", "03/02/2020", "05/05/2020"
), date2 = c("1/22/2020", "", "", ""), date3 = c("", "10/20/2017",
"", ""), date4 = c("", "10/25/2017", "", ""), date5 = c("", "",
"", ""), index1 = c("", "", "0", "0"), index2 = c("", "", "1", "0"),
index3 = c("", "", "0", "0")), row.names = c(NA, -4L), class = "data.frame")


text:
Q: I have an error With Mysql Query $sql="update item_master set department=$dept,make=$make,vat=$vat,cost=$mrp,packing=$pack,unit=$unit,exp_date=$ex,stock=$stock,description=$desc
where item_code=$id";
mysql_select_db('pds', $conn);

$result = mysql_query($sql);

And the error is :

-id= 1dept=Ayurvedicmake=arihantname=sample2vat=4mrp=100pack=1*100Could not run query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where item_code= 1' at line 2

A: There are a few things wrong here.
Seeing that many of your variables stand at being strings, they are required to be quoted.
Another thing I spotted is that there is no space between description=$desc and where.
For example: If $desc is defined as testing, then MySQL is interpreting that as:
description=testingwhere item_code=$id

which will explain that error for a few reasons, an unquoted variable and the missing space.
Change your code to the following.
$sql="UPDATE item_master SET
department = '$dept', make = '$make', vat = '$vat', cost = '$mrp',
packing = $pack, unit = '$unit', exp_date= '$ex', stock = '$stock',
description = '$desc' WHERE item_code=$id";

Sidenote: It's best using uppercase letters for functions and clauses. It helps to differentiate them from the rest of your code.
Plus, your code is highly prone to SQL injection. Consider using prepared statements, or sanitize your code for now, until you do.
Another important note.
If you're still having problems, then there may be characters being inserted that MySQL may be complaining about. Therefore, you will need to escape your data.

*

*http://php.net/manual/en/function.mysql-real-escape-string.php
Example, and do the rest for the others:
mysql_real_escape_string($dept);

*

*Double check your column types so that it matches the data, and their lengths also.

References:

*

*https://en.wikipedia.org/wiki/Prepared_statement

*http://php.net/manual/en/mysqli.prepare.php

*http://php.net/manual/en/pdo.prepared-statements.php

*https://en.wikipedia.org/wiki/SQL_injection

A: Change your query
$id need to like '$id'
$sql="update item_master set department=$dept,make=$make,
vat=$vat,cost=$mrp,packing=$pack,unit=$unit,exp_date=$ex,
stock=$stock,description=$desc where item_code='$id'";
mysql_select_db('pds', $conn);

$result = mysql_query($sql);


text:
Q: JQuery : Add row after the third row of a table I have a string  as 'new row'.I have a table which as 5 rows.I want to add this string after the third row of my table.How i do this using jQuery or javasript.

A: Use .eq() and .after for this
$("#yourtableid tr:eq(2)").after("
new row
");


text:
Q: Summing up this "factorial series"?? Ok so the series $k.k!$ can be summed up by writing $k$ as $k+1-1$, breaking the terms up and then adding. But if we take the sum of this series uptil infinity, it comes out to be $-1!$ = $-1$(Everything cancels). What I really can't get a grip on is HOW is this possible. Every consecutive term increases considering that we have a factorial term in there I think it's safe to say that it increases a LOT. So shouldn't this series diverge? Something like :
$\dfrac{1}{1.2.3} + \dfrac{2}{2.3.4} \dots$ is still understandable. Each term decreases and as the no of terms approaches a bigger value, the terms become very small and the series converges. But what about this factorial series? Is this some wizard level thing like what Ramanujan came up with, proving the sum of all natural nos to be equal to $\dfrac{-1}{12}$? Or something simpler?Pls try and refrain from using anything above 12th grade.
Thanks!!

A: $$k\cdot k! = (k + 1 - 1)\cdot k! = (k+1)! - k!$$
$$\sum_{k=1}^n k\cdot k! = (n+1)! - 1$$
$$\sum_{k=1}^\infty k\cdot k! = \lim_{n\to\infty}\sum_{k=1}^n k\cdot k! = \infty$$
Nothing cancels when $n\to\infty$.


text:
Q: Identical space around \[ \] and the amsmath environments set to a personnal value I wish to have the same spaces around the brackets \[ ... \] as the space around the environments align and equation (above and below, short or not) from amsmath, ideally (I set \parskip=1ex),
0.75\parskip plus 0.25\parskip minus 0.25 \parskip

MWE
\documentclass{article}
\usepackage{amsmath}
\setlength\parskip{1ex}
\begin{document}

Some very very very very very long text
\begin{align*}
E \colon Q  &\longrightarrow QQ \\
(x_1 , x_2) &\longmapsto LL
\end{align*}
Some very very very very very long text.

Some very very very very very long text
\[ A=A \]
Some very very very very very long text.

Some very very very very very long text
\begin{equation*}
E \colon Q   =  QQ
\end{equation*}
Some very very very very very long text.

\end{document}


text:
Q: "Must provide query string" error with Apollo Client on React and Nexus Graphql Server I'm starting to work with GraphQL and the new Nexus Framework GraphQL server, which is a great product.
On my server-side, I defined my schema, I can query my database with Prisma and everything runs smoothly. I can query data also from the Nexus GraphQL playground and also with Postman.
Now, I want to make things work on the client-side. I see that Apollo Client is the best solution to integrate React with GraphQL, but I just can't make things work. I read tons of docs but I'm missing something that I can't figure out.
GraphQL and the client part will be hosted on the same server, on separate node applications.
I'm configuring Apollo based on its documentations. The example below is for the new 3.0 Beta Version of Apollo which I'm testing, but the same scenario happens on the last stable version. I believe that I need to do something else to integrate Apollo and Nexus.
Every query returns: "Must Provide Query String".
The same query inside the playground works perfectly.
Here is my basic testing code:
apollo.js:
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: 'http://localhost:4000/graphql',
    fetchOptions: {
      mode: 'no-cors',
    }
  })
})

export default client

App.js:
import React from 'react'
import { ApolloProvider } from '@apollo/client';
import client from './database/apollo'
import Home from './components/Home'

const App = () => {
  return (
    <ApolloProvider client={client}>
      <Home />
    </ApolloProvider>
  )
}

export default App;

Home.js:
import React, { useState, useEffect, useReducer } from 'react'

import { useQuery, gql } from '@apollo/client'

const PUBLICATIONS = gql`
  {
    albumreviews(last: 1) {
      title
    }
  }
`
const Home = () =>{
  const { loading, error, data } = useQuery(PUBLICATIONS)

  if (loading) return
Loading...

  if (error) return
Error :(

  return data.albumreviews.map(({ review }) => (

{JSON.parse(review)}

  ))
}

export default Home

On the client-side: "Error" is displayed.
On the server-side: "Must provide query string"
Believe me, I've tried to adjust the query thousands of times trying to get a different answer.
Could some help me to move forward with this? Should I provide the Nexus schema to the apollo client? What is the better way of doing this?

A: You should pretty much never use no-cors. Off hand, I'm not sure why that option would cause your request to be malformed, but it will make it impossible for your response to be read anyway. Remove fetchOptions and whitelist your client URL in your CORS configuration on the server-side. CORs usage with Nexus is shown here in the docs.


text:
Q: Should a newcomer to Perl learn both Perl 5 and 6? I have started playing around with Perl 5 lately, and it seems very interesting. I would like to spend some time learning it more in depth when I can.
My question, since Perl 6 is slowly taking place (I believe...) and is said to break backward compatibility, is this: am I better learning Perl 5 and then Perl 6, or is learning Perl 6 directly a better time investment according to you?
If the changes from Perl 5 to 6 are making it hard to understand Perl 5, I should certainly start with Perl 5 to be able to read "old" scripts, then check Perl 6. There is also the "Perl 6 is not yet completely released" problem. I know there's an early adopter implementation for Perl 6, but if Perl 6 isn't officially released before some more years, I'll stick to 5 for now.
I would certainly like some insight on this. Feel free to discuss related stuff. My interest in scripting languages is fairly new.
Thanks!

A: In answer to the question in the headline: yes!
As you pointed out, focusing on Perl 5 is by no means a waste of your time, since the vast majority of examples, tutorials, and applications in Perl will be from the 5 branch.
This said, you should certainly keep up with the Perl 6 project and its progress.  I took some time to learn Python 3 before it's first release, just so I understood what changes were being made and why.  This helped me when migrating from the 2.x codebase to 3.x.
I wouldn't invest too much time learning the ins/outs of Perl 6; a deep understanding of Perl 5 will serve you better for the time being.  But once it's been released (whenever that bloody is), a basic understanding of Perl 6 will help you keep moving forward.

A: Perl 5 is the stable line, which will probably develop on a different line than Perl 6. Perl 6 is probably going to have to figure out a new name than Perl.
Perl 6 is, frankly, awesome. But it's not stable enough yet for enterprise use in production (at least, from what I understand). Of course, stable in the enterprise means Perl 5.8 in my experience...

A: Perl 5 and Perl 6 are different languages, not two versions of the same. Perl 6 is heavily inspired by Perl 5, but not exclusively. I would suggest focusing on Perl 5 for now. If you watch the community (I'd suggest the Planet Perl Iron Man aggregator, you'll also see posts and content from the Perl 6 community and can keep an eye on it. Also, many features of Perl 6 are slowly coming back to Perl 5.
Also: Despite some people's hate for Perl, it's 2010 now, not 1995 anymore, and Perl has immensely moved forward, and continues to do so.

A: Yes to Perl 5
Sure, go learn Ruby and even Python, but Perl is different.  And intelligent beyond reason.  Perl is one of those languages that you can learn things you never wanted and be glad you did and yet will have to re-read the Camel book every couple of years just so you don't fully mentally purge your perlisms.
Perl is of alien syntax, even to the most seasoned professionals.  Personally, I believe you will expand your horizons with Perl.
Perl 5 is what I consider to be Perl 1.5.  Perl 6 is what I consider Perl 2.0, maybe should even be named something different completely, so yes both 5 and 6 are worth learning in their own right and for their own merits.  Disclaimer=I'm still struggling with Perl6 myself...

A: Don't learn Perl 6.
CPAN doesn't even support it yet.  (I suspect it will ship with a module that allows Duke Nukem Forever to be played entirely through the use of regexes...)

A: Perl 5 is stable now and I think one must learn the most recent stable version first. Upgrading to another version would then become easier.

A: Best advice: no, no, no! Perl 5 is best right now since Perl 6 is not fully developed.

A: If you are interested in scripting style languages, I would suggest learning Python and/or Ruby instead. I first learned Perl several years ago. The main thing I learned from it is regular expressions. Most other languages that have built in regex are derivatives of the Perl implementation. But beyond that, I didn't use Perl for all that much. The main criticism of Perl is that some consider it a 'write-only' language. It is very hard to come back to old code and easily understand what was done.
It's my perception that more progress is being made with Python, and Ruby (like Rails), than there is with Perl. It's always good to stretch your brain an learn a new language, but Perl probably wouldn't be a top suggestion.


text:
Q: How can use Try/Catch in python I want use try catch in Python but python give me an error what's can I do?
this is my code
try:
    input('enter your number');
catch:
    print('please give integer');

A: try/catch in python is try/except.
you can use try/except like this:
try:
   input('enter your number');
except expression:
   print('please give integer');

A: try:
    int(input('enter your number'));
except ValueError:
    print('please give integer');

Use handling-exceptions

A: You can use following alternative for your use case :
try:
    input_ = int(input('enter your number'))
except:
    print('please give integer')
    exit() #if you want to exit if exception raised
#If no exception raised, execution continues from here
print(input_)


text:
Q: SQL. how to display missing row in another table? I have these tables
create table Employee2
(
     eid char(3),
     ename char(10),
     salary number(7,2),
     mid char(3),

     primary key (eid),
     foreign key (mid) references Employee2
);

create table ArtObject2
(
     aoid char(3),
     atitle char(12),
     artist varchar(10),
     pricea number(8,2),

     primarykey (aoid)
);

create table MakesD2
(
     aoid char(3),
     eid char(3),
     cid char(3),
     prices number,
     dates date,

     primary key (aoid, CID),
     foreign key (aoid) references ArtObject2,
     foreign key (CID) references Customer2,
     foreign key (eid) references Employee2
);

This is some sample data: http://imgur.com/a/ZapJy
I am trying to find employees who didn't sell a painting with the asking price over 500,000.
Here is what I have so far
SELECT DISTINCT e.ename
FROM Employee2 e
INNER JOIN MakesD2 md on md.eid = e.eid
INNER JOIN ArtObject2 a on a.aoid = md.aoid
WHERE NOT EXISTS (SELECT md.prices
                  FROM MakesD2
                  WHERE a.pricea < 500000);

Supposed to get these values
Wilson
Loftus
Smith
Fox
Wolf
Fox
Liy

A: You were close!
For [not] exists() you want to move those joins into the exists() subquery, and check the eid inside the subquery against the eid from the main query; and change a.pricea<500000 to a.pricea>500000 since this is not exists().
select e.ename
from Employee2 e
where not exists (
  select 1
  from MakesD2 md
    inner join ArtObject2 a
      on a.aoid = md.aoid
  where a.pricea > 500000
    and e.eid = md.eid
  );

A: I use NOT IN:
SELECT e.ename
FROM Employee2 e
WHERE e.eid NOT IN (SELECT md.eid
                    FROM MakesD2 md
                    INNER JOIN ArtObject2 a
                      ON a.aoid = md.aoid
                    WHERE a.pricea > 500000);


text:
Q: Detach event working only the first time with jQuery I have a timeline which is showing a different content depending on the selected date. Date can be selected either by clicking on the timeline, either scrolling with mouse wheel.
I have some animations attached to each content, in order to have a fade out/fade in effect of the different content elements, and for this I'm using nested animations, with callbacks.
What I'm not able to do, is to wait for the previous animation to end, before the next one begins, if scrolling fastly.
Or, better, I detach the scrolling event at the beginning of the animation function, and re-attach it, as a callback of the last animate function call: this works only the first time, but not with subsequent scrolls.
Any idea?
Function detecting scroll:
      //detect mouse scrolling and determine the direction
        function detectScroll() {
            $('.events-content').first().bind('mousewheel', function (e) {
                var delta = e.originalEvent.wheelDelta;
                if (delta > 0) {
                    jumpToEvent('prev');
                } else {
                    jumpToEvent('next');
                }
            });

            //firefox
            $('.events-content').first().on('DOMMouseScroll', function (e) {
                var delta = e.originalEvent.detail;
                if (delta < 0) {
                    jumpToEvent('prev');
                } else if (delta > 0) {
                    jumpToEvent('next');
                }
            });
        }

Function detatching scrolling
function detachScroll(){
            console.log('detach');
            $('.events-content').first().unbind('mousewheel');
            $('.events-content').first().off('DOMMouseScroll');
        }

Function with animations, called by jumpToEvent function, that choose the correct content to show:
 //display correct content depending on the selected date
function updateVisibleContent(event, eventsContent) {

    var visibleContent = ...., selectedContent =....;

    detachScroll();

    visibleContent.find('....').each(function () {
        $(this).animate({
            opacity: 0 //hide current content
        }, 600, function () {

            visibleContent.removeClass('selected');
            selectedContent.attr('class', 'selected');

            //now show the next content, with 3 subsequent steps (Showing only one for the sake of readability)
            selectedContent.find('...').first().animate({
                opacity: 1
            }, 500, function () {
                     detectScroll();
            });
        });
    });
}

A: You need to add .stop() before every animate call, this ensures that there is no pending/ongoing animation when calling the next animation.

A: Have you tried jQuery deferred-object, it is a way of waiting on async functions to finish.
function doAnimations(domElement, i) {
  var dfd = jQuery.Deferred();

  $(domElement[i]).animate({
    //do somthing
  }, 600, function() {
    dfd.resolve
  })

  return dfd.promise();
}

//And this is how you can itterate tru items
(function rec(i){
    if(i >= numbers of itterations) {
    console.log('End')
    return false
  }

  doAnimations(domElement, i).done(function(){
    rec(++i)
  })
})(0)


text:
Q: AttributeError: 'str' object has no attribute 'datetime': Python This is my code:
# Fetch today's date
Date = datetime.today().strftime('%Y-%m-%d-%H.%M.%S')
# Variable for log file
LogFile = os.getcwd()
print(LogFile)
os.mkdir("Logs12")
f = open("Password_Expiry_Date_Log_"+(Date)+".txt", "w+")

#Date Calculations
Date_Before = Date.datetime(Days_Before)
Days_After = Date.datetime(Days_After)

When I try to initialize the variable 'Date_Before', i get the error AttributeError: 'str' object has no attribute 'datetime'. However, I need date to be in a string format to write in into a text filename. Is there any workaround for this?
Thanks in advance.

A: You could do this:
from datetime import datetime, timedelta

# Fetch today's date
date = datetime.today()

string_date = date.strftime('%Y-%m-%d-%H.%M.%S')

# Variable for log file
log_file = os.getcwd()
print(log_file)
os.mkdir("Logs12")
f = open(f"Password_Expiry_Date_Log_{string_date}.txt", "w+")

f.close()

#Date Calculations
date_before = datetime.today() - timedelta(days=1)
days_after = datetime.today() + timedelta(days=1)

I also updated your string names to conform to PEP8
Edit: I also improved your syntax, please remember that you always need to close your files.


text:
Q: NullPointerException when using properties.load() I have a little problem with Properties in Java, maybe you could help me.
In the following code i write my Properties object to XML:
global.storeToXML(new FileOutputStream(propertiesPath + SEPERATOR + GLOBAL + FILEEXTENSION), "");

This works fine and produces the following file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>test</comment>
<entry key="port">5001</entry>
<entry key="maxPlayers">1</entry>
</properties>

But if i try to load this file with the following code:
FileInputStream fis = new FileInputStream(propertiesPath + SEPERATOR + GLOBAL + FILEEXTENSION);

if (fis != null)
 global.loadFromXML(fis);

the loadFromXML method throws a NullPointerException. According to the documentation of Properties this usually means that fis would be null, which it is obviously not.
I already tried the load() and store() methods (without XML) and get just the same error. When I try to read the file manually via fis it works fine.
Thank you for you help!

A: Forgot to initialize global. Sorry for the dumb question.


text:
Q: SQL Query to Split a string, format each result, then build back into a single row I've been working on a rather convoluted process to format some data for a work project. We received a data extract and need to export it for import during a migration, but some of the data won't import due to case sensitivity (user logons with sentence case for example).
In an ideal world, I could demand the data be sanitised and formatted before it's provided for me to build the import, but I can't, so I'm stuck where I have to format it myself.
Plan:

*

*Take string result

*Split string result by pipe delimitation

*Format each split results ( ) into lower case (where applicable)

*Put all split results back into one string using FOR XML PATH

Example of problem:
Field 'Assigned To' can contain a pipe delimitted string of users and/or user groups, e.g.
John Smith (jsmith)|College Group of Arts|Bob Jones (BJones)

Now as you can see above, John Smith (jsmith) looks fine, as does College Group of Arts, however Bob Jones has had his logon sentence cased, so I need to use a LOWER command, chained with SUBSTRING and CHARINDEX to convert the logon to lower. Standalone, this approach works fine, but the problem I'm having is where I'm using a function found here on Stack Overflow (slightly manipulated to account for pipe delimitation) T-SQL split string.
When I retrieve the table results of the split string, I can't apply CHARINDEX against any characters in the result string, and I can't work out why.
Scenario:
The raw data extract, untouched, returns the below when queried;
|College of Science Administrators|Bob Jones (BJones)|

I then apply the below query, which calls the function queried above;
declare @assignedto nvarchar(max) = (select assigned_to from project where project_id = 1234)

SELECT SUBSTRING(Name,CHARINDEX(Name,'('),255)

FROM dbo.splitstring(@assignedto)

I then get the below results;
College of Science Administrators
Bob Jones (BJones)

What I'd expect to see is;
College of Science Administrators
(BJones)

I could then apply my LOWER logic to change it to lower case.
If that worked, then thought process was then to take those results and pass them back into a single string using a FOR XML PATH.
So I guess technically, there are 2 questions here;

*

*Why won't my function let me manipulate the results with CHARINDEX?

*And is this the best way to do what I'm trying to achieve overall?

A: I would strongly suggest you take that splitstring function you found and throw it away. It is horribly inefficient and doesn't even take the delimiter as a parameter. There are so many better splitter options available. One such example is the DelimitedSplit8K_LEAD which can be found here.
I noticed you also have your delimiters at the beginning and the end so you have to eliminate those but not a big deal. Here is how I would go about parsing this string. I am using a variable for your string here with the value you said is in your table.
declare @Something varchar(100) = '|College of Science Administrators|Bob Jones (BJones)|'

select MyOutput = case when charindex('(', x.Item) > 1 then substring(x.Item, charindex('(', x.Item), len(x.Item)) else Item end
from dbo.DelimitedSplit8K_LEAD(@Something, '|') x
where x.Item > ''

A: For question #1 you must simply invert parameters in CharIndex :
CHARINDEX('(', Name))


text:
Q: Syncing CSS Animation I have a color changing CSS animation for my button. I decided to make it solid when hovered over. Though the code works and the color still changes, the animation resets each time when I hover over it. Is there a way to make the color animation for the hover state to be the same color as the non-hover state was prior to the action (so when non-hover is green, it is still green when hovered over).
http://codepen.io/Dingerzat/pen/mRdObJ

/* CSS */

.enquire_button {
  min-height: 2em;
  width: 7em;
  background-color: white;
  border: 4px solid #f35626;
  border-radius: 5px;
  color: #f35626;
  cursor: pointer;
  font-size: 2em;
  line-height: 2em;
  -webkit-transition: color .4s;
  -o-transition: color .4s;
  transition: color .4s;
  -webkit-animation: hue 60s linear;
  -o-animation: hue 60s linear;
  animation: hue 60s linear;
  text-align: center;
}
.enquire_button:hover {
  background-color: #f35626;
  color: #ffffff;
  -webkit-transition: color .4s;
  -o-transition: color .4s;
  transition: color .4s;
  -webkit-animation: hue 60s linear;
  -o-animation: hue 60s linear;
  animation: hue 60s linear;
}
.color_button {
  animation-name: color_change;
  animation-duration: 10s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}
.color_button:hover {
  animation-name: color_change2;
  animation-duration: 10s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}
@-webkit-keyframes color_change {
  0% {
    color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@-moz-keyframes color_change {
  0% {
    color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@-ms-keyframes color_change {
  0% {
    color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@-o-keyframes color_change {
  0% {
    color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@keyframes color_change {
  0% {
    color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@-webkit-keyframes color_change2 {
  0% {
    color: #ffffff;
    background-color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #ffffff;
    background-color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #ffffff;
    background-color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@-moz-keyframes color_change2 {
  0% {
    color: #ffffff;
    background-color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #ffffff;
    background-color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #ffffff;
    background-color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@-ms-keyframes color_change2 {
  0% {
    color: #ffffff;
    background-color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #ffffff;
    background-color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #ffffff;
    background-color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@-o-keyframes color_change2 {
  0% {
    color: #ffffff;
    background-color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #ffffff;
    background-color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #ffffff;
    background-color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
}
@keyframes color_change2 {
  0% {
    color: #ffffff;
    background-color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    color: #ffffff;
    background-color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    color: #ffffff;
    background-color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    color: #ffffff;
    background-color: #d41a82;
    border: 4px solid #d41a82;
  }
}
<button class="enquire_button color_button">Click here</button>

A: I think this is what you're trying to achieve, it requires extra markup though. I've tried to keep your code as intact as possible but have stripped it down for the example. Full required code attached in codepen.
HTML
<button class="enquire_button color_button">
  Click here
</button>

CSS
.enquire_button {
  animation-direction: alternate;
  animation-duration: 10s;
  animation-iteration-count: infinite;
  animation-name: color_change;
  background-color: #fff;
  border: 4px solid #f35626;
  border-radius: 5px;
  color: #f35626;
  cursor: pointer;
  font-size: 2em;
  line-height: 2em;
  min-height: 2em;
  position: relative;
  text-align: center;
  transition: color .4s;
  width: 7em;
}

.enquire_button:before {
  background: #fff;
  content: '';
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  transition: background-color .4s;
  width: 100%;
}

.enquire_button:hover .button_text {
  color: #fff;
}

.enquire_button:hover:before {
  background-color: transparent;
}

.button_text {
  position: relative;
}

@keyframes color_change {
  0% {
    background-color: #da6e16;
    color: #da6e16;
    border: 4px solid #da6e16;
  }
  25% {
    background-color: #82da16;
    color: #82da16;
    border: 4px solid #82da16;
  }
  50% {
    background-color: #16dad0;
    color: #16dad0;
    border: 4px solid #16dad0;
  }
  75% {
    background-color: #d41a82;
    color: #d41a82;
    border: 4px solid #d41a82;
  }
  100% {
    background-color: #d41a82;
    color: #d41a82;
    border: 4px solid #d41a82;
  }
}

A: I think what this can do through double button))

    <button>Button #1</button>
    <button>Button #2</button>

Button #1 - animation infinite.
Button #2 - white background
.bnt button + button {
    display: none;
}

A: *

*Using :after pseudoelement

/* Color changing button */

.enquire_button {
  min-height: 2em;
  width: 7em;
  background-color: white;
  border: 4px solid;
  border-radius: 5px;
  cursor: pointer;
  font-size: 2em;
  line-height: 2em;
  text-align: center;
}

.color_button {
  animation: color_change 10s infinite alternate;
}
.color_button:after {
  display: inline-block;
  font-size: 1em;
  content: "Click here";
}
.color_button:hover {
  background-color: currentcolor;
}
.color_button:hover:after {
  color: #fff;
}

@keyframes color_change {
  0% { color: #da6e16; }
  25% { color: #82da16; }
  50% { color: #16dad0; }
  75% { color: #d41a82; }
  100% { color: #d41a82; }
}
<button class="enquire_button color_button"></button>

*Using hue-rotate CSS filter

/* Color changing button */

.enquire_button {
  min-height: 2em;
  width: 7em;
  background-color: white;
  border: 4px solid;
  border-radius: 5px;
  cursor: pointer;
  font-size: 2em;
  line-height: 2em;
  text-align: center;
}

.color_button {
  color: #da6e16;
  animation: color_change 10s infinite alternate;
}
.color_button:hover {
  color: #fff;
  background-color: #da6e16;
  border-color: #da6e16;
}

@keyframes color_change {
  0% { filter: hue-rotate(0deg); }
  100% { filter: hue-rotate(360deg); }
}
<button class="enquire_button color_button">
  Click here
</button>


text:
Q: How to set the SoC's register values in Linux kernel and U-boot? I have been given all the register values like SRAM Window 0 Control Register,PCI Express Configuration Address Register and numerous other register values for Armada 370 SoC.
Now for board bringup I have to set all these register values in U-boot and Linux kernel.
Is there a way to do this easily?
For example, if I want to set the PCI Express Configuration Address Register, how do I start?
Any direction to good resource will be helpful. Thanks.

A: 1) In u-boot, look at /board subdirectory: there is your board-specific files should be located. There is several Marvell platforms presented, but no armada 370, so looks like you should add it by yourself. Maybe, you already have proper distribution?
Examining existing code, I guess you should use GT_REG_WRITE macro (defined in /board/Marvell/common/core.h). But it can differ for armada 370.
2) In linux kernel, there is a place for board specific code too: look in /arch subdirectory. Armada 370 is based on ARM, so it should be placed into /arch/arm. There is a block of common code for all of ARM platforms, and specific subdirectories named "mach-" and "plat-". Your code should be arranged like there. In "mach-" subdirectories look for "board-" files, they are contain code executed at linux kernel start.

A: You should have a look into arch/arm/mach-mvebu ! (I am refering to the 3.16 kernel).
Free-Electrons have also worked a lot on this SoC Family. You can have a look to their git here:
https://github.com/MISL-EBU-System-SW/mainline-public/commits/3.16/cpuidle-v3