text:
Q: c Segmentation fault in macOS ; sometimes, and sometimes not   void makeDouble(int **a, int *size){
    int i, j;
    *size *= 2;
    *a = (int *)realloc(*a, (*size)*sizeof(int));
    for(i=0; i<*size/2; i++){
        (*a)[*size/2+i] = (*a)[i] * 2;
    }

    int temp;
    for(i=0; i<*size-1; i++){
        for(j=0; j<*size-i-1; j++){
            if((*a)[j]>(*a)[j+1]){
                temp = (*a)[j];
                (*a)[j] = (*a)[j+1];
                (*a)[j+1] = temp;
            }
        }
    }
}

$
this is my code. What I wanted to do is getting a size and input as size, then making them all doubled, and sorting them.
But when I compile this, sometimes it collapses with segmentation fault and sometimes doesn't. And sometimes, it says "malloc: * error for object 0x7fda70c02730: incorrect checksum for freed object - object was probably modified after being freed.
* set a breakpoint in malloc_error_break to debug
Abort trap: 6"
Why and What can I do with this? Sorry if my question is bad, I'm beginner with c.

A: First Segfault
One place where this would cause a segfault for sure is:
int size;
scanf("%d", &size);
int* a = (int *)malloc(size*sizeof(int));

if you pass it a character instead of a number that fits into an integer this would fail, because scanf is not gonna write to size.
You have to check the return of scanf which is the number of input items successfully matched:
if (scanf("%d", &size) != 1) {
    fprintf(stderr, "Supplied size is not a valid number.\n");
    return 1;
}

Memory Leak
if realloc returns NULL because it failed to allocate enough space, you get a memory leak because you do:
int *a = realloc(a, ...);

This pattern is buggy, because assigning the return of realloc to the array you wanna reallocate means you lose the reference to the allocated array since a == NULL. Do:
int *temp = realloc(a, ...);
if (temp == NULL) {
    free(a); // Or continue using it ..
} else {
    a = temp;
}

Heap Corruption
Your function makeDouble is causing a heap corruption because you're accessing and modifying out of bound memory. I'm getting a realloc() abort: invalid next size with glibc, so you're most likely smashing the heap already allocated by the runtime, but not reaching the next page, hence no Segfault and a runtime error instead.


text:
Q: npm install , installs package not even listed in my package.json file I am new to NodeJS and just cloned the code and checked my node_modules folder which has almost 100's of dependencies installed. This is my directory structure
node_modules/
├── accepts
├── after
│   └── test
├── ansi-regex
├── ansi-styles
├── arraybuffer.slice
│   └── test
├── array-flatten
├── asn1
│   ├── lib
│   │   └── ber
│   └── tst
│       └── ber
├── assert-plus
├── async
│   ├── lib
│   └── support
├── aws-sign2
├── backo2
│   └── test
├── base64-arraybuffer
│   ├── lib
│   └── test
├── base64id
│   └── lib
├── base64-url
├── benchmark
│   ├── doc
│   └── test
├── better-assert
├── bindings
├── bl
│   ├── node_modules
│   │   └── readable-stream
│   │       ├── doc
│   │       │   └── wg-meetings
│   │       └── lib
│   └── test
├── blob
│   └── test
├── bluebird
│   └── js
│       ├── browser
│       └── main
├── body-parser
│   └── lib
│       └── types
├── boom
│   ├── images
│   ├── lib
│   └── test
├── bson
│   ├── alternate_parsers
│   ├── browser_build
│   ├── lib
│   │   └── bson
│   │       └── parser
│   └── tools
├── bufferutil
│   ├── build
│   │   └── Release
│   │       └── obj.target
│   │           └── bufferutil
│   │               └── src
│   └── src
├── bytes
├── callsite
├── caseless
├── chalk
├── combined-stream
│   └── lib
├── commander
├── component-bind
├── component-emitter
├── component-inherit
│   └── test
├── connect-mongodb-session
│   └── test
├── content-disposition
├── content-type
├── cookie
├── cookie-parser
├── cookie-signature
├── core-util-is
│   └── lib
├── crc
│   └── lib
├── cryptiles
│   ├── lib
│   └── test
├── dashdash
│   └── lib
├── debug
├── delayed-stream
│   └── lib
├── depd
│   └── lib
│       ├── browser
│       └── compat
├── destroy
├── ecc-jsbn
│   └── lib
├── ee-first
├── engine.io
│   ├── lib
│   │   └── transports
│   └── node_modules
│       ├── debug
│       └── ms
├── engine.io-client
│   ├── lib
│   │   └── transports
│   └── node_modules
│       ├── debug
│       ├── ms
│       └── parseuri
├── engine.io-parser
│   └── lib
├── es6-promise
│   ├── dist
│   └── lib
│       └── es6-promise
│           └── promise
├── escape-html
├── escape-string-regexp
├── etag
├── express
│   ├── lib
│   │   ├── middleware
│   │   └── router
│   └── node_modules
│       ├── cookie
│       ├── depd
│       │   └── lib
│       │       └── compat
│       └── qs
│           ├── lib
│           └── test
├── express-session
│   ├── node_modules
│   │   └── cookie
│   └── session
├── extend
├── extsprintf
│   ├── examples
│   └── lib
├── finalhandler
├── flushwritable
│   ├── lib
│   └── test
├── forever-agent
├── form-data
│   ├── lib
│   └── node_modules
│       └── async
│           ├── dist
│           └── lib
├── forwarded
├── fresh
├── generate-function
├── generate-object-property
├── global
│   └── test
├── graceful-readlink
├── gridfs-stream
│   ├── lib
│   └── test
│       └── fixtures
├── har-validator
│   ├── bin
│   └── lib
│       └── schemas
├── has-ansi
├── has-binary
│   └── fixtures
├── has-binary-data
│   └── fixtures
├── has-cors
├── hawk
│   ├── dist
│   ├── example
│   ├── images
│   ├── lib
│   └── test
├── hoek
│   ├── images
│   ├── lib
│   └── test
│       └── modules
├── hooks-fixed
├── http-errors
├── http-signature
│   └── lib
├── iconv-lite
│   ├── encodings
│   │   └── tables
│   └── lib
├── indexof
├── inherits
├── ipaddr.js
│   ├── lib
│   ├── src
│   └── test
├── isarray
│   └── build
├── is-my-json-valid
│   └── test
│       ├── fixtures
│       └── json-schema-draft4
├── is-property
├── isstream
├── is-typedarray
├── jodid25519
│   └── lib
├── jsbn
├── json3
│   ├── coverage
│   │   └── lcov-report
│   │       └── lib
│   └── lib
├── jsonpointer
├── json-schema
│   ├── draft-00
│   ├── draft-01
│   ├── draft-02
│   ├── draft-03
│   │   └── examples
│   ├── draft-04
│   ├── lib
│   └── test
├── json-stringify-safe
│   └── test
├── jsprim
│   └── lib
├── kareem
│   └── test
├── lodash
│   ├── array
│   ├── chain
│   ├── collection
│   ├── date
│   ├── function
│   ├── internal
│   ├── lang
│   ├── math
│   ├── number
│   ├── object
│   ├── string
│   └── utility
├── media-typer
├── merge-descriptors
├── methods
├── mime
│   └── build
├── mime-db
├── mime-types
├── moment
│   ├── locale
│   └── min
├── mongodb
│   ├── lib
│   │   ├── bulk
│   │   ├── gridfs
│   │   └── gridfs-stream
│   └── test_boot
│       └── data
│           └── diagnostic.data
├── mongodb-core
│   └── lib
│       ├── auth
│       ├── connection
│       ├── tools
│       ├── topologies
│       │   └── strategies
│       └── wireprotocol
├── mongoose
│   ├── examples
│   │   ├── aggregate
│   │   ├── express
│   │   │   └── connection-sharing
│   │   ├── geospatial
│   │   ├── globalschemas
│   │   ├── lean
│   │   ├── mapreduce
│   │   ├── population
│   │   ├── promises
│   │   ├── querybuilder
│   │   ├── replicasets
│   │   ├── schema
│   │   │   └── storing-schemas-as-json
│   │   └── statics
│   ├── lib
│   │   ├── drivers
│   │   │   ├── browser
│   │   │   └── node-mongodb-native
│   │   ├── error
│   │   ├── schema
│   │   │   └── operators
│   │   ├── services
│   │   └── types
│   └── node_modules
│       ├── async
│       │   └── lib
│       └── bson
│           ├── alternate_parsers
│           ├── browser_build
│           ├── lib
│           │   └── bson
│           │       └── parser
│           └── tools
├── mpath
│   ├── lib
│   └── test
├── mpromise
│   ├── lib
│   └── test
├── mquery
│   ├── lib
│   │   └── collection
│   └── test
│       └── collection
├── ms
├── muri
│   ├── lib
│   └── test
├── nan
│   ├── doc
│   └── tools
├── negotiator
│   └── lib
├── node-gcm
│   ├── lib
│   └── node_modules
│       └── debug
│           └── lib
├── node-uuid
│   ├── benchmark
│   ├── bin
│   └── test
├── oauth
│   ├── examples
│   │   └── express-gdata
│   │       └── views
│   ├── lib
│   └── tests
├── oauth-sign
├── object-component
│   └── test
├── object-keys
├── on-finished
├── on-headers
├── options
│   └── lib
├── parsejson
├── parseqs
├── parseuri
├── parseurl
├── passport
│   └── lib
│       ├── errors
│       ├── framework
│       ├── http
│       ├── middleware
│       └── strategies
├── passport-facebook
│   └── lib
│       └── errors
├── passport-local
│   └── lib
├── passport-oauth2
│   └── lib
│       └── errors
├── passport-strategy
│   └── lib
├── password-hash
│   ├── bin
│   ├── lib
│   └── test
├── path-to-regexp
├── pause
├── pinkie
├── pinkie-promise
├── process-nextick-args
├── proxy-addr
├── qs
│   ├── dist
│   ├── lib
│   └── test
├── random-key
├── range-parser
├── raw-body
├── readable-stream
│   └── lib
├── regexp-clone
│   └── test
├── request
│   └── lib
├── send
│   └── node_modules
│       └── depd
│           └── lib
│               └── compat
├── serve-static
├── sliced
│   ├── lib
│   └── test
├── sntp
│   ├── examples
│   ├── lib
│   └── test
├── socket.io
│   ├── lib
│   └── node_modules
│       ├── debug
│       └── ms
├── socket.io-adapter
│   └── node_modules
│       ├── debug
│       ├── ms
│       └── socket.io-parser
│           ├── bench
│           └── node_modules
│               └── debug
│                   └── lib
├── socket.io-client
│   ├── lib
│   └── node_modules
│       └── debug
│           └── lib
├── socket.io-parser
│   ├── bench
│   └── node_modules
│       └── debug
│           └── lib
├── sshpk
│   ├── bin
│   ├── lib
│   │   └── formats
│   └── node_modules
│       └── assert-plus
├── statuses
├── string_decoder
├── stringstream
├── strip-ansi
├── supports-color
├── to-array
├── tough-cookie
│   └── lib
├── tunnel-agent
├── tweetnacl
├── type-is
├── uid2
├── uid-safe
├── ultron
├── unpipe
├── utf8
│   └── tests
├── utf-8-validate
│   ├── build
│   │   └── Release
│   │       └── obj.target
│   │           └── validation
│   │               └── src
│   └── src
├── util-deprecate
├── utils-merge
├── vary
├── verror
│   ├── examples
│   ├── lib
│   └── tests
├── ws
│   └── lib
├── xmlhttprequest
│   ├── example
│   ├── lib
│   └── tests
└── xtend

and this my package.json
{
  "name": "my-api",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "async": "^0.9.0",
    "body-parser": "^1.12.0",
    "cookie-parser": "^1.3.4",
    "express": "latest",
    "express-session": "^1.11.1",
    "gridfs-stream": "latest",
    "moment": "^2.10.6",
    "mongoose": "latest",
    "node-gcm": "latest",
    "passport": "^0.2.1",
    "passport-facebook": "latest",
    "passport-local": "latest",
    "password-hash": "^1.2.2",
    "random-key": "^0.3.2",
    "socket.io": "^1.3.5",
    "connect-mongodb-session" : "latest"
  }
}

What is wrong with it? My friend had the same project but in his node_modules only the folders mentioned in package.json are created.

A: They're dependencies of dependencies -
Example:
You have a dependency on express.
This in turn, has dependencies on several packages
Each of these have dependencies, on so on...
When you npm install the whole dependency graph needs to be downloaded into your node_modules folder
A nice itneractive tool for visualising the dependency graph of express is http://npm.anvaka.com/#/view/2d/express

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rserve - Eclipse & Java Hi I am setting up rserve based on the instructions on this website.
http://www.codophile.com/how-to-integrate-r-with-java-using-rserve/
However in eclipse I am getting an error when using 'eval'
             double d[] = c.eval("rnorm(10)").asDoubles();

error - 'The method eval(String) is undefined for the type RConnection'
The JARS have been correctly loaded into the build path and rserve is running, however I cannot figure out why only the eval function is causing an issue.
In addition to this the import of ...
   import org.rosuda.REngine.Rserve.RConnection;

causes an error - 'The import org.rosuda.REngine.Rserve.RConnection conflicts with a type defined in the same file'
does anyone have any idea why this is the case? Thanks
all imports :
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;

 public class RConnection {
public int[] mean(String a[]) {

    setupR();

    return null;
}

public void setupR(){

    try {

        /* Create a connection to Rserve instance running
         * on default port 6311
         */

        RConnection c = new RConnection();// make a new local connection on default port (6311)

        double d[] = c.eval("rnorm(10)").asDoubles();
        org.rosuda.REngine.REXP x0 = c.eval("R.version.string");
        System.out.println(x0.asString());

    } catch (RserveException e) {
        e.printStackTrace();
    } catch (REXPMismatchException e) {
        e.printStackTrace();
    }
}
}

A: By using import org.rosuda.REngine.Rserve.RConnection; you are tying to make RConnection known in the local namespace.
However, you already defined a class called RConnection locally.
Please rename your class RConnection, and you should be able to import org.rosuda.REngine.Rserve.RConnection.


text:
Q: Low Wifi signal in ubuntu 14 I have recently installed ubuntu 14 in my system alongside windows8.1. While the wifi works perfectly fine in windows, i am getting very low signal for the wifi connection. Most of the time I have to restart the connection via terminal  (network manager restart) to get the wifi working. And even so if I move away a little, the wifi connection is lost. What could be the problem?
P.S. I am using an HP 15 af006ax notebook. My wifi router is Tp-link wr740n wireless router .

A: The problem is in antenna slot, the ubuntu goes for slot 1 (default).
But in HP 15-af006ax the antenna connection is in 2nd slot.
You can change it by,
sudo modprobe -v rtl8723be ant_sel=2

and for making it permanent,
echo "options rtl8723be ant_sel=2 fwlps=0" | sudo tee /etc/modprobe.d/rtl8723be.conf

thats it your problem must be solved after this i got it working the same.


text:
Q: Would Crabbe's Fiendfyre have destroyed Horcrux in HP? Inspired by trying to answer "Is a living being a poor choice for a Horcrux?"
We know that Crabbe's Fiendfyre destroyed the Diadem as a Horcrux.
Is there any evidence in canon that would indicate whether - in the unfortunate event of Harry failing to escape the Room of Hidden Things - the Fiendfyre would also have ...

 ...destroyed the fragment of Voldemort's soul contained in Harry himself, e.g. destroying Harry as a Horcrux in addition to simply killing him?

A: I'm going to suggest, after reading these discussions, that yes, the Fiendfyre would have destroyed the horcrux.  Hermione explains that it is the object of the horcrux that protects the piece of soul, not the other way around, ergo destroying/killing Harry would indeed have destroyed the piece of soul along with him.  As for whether he could be killed, I'll take a bit of Slytherincess's quote from the other answer:

His body keeps her sacrifice alive, and while that enchantment survives, so do you and so does Voldemort's one last hope for himself

Lily's sacrifice only works against Voldemort. I'm pretty sure that's stated explicitly somewhere, but at the moment I'm not sure where. Therefore, the Fiendfyre, coming from Crabbe and not Voldemort, would have been able to kill Harry and destroy the piece of Voldemort's soul stuck inside him.

A: Pursuant to my answer here, I think that if Crabbe's Fiendfyre had destroyed the piece of Voldemort's soul within Harry -- and we know that Fiendfyre is one of the few means of destroying a Horcrux -- Harry himself would not have died as long as Voldemort remained alive, as Harry and Voldemort's lives were strongly tethered by the point of the Fiendfyre/Room of Requirement scene. Do I think Voldemort could have chosen to use Fiendfyre instead of Avada Kedavra to kill Harry in the forest, and thus destroy the Horcrux inside of Harry? Yes. He could have optioned Fiendfyre instead of Avada Kedavra. But as long as Voldemort remained alive, Harry himself -- his physical body, mind, and soul -- was protected from death by Lily's enchantment.

A: The Fiendfyre would have first destroyed the part of Voldemort's soul in Harry but because it wasn't being controlled it would have kept going, destroying Harry's body and leaving him with no body to return to.  So not only would his mind be in limbo, his body would be dead.

A: Yes, Fiendfyre would've killed him and destroyed the soul piece.
If Harry had fallen into the Fiendfyre, the piece of soul in him would die when he did. J.K. Rowling has said in many places that the piece of soul in Harry would have been destroyed if he had died.

7. Why wasn't the Horcrux inside Harry destroyed when he was bitten by the Basilisk in Harry Potter and the Chamber of Secrets?
A Horcrux can only be destroyed if its container is damaged beyond repair. Harry was healed by Fawkes. Had he died, the Horcrux would indeed have been destroyed. - F.A.Q. (J.K. Rowling's website)

Also, Fiendfyre is itself a method of destroying Horcruxes, meaning non-living intentionally made Horcruxes with strong protective enchantments on them, and it's highly dangerous.

"Fiendfyre – cursed fire – it's one of the substances that destroy Horcruxes, but I would never, ever have dared use it, it's so dangerous." - Harry Potter and the Deathly Hallows, Chapter 31 (The Battle of Hogwarts)

Harry is never shown as being immune to physical harm - he injured himself playing Quidditch and broke his arm, so it's just as possible to hurt Harry as it is to hurt any other wizard.

"The Bludger had hit him at last, smashed into his elbow, and Harry felt his arm break. Dimly, dazed by the searing pain in his arm, he slid sideways on his rain-drenched broom, one knee still crooked over it, his right arm dangling useless at his side." - Harry Potter and the Chamber of Secrets, Chapter 10 (The Rogue Bludger)

Therefore, it's almost certain that falling into Fiendfyre and not being rescued in time would kill him, and would also destroy the soul piece residing within him when it does.


text:
Q: Group orders and get a list of the products of each order I have a database that contains 3 tables: user, orders, products and order_products this way :

I tried to get orders and their products then group them by orders.id this way :
SELECT `orders`.*, `product`.*
FROM `product`, `orders`
JOIN `order_products` op ON op.orderid=orders.id
GROUP BY orders.id

but it only gets me the last product from each order.
Is it possible to get each order by itself and a list of products of that order ? I really need your help.

A: If you just want one column, such as the product title concatenated into a string (which is a reasonable interpretation of the title of your question), then you can use group_concat():
SELECT o.*, GROUP_CONCAT(p.title)
FROM orders o JOIN
     order_products op
     ON op.orderid = o.id JOIN
     product p
     ON op.productid = p.productid
GROUP BY o.id;


text:
Q: Expressing two probability measures as an integral over their average. I've been given the following statement without proof and have been struggling to prove it myself:
Given two probability measures $\mathbf{P}_1$ and $\mathbf{P}_2$ there exists a probability measure $\nu$ as well as measurable functions $f_1$ and $f_2$ such that:
\begin{equation*}
\mathbf{P}_1(A) = \int_A f_0 d\nu \textrm{ and }
\mathbf{P}_2(A) = \int_A f_1 d\nu
\end{equation*}
It has also been stated that this claim can be proven using measure theory for $\nu = \frac{\mathbf{P}_1+\mathbf{P}_2}{2}$.
At first I thought that the claim can be proven trivially using Fubini's theorem, however I somehow couldn't get the form we need.
It has also been stated that in the case when $\mathbf P_1$ and $\mathbf P_2$ have probability densities $g_1$ and $g_2$ (for probability measures on the Borel algebra of $\mathbb R$) for any probability measure $\nu$ with probability density $g$ we get $f_i=\frac{g_i}{g}$.

A: You have to use the Radon-Nikodým theorem, which is applicable since both $P_1$ and $P_2$ are absolutely continuous w.r.t. $\nu$.

A: There is a nice proof using Hilbert space theory. The functional $\phi : L^2((P_1 + P_2)/2) \to \mathbb{C}$ defined by $$\phi(g) = \int g \,dP_1$$ is easily verified to be continuous by use of Cauchy Schwarz inequality. By Hilbert space theory, there exists $f \in L^2((P_1 + P_2)/2)$ such that for all $g \in L^2((P_1 + P_2)/2)$, $$\int g \,dP_1 = \int gf \,d\nu.$$
Since indicators $g = 1_A$ are in $L^2$, we are done.


text:
Q: How to pause flash application in browser? How to pause flash application in browser if there isn't any buttons that would allow it ?

A:
Well, there is a website, there is a swf file, i want to pause it.

Do you have access to these files and their source? Is it on the same domain?
Anyway, the previous two answers suggested wrapping the swf with another Flash application and then setting the framerate to 0. That's not accurate, because the minimum framerate you can set is 0.01. Flash code is built around the framerate, it makes sense.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Stage.html#frameRate
If you have access to the original files you want to pause, the proper way to accomplish this would be through ExternalInterface
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html
http://www.viget.com/inspire/bi-directional-actionscript-javascript-communication/

A: yes by adding this stage.frameRate = 0;
pause flash
Pause-Game-Using-stage-framerate
pause using javascript

A: Your question is a little vague, I'm a little confused at exactly what you want. I did find something that MIGHT help in this question. But here's what I saw that might help you out:
Embed an swf, that'll load the game. Then you'll be able to have some control, because the loaded SWF is running in the same instance as the loading SWF. For most games, it should suffice setting the frame rate to 0.
So setting the frame rate to 0 is essentially pausing it... But I would be able to provide a more detailed answer if you clarify your question a bit more.


text:
Q: Convert multichar %xx escapes to unicode In the middle of writing this I got this to work. Here it is anyway in case it's useful or the solution is less than optimal.
I have a unicode string u'http://en.wikipedia.org/wiki/Espa%C3%B1ol' from which I'd like to have u'http://en.wikipedia.org/wiki/Español'. My attempt using urllib.unquote gives me u'http://en.wikipedia.org/wiki/Espa\xc3\xb1ol'.

A: The string is unnecessarily unicode, so convert to a byte string representation first, then decode to unicode like so:
urllib.unquote(str(u'http://en.wikipedia.org/wiki/Espa%C3%B1ol')).decode('utf8')

A: The problem is that what %C3%B1 means depends on the encoding of the string.
As Unicode, it means ñ. As Latin-1, it also means ñ. As UTF-8, it means ñ.
So, you need to unescape those characters before decoding from UTF-8.
In other words, somewhere, you're doing the equivalent of:
u = urllib.unquote(s.decode('utf-8'))

Don't do that. You should be doing:
u = urllib.unquote(s).decode('utf-8')

If some framework you're using has already decoded the string before you get to see it, re-encode it, unquote it, and re-decode it:
u = urllib.unquote(u.encode('utf-8')).decode('utf-8')

But it would be better to not have the framework hand you charset-decoded but still quote-encoded strings in the first place.


text:
Q: Windows service does not capture shutdown event C/C++ I created a small windows service to capture some events, including the system shutdown. Every time I turn off the computer, the service event is not called. But when I restart the computer the event works normally.
I already tried to use: SERVICE_ACCEPT_PRESHUTDOWN + SERVICE_CONTROL_PRESHUTDOWN and was not successful.
How could I catch the computer shutdown event?
Ps: After compiling I register the service with the following command: sc.exe create "ZSimpleService" binPath = "C:\path\ZSimpleService.exe"
Edit 1: I'm using windows 10
Code:
SERVICE_STATUS g_ServiceStatus = { 0 };
SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
HANDLE g_ServiceStopEvent = INVALID_HANDLE_VALUE;

VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv);
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam);
DWORD WINAPI CtrlHandlerEx(DWORD CtrlCode, DWORD eventType, LPVOID eventData, LPVOID context);

#define SERVICE_NAME _T("ZSimpleService")

VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv) {

    g_StatusHandle = RegisterServiceCtrlHandlerEx(SERVICE_NAME, CtrlHandlerEx,
    NULL);

    if (g_StatusHandle == NULL) {
        goto EXIT;
    }

    // Tell the service controller we are starting
    ZeroMemory( & g_ServiceStatus, sizeof(g_ServiceStatus));

    g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP
            | SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_SESSIONCHANGE
            | SERVICE_ACCEPT_SHUTDOWN;
    g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwServiceSpecificExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        //...
    }

    g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (g_ServiceStopEvent == NULL) {
        //...
        goto EXIT;
    }

    g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        //...
    }

    HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThread, NULL, 0, NULL);

    WaitForSingleObject(hThread, INFINITE);

    CloseHandle(g_ServiceStopEvent);

    g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 3;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {

    }

    EXIT: return;
}

void suspending() {
    FILE *file = fopen("C:\\test\\suspending.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void logoff() {
    FILE *file = fopen("C:\\test\\logoff.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void lock_session() {
    FILE *file = fopen("C:\\test\\lock_session.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void poweroff() {
    FILE *file = fopen("C:\\test\\poweroff.txt", "w+");
    if (file)
        fprintf(file, "...");
}

DWORD WINAPI CtrlHandlerEx(DWORD CtrlCode, DWORD eventType, LPVOID eventData,
        LPVOID context) {
    switch (CtrlCode) {

    case SERVICE_CONTROL_STOP: {
        g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
        g_ServiceStatus.dwWin32ExitCode = 0;
        g_ServiceStatus.dwCheckPoint = 0;
        g_ServiceStatus.dwWaitHint = 0;

        if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
            //...
        }

        SetEvent(g_ServiceStopEvent);

        return NO_ERROR;
    }
    case SERVICE_CONTROL_POWEREVENT: {
        if (eventType == PBT_APMQUERYSUSPEND) {
            //Computer is suspending
            suspending();

        }
        return NO_ERROR;
    }
    case SERVICE_CONTROL_SESSIONCHANGE: {
        switch (eventType) {
        case WTS_SESSION_LOGOFF:
            //User is logging off
            logoff();
            break;
        case WTS_SESSION_LOCK:
            //User locks the session
            lock_session();
            break;
        }
        return NO_ERROR;
    }
    case SERVICE_CONTROL_SHUTDOWN: {
        //Computer is shutting down
        poweroff();

        return NO_ERROR;
    }
    default:
        return ERROR_CALL_NOT_IMPLEMENTED;
    }

}

DWORD WINAPI ServiceWorkerThread(LPVOID lpParam) {

    while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0) {

        //many cool code....

        Sleep(3000);
    }

    return 0;
}

DWORD RunService() {
    SERVICE_TABLE_ENTRY serviceTable[] = { { SERVICE_NAME, ServiceMain },
            { 0, 0 } };

    if (StartServiceCtrlDispatcher(serviceTable)) {
        return 0;
    } else {
        DWORD erro = GetLastError();

        //handler erro...

        return 1;
    }
}

int _tmain(int argc, TCHAR *argv[]) {
    RunService();
    return 0;
}

A: When the fast startup option enabled, click start menu -> shutdown will put the machine into sleep mode/hibernation instead of shutdown. But restart menu isn't affected. (And shuting down from command line isn't affected too as we already found.)
So you can disable fast startup to solve this issue.


text:
Q: Push data from TextFormField Flutter to Listview.builder Items when form field is validated I have form field :
This form field will collect all the data from my client.
Each of these field is specific and I want push the entry of each of these field into a ListView.builder according to the name of the field.
For example the field " Alias" has to be push into the listview.builder that you can see above, and the others fields has to be push to another listview.builder in order to build an address book.
this is my code for listview.builder.
Please I accept suggestion how to to that thanks:
Container(
            height: 1000,
            child: ListView.builder(
              shrinkWrap: true,
              itemBuilder: (ctx, int) {
                return Card(
                    color: Color(0xFF1f2032),
                    elevation: 15,
                    child: Container(
                      width: 60,
                      height: 60,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          Card(
                            color: Color(0xfffeaf0d),
                            child: Container(
                                height: 40,
                                width: 40,
                                child: Icon(Icons.location_on,color: Colors.white,size: 25,)),

                          ),
                          Text('User id № $int',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
                          Text(userDestinationFullName,style: TextStyle(fontWeight: FontWeight.bold,color: Color(0xfffeaf0d),),),
                          Text(aliasName,style: TextStyle(color: Colors.lightGreenAccent),),
                          Icon(Icons.cancel,color: Colors.white,)
                        ],
                      ),
                    ));
              },
            ),
          ),

A: Ok
the list view is the code I posted above
in such listview I need to have the data that I retrieve from the formfield which the customer will fill up.
For example:
In the field "Alias" into the form customer will write " Home "
this "Home" has to be shown into the listview
Customer will also write as "Nome e Cognome" the full name of the for example "Mario Rossi", then Mario Rossi has to appear into the list view in a single row.
this is the screenshot of the list view.
https://ibb.co/LN2nVtk
as you can see the horizontal list where is + alias, Alias... has to be substitute with the written field that customer fill in the form
vertical ListView has rows with several text, each of these text is a field into the form, so each of these field has to be substitute with the written filled into the form

A: This is just a field to a form
for example Full name field once filled the content has to be push into the listview as shipmentFullName
Widget FullName() {
  return TextFormField(
    validator: (value) {
      if (value.isEmpty) {
        return 'Nome e Cognome obbligatorio';
      }
      return null;
    },
    keyboardType: TextInputType.text,
    style: TextStyle(color: Color(0xFF1f2032), fontSize: 14),
    decoration: InputDecoration(
      fillColor: Color(0xfffeaf0d),
      filled: true,
      labelText: 'Nome e Cognome',
      labelStyle: TextStyle(color: Color(0xFF1f2032)),
      prefixIcon: Icon(
        Icons.person_add,
        color: Color(0xFF1f2032),
        size: 17,
      ),
      hintStyle: TextStyle(
        color: Color(0xFF1f2032),
      ),
      hintText: 'Nome e Cognome del Destinatario',
      contentPadding: EdgeInsets.symmetric(vertical: 5, horizontal: 35.0),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFF1f2032), width: 1.5),
        borderRadius: BorderRadius.circular(5),
      ),
    ),
  );
}


text:
Q: have separate js objects in a webpack project which interact with same variable I wanted to know if it was possible by combining webpack and js' oop to arrive at a functional code like the one presented below.
The goal is to be able to isolate each of the elements of my site (sidebar, main,...) in different files while making sure that they can interact between.
Is this possible with webpack and pure js or not?
import ApplePicker from "./my_path/applePicker.js";
import NiceFarmer from "./my_path/niceFarmer.js";

const orchard = function () {
    const appleNumber = 10;

    const jack = new ApplePicker();
    const daniel = new NiceFarmer();

    jack.eatAnApple();
    daniel.eatAnApple();

    // appleNumber have to be now === 2

}

// Example of applePicker.js structure

const ApplePicker = function () {

    this.eatAnApple = function () {
        // Do something
    }

}

export default ApplePicker;

A: yes you can.
If you simply want to consume a variable from applePicker.js:
// applePicker.js
export const apples = 10

If you want to be able to reassign that variable you might want to add a simple facade layer on top of that:
// applePicker.js
let apple = 5

export function getApple() {
   return apple;
}

export function setApple(newValue) {
   apple = newValue;
}

Even better, if you want other functions to "fire" when a variable is changed, use the Observer pattern


text:
Q: Prepare repo vm for Ubuntu upgrade Assume there are 10 VM's, installed w Ubuntu 18 (Bionic Beaver).
As a security regulation, only 1 specific 'repo server' download packages via the internet from an external repo. The remaining VM's are not connected to the internet, and download packages via this repo server. The VM's configure this in /etc/apt/sources.list. This works properly.
Now, the issue I'm struggling with is preparing the upgrade of the environment to Ubuntu 20.04. The repo server should have packages available for an upgrade.
How can I configure the repo server to:

*

*Download packages for Ubuntu 20.04, without meddling with the Ubuntu 18.04 packages placed on disk

*Download only the 'latest' and/or required packages for 20.04, instead of downloading 'all' packages

*Ensure all 'other' required files are present on this vm, so other the clients can easily perform the upgrade

*Download only files for the sources, as currently configured:

deb http://ftp.nluug.nl/os/Linux/distr/ubuntu/ bionic main restricted multiverse
deb http://ftp.nluug.nl/os/Linux/distr/ubuntu/ bionic-updates main restricted multiverse
deb http://ftp.nluug.nl/os/Linux/distr/ubuntu/ bionic universe
deb http://ftp.nluug.nl/os/Linux/distr/ubuntu/ bionic-updates universe

FYI, apt-mirror is currently used to clone files from an external repo.

A: I also use apt-mirror and transitioned from 18.04 to 20.04.
Long story short, I just added the 20.04 sources to my mirror.list. This worked fine as far as downloading the packages. However...
You will run into problems there, because apt-mirror is not maintained, and changes in how apt works in 20.04 broke it. (see this Q&A Apt-mirror for amd64 did not include focal/main/dep11 and focal/main/cnf/Commands-amd64) I had to go to https://github.com/Stifler6996/apt-mirror and download a forked version. This helped greatly, but still was not a complete fix. I had to add these lines to my postmirror.sh to unpack the c-n-f files.
unxz -fk [mirror location]/mirror/us.archive.ubuntu.com/ubuntu/dists/focal-security/main/cnf/Commands-amd64.xz
unxz -fk [mirror location]/mirror/us.archive.ubuntu.com/ubuntu/dists/focal-security/multiverse/cnf/Commands-amd64.xz
unxz -fk [mirror location]/mirror/us.archive.ubuntu.com/ubuntu/dists/focal-security/restricted/cnf/Commands-amd64.xz
unxz -fk [mirror location]/mirror/us.archive.ubuntu.com/ubuntu/dists/focal-security/universe/cnf/Commands-amd64.xz
#
unxz -fk [mirror location]/mirror/us.archive.ubuntu.com/ubuntu/dists/focal-updates/main/cnf/Commands-amd64.xz
unxz -fk [mirror location]/mirror/us.archive.ubuntu.com/ubuntu/dists/focal-updates/multiverse/cnf/Commands-amd64.xz
unxz -fk [mirror location]/mirror/us.archive.ubuntu.com/ubuntu/dists/focal-updates/restricted/cnf/Commands-amd64.xz
unxz -fk [mirror location]/mirror/us.archive.ubuntu.com/ubuntu/dists/focal-updates/universe/cnf/Commands-amd64.xz

(I may have done a one-time unzip on the basic repo, I can't remember)
After all that, the mirror worked well for 20.04. Once I transitioned all the systems from 18.04, I removed the 18.04 lines from mirror.list and apt-mirror cleaned up the mirror automatically.


text:
Q: How to detect spaces in shell script variable e.g string = "test test test"
I want after finding any occurance of space in string, it should echo error and exit else process.

A: The case statement is useful in these kind of cases:
case "$string" in
    *[[:space:]]*)
        echo "argument contains a space" >&2
        exit 1
        ;;
esac

Handles leading/trailing spaces.

A: There is more than one way to do that; using parameter expansion
you could write something like:
if [ "$string" != "${string% *}" ]; then
     echo "$string contains one or more spaces";
fi

A: For a purely Bash solution:
function assertNoSpaces {
    if [[ "$1" != "${1/ /}" ]]
    then
        echo "YOUR ERROR MESSAGE" >&2
        exit 1
    fi
}

string1="askdjhaaskldjasd"
string2="asjkld askldja skd"

assertNoSpaces "$string1"
assertNoSpaces "$string2" # will trigger error

"${1/ /}" removes any spaces in the input string, and when compared to the original string should be exactly the same if there are not spaces.
Note the quotes around "${1/ /}" - This ensures that leading/trailing spaces are taken into consideration.
To match more than one character, you can use regular expressions to define a pattern to match - "${1/[ \\.]/}".
update
A better approach would be to use in-process expression matching. It will probably be a wee bit faster as no string manipulation is done.
function assertNoSpaces {
    if [[ "$1" =~ '[\. ]' ]]
    then
        echo "YOUR ERROR MESSAGE" >&2
        exit 1
    fi
}

For more details on the =~ operator, see the this page and this chapter in the Advanced Bash Scripting guide.
The operator was introduced in Bash version 3 so watch out if you're using an older version of Bash.
update 2
Regarding question in comments:

how to handle the code if user enter
    like "asd\" means in double quotes
    ...can we handle it??

The function given above should work with any string so it would be down to how you get input from your user.
Assuming you're using the read command to get user input, one thing you need to watch out for is that by default backslash is treated as an escape character so it will not behave as you might expect. e.g.
read str              # user enters "abc\"
echo $str             # prints out "abc", not "abc\"
assertNoSpaces "$str" # no error since backslash not in variable

To counter this, use the -r option to treat backslash as a standard character. See read MAN Page for details.
read -r str           # user enters "abc\"
echo $str             # prints out  "abc\"
assertNoSpaces "$str" # triggers error

A: The == operator inside double brackets can match wildcards.
if [[ $string == *' '* ]]

A: You can use grep as:
string="test test test"
if ( echo "$string" | grep -q ' ' ); then
        echo 'var has space'
        exit 1
fi

A: I just ran into a very similar problem while handling paths. I chose to rely on my shell's parameter expansion rather than looking for a space specifically. It does not detect spaces at the front or the end, though.
function space_exit {
  if [ $# -gt 1 ]
  then
    echo "I cannot handle spaces." 2>&1
    exit 1
  fi
}


text:
Q: How to solve cyclic dependencies while installing software on linux? I am new to the computing world. My intention is to figure out a generic approach to solve cyclic dependencies while installing new software on Linux, if it exists. Here I am using the case of Google chrome to better illustrate my question. While installing Google chrome (both using package manager and apt-get) I encounter the following problem:
Selecting previously unselected package google-chrome-stable.
(Reading database ... 262709 files and directories currently installed.)
Preparing to unpack google-chrome-stable_current_amd64.deb ...
Unpacking google-chrome-stable (55.0.2883.87-1) ...
dpkg: dependency problems prevent configuration of google-chrome-stable:
google-chrome-stable depends on libappindicator1; however:
Package libappindicator1 is not installed.

To solve the above error, I tried installing libappindicator1 but that returns another dependency error:
The following packages have unmet dependencies:
libappindicator1 : Depends: libindicator7 (>= 0.4.90) but it is not going to be installed

Now here we encounter the cyclic dependency. When trying to install libindicator7 the following error is received:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 google-chrome-stable : Depends: libappindicator1 but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

As you can see that I cannot install the package because of the dependencies. Now one way is to use apt-get -f install and let Linux magically do it's work. But that won't teach me much. Using this example (or suggest a better example), can we figure out a better approach to solve the problem of cyclic dependency? If this is a stand-alone case of cyclic dependency while installing a new software or I made a mistake in interpreting the errors then I can remove the question.
Some helpful links-
[1]: https://askubuntu.com/questions/764040/im-having-a-hard-time-installing-google-chrome-on-16-04-lts-please-help [2]: How to solve Cyclic Dependency [3]: How to Solve Circular Dependency [4]: cyclic dependency ... how to solve?

A: The problem is usage of dpkg to install google-chrome-stable. DPKG does now install the required dependencies and leave the system in a broken state.
sudo apt install ./google-chrome-stable.deb

This installs the package with required dependencies.
dpkg only installs a package, so doing dpkg -i packageName.deb will only install this Deb package, and will notify you of any dependencies that need to be installed, but it will not install them, and it will not configure the packageName.deb because well...the dependencies are not there.
apt is a Package Management System that handles the installation of Deb packages on Debian-based Linux distributions. A Package Management System is a set of tools that will help you install, remove, and change packages easily. So apt is like a clever dpkg

A: DPKG is the software at the base of the package management system in the free operating system Debian and its numerous derivatives. dpkg is used to install, remove, and provide information about .deb packages. dpkg (Debian Package) itself is a low-level tool. [1]
APT (for Advanced Package Tool) is a set of tools for managing Debian packages, and therefore the applications installed on your Debian system. APT makes it possible to  Install applications, Remove applications, Keep your applications up to date and much more.[2]
So if you move step by step on your installation

*

*Once you download a .deb package you can unzip it. Unzip the contained control.tar.gz file. You would find a set of all the required packages.

*Find all the dependencies for that specific Debian package. For google-chrome you would have something like
Package: google-chrome-stable
Version: 55.0.2883.87-1
Architecture: amd64
Maintainer: Chrome Linux Team <chromium-dev@chromium.org>
Installed-Size: 175549
Pre-Depends: dpkg (>= 1.14.0)
Depends: gconf-service, libasound2 (>= 1.0.16), libatk1.0-0 (>= 1.12.4), libc6 (>= 2.11), libcairo2 (>= 1.6.0), libcups2 (>= 1.4.0), libdbus-1-3 (>= 1.1.4), libexpat1 (>= 2.0.1), libfontconfig1 (>= 2.9.0), libfreetype6 (>= 2.3.9), libgcc1 (>= 1:4.1.1), libgconf-2-4 (>= 2.31.1), libgdk-pixbuf2.0-0 (>= 2.22.0), libglib2.0-0 (>= 2.26.0), libgtk2.0-0 (>= 2.24.0), libnspr4 (>= 2:4.9-2~) | libnspr4-0d (>= 1.8.0.10) | libnspr4 (>= 4.9.5-0ubuntu0), libnss3 (>= 2:3.13.4-2~) | libnss3-1d (>= 3.12.4), libpango1.0-0 (>= 1.14.0), libstdc++6 (>= 4.8.0), libx11-6 (>= 2:1.4.99.1), libx11-xcb1, libxcb1 (>= 1.6), libxcomposite1 (>= 1:0.3-1), libxcursor1 (>> 1.1.2), libxdamage1 (>= 1:1.1), libxext6, libxfixes3, libxi6 (>= 2:1.2.99.4), libxrandr2 (>= 2:1.2.99.3), libxrender1, libxss1, libxtst6, ca-certificates, fonts-liberation, libappindicator1, libnss3 (>= 3.17.2), lsb-base (>= 4.1), xdg-utils (>= 1.0.2), wget
Provides: www-browser
Section: web
Priority: optional
Description: The web browser from Google
Google Chrome is a browser that combines a minimal design with sophisticated technology to make the web faster, safer, and easier.

*You would need to install all the dependencies for that specific package. Each dependency might depend on a set of other dependencies. You would have a tree of these dependencies. Either you can manually install all these dependencies or use something like apt or yum or aptitude ...

*What either of these package managers would do for you is they would construct a dependency tree for you and install all the relevant packages before installing your Debian package.
So, Ideally there should not be any loops in the dependency tree, but it might be the case that some of the existing packages are already installed and are in newer/older version of what is currently installed and is a required package for an already existing installed package. Then you can end up in cyclic dependency loop.
So, how apt handles cyclic dependencies is mentioned in [3], I think you can consider it as a generic algorithm for solving a dependency manually but it's not recommended. Circular dependencies happen in the repositories, but the ones left standing to obey some specific rules. Usually, these are tightly bound packages. So the Depends relationship between them specifies the exact version number.

*

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

*https://wiki.debian.org/Apt

*https://web.archive.org/web/20150905091555/http://algebraicthunk.net/~dburrows/blog/entry/from-blogspot/2005-05-09--21:30:00/

A: What helped me with installing libappindicator1 on Debian and in Docker as well - is installing this package manually. Also, it depends on another one libindicator7.
RUN curl -p --insecure "http://ftp.de.debian.org/debian/pool/main/liba/libappindicator/libappindicator1_0.4.92-7_amd64.deb" --output libappindicator1_0.4.92-8_amd64.deb \
    && curl -p --insecure "http://ftp.de.debian.org/debian/pool/main/libi/libindicator/libindicator7_0.5.0-4_amd64.deb" --output libindicator7_0.5.0-4_amd64.deb \
    && dpkg -i libindicator7_0.5.0-4_amd64.deb \
    && dpkg -i libappindicator1_0.4.92-8_amd64.deb \
    && rm libindicator7_0.5.0-4_amd64.deb \
    && rm libappindicator1_0.4.92-8_amd64.deb


text:
Q: The long_words function returns all words that are at least 7 characters. Fill in the regular expression to complete this function Can anyone help me with this code?
import re
def long_words(text):
  pattern = ___
  result = re.findall(pattern, text)
  return result

print(long_words("I like to drink coffee in the morning.")) # ['morning']
print(long_words("I also have a taste for hot chocolate in the afternoon.")) # ['chocolate', 'afternoon']
print(long_words("I never drink tea late at night.")) # []

I need help

A: import re
def long_words(text):
  pattern = "\w{7,}"
  result = re.findall(pattern, text)
  return result
text='I like to drink coffee in the morning.'

print(long_words("I like to drink coffee in the morning.")) # ['morning']
print(long_words("I also have a taste for hot chocolate in the afternoon.")) # ['chocolate', 'afternoon']
print(long_words("I never drink tea late at night.")) # []

Here, \w matches the word and {7,} searches for minimum length of 7
learn more about python regex here


text:
Q: How to get duration of webm video file when duration is not explicitly defined I have a segment of a webm file with an incomplete header, I want to cut this segment down to 10 seconds by trimming x seconds off the front of the file, however I am unable to use the -sseof tag because the end of the file isn't defined. I have discovered that if I ask ffmpeg to pull out the audio or video from the file it responds with some data long the lines of size=     212kB time=00:00:13.32 bitrate= 130.2kbits/s speed=1.79e+03x     video:0kB audio:210kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.991311% Showing that there is 13.32 seconds of data in the file, however if I use ffprobe for the file length it replies with N/A. Is there a way to get that 13.32 value by itself without encoding the webm file?

A: Run
ffprobe -v 0 -hide_banner -of compact=p=0:nk=1 -show_entries packet=pts_time -read_intervals 99999%+#1000 input.webm | tail -1
Assuming the file isn't longer than 99999 seconds, this will print the timestamp of the last media packet in the file.


text:
Q: Can Generic Class be method/return type? I am Currently learning Generics I have this Generic class here
package generics.lesson;

public class Pair<T> {

    private T first;
    private T second;

    public Pair(){ first = null; second = null; }
    public Pair(T first, T second){ this.first = first ; this.second = second;}

    public T getFirst() { return first; }
    public T getSecond() { return second; }

    public void setFirst(T first) { this.first = first; }
    public void setSecond(T second) { this.second = second; }
}

So far I understand this but then I came across this
public static Pair<String> minmax(String[] a)
    {
        if(a.length == 0 || a == null) return null;
        String min = a[0];
        String max = a[0];

        for(int i = 1 ;  i < a.length ; i++)
        {
            if(min.compareTo(a[i])>0) min = a[i];
            if(max.compareTo(a[i])<0) max  = a[i];
        }
        return new Pair<String>(min,max);
    }

What confuses me is this
public static Pair<String> minmax(String[] a)

QUestion
How is this possible? and can a generic class be a method return type?

A: Yes, it can.
Why would you think it can't?

A: If this works
public T getFirst() { return first; } // returns a generic type
public T getSecond() { return second; } // returns a generic type

(which you said you "understand this")
I would expect this to also work
public static Pair<String> minmax(String[] a) // returns a generic type

BTW: In Java 1.4 neither works, In Java 5.0+ both work. ;)


text:
Q: Why does getting a xml dataset table return all values?
Currently, I have this Datagridview displaying some XML data, the data is
<?xml version="1.0" encoding="utf-8" ?>
<survey>
  <floor location="Drill Floor">
    <sign location ="1" ref="OFS-FE01" size="180x180"  Material="RPP" Quantity="2" Backingboard="No"  />
  </floor>
  <floor location="Top Deck">
    <sign location ="2" ref="OFS-FE07" size="180x180"  Material="RPP" Quantity="2" Backingboard="Yes"  />
  </floor>
  </survey>

This is where I'm stuck as there are multiple floors and I need a way to display only a chosen floor location.
    private void Form4_Load(object sender, EventArgs e)
    {
        DataSet dataSet = new DataSet();
        dataSet.ReadXml(@"basicStorage.sws", XmlReadMode.Auto);
        datagridview.DataSource = dataSet.Tables[1].DataSet.Tables[1];
    }

Above is how im loading the datagridview, It works but it gets all the places, while I only want to get it from a certain floor.

A: You could pre-process the XML file to remove the data which you don't want to show in the data grid view (I'm assuming basicStorage.sws is an xml file)
For example:
private void Form4_Load(object sender, EventArgs e)
{
    XDocument storedData = XDocument.Load(@"basicStorage.sws");

    // the floor that you want to keep
    string selectedFloor = "Drill Floor";

    // remove everything that isn't the floor we want to keep
    storedData
        .Descendants("floor")
        .Where(a => a.Attribute("location").Value != selectedFloor)
        .Remove();

    // now use the remaining xml to populate the dataset
    DataSet dataSet = new DataSet();
    dataSet.ReadXml(storedData.CreateReader());
    datagridview.DataSource = dataSet.Tables[1].DataSet.Tables[1];
}


text:
Q: Customizing TraceSource to avoid creating TraceEventCache My project have many classes. Each class use TraceSource for logging. I don't want to use TraceEventCache while logging. Basically the answer for it is we can tell the listner to do not  write TraceEventCache using TraceOptions (CallStack, ProcessID etc). That means TraceSource already has the TraceEventCache. So my question is does TraceData and TraceEvent methods of TraceSource class create TraceEventCache for every call ? Or is just single object created by the framework per thread and just used in TraceSource class.

A: Your question hinges on how you think the TraceSource class is written.  Better than speculating, you can check the reference source code, both Microsoft's and Mono's.
Anyhow, in there you can see this is called for each call to Trace(...)
TraceEventCache manager = new TraceEventCache();

As far as I can tell, the only way in which it behaves like a cache is that call stack (and a few other) properties defer determining their values until called and if called twice, return the value from a local variable. This is because things like CallStack are slow. Otherwise, TraceEventCache is just a collection of boring properties. It isn't a cache like the ASP.NET intrinsic Cache.
To improve performance, just don't tell any of your trace listeners to output the call stack or any thing else that might be slow.


text:
Q: Computing an Exponential Moving Average Via Convolution According to the Wikipedia page on moving averages, "This is also why sometimes an EMA is referred to as an $N$-day EMA.  Despite the name suggesting there are $N$ periods, the terminology only specifies the $\alpha$ factor.  $N$ is not a stopping point for the calculation in the way it is in an SMA or WMA."
I was very shocked to read this. It seems to be suggesting that the sequence of weights used to compute the Exponential Moving Average via discrete convolution with, i.e., historical market price data goes on forever. I understand that the sum of an infinite number of weights can converge to $1$, but not how an infinite weight function sequence could be convolved with a finite sequence of historical market price data.
How is an $N$-period Exponential Moving Average computed as the convolution of a weight function and historical data? Is the weight function sequence indeed infinite, or does it only contain $N (\pm 1?)$ elements, or does it contain as many elements as historical data points are available $(\pm 1?)$ which is usually greater than $N$? This distinction seems important because adding additional elements will re-normalize the significant elements given that all elements sum to $1$.  What is a typical example of how this convolution product would be formulated?

A: As the comment by @MinusOneTwelfth suggests, the recursive formula for the exponential moving average $$E_n = \alpha x_n + (1-\alpha) E_{n-1}$$ admits an expression as a sum:
$$\begin{align*}
E_n &= \alpha x_n + (1-\alpha) E_{n-1} \\
&= \alpha x_n + (1 - \alpha) \left( \alpha x_{n-1} + (1-\alpha)E_{n-2} \right) \\
&= \alpha x_n +\alpha (1-\alpha) x_{n-1} +(1-\alpha)^2 E_{n-2} \\
&\vdots \\
&= \alpha\sum_{k=0}^\infty (1-\alpha)^kx_{n-k}
\end{align*}$$
where we note that the sum is well-defined if, for instance, $0 < \alpha < 1$ and $\sup \mathbb{E}(X_n^2) < \infty$, via a geometric series argument.
Sadly, in practice, we don't often have access to time series of infinite legnth indexed by $\mathbb{Z}$, so we must truncate this expression somehow. What we may do is set $$\hat{E}_n = \alpha\sum_{k=0}^{N-1}(1-\alpha)^kx_{n-k} + (1-\alpha)^N x_{n-N}$$
where $N$ is a parameter that may be chosen to agree with the terminology "$N$-day EMA"; nevertheless, in practice people may use the entire time series instead. Notice that this sum is indeed a convolution product between the time series and the sequence of exponentially decaying weights.
You may find a gentle introduction to exponential smoothing in Chapter 7 Rob Hyndman's book Forecasting: Principles and Practice.


text:
Q: Why base current is affected most on changing beta in voltage divider bias configuration of BJT? In the given voltage divider bias configuration when the value of \$ \beta \$ is changed from 80 to 140 the base current changes from 21.26\$\mu\text{A}\$ to 12.9\$\mu\text{A}\$ which is a change of 39 % where as the change in quantities like collector current,collector to emitter voltage is merely 5.4 % and 5.6 % respectively.

simulate this circuit – Schematic created using CircuitLab
So,my question is why has the base current changed the most?
My guess to this question is that base current is in micro amperes so a change of about 10 micro ampere ,wouldn't bring much change to the circuit,although the operating point will be shifted.

A: What if beta were infinity? The base voltage would be exactly defined by the potential divider formed by R1 and R2 and the 16 volt supply: -
i.e. Vb would be 16V \$\times \dfrac{9.1}{9.1+62}\$ = 2.048 volts.
If beta dropped from infinity, the current taken by the base (although small) would lower that 2.048 volts a little bit. With a base current of 20 uA, Vb drops to about 1.89 V (a drop of about 7.8%).
I converted the 16 volt source to a current source and paralleled R1 and R2 then subtracted 20 uA to get the new base voltage by the way
I'm just trying to demonstrate that a fundamentally massive swing in beta from around 90 to infinity results in a change in Vb of about 8%. This change in bias voltage has a knock-on effect on Ic and Ib of approximately the same amount.
If R1 and R2 were lowered in value by 10 the influence of the 20 uA base bias current would take Vb from 2.048 volts to 2.03 volts i.e. a drop of about 1%.
This is why "strong" bias resistor values are preferred because (in conjunction with an emitter resistor) the change in beta from one transistor to another (or from one temperature to another) results in a far smaller change in quiescent operating conditions.

A: Compute the Thevenin equivalent for the biasing point set by \$R_1\$ and \$R_2\$. In your case, this is \$V_{TH}=V\cdot\frac{R_2}{R_1+R_2}\approx 2.048\:\textrm{V}\$ and \$R_{TH}\approx 7.935\:\textrm{k}\Omega\$. The base current in the BJT then follows this calculation (which takes into account the thermal voltage's equivalent resistance):
$$\begin{align*}
I_B&=\frac{V_{TH}-V_{BE}}{R_{TH}+\left(\beta+1\right)\cdot R_E}\end{align*}$$
If I start out by estimating \$V_{BE}\approx 680\:\textrm{mV}\$, then I get the following results:
$$\begin{array}{l@{}r@{}c}
 & & I_{B} \\
\begin{array}{l}
\beta
\end{array}
&
\begin{array}{r}
80 \\
140
\end{array}
&
\begin{array}{l}
{
\begin{array}{cc}
21.95\:\mu\textrm{A} \\
13.26\:\mu\textrm{A}
\end{array}
}
\end{array}\end{array}$$
Which is close to your results. The above equation tells you all you need to know about why \$\beta\$ multiplies the effect of the emitter resistor. (The Early effect also affects this and would work to slightly reduce the base current from the above figures.)

You can see a related discussion I had a while back here: BJT amplifier (Vce) voltage!

A: Your confusion seems to come from an understanding of the BJT function which is not correct (better: not in accordance with the physical behaviour of the BJT).
Please note that - in contrast to the explanations which can be found, unfortunately, in some textbooks - the BJT is a voltage-controlled device and NOT a current-controlled part.
That means: It is the voltage VBE which detrmines the current Ic=f(Vbe). This function is the well-known transfer function as given by the famous W. Shockley.
Unfortunately, the BJT has a base current which cannot be avoided (but it has no controlling function!) and, therefore, it is also to be considered during calculation of the base resistors. However, if the resistor niveau is chosen relatively low the actual value of the base current (and the corresponding uncertainties) play a minor role only.
And exactly this was the effect you have observed.
For this purpose, it is common practice to select these resistors so that the current through the divider is at least 10 times the base current. In your example, the divider current is app. 230µA.
(Remark: Your question is a good example which shows why a false understanding of the BJT`s working principle can cause misunderstandings and confusion).

A: We want the bipolar to operate as a constant-current device, so the operating point, the Vce, is constant. Picking resistors to accomplish that ---the constant-current --- is an acquired design skill.


text:
Q: I don't fully understand scrollRectToVisible when I'm using contentInset I added very big text to UItextView. My initial offset is -55. Then I scrolled to the bottom of UITextView. My offset is 406.
Then I called scrollToZero. My offset is -55. I called scrollToZero again and my offset is 0. Why is scrollToZero so unpredictable? I don't undestand why offset changed when I clicked again.
-(void) viewDidLoad
{
 [super viewDidLoad];
 textView.text = @"Very big text";
 textView.contentInset = UIEdgeInsetsMake(55.0, 0, 0, 0);
 [textView scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO];
}

-(IBAction) scrollToZero:(id)sender
{
 [textView scrollRectToVisible:CGRectMake(0, 0, textView.frame.size.width, textView.frame.size.height) animated:NO];
}
-(IBAction) onLog:(id)sender
{
 NSLog(@"___content offset %f", textView.contentOffset.y);
}

A: I have been battling this very problem. I am convinced that this is a bug in the UIScrollView class, I can see no other explanation.
First set your insets to zero, call scrollRectToVisible:animated:, and then restore your insets. It only matters if the scroll-to rect is 'left of' the current rect. 'right of' works as expected.
CGRect rect = self.scrollView.bounds;
CGRect scrollToRect = CGRectOffset(rect, scrollDelta, 0);

if (CGRectIsLeftOfRect(scrollToRect, rect)) {
    UIEdgeInsets insets = self.carouselView.contentInset;
    self.scrollView.contentInset = UIEdgeInsetsZero;
    [self.scrollView scrollRectToVisible:scrollToRect animated:animated];
    self.scrollView.contentInset = insets;
} else {
    [self.scrollView scrollRectToVisible:scrollToRect animated:animated];
}


text:
Q: Alterar dinamicamente variável CSS dentro de uma iframe tenho a variável dentro do iframe definida assim:
:root {
  --color_bg: #ffffff;
}

Quero alterar essa variável CSS do lado de fora, ja tentei:
$(function() {
    setTimeout(function(){
        var iframe = $('iframe');
        $('.title', iframe.contents()).html('teste'); //FUNCIONA
        $(":root", iframe.contents()).css("--color_bg", '#000000'); //NAO FUNCIONA
        $('iframe').contents().find('html').css("--color_bg", '#000000'); //NAO FUNCIONA
    },1000)
});

Reparem que $('.title', iframe.contents()).html('teste'); funciona perfeitamente.
Se eu fizer $(":root").css("--color_bg", '#000000'); dentro do iframe também funciona sem problema.
Alguém tem ideia como posso fazer isto?

A: Depois de alguma pesquisa é testes arranjei uma soulção, não sei se é a mais elegante mas funciona:
$('iframe').contents().find('html').get(0).style.setProperty("--color_bg", "#000");

ou
$(":root", iframe.contents()).get(0).style.setProperty("--color_bg", "#000");


text:
Q: What makes a formula field non-deterministic and hence not available for a custom index? The Knowledge Article: 000006007 - Custom indexes for an organization to help improve performance lists the following in relations to indexes on formula fields:

Note:
    Formula field can also be indexed since Summer 12. The following rules have to be true in order to index a formula field:

*

*The formula contains fields from a single object only (not relationship fields).

*The formula field doesn't reference any non-deterministic functions (e.g. SYSDATE).

*The formula field doesn't reference any non-supported fields for including in indexes.  This list isn't documented anywhere specifically (there are lots of special cases), but in Spring 12(176), createdById was non-supported, but in Summer 12 (178), it is supported.  Same story for CreatedDate.

*The formula field contains references to Primary Keys (e.g Id)

  If one of the condition above is false, the "Add index" does not display on the BT of the field.

Referencing a date function that returns a different result each day is a clear example of something that would be non-deterministic.
What else would make a formula non-deterministic and therefore not available for a custom index?

A: I found the following in Force.com SOQL Best Practices: Nulls and Formula Fields:

Here are examples of common non-deterministic formulas. Force.com cannot index fields that:

*

*Reference other entities (i.e., fields accessible through lookup fields)

*Include other formula fields that span over other entities

*Use dynamic date and time functions (e.g., TODAY, NOW)

  A formula is also considered non-deterministic when it includes:

*

*Owner, autonumber, divisions, or audit fields (except for CreatedDate and CreatedByID fields)

*References to fields that Force.com cannot index

*

*Multi-select picklists

*Currency fields in a multicurrency organization

*Long text area fields

*Binary fields (blob, file, or encrypted text)

*Standard fields with special functionalities

*

*Opportunity: Amount, TotalOpportunityQuantity, ExpectedRevenue, IsClosed, IsWon

*Case: ClosedDate, IsClosed

*Product: Product Family, IsActive, IsArchived

*Solution: Status

*Lead: Status

*Activity: Subject, TaskStatus, TaskPriority

Also in Working with Very Large SOQL Queries - Custom Index Considerations for Selective SOQL Queries

*

*A custom index can't be created on these types of fields: multi-select picklists, currency fields in a multicurrency organization, long text fields, some formula fields, and binary fields (fields of type blob, file, or encrypted text.) New data types, typically complex ones, are periodically added to Salesforce, and fields of these types don't always allow custom indexing.

*You can't create custom indexes on formula fields that include invocations of the TEXT function on picklist fields.


text:
Q: php print integer in words
Possible Duplicate:
Converting a number (1, 2, 3) to a string (one, two, three) in PHP

I have a form in which products will be listed out when,i clich total chk box it will be calculated but,it will be integera only,i want this to print in words.
For eg:217 it should print in words two hundred seven only. Hope,this is clear.
Thnx in advance

A: PEAR's Numbers Words is old, but competent.

A: The duplicate question seems to answer this quite well, DAFFODIL, have a look there. You will have to have PEAR installed. Easiest way is to try Numbers_Words::toWords(200) and see if that throws up an error.


text:
Q: How to make a table column that belongs to two row-colomns I have produced a table that looks like this:

I want to reproduce the table almost identical as the picture, but I have some difficulties. I used the following:
\begin{table}[h]
\centering
\begin{tabular}{l|l|l|}
\hline
\multicolumn{1}{|l|}{\textbf{Type}}                   & \textbf{Model}                                                                                & \textbf{Example}                 \\ \hline
\multicolumn{1}{|l|}{A}                   & Belongs to A                                                                                & Example 1                             \\ \hline
\multirow{2}{*}{}                                     & \multirow{2}{*}{HERE IS PROBLEM}                                                                       & \multirow{2}{*}{PROBLEM} \\
                                                      &                                                                                &                                  \\ \hline
\multicolumn{1}{|l|}{\multirow{4}{*}{B}} & \begin{tabular}[c]   {@{}l@{}}Belongs to B\\  - \textit{Example1}\end{tabular} & Examples                               \\ \cline{2-3}
\multicolumn{1}{|l|}{}                                & Belongs to B                                                                                & Examples                  \\ \cline{2-3}
\multicolumn{1}{|l|}{}                                & Belongs to B                                                                                & Examples                           \\ \cline{2-3}
\multicolumn{1}{|l|}{}                                & Belongs to B                                                                                & Examples                              \\ \hline
\end{tabular}
\caption{Table problem}
\label{table123}
\end{table}

What I really want is the that 'A' and 'B' covers the cell with 'Belongs to A and B' , such that there is a overlap between A and B, as indicated in the figure.
Also, I would like to use:
\begin{enumerate} ... \end{enumerate}

in the table but did not succeed.
Any tips?

A: Like this? I used the makecell package, which allows for line breaks in cells, and a common formatting of specific cells, with the commands \makecell and \thead:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{array, multirow, makecell}
\renewcommand\theadfont{\normalsize\bfseries}
\renewcommand\theadalign{lc}

\begin{document}

\begin{table}[h]
  \centering\setcellgapes[t]{3pt}\makegapedcells
  \begin{tabular}{|l|l|l|}
    \hline
    \thead{Type} & \thead{Model} & \thead{Example} \\ \hline
    \multirow{2}{*}{A} & Belongs to A & Example 1 \\ \cline{2-3}
    & \raisebox{-1.5ex}[\height][0pt]{HERE IS PROBLEM} & \raisebox{-1.5ex}[\height][0pt]{PROBLEM} \\ \cline{1-1}
    \multirow{6}{*}[-1ex]{B} & & \\\cline{2-3}
   & \makecell[t]{Belongs to B \\ - \textit{Example1}} & Examples \\ \cline{2-3}
     & Belongs to B & Examples \\ \cline{2-3}
     & Belongs to B & Examples \\ \cline{2-3}
    & Belongs to B & Examples \\ \hline
  \end{tabular}
  \caption{Table problem}
  \label{table123}
\end{table}

\end{document}


text:
Q: Discord Bot Issue - TypeError: Cannot read properties of null (reading 'id') I'm getting the following error: TypeError: Cannot read properties of null (reading 'id') at /index.js:144:31. My index.js code is below:
if(interaction.customId == 'generateCode') {

        // defer
        await interaction.deferReply({ ephemeral: true });

        // already generated?
        data = JSON.parse(fs.readFileSync(`./system/index.json`));
*This is row 144, user.id is the issue*
        if(data.filter(t => t.id == interaction.user.id)[0]) {
            embed = new MessageEmbed()
                .setColor('DARK_BLUE')
                .setAuthor({ name: interaction.user.tag, iconURL: interaction.user.displayAvatarURL() })
                .setDescription("`"+data.filter(t => t.id == interaction.user.id)[0].code+"`")
            await interaction.editReply({ embeds: [embed] });
            return
        }

A: The error is telling you that your user object is null. It looks like the data = JSON.parse(fs.readFileSync()) is not pulling in the file.
Based on this: JSON.parse(fs.readFileSync()) returning a buffer - string of numbers readFileSync returns a buffer if you don't add an encoding.
data = JSON.parse(fs.readFileSync(`./system/index.json`, 'utf8'))


text:
Q: match multiple conditions with GNU sed I'm using sed to replace values in other bash scripts, such as:
somedata="$(<somefile.sh)"
somedata=`sed 's/ ==/==/g' <<< $somedata` # [space]== becomes ==
somedata=`sed 's/== /==/g' <<< $somedata` # ==[space] becomes ==

The same for ||, &&, !=, etc.  I think steps should be reduced with the right regex match.  The operator does not need surrounding spaces, but may have a space before and after, only before, or only after.  Is there a way to handle all of these with one sed command?
There are many other conditions not mentioned also.  The script takes more time to execute than desired.
The goal is to reduce the overall execution time so I am hoping to reduce the number of commands used with clever regex to match multiple conditions.
I'm also considering tr, awk or perl - whichever is fastest?

A: With GNU sed, you can use the | (or) operator:
$ sed -r 's/ *(&&|\|\|) */\1/g' <<< "foo && bar || baz"
foo&&bar||baz

*

**(&&|\|\|) *: search for zero or more space followed by any of the | separated strings followed by zero or more space

*the matching strings are captured and output using backreference

Edit:
As pointed out in comments, you can use the -E flag with GNU sed in place of -r. Your command will be more portable:
sed -E 's/ *(\&\&|\|\|) */\1/g'

As GNU sed also supports \| alternation operator with Basic Regular Expressions, you can use it for better readability:
sed 's/ *\(&&\|||\) */\1/g'

A: You can chain multiple sed substitutions with the -e flag:
$ echo -n "test data here" | sed -e 's/test/TEST/' \
                                 -e 's/data/HERE/' \
                                 -e 's/here/DATA/'
$ TEST HERE DATA

A: you can use a sedfile (-f option) alongside with the -i option (replace in-place, no need to store in env. variable):
sed -i -f mysedfile somefile.sh

mysedfile may contain expressions, 1 per line
s/ *&& */\&\&/g
s/ *== */==/g

(or use the -e option to use several expression, but if you have a lot of them, it wil become quickly unreadable)
BTW: -i option creates a temporary file within the processed file directory, so in the end, if operation succeeds, the original file is deleted and the temporary file is renamed into the original file name

When the end of the file is reached, the temporary file is renamed
       to the output file's original name.  The extension, if supplied,
       is used to modify the name of the old file before renaming the
       temporary file, thereby making a backup copy(2))

so there's no I/O overhead with that option. No need at all to store in a variable.


text:
Q: Google Chrome Javascript debugging issue It used to be that when I stopped at a breakpoint in Google Chrome, and hovered over a variable, there would be a popup showing me the value of that variable.  For some reason, that has simply stopped happening.  Can anyone think what might have stopped this behaviour and how I might be able to restore it?

A: Sometimes it hangs up and doesn't show tooltip the variable, but this could be fixed with closing/opening debugger.
There may be another reason. You're in one scope, but trying to access variable from another scope.
arr.forEach(function(e){ // breakpoint is here
  e.doSeomthing(); // but `e` in inner scope is not defined
});

The same for accesing property from outside scope. For latter one may switch on callstack and move to the proper call depth and scope.

A: This seems to be an intermittent problem with Chrome, which is sometimes caused by being in the wrong scope, but not always... sometimes Chrome is just stubborn and doesn't display the tooltip variable evaluations for no obvious reason.  I'd recommend trying to close and open the developer tools, and/or close and open Chrome.  It might get it working.  If that fails, use Firefox.  ;-)
Mine just started working again for no obvious reason.


text:
Q: Not Showing Detailsview in ModalPopupExtender i used ModalPopupExtender today only ,so i have not much idea how it works
i am stuck in problem here
i have Gridview showing all students data,now when i click on Linkbutton of particular student in Gridview than that student data should shown in Detailsview on popup
i am getting a perticular student data in Detailsview but its not showing in popup,should i have to add anything else here?
here is my code for modelpopupextender
aspx code-
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                    DataKeyNames="Stu_id" onselectedindexchanged="GridView1_SelectedIndexChanged">
                <Columns>
                    <asp:TemplateField HeaderText="ID">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Stu_id") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("Stu_id") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                            <asp:BoundField DataField="Fullname" HeaderText="name" />
                            <asp:BoundField DataField="Username" HeaderText="Username" />
                            <asp:BoundField DataField="Email" HeaderText="Email" />
                            <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                            <asp:LinkButton ID="btnviewdetails" runat="server" CausesValidation="false"
                                CommandName="Select" Text="select" CommandArgument='<%# Eval("Stu_id") %>'
                                onclick="LinkButton1_Click"></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                 </Columns>
            </asp:GridView>
        </ContentTemplate>
  </asp:UpdatePanel>
<asp:Button ID="btnshowpopup" runat="server"/>
        <asp:ModalPopupExtender ID="mdlpopup" runat="server" TargetControlID="btnshowpopup" PopupControlID="pnlpopup" CancelControlID="btncancel" BackgroundCssClass="pop">
        </asp:ModalPopupExtender>

    <asp:Panel ID="pnlpopup" runat="server" Width="500px" style="display:none">
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
            <ContentTemplate>

                <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="Stu_id" Height="50px" Width="125px">
                        <Fields>
                                <asp:BoundField DataField="Stu_id" HeaderText="ID" />
                                <asp:BoundField DataField="Fullname" HeaderText="Fullname" />
                                <asp:BoundField DataField="Username" HeaderText="Username" />
                                <asp:BoundField DataField="Email" HeaderText="Email" />
                        </Fields>
                </asp:DetailsView>

                       <asp:Button ID="btncancel" runat="server" Text="cancel" />

            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>

cs code-
public partial class Admin_Default : System.Web.UI.Page

 {
    portalDal dal = new portalDal();
    adminBal bal = new adminBal();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = bal.student_bind();
            GridView1.DataBind();
        }
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {

    }
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

    this.DetailsView1.Visible = true;
    LinkButton l1 = (LinkButton)sender;
    dal.stu_id = Convert.ToInt16(l1.CommandArgument);
    DetailsView1.DataSource = bal.select_student(dal);
    DetailsView1.DataBind();
    this.UpdatePanel2.Update();
    this.mdlpopup.Show();

}

bal file-
public DataTable student_bind()
    {
        con.Open();
        cmd = new SqlCommand("select * from Stu_registration", con);
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        con.Close();
        return dt;
    }

    public DataTable aselect_student(portalDal dal)
    {
        con.Open();
        cmd = new SqlCommand("select_student", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Stu_id", dal.stu_id);
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        con.Close();
        return dt;
    }

A: I few observations:

*

*You need to move the ModalPopupExtender control outside the Panel that you are using for the modal popup (pnlpopup, in your case).

*Once you do that, you'llneed to change your CancelControlID to UpdatePanel2$btncancel (otherwise your ModalPopupExtender won't be able to find the "btncancel" control inside that UpdatePanel).

*You also need to move the control you're using as the "TargetControlID" (btnshowpopup, in your case) outside of the modal popup control.

So your markup should look like this:
<asp:Panel ID="pnlpopup" runat="server" Width="500px" style="display:none">
    <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
                DataKeyNames="Stu_id" Height="50px" Width="125px">
                <Fields>
                    <asp:BoundField DataField="Stu_id" HeaderText="ID" />
                    <asp:BoundField DataField="Fullname" HeaderText="Fullname" />
                    <asp:BoundField DataField="Username" HeaderText="Username" />
                    <asp:BoundField DataField="Email" HeaderText="Email" />
                </Fields>
            </asp:DetailsView>

                <asp:Button ID="btncancel" runat="server" Text="cancel" />

        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Panel>

<asp:ModalPopupExtender ID="mdlpopup" runat="server"
    TargetControlID="btnshowpopup" PopupControlID="pnlpopup"
    CancelControlID="UpdatePanel2$btncancel" BackgroundCssClass="pop">
</asp:ModalPopupExtender>
<asp:Button ID="btnshowpopup" runat="server"/>

I would also change the order of the "Update" and "Show" commands in your codebaheind file.  I don't think it will make any difference, but it is definitely more logical:
this.mdlpopup.Show();
this.UpdatePanel2.Update();


text:
Q: Problem with horizontal and vertical centering of multiline cells in a table I'm having difficulties perfectly centering (both horizontally and vertically) a few cells in my table. Here is a screenshot of what it looks like right now:

The problem line is the one which begins with "Courant", "Champ magnétique", etc.
The text is rather centered, but is frustratingly slightly aligned to the left...
Here is my code:
\begin{table}[h]
\centering
\caption{Variation de l'amplitude de la force électromotrice en fonction du courant circulant dans des bobines d'Helmholtz à une fréquence de rotation de la bobine d'induction constante ($(40\pm2)$ Hz)}
\label{tableau1}
\begin{tabular}{|>{\centering\arraybackslash}m{1.25cm}|>{\centering\arraybackslash}m{1.25cm}|>{\centering\arraybackslash}m{1.25cm}|>{\centering\arraybackslash}m{1.25cm}|>{\centering\arraybackslash}m{1.3cm}|>{\centering\arraybackslash}m{1.3cm}|>{\centering\arraybackslash}m{2cm}|>{\centering\arraybackslash}m{2cm}|}
\hline
\multicolumn{2}{|>{\centering\arraybackslash}m{2.5cm}|}{Courant} & \multicolumn{2}{>{\centering\arraybackslash}m{2.5cm}|}{Champ magnétique} & \multicolumn{2}{>{\centering\arraybackslash}m{2.6cm}|}{Force électromotrice expérimentale (amplitude)} & \multicolumn{2}{>{\centering\arraybackslash}m{4cm}|}{Force électromotrice théorique (amplitude)} \tabularnewline
\hline
$I_1$ & $\Delta I_1$ & $B$ & $\Delta B$ & $\epsilon_{Exp. 0}$ & $\Delta \epsilon_{Exp. 0}$ & $\epsilon_{Th. 0}$ & $\Delta \epsilon_{Th. 0}$ \tabularnewline
\hline
(A) & (A) & (mT) & (mT) & (V) & (V) & (V) & (V) \tabularnewline
\hline
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \tabularnewline
\hline
0,55 & 0,04 & 0,50 & 0,04 & 0,10 & 0,04 & 0,90 & 0,02 \tabularnewline
\hline
1,00 & 0,04 & 0,91 & 0,05 & 0,20 & 0,04 & 0,16 & 0,04 \tabularnewline
\hline
1,50 & 0,05 & 1,36 & 0,07 & 0,28 & 0,04 & 0,25 & 0,05 \tabularnewline
\hline
2,00 & 0,05 & 1,81 & 0,08 & 0,39 & 0,04 & 0,32 & 0,07 \tabularnewline
\hline
2,50 & 0,06 & 2,3 & 0,1 & 0,47 & 0,04 & 0,41 & 0,09 \tabularnewline
\hline
3,20 & 0,06 & 2,9 & 0,1 & 0,57 & 0,04 & 0,5 & 0,1 \tabularnewline
\hline
3,52 & 0,07 & 3,2 & 0,1 & 0,66 & 0,04 & 0,6 & 0,1 \tabularnewline
\hline
\end{tabular}
\end{table}

Thanks!

A: To get the right wide of the \multicolumn you have to add the right \tabcolsep from the first column and the left from the second column to the both column widths. For example:
\multicolumn{2}{|>{\centering\arraybackslash}m{\dimexpr2.5cm+2\tabcolsep\relax}|}{Courant}

Code:
\documentclass[captions=tableabove]{scrartcl}

\usepackage{array}
\newcolumntype{M}[1]{>{\centering\arraybackslash}m{#1}}
\newcolumntype{T}[1]{M{\dimexpr#1+2\tabcolsep\relax}}

\begin{document}
\begin{table}[htb]
  \centering
  \caption{Variation de l'amplitude de la force électromotrice en fonction du courant circulant dans des bobines d'Helmholtz à une fréquence de rotation de la bobine d'induction constante ($(40\pm2)$ Hz)}
  \label{tableau1}
  \begin{tabular}{|*{4}{M{1.25cm}|}*{2}{M{1.3cm}|}*{2}{M{1.8cm}|}}
    \hline
    \multicolumn{2}{|T{2.5cm}|}{Courant}
      & \multicolumn{2}{T{2.5cm}|}{Champ magnétique}
      & \multicolumn{2}{T{2.6cm}|}{Force électromotrice expérimentale (amplitude)}
      & \multicolumn{2}{T{3.6cm}|}{Force électromotrice théorique (amplitude)} \tabularnewline
    \hline
    $I_1$ & $\Delta I_1$ & $B$ & $\Delta B$ & $\epsilon_{Exp. 0}$ & $\Delta \epsilon_{Exp. 0}$ & $\epsilon_{Th. 0}$ & $\Delta \epsilon_{Th. 0}$ \tabularnewline
    \hline
    (A) & (A) & (mT) & (mT) & (V) & (V) & (V) & (V) \tabularnewline
    \hline
    0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \tabularnewline
    \hline
    0,55 & 0,04 & 0,50 & 0,04 & 0,10 & 0,04 & 0,90 & 0,02 \tabularnewline
    \hline
    1,00 & 0,04 & 0,91 & 0,05 & 0,20 & 0,04 & 0,16 & 0,04 \tabularnewline
    \hline
    1,50 & 0,05 & 1,36 & 0,07 & 0,28 & 0,04 & 0,25 & 0,05 \tabularnewline
    \hline
    2,00 & 0,05 & 1,81 & 0,08 & 0,39 & 0,04 & 0,32 & 0,07 \tabularnewline
    \hline
    2,50 & 0,06 & 2,3 & 0,1 & 0,47 & 0,04 & 0,41 & 0,09 \tabularnewline
    \hline
    3,20 & 0,06 & 2,9 & 0,1 & 0,57 & 0,04 & 0,5 & 0,1 \tabularnewline
    \hline
    3,52 & 0,07 & 3,2 & 0,1 & 0,66 & 0,04 & 0,6 & 0,1 \tabularnewline
    \hline
  \end{tabular}
\end{table}
\end{document}

A: As a possible solution I would use the package makecell.
Voilà:
\documentclass[a4paper, 12pt]{article}

\usepackage[utf8]{inputenc}
\usepackage[english,french]{babel}
\usepackage{makecell}

\begin{document}

%makecell setting for fonts, spacing etc.
\setlength\rotheadsize{3cm}
\renewcommand\theadfont{\small}
\renewcommand\theadfont{\bfseries}
\renewcommand\theadset{\renewcommand\arraystretch{0.9}%
\setlength\extrarowheight{1pt}}
\renewcommand\cellalign{cc}
\renewcommand\cellgape{\Gape[1pt]}

\begin{table}[h]
\centering
\caption{Variation de l'amplitude de la force électromotrice en fonction du courant circulant dans des bobines d'Helmholtz à une fréquence de rotation de la bobine d'induction constante ($(40\pm2)$ Hz)}
\vspace{1ex}
\label{tableau1}
\begin{tabular}{*{8}{|m{1.25cm}}|}
\hline
\multicolumn{2}{|c|}{\thead{Courant}} & \multicolumn{2}{c|}{\thead{Champ\\ magnétique}} & \multicolumn{2}{c|}{\thead{Force\\ électromotrice\\ expérimentale\\ (amplitude)}} & \multicolumn{2}{c|}{\thead{Force\\ électromotrice\\ théorique\\ (amplitude)}} \tabularnewline
\hline
\makecell{$I_1$} & \makecell{$\Delta I_1$} & \makecell{$B$} & \makecell{$\Delta B$} & \makecell{$\epsilon_{Exp. 0}$} & \makecell{$\Delta \epsilon_{Exp. 0}$} & \makecell{$\epsilon_{Th. 0}$} & \makecell{$\Delta \epsilon_{Th. 0}$} \tabularnewline
\hline
\makecell{(A)} & \makecell{(A)} & \makecell{(mT)} & \makecell{(mT)} & \makecell{(V)} & \makecell{(V)} & \makecell{(V)} & \makecell{(V)} \tabularnewline
\hline
\makecell{0} & \makecell{0} & \makecell{0} & \makecell{0} & \makecell{0} & \makecell{0} & \makecell{0} & \makecell{0} \tabularnewline
\hline
\makecell{0,55} & \makecell{0,04} & \makecell{0,50} & \makecell{0,04} & \makecell{0,10} & \makecell{0,04} & \makecell{0,90} & \makecell{0,02} \tabularnewline
\hline
\makecell{1,00} & \makecell{0,04} & \makecell{0,91} & \makecell{0,05} & \makecell{0,20} & \makecell{0,04} & \makecell{0,16} & \makecell{0,04} \tabularnewline
\hline
\makecell{1,50} & \makecell{0,05} & \makecell{1,36} & \makecell{0,07} & \makecell{0,28} & \makecell{0,04} & \makecell{0,25} & \makecell{0,05} \tabularnewline
\hline
\makecell{2,00} & \makecell{0,05} & \makecell{1,81} & \makecell{0,08} & \makecell{0,39} & \makecell{0,04} & \makecell{0,32} & \makecell{0,07} \tabularnewline
\hline
\makecell{2,50} & \makecell{0,06} & \makecell{2,3} & \makecell{0,1} & \makecell{0,47} & \makecell{0,04} & \makecell{0,41} & \makecell{0,09} \tabularnewline
\hline
\makecell{3,20} & \makecell{0,06} & \makecell{2,9} & \makecell{0,1} & \makecell{0,57} & \makecell{0,04} & \makecell{0,5} & \makecell{0,1} \tabularnewline
\hline
\makecell{3,52} & \makecell{0,07} & \makecell{3,2} & \makecell{0,1} & \makecell{0,66} & \makecell{0,04} & \makecell{0,6} & \makecell{0,1} \tabularnewline
\hline
\end{tabular}
\end{table}
\end{document}

A: I re-designed the table, also using the makecell package for column heads, with S type columns, to have alignment on decimal comma (from siunitx) and finally threeparttable so that the caption has the same widthj as the table. No vertical lines, that's bad typographical practice:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{mathtools}
\usepackage{array, tabularx}
\usepackage{booktabs}
\usepackage{ragged2e}
\newcolumntype{Y}{ >{\hsize=1.75\hsize}X}
\newcolumntype{Z}{ >{\hsize=.875\hsize\RaggedLeft}X}
\usepackage{caption}
\usepackage{makebox}
\captionsetup{font = small}
\usepackage{makecell}
\renewcommand{\theadfont}{\upshape\bfseries\footnotesize}
\setcellgapes{3pt}
\makegapedcells
\usepackage{threeparttable}
\usepackage{siunitx}

\usepackage[french]{babel}

\begin{document}

\begin{table}[h]
    \begin{threeparttable}
\centering\sisetup{table-number-alignment = center, table-figures-integer=1, table-figures-decimal=2, locale = FR}
\caption{Variation de l'amplitude de la force électromotrice en fonction du courant circulant dans des bobines d'Helmholtz à une fréquence de rotation de la bobine d'induction constante ($(40\pm2)$ Hz)}
\label{tableau1}
\begin{tabular}{SSSSSSSS}
\Xhline{0.8pt}
 \multicolumn{2}{c}{\thead{Courant}} & \multicolumn{2}{c}{\thead{Champ\\magnétique}} & \multicolumn{2}{c}{\thead{Force\\ électromotrice\\ expérimentale\\ (amplitude)}} & \multicolumn{2}{c}{\thead{Force\\ électromotrice\\ théorique\\ (amplitude)}} \\[-0.5ex]
\hline\noalign{\vskip3pt}
{$I_1 $} & {$Δ I_1$} & {$B$} & {$Δ B$} & \clap{$ϵ_\mathrm{Exp. 0}$} & \clap{$Δ ϵ_\mathrm{Exp. 0} $} & \clap{$ϵ_\mathrm{Th. 0}$} & \clap{$Δ ϵ_\mathrm{Th. 0}$} \\[-0.4ex]
\multicolumn{2}{c}{\small(A)} & \multicolumn{2}{c}{\small(mT)} & \multicolumn{2}{c}{\small(V)} & \multicolumn{2}{c}{\small(V)} \\[0.6ex]
\hline\noalign{\vskip1pt}
{0} & {0} & {0} & {0} & {0} & {0} & {0} & {0} \\[1pt]
0,55 & 0,04 & 0,50 & 0,04 & 0,10 & 0,04 & 0,90 & 0,02 \tabularnewline
1,00 & 0,04 & 0,91 & 0,05 & 0,20 & 0,04 & 0,16 & 0,04 \tabularnewline
1,50 & 0,05 & 1,36 & 0,07 & 0,28 & 0,04 & 0,25 & 0,05 \tabularnewline
 2,00 & 0,05 & 1,81 & 0,08 & 0,39 & 0,04 & 0,32 & 0,07 \tabularnewline
 2,50 & 0,06 & 2,3 & 0,1 & 0,47 & 0,04 & 0,41 & 0,09 \tabularnewline
 3,20 & 0,06 & 2,9 & 0,1 & 0,57 & 0,04 & 0,5 & 0,1 \tabularnewline
 3,52 & 0,07 & 3,2 & 0,1 & 0,66 & 0,04 & 0,6 & 0,1 \tabularnewline
\Xhline{0.8pt}
\end{tabular}
\end{threeparttable}
\end{table}

\end{document}


text:
Q: Add only available date values to monthly dataframe I have a DataFrame with employee time sheets, total hour worked as well as overtime hours.
example = pd.DataFrame({'Employee': ["Alex", "Alex", "Alex", "Bob", "Peter", "Peter"], 'date': ['2021-01-01', '2021-01-01', '2021-01-03', '2021-01-02', '2021-01-01', '2021-01-02'],
                       'Total Hour': [1.5, 2.2, 7, 1, 3, 6], 'Overtime': [1.5, 0, 1.2, 2.3, 1.7, 5]})
print(example)

  Employee        date  Total Hour  Overtime
0     Alex  2021-01-01         1.5       1.5
1     Alex  2021-01-01         2.2       0.0
2     Alex  2021-01-03         7.0       1.2
3      Bob  2021-01-02         1.0       2.3
4    Peter  2021-01-01         3.0       1.7
5    Peter  2021-01-02         6.0       5.0

I want to create a monthly DataFrame with all the days of the month and fill only available timesheets in it, something like this:
                          2021-01-01  2021-01-02  2021-01-03  2021-01-04  2021-01-05  ... 2021-01-31
  Employee
0     Alex   Total Hour       3.7                     7.0
1     Alex   Overtime         1.5                     1.2
2     Bob    Total Hour                   1
3     Bob    Overtime                     2.3
4     Peter  Total Hour       3.0         6
5     Peter  Overtime         1.7         5

So as employees enter their hours, this will become more complete.
I tried to figure it out but I think I am missing something very fundamental here.

A: Let's use pivot_table then stack level 0 to convert column MultiIndex to row MultiIndex:
result_df = example.pivot_table(
    index='Employee',
    columns='date',
    values=['Total Hour', 'Overtime'],
    aggfunc='sum'
).stack(level=0)

Or equivalently with groupby sum then stack + unstack to swap column and row MultiIndexes:
result_df = example.groupby(['Employee', 'date']).sum().stack().unstack(level=1)

result_df:
date                 2021-01-01  2021-01-02  2021-01-03
Employee
Alex     Overtime           1.5         NaN         1.2
         Total Hour         3.7         NaN         7.0
Bob      Overtime           NaN         2.3         NaN
         Total Hour         NaN         1.0         NaN
Peter    Overtime           1.7         5.0         NaN
         Total Hour         3.0         6.0         NaN

Either approach can be followed with reindex to order level 1 so that Overtime appears first and Total Hour appears second per Employee. Then rename_axis and reset_index for some clean up of index and column labels:
result_df = result_df.reindex(
    ['Overtime', 'Total Hour'], level=1
).rename_axis(
    index=['Employee', 'Hours'], columns=None
).reset_index()

result_df:
  Employee       Hours  2021-01-01  2021-01-02  2021-01-03
0     Alex    Overtime         1.5         NaN         1.2
1     Alex  Total Hour         3.7         NaN         7.0
2      Bob    Overtime         NaN         2.3         NaN
3      Bob  Total Hour         NaN         1.0         NaN
4    Peter    Overtime         1.7         5.0         NaN
5    Peter  Total Hour         3.0         6.0         NaN


text:
Q: Как обновлять аяксом ссылки? Проблема возникает в том, что нужно при загрузке страницы вывести список ссылок, после обновлять их каждые(ну допустим 2 минуты) при большом времени обновления они сразу при перезагрузке не отображаются, а при маленьком...настолько часто происходит обновление, что переход по ним невозможен ... как доработать это...
<script type="text/javascript">
function show(){
$.ajax({
 url: "pages/blocks/message/me.php",
 success: function(html){
 $('#dau').html(html);
}
});
}
setInterval('show()', 1000);
</script>


text:
Q: How do I do "calculations" with tensors? I just started to read about tensor products and tensors and I understand that a tensor product $V \otimes W$ is a space used to replace bilinear maps $V \times W \to U$ with linear maps $V \otimes W \to U$. Now I have tried to solve a few simple exercises and I realize that I have no idea how to actually "work" with those tensor products/tensors.

Let's look at $$u_1 = \begin{pmatrix} 1\\ 1\\ 0 \end{pmatrix}, u_2 = \begin{pmatrix} 0\\ -1\\ 1 \end{pmatrix}, u_3 = \begin{pmatrix} 1\\ 0\\ -1 \end{pmatrix}$$ as a basis of $V = \mathbb{R}^3$. Let $G$ be a tensor in $V^* \otimes V^*$, given by
  $$G(x,y) = x_1 y_3 + x_2 y_2,$$ where $x = (x_1, x_2, x_3), y = (y_1, y_2, y_3)$ in $\mathbb{R}^3$. Express $G$ in terms of the basis $(u_i^* \otimes u_j^*)$ of $V^* \otimes V^*$.

Looking at the solution, this exercise should be really easy to solve, as we can write $$G = e_1^* \otimes e_3^* + e_2^* \otimes e_2^*.$$
Why can we write $G$ in this way? Maybe I am lacking some basic knowledge of tensors, because without the solution, I would have no idea how to even approach this exercise and even with the solution, I have no idea why it is true.

A: It seems to me if you already know its representation in terms of $e_i^\ast\otimes e_j^\ast$, and you want to know it in terms of $u_i^\ast\otimes u_j^\ast$, isn't it straightforward to apply change of bases?
All you should need for that is the change of basis matrix between the bases $E=\{e_1\dots e_n\}$ and $U=\{u_1\dots u_n\}$, the matrix $A$ that computes $Av_E=v_U$ where $v_E$ means "$v$ in terms of $E$" and $v_U$ means "$v$ in terms of $U$".
$$
A=\begin{pmatrix}\frac{1}{2}&\frac{1}{2}&\frac{1}{2}\\\frac{1}{2}&-\frac{1}{2}&-\frac{1}{2}\\\frac{1}{2}&\frac{1}{2}&-\frac{1}{2} \end{pmatrix}
$$
and
$$
A^{-1}=\begin{pmatrix}1&1&0\\0&-1&1\\1&0&-1 \end{pmatrix}
$$
The rest should flow from the transformation rules for tensors, right?