text:
Q: Loop through directories, check if string exists in one file, move another file I'm working on a bash script that should do the following:  for every directory beginning with Event_*, (in cat eventList), cd into the directory, and if the string "ZJ.ROT" exists in the file *.mcp, I want to copy the file "ROT" to another directory.  In simpler terms: loop through directories: if string "ZJ.ROT" exists in a file in that directory, output another file from that directory to a separate directory.
#!/bin/bash

mkdir newdire
for dir in `cat eventList`; do
cd $dir
pwd
if grep "ZJ.KNYN" *.mcp; then
cp "ROT" "newdire"
fi
done

The error I get is:
./azim.sh: line 5: cd: Event_2014.11.21.10.10.19.630: No such file or directory
/Users/files/Event_2013.12.01.06.29.57.800
grep: *.mcp: No such file or directory

For some reason, this for loop isn't looping through each directory, but it's stuck in the first directory Event_2013....  Any ideas about how to implement this code?

A: After the first time you cd to a subdirectory you are in it for all future loop iterations so your subsequent cds will fail, as you are experiencing. You also need to quote your variables and there's other issues. Try this:
pwd="$PWD"
mkdir newdire
while IFS= read -r dir; do
    cd "$dir"
    grep -Fq "ZJ.KNYN" *.mcp &&
    cp "ROT" "${pwd}/newdire"
    cd "$pwd"
done < eventList

but of course you don't actually need to cd:
mkdir newdire
while IFS= read -r dir; do
    grep -Fq "ZJ.KNYN" "$dir"/*.mcp &&
    cp "${dir}/ROT" newdire
done < eventList

A: Problem seems to be here:
if grep "ZJ.KNYN" *.mcp; then

You should use -q option in grep to suppress the output and check the return status like this:
if grep -qF "ZJ.KNYN" *.mcp; then

-F is for fixed string search.
Also there is no need to change directory inside the loop.
Your full script can be better rewritten as:
#!/bin/bash

mkdir newdire

for dir in Event_*; do
   if [[ -d "$dir" ]] && grep -qF "ZJ.KNYN" "$dir"/*.mcp 2>/dev/null; then
      cp "$dir/ROT" "newdire/"
   fi
done


text:
Q: How do web developers deal with editing (pre-processed) vendor prefixed CSS in browser dev tools? I have a dillema working with CSS. I use a pre-processor to add all necessary vendor prefixes to CSS when it's served, keeping my source code short and simple. However the issue is, by far the most effective way to to edit styles realistically (and see real-time updating of the page) is to use the web page's dev tools in whichever browser(s) you're currently testing, edit the CSS there, and copy/paste it to the source code after making significant changes.
So then my CSS source code is full of vendor prefixes.
Is there a simple solution to this? What solutions exist to solve this problem?

A: What you want is live/hot reload.
If you use live reloading, as soon as you make and save a change to your css file, the tools will rebuild the final css and load the new version into the browser. No need to refresh, it just happens. That way you can make change and see quick feedback, just like if you had modified the dev tools in the browser. But your changes are already in your source (no need to copy back).
How do to this depends on your the rest of your stack. But the chances are that whatever tool you are using to build your css: grunt/gulp/webpack/etc has addons to support livereload available.

A: Sounds like you need a de-processor to remove the prefixes. Could you write one in JavaScript and embed it in a local page? What I'm imagining is a page with two text boxes, you copy your modified CSS into one box, press a button to run the prefix-removal code, and the un-prefixed code appears in the other text box. Then you simply C&P the processed code back into your application source. If you're really good you could probably write a browser extension to de-prefix whatever code is highlighted and display it in a separate dialog, but I'm nowhere near that good so I really can't guess how much effort that would take.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use mouse to move window in XZ plane in opengl I want to move the view in the XZ plane, when I move the mouse. The mlon and mlat which are linear function of mouse coordinate x and y. I have glutPassiveMotionFunc(mouse_motion); in my main function. What I need to do in order to move the window view in the XZ plane? Any explanation?
void mouse_motion(int x, int y) {

 /* To be completed */
 x=lon+mlon;
 y=lat+mlat;

} // mouse_motion()

A: I'd start with calling glutPostRedisplay in the mouse motion handler so that the scene gets redrawn. Redraw with the updated position.


text:
Q: Image slider algorithm I want to create an image slider in Javascript (not in jquery) and fail to think about an algorithm to do this.
On the internet I found writing code examples but I do this job to help me understand how to think programs.
I thought a few steps that I think should be displayed.
1.make an array where we store all the images in a folder.
It is important that this be done dynamically,
For example, the code below images are added manually ... but what if we have 1,000 images? We can not add to all manual
 var images = [
    '/images/img1.jpg',
    '/images/img2.jpg'
];

2.We use a "FOR" to browse all vector(images).
for(var i=0;i<images.length;i++)
{
//Here not figure out what should be written

}

3.It is important for each image to display two things.
Image name and date on which it was created.
This step I realize it should do.
4.You should also arrows left and right. I thought each arrow to make such a function where to write code
functions left()
{
//some code for running images
}

So much I think I managed to ... I hope to help me understand how to design a script.
Certainly not something complicated and many people here know to do it but I want to understand how to think such scripts.
I want to understand why we need to create objects and so on ... everything.
Thanks in advance!


text:
Q: Docker container exited abruptly during react-scripts start I want to run a simple React application inside Docker. It runs well outside but when I try to run it from docker, I get the following errors and at the moment I have no clue.
custportal_1         | yarn run v1.15.2
custportal_1         | $ react-scripts start
custportal_1         | ℹ 「wds」: Project is running at http://172.24.0.12/
custportal_1         | ℹ 「wds」: webpack output is served from
custportal_1         | ℹ 「wds」: Content not from webpack is served from /usr/src/app/public
custportal_1         | ℹ 「wds」: 404s will fallback to /
custportal_1         | Starting the development server...
custportal_1         |
custportal_1         | Done in 2.61s.
custportal_1 exited with code 0

The application is created by create-react-app command. My Dockerfile configuration is
FROM node:11 as build-deps
WORKDIR /usr/src/app
COPY package.json yarn.lock ./
RUN yarn
COPY . ./
RUN yarn build

Again the application runs well outside but breaks when called inside Docker. In docker-compose I call the container with
command: bash -c "export PORT=8081 && yarn start"

** I have nginx reverse proxy running on the background.

A: Adding stdin_open: true in docker-compose solves the problem. Took hand-full of hours to get this solution. Reference github
Also I have noticed that react-script was calling the browser abruptly inside docker during start up. It's not necessary inside docker. Adding environment variable like BROWSER=none can omit this behaviour.
Happy coding..


text:
Q: SSH still asks for password after setting up key based authentication I have successfully created a key based auth for root user from my A machine to my B machine.
Now, I created a new user on B machine, the same as on A machine, let's call him USER. I created a home dir for him on B machine /home/USER and I want to create key based auth for him from machine A to B machine.
So, I ran on A machine

*

*ssh-keygen -t rsa, accepted all paths, so /home/USER/.ssh/id_rsa and with no phrases

*ssh-copy-id -i /home/USER/.ssh/id_rsa.pub USER@BmachinesIP, entered password and got massage

Now try logging into the machine bla bla bla

So everything seems to be OK.
But when I tried to connect ssh USER@BmachinesIP I was asked for a password.
I tried to see the log and ran ssh -vvv USER@BmachinesIP and here is a part of output:
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/USER/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/USER/.ssh/id_dsa
debug3: no such identity: /home/USER/.ssh/id_dsa
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
USER@BmachinesIP's password:

So, can anyone tell me what I've done wrong or what I should change? Maybe the issue is in the permissions, here they are:
on A machine:
drwx------  2 USER USER    SIZE DATE TIME .ssh
-rw-------  1 USER USER 1675 2011-10-31 14:36 id_rsa
-rw-r--r--  1 USER USER 413 2011-10-31 14:36 id_rsa.pub

and on B machine:
drwx------  2 USER defaultGroup    SIZE DATE TIME .ssh
-rw-------    1 USER defaultGroup    SIZE DATE TIME authorized_keys

A: Same problem for me fresh CentOS7 install.
1. check home dir permissions and ~/.ssh and ~/.ssh/authorized_keys permissions (as per @erik)
chmod o-w ~/; chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys

2. check /etc/ssh/sshd_config settings && service sshd restart (after each edit) Useful: try "LogLevel VERBOSE" in sshd_config.
I still got password prompt after checking all that was ok.
Run ssh client with -vvv logs:
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply

Server (/var/log/secure) logs:
Failed publickey for * from * port * ssh2: RSA *

ssh server doesn't send more error info to client as that would be a security risk.
If I ran sshd on different port 'sshd -p 5555 -d'. The key worked. Passwordless login ok. WTF?
Then I disabled selinux (set SELINUX=disabled in /etc/selinux/config) and reboot. Passwordless login then worked ok.
my current working sshd_config settings:
[root@hp-bl-05 ~]# grep -vE "^#|^$" /etc/ssh/sshd_config
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
SyslogFacility AUTHPRIV
LogLevel VERBOSE
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile  .ssh/authorized_keys
HostbasedAuthentication yes
PasswordAuthentication yes
ChallengeResponseAuthentication no
GSSAPIAuthentication no
GSSAPICleanupCredentials no
UsePAM yes
X11Forwarding yes
UseDNS no
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
Subsystem   sftp    /usr/libexec/openssh/sftp-server

So it would be nice to know could we change something small in selinux to get passwordless ssh login to work. Can anyone improve the answer?

A: I have found a solution. There was an issue in permissions.
/home/USER on remote machine was granted all permissions, but for key based auth it must be set to 755

A: The solution is not disabling SELinux but to fix the SELinux permissions of the user directory. The user directory context must be set to user_home_t.
To check,
$ sudo ls -Z /home/

If the context for your user directory is anything than user_home_t, SELinux would not allow SSH via public key into that user directory for that user.
To fix,
$ sudo semanage fcontext -a -t user_home_t /home/azureuser
$ sudo restorecon -vvRF /home/azureuser

The key based login should now work.


text:
Q: Index and Joins I know the the how how does indexing works for the table...
but I want to know if I fire the following join statement and index on the column   CustomerID in this case index play any role if yes then how or is there any other way to create index for that ??
SELECT o.OrderID
     , o.CustomerID
     , c.CustomerName
     , o.OrderDate
  FROM Orders o
  JOIN Customers c
    ON o.CustomerID = c.CustomerID
 order
    by o.CustomerID;

and tables are like
Orders table:
    +----------------------+------------+------------+
    | OrderID              | CustomerID | OrderDate  |
    +----------------------+------------+------------|
    | 10308                | 2          |1996-09-18  |
    | 10309                | 37         |1996-09-19  |
    | 10310                | 77         |1996-09-20  |
    +----------------------+------------+------------+

Customers table:
CustomerID  CustomerName                        ContactName    Country
         1  Alfreds Futterkiste                 Maria Anders   Germany
         2  Ana Trujillo Emparedados y helados  Ana Trujillo   Mexico
         3  Antonio Moreno Taquería             Antonio Moreno Mexico

A: When JOINing tables, the Optimizer first decides which table to start with.  In your particular example, there is no WHERE, but there is an ORDER BY.  So, the Optimizer will probably decide to start with the table being ORDERed.  This may avoid a sort.
Assuming it starts with Orders in an attempt to avoid the sort, you need this on Orders:
INDEX(CustomerID)

The second table in the JOIN is, therefore, Customers.  To reach into Customers after looking into Orders, you have ON Orders.CustomerID = Customers.CustomerID.  So, you need this on Customers:
INDEX(CustomerID)

(Note:  Since a PRIMARY KEY is an index, there is no need to add the INDEX if you already have PRIMARY KEY(CustomerID).  It would help if you showed us SHOW CREATE TABLE for each table.)


text:
Q: Como unir un .h y un .cc Acabo de crear dos archivos. El primero es rectangulo.h:
#ifndef _RECTANGULO_
#define _RECTANGULO_
#include <iostream>
using namespace std;

class Rectangulo{
    private:
        int x;
        int y;

    public:
        Rectangulo(int a, int b);
        int area();
};
#endif

Y el segundo es su correspondiente rectangulo.cc
#include "rectangulo.h"
Rectangulo::Rectangulo(int a, int b){
    x = a;
    y = b;
}

int Rectangulo::area(){
    return x * y;
}

Ahora lo quiero probar pero no se como hacerlo. ¿Como y donde hago la función main?
Supongo que es lo más fácil pero me han explicado como dividir el código pero no como probar que funciona después.
Gracias de antemano.

A: La función main únicamente necesita la cabecera para funcionar. Ya que lo único que necesita saber es cuánto ocupa la clase Rectangulo en memoria y cómo se organizan sus variables y qué funciones tiene.
El resto de la magia se produce durante el proceso de enlazado. Es en esta fase cuando el compilador cogerá el código objeto del main y el de la clase Rectangulo y con ellas generará el binario final.
Como ves, solo hace falta hacer un include de la cabecera:
#include <iostream>

#include "rectangulo.h"

int main()
{
  Rectangulo r(2, 3);
  std::cout << r.area();
}


text:
Q: Assign index of deleted product I have a simple jQuery script that allows user to add products to basket and see the animation.
http://jsfiddle.net/Z6ave/7/
Now, I have a slight problem and just can't seem to find a plausible solution.
As you can see in the code, when you add a product to basket, the order attribute gets assigned:
Product that was added 1st - Order 1
Product that was added 2nd - Order 2
Product that was added 3rd - Order 3
Product that was added 4th - Order 4
Product that was added 5th - Order 5
Product that was added 6th - Order 6

and so on...
and that's fine, every position has a certain CSS rule attached to it.
But, if I delete some product in the middle or any other that isn't the last one, and when I add another one after that, I need it to fill the empty place.
What happens right now is this...
If I delete product number 3 from the list above, and add another one after that, the list will look like this:
Product that was added 1st - Order 1
Product that was added 2nd - Order 2
Product that was added 4th - Order 4
Product that was added 5th - Order 5
Product that was added 6th - Order 6
Product that was added 7th - Order 7

You see that the problem is the empty space of number 3, so the 7 should actually go under 3.
Can you help me with this one? I know there must be some easy/elegant solution.
Thank you

A: i added a comment earlier. here is an example of doing it via an array : http://jsfiddle.net/Z6ave/8/
i created an array var removedArray = [];
then when you delete an item it adds to the array:

$(".del").live("click", function() {
var removed = $(this).parent().attr("order");
removedArray.push(removed);
$(this).parent().remove(); });

and uses this when creating an element
if(removedArray.length > 0){

  var deletedNumber = removedArray[0];

  inbasketimage.addClass("slot" + deletedNumber);
  inbasketimage.attr("order", deletedNumber);
  inbasketimage.find("img").attr("src", img.attr("src"));
  inbasketimage.attr("product_name", productName);

  removedArray.shift();

}else{

  if(isNaN(order)) {
    order = 1;
  } else {
    order = order + 1;
  }

  inbasketimage.addClass("slot" + order);
  inbasketimage.attr("order", order);
  inbasketimage.find("img").attr("src", img.attr("src"));
  inbasketimage.attr("product_name", productName);
}


text:
Q: Compiling gwt with maven - specify jvm I am trying to specify, in my maven settings.xml and my pom.xml, which jvm to use for my gwt project.
I am using the suggestion from https://stackoverflow.com/a/20787334/265119. I have used this on other, non-gwt projects successfully.
Now however it seems that maven is ignoring this, and continues to use java 8, whereas I have set the following in my settings.xml:
<profiles>
<profile>
<id>default</id>
    <properties>
            <JAVA_1_7_HOME>/usr/lib/jvm/java-7-oracle/bin/javac</JAVA_1_7_HOME>
            <JAVA_1_8_HOME>/usr/lib/jvm/java-8-oracle/bin/javac</JAVA_1_8_HOME>
        </properties>
</profile>
  </profiles>
  <activeProfiles>
    <activeProfile>default</activeProfile>
</activeProfiles>

And in my pom.xml:
 <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                        <executable>${JAVA_1_7_HOME}</executable>
                    </configuration>
                </plugin>

Does anyone know why maven is ignoring these?
Does the gwt maven plugin also need to specify the jvm version?
Thanks

A: Is the profile really activated? Your POM ought to work, but only if the profile is activated.
You can run mvn help:active-profiles to find out if your profile is active.
Also, in order for <executable> to work, you need to set <fork>true</fork> as well. As explained here: http://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#executable


text:
Q: MS SQL Server DB version without restoring? Is there a way of telling which version of Microsoft SQL Server a database backup is from without restoring it?

A:
RESTORE HEADERONLY
FROM DISK = 'pathTobackupFile'

The database version can be found in the column: DatabaseVersion
From Jonathan Kehayias blog post here the number in this column:

*

*SQL Server 7.0 databases have version number 515

*SQL Server 2000 databases have version number 539

*SQL Server 2005 databases have version number 611/612

*SQL Server 2008 databases have version number 655

[To those that want to edit this answer to include additional version numbers, that is not the intention of this answer. It was just for example and quoting the information that is from the link provided. The version number of a database can vary and may not be exact across every database based on what SP or CU is installed, or setting/feature that is being used. The version numbers are not documented by Microsoft and is just a simple reference to understand that the number increases as you move between SQL Server versions.]
If you try to run this command for a more recent database version than the one you're running it under (e.g. a 2012 DB from SSMS 2008), the database results display as INCOMPLETE
To check the build number of the instance check for columns:

*

*SoftwareVersionMajor

*SoftwareVersionMinor

*SoftwareVersionBuild

Documentation can be found here (TechNet link).


text:
Q: What does Chris Christie is "350 pounds of toast" mean? Maureen Dowd quoted Bill Maher's description of Chris Christie as "350 pounds of toast," in her article titled, "Christie puts the gloves on" in New York Times (February 22):

"I tend to agree with Bill Maher that Christie is "350 pounds of
  toast," and that he should have run for president in 2012 when he had
  "that new candidate smell" because "the longer you stay in the more
  likely some bad thing will stick to you."

http://www.nytimes.com/2014/02/23/opinion/sunday/dowd-christie-puts-the-gloves-on.html?hp&rref=opinion
The article of Daily KOS (February 15) titled "Bill Maher says Governor Christie is "350 pounds of toast" shows  a cartoon of Chris Christie being toasted on toaster.
Cambridge English Dictionary simply defines 'toast' as;
 sliced bread made warm, crisp, and brown by being put near a high heat:
However, Oxford English Dictionary defines 'toast'' as a noun to mean
a person or thing that is very popular or held in high regard by a particular group of people, beside the common notion of "sliced bread browned on both sides by exposure to radiant heat, such as a grill or fire."
Does "toast' have the meaning of a people being examined or grilled.
What does "toast" here mean? "condemnation" or "praise"?

A: The real OED has this definition as a 2002 addition:

Frequently in proleptic use, especially in you're (also I'm, we're,
  etc.) toast:
you (I, we, etc.) will soon be dead, in trouble, etc.

So what the writer means is simply that Chris Christie's presidential ambitions are doomed.

A: The usefulness of the 'toast' comparison draws on the fact that toasted bread easily morphs from being desirable (when it is properly heated) to being very undesirable (if it gets overheated and chars). At that point it becomes good for nothing. Dowd's piece subtly suggests that Christie (and by implication, his career) now stinks like burned toast when she quotes Bill Maher's remark that

he should have run for president in 2012 when he had "that new candidate smell"

Incidentally, the other type of toast (as in "He's the toast of the town") refers to the custom of communally toasting a person's health or well-being by raising a glass of a (usually alcoholic) drink, uttering some words to match the occasion, and only then putting the glass to one's lips.

A: As a supplement to Barrie England's correct answer, the detailed origin of toast as a proleptic construction—that is to say, one that offers a foregone conclusion as the present state, along the lines of you're history—is somewhat fascinating.
The earliest citation in the OED is from the screenplay for the 1984 film Ghostbusters, where the actual words spoken were:

This chick is toast.

From that line, popular culture picked up the term in poleptic form and adopted it greedily.
However, OED notes that much of the film was ad-libbed and that the original screenplay did not employ this proleptic construction.

Okay. That's it! I'm gonna turn this guy into toast.

So this sense of the word toast, which permeates casual writing and speech in American English, appears to have been the result of actor Bill Murray's improvisation.


text:
Q: Pass a constant copy of the iterator for Task.Factory.StartNew() In my program I currently have a structure similar to this:
for (int i=0; i<MyCollection.Count; i++)
{
    Task.Factory.StartNew(()=>
    {
        DoStuffWith(MyCollection[i]);
        DoEvenMoreStuffWith(MyCollection[i]);
    });
}

It does not work properly because functions DoStuffWith() and DoEvenMoreStuffWith() take more time to complete than i++, hence one of these will usually modify the wrong element of the collection.
I know I can't do int a = i before the Task.Factory because it's gonna be the same, really.
How do I make sure each thread works with their own index exclusively?
P.S.: Sorry, I tried looking for an answer here but I don't even know how to google it properly. I know it's something that has to do with reference types and value types, but I've never used them around Task.Factory before.

A: If you use a standard for loop, you can keep a local copy of the variable within the closure of the loop body (just as you suggested was not possible), and this closure will be captured by the body of your deferred code.
So:
for (int i=0; i<MyCollection.Count; i++)
{
    var a = i;
    Task.Factory.StartNew(()=>
    {
        DoStuffWith(MyCollection[a]);
        DoEvenMoreStuffWith(MyCollection[a]);
    });
}

However, there is a better way.
Recently(ish), the c# language was changed to close over the loop variable in foreach loops.
So, unless you're stuck with 2012-era tooling, now you can:
foreach(var item in MyCollection)
{
    Task.Factory.StartNew(()=>
    {
        DoStuffWith(item);
        DoEvenMoreStuffWith(item);
    });
}

without this issue happening.
As an aside, do you know the difference between Task.Factory.StartNew and Task.Run? You should do.


text:
Q: Android: скриншот SurfaceView во время видеозаписи - чёрный экран Есть SurfaceView:
this.surf = (SurfaceView) findViewById(R.id.surf);
this.surf.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
this.surf.addCallback(new Callback() {

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Cam.this.h = holder;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Cam.this.h = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

});

и есть MediaRecorder, записывающий видео:
MediaRecorder mMediaRecorder = new MediaRecorder();
mMediaRecorder.setCamera(Cam.this.mCamera);
mMediaRecorder.setAudioSource(AudioSource.MIC);
mMediaRecorder.setVideoSource(VideoSource.CAMERA);
mMediaRecorder.setPreviewDisplay(Cam.this.surf);
mMediaRecorder.setOutputFormat(OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(VideoEncoder.H264);
mMediaRecorder.setVideoSize(1280, 720);
mMediaRecorder.setOutputFile(Cam.this.mParcelFileDescriptor[1].getFileDescriptor());
mMediaRecorder.setMaxDuration(60000);
mMediaRecorder.prepare();
mMediaRecorder.start();

Никаких проблем с записью видео нет. Но, почему-то, при получении скриншота приложения можно заметить, что вместо SurfaceView отображается чёрный прямоугольник. Вот код получения скриншота:
View v = findViewById(R.id.mainLayout); // основная компоновка (в моём случае RelativeLayout)
v.setDrawingCacheEnabled(true);
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
FileOutputStream o = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "frame.jpeg"));
b.compress(CompressFormat.JPEG, 100, o);
o.flush();
o.close();

и XML-код данной Activity:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="test.Cam" >

    <SurfaceView
        android:id="@+id/surface"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Как исправить ошибку, сделать так, чтобы SurfaceView не отображался чёрным прямоугольником на скриншоте?

Знаю один неплохой вариант, требующий root права:

su /system/bin/screencap -p /sdcard/screenshot.jpf

Сразу вариант не подходит, так как root прав нет.


text:
Q: PM2 command not running under PowerShell script I have following command in my Windows instance user data in AWS. I can see pm2 env variable is setup but in next line in PowerShell does not start pm2 server. I am running pm2 under system profile NOT under any user profile.
See below code:
$myvar = "D:\Mycode"
[Environment]::SetEnvironmentVariable("PM2_HOME", "C:\etc\.pm2", "Machine")

& 'C:\Windows\system32\config\systemprofile\AppData\Roaming\npm\pm2.cmd' start $myvar"\app.js" |
    Out-File D:\debug.txt -Append

A: Your call to [Environment]::SetEnvironmentVariable(...) doesnt impact the current shells environment variables, so the PM2_HOME variable will not exist when you call pm2.cmd.
A simple fix is after you call SetEnvironmentVariable, use the following command to then retrieve that value, and create that variable in the current shell:
$env:PM2_HOME = [System.Environment]::GetEnvironmentVariable("PM2_HOME","Machine");

This is only required during the userdata script as all future sessions will have this environment variable (ie environment variables are loaded when a session starts).
An alternative would be to invoke a new instance of powershell.exe (or even cmd.exe) to start pm2.cmd - as this would create a new session, which would receive the new environment variable.


text:
Q: Connecting to a server via Java Socket and ServerSocket Class I have what will hopefully be a very simple question. I'm writing a series of java programs which utilize cryptographic functions like RSA, El Gamal, etc for a security class. so that a client (Alice) and server (Bob) can communicate securely. But, I have no clue how to connect to a server on my computer using java. I've used MAMP to connect to a web server where I've written code in PHP/SQL, but I don't know how it would work using Java. Specifically, the starter files I was given all use the Java class Socket and ServerSocket like so:
String host = "localhost";
int port = 7999;
Socket s = new Socket(host, port);
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());

And for the server (Bob):
int port = 7999;
ServerSocket s = new ServerSocket(port);
Socket client = s.accept();
ObjectInputStream is = new ObjectInputStream(client.getInputStream());

What would I do on my computer to connect to a server via this code?

A: Client.java
import java.io.*;
import java.net.*;

public class Client {

    public static void main(String[] args) throws Exception {

        String host = "localhost";
        int port = 7999;
        Socket s = new Socket(host, port);
        ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());

        os.writeObject("Hello World");
        os.close();
    }

}

Server.java
import java.io.*;
import java.net.*;

public class Server {

    public static void main(String[] args) throws Exception {

        int port = 7999;
        ServerSocket s = new ServerSocket(port);
        Socket client = s.accept();
        ObjectInputStream is = new ObjectInputStream(client.getInputStream());

        String str = (String)is.readObject();

        System.out.println("Read string: " + str);

        is.close();
    }

}

Compile with
javac Client.java

and
javac Server.java

Run the server (you can test this running both on the same machine.)
java Server

Run the client (in another terminal or DOS prompt.)
java Client

On the server you should see:
server$ java Server
Read string: Hello World
server$


text:
Q: How to call action in some other controller in Mojolicious? I have an application that uses the Mojolicious framework. I have a table in the database that has a list of error response and additional details associated with it. I have created corresponding Result and Resultset to work with the DB table. There is also a controller to get details about the Error by interacting with the Resultset.
My idea is to Call an action in this controller that would get the details of the error that is passed to it (by another controller) by querying the database, add-in runtime information about the environment that requested for the resource that resulted in the error, create a response and return to the controller that called it.
I am struggling with the call from one controller to another. How do I do it in Mojolicious? I can pass the controller object ($self) to accomplish this, but is there a better way to do it, so that I separate entirely my error handling response from the calling controller?

A: In Mojolicious, you would probably want to pass that object around with a helper without creating a Mojolicious::Controller out of it:
In your main class:
sub startup {
    my $app = shift;

    # ...
    my $thing = Thing->new(foo => 42);
    $app->helper(thing => sub {$thing});
}

In your controller:
sub cool_action {
    my $c = shift;

    # ...
    my $foo = $c->thing->gimmeh_foo('bar');
    # ...
}

However, if you would like to prepare something (e.g. databases) for some actions, maybe under is helpful for you:

To share code with multiple nested routes you can [...]

PS: This feature of Mojolicious was previously named Bridges. Answer updated accordingly.


text:
Q: Web Speech api not working on android chrome Web speech api (webkitSpeechRecognition) return 'not-allowed' error on android phone.
(I gave Microphone permission to chrome app and site on android settings)
Chrome on desktop is working.
But, on android is not.
(Test phone is Samsung Galaxy S9, Android Version 10, Chrome Version 86)
I tested MicrosoftEdge, SamsungInternet as well as Chrome on android.
but all returns 'not-allowed' error.
Test Page
https://www.google.com/intl/en/chrome/demos/speech.html
test code on chrome remote device console.
const a = new webkitSpeechRecognition()
a.onerror = (err) => {console.log("err:", err)}
a.start()
=> VM187:1 err: SpeechRecognitionErrorEvent {isTrusted: true, error: "not-allowed", message: "", type: "error", target: SpeechRecognition, …}

Is it a android problem?
How can I make it working?

A: I'm aware that it is a very old question.
In my case problem was caused by an invalid SSL certificate.
Desktop Chrome (Linux) was fine with that but Android Chrome was throwing "not-allowed" error. Fixing SSL certificate solved the problem.


text:
Q: Only submit 'relevant' parts of HTML form Apologies if it's a stupid but it's been a long day.
So my form look something like this...
<form action="/basket.php" method="get">
.co.uk
<select name="years">
<option value="1">1 year</option>
<option value="2">2 years</option>
<option value="3">3 years</option>
<option value="4">4 years</option>
<option value="5">5 years</option>
</select>
<input type="checkbox" name="url" value=".co.uk">
<br>
.com
<select name="years">
<option value="1">1 year</option>
<option value="2">2 years</option>
<option value="3">3 years</option>
<option value="4">4 years</option>
<option value="5">5 years</option>
</select>
<input type="checkbox" name="url" value=".com">
<button type="submit">
</form>

Let say I only ticked the .com parameter and changed the years to 3 years..
I would currently get the URL as follows:
/basket.php?years=1&url=.com&years=3

What I would like is...
/basket.php?url=.com&years=3

The actually form contains more choices but I only want to submit the 'lines' that have the final checkbox ticked.
Hope this make sense! Many thanks in advance.

A: First of all, if your two checkboxes are mutually exclusive, you want to be using radio buttons so that only one can be checked, like so:
<input type="radio" name="url" value=".com"/>
<input type="radio" name="url" value=".co.uk"/>

Assuming you're looking for a PHP solution rather than one which uses JavaScript, I would suggest having your form POST to basket.php, which should determine which inputs to keep based on the value of $_POST['url'], and then redirect with the corresponding years value.
Also note that you should use a different name for your select elements so that they can be distinguished between.
That being said, the best option would be to use two form elements, but this would require either two submit buttons, or JavaScript to perform the submission.
Also, if they both share the same options for years, you could remove the duplicate select to make things easier.


text:
Q: How to create your own commands that can be used anywhere I am new to linux, and I am learning bash scripting at the moment. I was wondering how I would save my script as a command and then be able to call that command anywhere in the terminal. So i could save the command in a folder somewhere, but be able to use that command in a different folder without having to type out the path to said command.
Is there a way to do this? For example, I make a script that runs chmod +x 'file' and then takes an argument for the file to run the command on. How would i go about coding this and then saving it so i can call that script from anywhere.
Sorry if i didn't explain my question too well, and thank you for any help with my problem.

A: Let's assume that you often place random scripts in ~/bin as one of the comments mentioned. Just open your ~/.bashrc (provided that BASH is your shell of choice) and as the last line add:
export PATH="${PATH}:~/bin"

and that's pretty much it. You can add any directory to your PATH environment variable this way and it will allow you to run any executable file from any location on this system. If you want to add more directories, just prepend each one with a colon, i.e.
export PATH="${PATH}:~/bin:otherdir:yetanother"

Just remember that this will only work once you open the terminal again or if you don't want to, just reload BASH configuration with:
source ~/.bashrc


text:
Q: R Data Frame - Convert all  to blank(" ") for character columns I am looking for a solution to convert all  to blank(' ') for all character columns in the data frame. I would prefer Base R solution. I tried solution described in (Setting <NA> to blank
) but it requires to convert entire data frame as a factor and that creates an issue for numeric columns e.g.
df <- data.frame(x=c(1,2,NA), y=c("a","b",NA))

To convert numeric NA to 0
df[is.na(df)] <- 0

To convert character  to Blank(" ") - It converts all columns to character.
df <- sapply(df, as.character)
df[is.na(df)] <- " "

A: It's maybe not the most elegant way but using dplyr, you can convert all factor column to character column using mutate_if and then replace all NA by "" in character columns by using ifelse in mutate_if:
library(dplyr)
df %>% mutate_if(is.factor, ~as.character(.)) %>%
  mutate_if(is.character, ~ifelse(is.na(.)," ",.))

   x y
1  1 a
2  2 b
3 NA

A: Create your dataframe with stringsAsFactors = FALSE
df <- data.frame(x=c(1,2,NA), y=c("a","b",NA), stringsAsFactors = FALSE)

Find character columns
cols <- sapply(df, is.character)

Turn them to blank
df[cols][is.na(df[cols])] <- ' '
df

#   x y
#1  1 a
#2  2 b
#3 NA


text:
Q: Wordpress Woocommerce change all products to out of stock Hello i have a online shop using Wordpress and Woocommerce but i have the following problem. I need to change all of my 2000 products to be out of stock, i haven't selected any quantity i only need to change the status. I started doing it by hand but it will take quite a while to mark all the items. After browsing the net i saw that this can be done relatively easy in phpmyadmin, the status is stored in wp_postmeta, i myself tried fiddling with the queries of phpmyadmin but to no avail  . Can someone help me with building the query that i need to use ? I use WP 4.1.1

A: ok bro write this query in your db
Update wp_postmeta Set meta_value = 'outofstock' Where meta_value = 'instock' And meta_key = '_stock_status'

I  restricted update query more by using And meta_key = '_stock_status'
Hope this will help you ... don't worry query is completely right but you must take a DB backup


text:
Q: Javascript For Loop execution on dom element I have javascript code to get the elements with class name and iterate over that remove the class from elements.
  var elements = document.getElementsByClassName("test");
       console.log("Length " + elements.length)
        for (var i=0; i< elements.length;i++) {
               console.log("---- "+i)
               elements[i].setAttribute("class","");
         }

and there are 3 span with the class name "test". HTML code is
Test1
Test2
Test3

But I am getting only 2 class removed. The second span class still remains there.
The console output is

Length 3
---- 0
---- 1

A: getElementsByClassName returns a live HTMLCollection object, which gets updated when you remove the class from the elements.
So one simple logic you can use is to use a while loop and see if the collection has any items, if so remove the class from the first item.

function removeClass() {
  var elements = document.getElementsByClassName("test");
  console.log("Length " + elements.length)
  while (elements.length) {
    elements[0].setAttribute("class", "");
  }
}
.test {
  color: red;
}
Test1
Test2
Test3
<button onclick="removeClass()">Test</button>


text:
Q: How to make laravel display grouped values I'm developing a question answer app using laravel, I want to display all answers under each question for that particular question. The problem I'm facing is I'm unable to alter the view to display answer under the respective question, since there is no way to match ID's in laravel views!
My view code:
@section('list-questions-answers')

        @foreach($listQuestions as $q)

question_id)}}">{{ $q->question }}

            @foreach($listAnswers as $a)

{{ $a->answer }}

            @endforeach
        @endforeach

@endsection

Answer's model
public function User()
{
    return $this->belongsTo('App\User');
}
public function questions()
{
    return $this->belongsTo('App\questions','answer_id');
}
public function scopefetchAnswers($query)
{
    return $query->select('answer')->where('people_id','<>',Auth::id())->get();
}

Question's model:
protected $table='questions';
protected $primaryKey='question_id';
protected $fillable = [
   'question', 'created_at','details'
];
//protected $hidden=['question_id'];
public function setUpdatedAtAttribute($value) {}
public function User() {
    return $this->belongsTo('App\User');
}
public function answers()
{
    return $this->hasMany('App\answers','question_id');
}
public function scopefetchQuestions($query) {
    return $query->select('question','question_id')->where('people_id','=',Auth::id())->get();
}

Everything is display on the dashboard.blade.php, which runs on dashboard controller
class Dashboard extends Controller
{
    public function index(){

        $listQuestions=questions::latest('created_at')->fetchQuestions();
        //$listAnswers=answers::groupBy('question_id')->fetchAnswers();
        $listAnswers=answers::fetchAnswers();
        return view('forms.question',compact('listQuestions','listAnswers'));
    }
}

Output I'm getting

Ouput I want

Answer's table

How can I achive that output? I'm using Laravel 5.2

A: Your query to fetch questions should be as:
$listQuestions= Question::where('people_id', '=', Auth::id())
                            ->with(['answers' => function($q) {
                                $q->where('people_id', '<>' ,Auth::id());
                             }])
                            ->get();

And your view file should be as:
section('list-questions-answers')

        @foreach($listQuestions as $q)

question_id)}}">{{ $q->question }}

            @foreach($q->answers as $a)

{{ $a->answer }}

            @endforeach
        @endforeach

@endsection


text:
Q: Navbar 100% page width I'm trying to make an HTML/CSS navbar that is 100% width of the screen.  Right now, it has small areas on the sides that aren't the navbar.
I'm not using absolute or relative positioning.
You can see my code here http://jsfiddle.net/una5kpx9/1/

Text Goes Here

CSS:
#nav { float: left; clear: both; width: 100%;  padding: 0; background: #787F6C;}
#nav-inner { float: left; clear: both; width: auto; padding: 10px 20px; background: transparent; }

Any help appreciated,
Thanks

A: You need to add:
body { margin:0 }

*

*Without: http://jsfiddle.net/9uzp5xgr/

*With: http://jsfiddle.net/r564nu9f/
Or if you want the navbar to follow when you scroll you can set the position to absolute:
nav {
position:absolite;
top:0;
right:0;
left:0;
height:50px
}


text:
Q: Redirect when app is initialized in angularjs On first page load when app gets initialized I want to redirect the user to login page. I think the relevant part of the code is this
$rootScope.$on("$routeChangeStart", function (event, next, current) {
    alert("change location");

    $location.path('/login');
});

It is based on https://github.com/fnakstad/angular-client-side-auth/blob/master/app/js/app.js The problem is on page load the alert is triggered but location does not change. I have to click on a navigation item of my app and then the login action will be called and the route changes.
.run(['$rootScope', '$location', '$cookieStore', function ($rootScope,
                                                     $location, $cookieStore) {

    $location.path('/login');

    $rootScope.$on("$routeChangeStart", function (event, next, current) {

        $location.path('/login');

    });

    $rootScope.appInitialized = true;
}]);

This will work however seems redundant. And why is alert triggered but not location change?
Why does the location not changes on full page load? How to fix this?
Full code http://jsfiddle.net/qfSC3/ but fiddle does not work.

A: Try using the $locationChangeStart event instead
$scope.$on("$locationChangeStart", function(event){
    event.preventDefault();
})

Based off this question: AngularJS - Detecting, stalling, and cancelling route changes


text:
Q: Adding Controller using Ado.Net Entity Framework I am new for MVC, I am trying to add a control in my project.

*

*I added Entity Model in Model folder from database. It's name is MyModel.edmx and my entity's name is MyEntities.

*I followed this path: Controllers -> right click -> Add -> Controller. A window opened.

*In window:  I gave a name for my controller and I chose 'MVC Controller with read/write actions and views,using Entity Framework' for template.

*I think I must choose ModelModel.edmx as Model Class and 'MyEntites' as Data Context Class.

But ModelModel.edmx don't exist in Model class combobox.
I don't know if I did something wrong. Do you have any suggestions?

A: Do not choose ModelModel.edmx as model class,
Create a ViewModel that contains the properties that you need, use your service layer to populate the ViewModel and your controller will use that as the Model for its base.
Check this Link


text:
Q: what is this dynamic object creation * [] What does this mean? The following is a snippet from
here
class HashTableEntry {
   public:
      int k;
      int v;
      HashTableEntry(int k, int v) {
         this->k= k;
         this->v = v;
      }
};
class HashMapTable {
   private:
      HashTableEntry **t;
   public:
      HashMapTable() {
         t = new HashTableEntry * [T_S]; //What does this do
         for (int i = 0; i< T_S; i++) {
            t[i] = NULL;
         }
      }

In this code, t is a double pointer and it is assigned to new HashTableEntry * [T_S]
Does new HashTableEntry * [T_S] mean the Object HashTableEntry is being made into a pointer to point to an array with size of T_S?
If it is, I am not understanding how a dynamically created object with the new HashTableEntry is being delcared as an [T_S] when the definition of HashTableEntry is clearly a class/struct

A: t = new HashTableEntry * [T_S]

This creates an array of pointers to HashTableEntry. It creates T_S counts of them.
Perhaps it is clearer if written like this:
using HTEntry = HashTableEntry*;
t = new HTEntry [T_S];


text:
Q: Format phone number using Eval I am trying to format a phone number (stored as string) in a label on an .aspx page using Eval but am having trouble getting it to work.  I have tried doing this in the following ways:
<asp:Label ID="Label2" runat="server" Text='<%# Eval("PhoneNumber", "{0:(###) ###-####}")%>'></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%# string.Format("{0:(###) ###-####}", Eval("PhoneNumber")) %>'></asp:Label>

I know I can create a method to format the string, but I am only displaying the phone number once in this app and am not concerned with reusability - plus I'm curious to know if it can be done using Eval.
Any help is greatly appreciated!

A: You can not put your code in the Text attribute of the Label tag. This will cause an error "The server tag is not well formed".
You should put your code inside the tags
Below is an example:
<asp:Label ID="Label1" runat="server" Text="Label"><%# !String.IsNullOrEmpty(Convert.ToString(Eval("PhoneNumber"))) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(Eval("PhoneNumber").ToString())) : String.Empty%></asp:Label>

A: I think it would be best to centralize a function for formatting phone numbers as you will probably do this in more than one place. You could do something like:
public static class Toolkit
{
    public static string FormatPhone(string n)
    {
        string returnNumber = n;
        //Handle US Phones (10 digits) or else don't format
        if (!String.IsNullOrEmpty(n) && n.Length == 10)
        {
            string areaCode = n.Substring(0, 3);
            string usPrefix = n.Substring(3, 3);
            string usNum = n.Substring(6, 4);
            returnNumber = String.Format("({0}) {1}-{2}", areaCode, usPrefix, usNum);
        }
        return returnNumber;
    }
}

And then call it in your repeater:
<asp:Label ID="Label1" runat="server" Text='<%# YOURNAMESPACE.Toolkit.FormatPhone(Convert.ToString(DataBinder.Eval(Container.DataItem, "PhoneNumber")))%>'></asp:Label>

Of course, it might be cleaner to just format the phone number before it is passed as the datasource... or you could do it on the DataBound event if you are doing more formatting. Also, I think your formatting would work against a number but not a string.

A: I know this is a year old, but a simpler way would be to utilize the built-in RegEx.Replace:
<asp:Label ID="Label1" runat="server" Text='<%# Regex.Replace(Eval("PhoneNumber"), "(\d\d\d)(\d\d\d)(\d\d\d\d)", "($1)$2-$3")%>' />


text:
Q: Using an ExpandableObjectConverter on a Generic class for a PropertyGrid I want to have a property grid that looks like this when it has two SteppedValue objects:

But I would also like the SteppedValue object to be a generic, for example:
var fastEma = new SteppedValue<int>();
var slowEma = new SteppedValue<float>();

I have this mostly working by implementing ExpandableObjectConverter... but the only problem I am having is when I instantiate the object to return in ConvertFrom... I can't figure how to get the System.Type of T (from the instance of the generic) at this point.
Problem Code
public override object ConvertFrom(ITypeDescriptorContext iTypeDescriptorContext, CultureInfo cultureInfo, object value)
{
    if (value is string)
    {
        var classType = typeof(SteppedValue<>);
        Type[] typeArgs = { typeof(int) }; // <== Need to determine this
                                           //  needs to be T of the generic
                                           //  instance (not "typeof(int)")
        var instanceType = classType.MakeGenericType(typeArgs);
        object o = Activator.CreateInstance(instanceType, value);
        return o;
    }
    return base.ConvertFrom(iTypeDescriptorContext, cultureInfo, value);
}

Full Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;

namespace Test
{
    [TypeConverter(typeof(SteppedValueConverter))]
    public class SteppedValue<T>
    {
        public T Begin { get; set; }
        public T End { get; set; }
        public T Step { get; set; }

        public SteppedValue(T begin, T end, T step)
        {
            Begin = begin;
            End = end;
            Step = step;
        }

        public SteppedValue(string str)
        {
            var parts = ParseParts(str);
            Begin = parts[0];
            End = parts[1];
            Step = parts[2];
        }

        public static T ToT(object obj)
        {
            return (T)Convert.ChangeType(obj, typeof(T));
        }

        public static SteppedValue<T> Parse(string str)
        {
            return new SteppedValue<T>(str);
        }

        public List<T> ParseParts(string str)
        {
            while (str.Contains("  ")) str = str.Replace("  ", " ");
            var arr = str.Trim().Split(' ');
            if (arr.Length == 0)
                return new List<T> { default(T), default(T), default(T) };
            else if (arr.Length == 1)
                return new List<T> { ToT(arr[0]), ToT(arr[0]), default(T) };
            else if (arr.Length == 3 && arr[1].ToLower() == "to")
                return new List<T> { ToT(arr[0]), ToT(arr[2]), default(T) };
            else if (arr.Length == 5 && arr[1].ToLower() == "to" && arr[3].ToLower() == "step")
                return new List<T> { ToT(arr[0]), ToT(arr[2]), ToT(arr[4]) };
            throw new Exception("Unable to parse'" + str + "'");
        }

        public override string ToString()
        {
            if (Begin.Equals(End))
                return Begin.ToString();
            else if (Step == null || Step.ToString() == "")
                return Begin + " to " + End;
            else
                return Begin + " to " + End + " step " + Step;
        }
    }

    public class SteppedValueConverter : ExpandableObjectConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext iTypeDescriptorContext, Type type)
        {
            if (type == typeof(string))
                return true;
            return base.CanConvertFrom(iTypeDescriptorContext, type);
        }

        public override object ConvertFrom(ITypeDescriptorContext iTypeDescriptorContext, CultureInfo cultureInfo, object value)
        {
            if (value is string)
            {
                var classType = typeof(SteppedValue<>);
                Type[] typeArgs = { typeof(int) }; // <== Need to determine this
                var instanceType = classType.MakeGenericType(typeArgs);
                object o = Activator.CreateInstance(instanceType, value);

                return o;
            }
            return base.ConvertFrom(iTypeDescriptorContext, cultureInfo, value);
        }

        public override object ConvertTo(ITypeDescriptorContext iTypeDescriptorContext, CultureInfo cultureInfo, object value, Type destinationType)
        {

            if (destinationType == typeof(string) && value.GetType().GetGenericTypeDefinition() == typeof(SteppedValue<>))
                return value.ToString();

            return base.ConvertTo(iTypeDescriptorContext, cultureInfo, value, destinationType);
        }
    }
}

A: You can get the type from the context, like this (in your SteppedValue case, it's the first generic type):
Type steppedValueType = iTypeDescriptorContext.PropertyDescriptor.PropertyType.GetGenericArguments()[0];


text:
Q: rails 3: trying to COUNT/GROUP on multiple fields, but getting SQL error My table StoreCodes holds unique products codes (and their availablity) for each store, eg:
category:integer
code:string
available:boolean
store_id:reference

I'm trying to show a simple table with 3 columns showing how many codes are in each category, AND how many of those codes have available = true
Category_number / Count_Codes_in_category / Count_Codes_in_category_available==TRUE

In my controller, the following attempt to COUNT and GROUP on both category and available throws this error:
SQLite3::SQLException: near "WHERE": syntax error: SELECT category, available, COUNT(*) AS instances GROUP BY category, available WHERE (store_id = 8)

My controller code:
@b2 = StoreCode.find_by_sql ['SELECT category, available, COUNT(*) AS instances GROUP BY category, available WHERE (store_id = ?)', @store.id]

A: Your SQL statement has no 'FROM' clause, I also think the 'GROUP BY' should come after the 'WHERE'.

A: Your SQL is wrong. You have to put the GROUP BY clause after the WHERE clause, and when using find_by_sql you also need to write the complete statement (include the FROMclause)
Like this:
@b2 = StoreCode.find_by_sql ['SELECT category, available, COUNT(*) AS instances
FROM store_codes WHERE (store_id = ?) GROUP BY category, available', @store.id]


text:
Q: Rails 4: nested resources -> nested models? Today I upgraded from Rails 3 to Rails 4 and I noticed that when I tried to open the web browser there was an error saying unitialized constant Foo::Bar. The controller code in question looks something like
@foo = Foo.find(params[:foo])
@bars = @foo.bars # here the error occurs

My routes are simple: resources :foo { resources :bar }
I have switched to strong_params and thus have moved all attr_accessible to the controller params.
This nesting of models was not intentioned by me, Rails did that behind my back. When I actually moved bar into app/models/foo/bar.rb, it seemed to work which I find somewhat strange. I have searched the net to no avail.
Any explanations?


text:
Q: If $f:(X,d) \rightarrow (Y,d^{\prime})$ is an surjective isometry , then Show that if $$f:(X,d) \rightarrow (Y,d^{\prime})$$ is an surjective isometry then for any $x,y \in X$ we have $$f(E_d(x,z))=E_{d^{\prime}}(f(x),f(z))$$
Recall that for any metric space $(X,d)$ and $x,z \in X,$ then the equality set for $x,z$ is $$E_d(x,z)= \{ y \in X : d(x,z) = d(x,y)+d(y,z) \} $$ For the L.H.S. we have (going to stop writing 'E')
$$f(E_d(x,z)) = f(d(x,y))+f(d(y,z))$$ $$=f(x-y)+f(y-z)$$
$$f(x)-f(y) +f(y)-f(z)$$ $$=f(x)-f(z)$$ $$=E_{d^{\prime}}(f(x),f(z)).$$
I am relatively confident in my solution. Three problems I am curious about. I have generalized the metrics to simply be the difference between two points in the image and two points in the pre-image of my map. Is this possible? Also, I have shown (I believe) that the left hand side equals the right hand side. Do I need to do the same for the right hand side? Finally, do I need to say more about why the map is linear (if it is)?

A: Unfortunately your solution doesn't make a lot of sense. If $x,y\in X$ then $d(x,y)\in\mathbb{R}$, so in most cases it doesn't make sense to talk about $f(d(x,y))$. It is also not correct to assume $d(x,y)=x-y$. Even if subtraction is defined on your space this is not a metric.
Let us assume $a\in f(E_d(x,z))$. Then $a=f(y)$ where $y\in E_d(x,z)$, so $d(x,z)=d(x,y)+d(y,z)$. Since $f$ is an isometry, we have $d'(f(x),f(z))=d'(f(x),f(y))+d'(f(y),f(z))$, so $a=f(y)\in E_{d'}(f(x),f(z))$. This shows $f(E_d(x,z))\subseteq E_{d'}(f(x),f(y))$.
Suppose now $a\in E_{d'}(f(x),f(z))$. Since $f$ is surjective, $a=f(y)$ for some $y\in X$, and we have $d'(f(x),f(z))=d'(f(x),f(y))+d'(f(y),f(z))$. Applying the isometry property once again we have $d(x,z)=d(x,y)+d(y,z)$, so $y\in E_d(x,z)$, and hence $a=f(y)\in f(E_d(x,z))$. This shows $E_{d'}(f(x),f(z))\subseteq f(E_d(x,z))$, completing the proof.


text:
Q: Smooth vs analytic spacetimes Recently in more technical settings (I was learning algebraic QFT), I encountered the term "real analytic" manifolds (Lorentzian manifolds, to be precise). This is in contrast to smooth manifolds, the same way real analytic functions are not the same as smooth ($C^\infty$) functions.
What I have trouble wrapping my head around are "simple" examples of analytic Lorentzian manifolds that differ from standard smooth Lorentzian manifolds. This issue is related to another post here, but I guess I am looking for something more concrete (and possibly simpler). I can frame this in two ways:

*

*Are the standard examples in general relativity considered real-analytic manifolds? The ones I encounter most of the time---Minkowski, Schwarzschild,
FRW spacetimes, seem to be the case: the Schwarzschild geometry has
$f(r)=1-2M/r$. The FRW with good enough scale factors (like $a(\eta)=-1/(H\eta)$ for de Sitter case) is also real-analytic on $\eta<0$. I believe the same goes for the entire Kerr-Newman family and its maximal extension. In the Stackexchange post above, the argument seems to be a matter of talking about "the" maximal analytic extension, but if I just want to talk about the exterior of Schwarzschild or exterior of a star, for example, is real-analyticity really too strong? Another example I can probably think of is "gravitational shockwaves" (e.g., Aichelburg-Sexl metric) where the metric is not real-analytic (it is distributional, I guess). Does that mean all spacetimes whose metric can be written in terms of elementary real functions automatically real-analytic then?

*If the spacetime is real-analytic, does the test fields on top of it have to be? For example, must hyperbolic wave equation be "real-analytic" (e.g., with real-analytic potentials) if the metric is real analytic? It looks to me that usually the fields living on some spaces does not need to inherit the properties of the background geometry, but I don't know.

A: We only impose $C^{\infty}$ when setting up the general theory, because real-analyticity would be too strong a condition to impose. However, when trying to find specific solutions (Schwarzschild, Reissner Nordstrom etc etc) it turns out that we end up with a set that can be covered by charts whose transitions are real-analytic; so it is by a miracle that we end up with a real-analytic structure. Also, the metric when expressed in any coordinate system in these examples has real-analytic components. Therefore, it is a very fortunate matter that having solved Einstein's equations in one chart automatically means it is satisfied on the entire manifold.
So once again, we do not require that our manifolds/fields be real-analytic simply because real-analyticity would be too strong a condition  to demand a-priori (because of uniqueness of analytic continuation). If it turns out after our symmetry ansatz's and calculations that we end up with something analytic, we just thank our lucky stars and be happy with it. Hopefully this answers your second question as well: no we do not have to (nor do we) demand that fields be analytic; if we have an analytic manifold, then we're perfectly within our right to consider fields which are analytic but we can also consider $C^{\infty}$ fields, or if we want, just $C^2$ fields.

Edit:
@BenceRacskó has kindly pointed out that every $C^k$ manifold ($k\geq 1$) actually has an analytic sub-atlas, which I didn't realize. But still, having an analytic fields (in particular the metric) is non-trivial because of analytic continuation: its values on some non-empty open set (no matter how small) would determine it uniquely on the entire manifold (provided such an extension exists).


text:
Q: Code won't acknowledge the odd numbers, not placing them in column B The task is to write a code that will import the text from a .txt file. In this task, I am to sort the pair and odd numbers in different columns A,B.
The code runs fine by copying over the work of the pair numbers (from the .txt file) but doesn't even copy over the odd numbers.
Tried changing the formula, this is the only one that works.
Close #1
Dim xopen As Variant
Dim xclose As Variant

xopen = Application.GetOpenFilename

If xopen = "False" Then
    MsgBox "error nav fails"
Else
    Open xopen For Input As #1
    i = 1
    j = 1
    Do Until EOF(1)
        Line Input #1, st

        If IsNumeric(st) = False Then
            MsgBox "error nav skaitlis(number)"
            Close #1
            Close #2
            Exit Do
        End If

        Line Input #1, st
        If st > 0 Then
            Cells(i, 1) = st
            i = i + 1
        Else
            If Val(st) Mod 2 = 1 Then
                Cells(j, 2).Value = st
                j = j + 1
            End If
        End If
    Loop

    Close #1
    xclose = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt),*.txt")
    ThisWorkbook.SaveAs Filename:=xclose, FileFormat:=xlText
End If

A: Your problem is inside the If - Else logic, try this code and see below for an explanation:
If st > 0 Then
    If st Mod 2 = 0 Then
        Cells(i, 1).Value2 = st
        i = i + 1
    Else
        Cells(j, 2).Value2 = st
        j = j + 1
    End If
End If

The way your code is written you can only enter the Else statement when your number st is <= 0. But you actually want to check  if the number is larger than 0 and if that is true split the numbers into odd and even numbers. Basically your Else was in the wrong place.

A: '''
    Line Input #1, st
    If IsNumeric(st) = False Then
        MsgBox "error nav skaitlis(number)"
        Close #1
        Close #2
        Exit Do
    End If

'''
This was the cause of the problem, deleting this would solve it and let me copy over the odd numbers. It kept looping through that phase. And wouldn't let it go past it.


text:
Q: Writing to allocated char buffer I have following code:
framingStatus compressToFrame(char* inputBuffer, size_t inputBufferLength, char* frame, size_t* frameLength)
{
    dword crc32 = GetMaskedCrc(inputBuffer,inputBufferLength);
    size_t length = snappy_max_compressed_length(inputBufferLength);
    char* compressed = (char*)malloc(length);
    snappy_status status = snappy_compress(inputBuffer,inputBufferLength,compressed,&length);
    if( status!=SNAPPY_OK )
        return FS_ERROR;
    frame[0] = 0x00; // Typ ramki skompresowany
    frame[1] = length&0xff;
    frame[2] = (length&0xff00)>>8;
    frame[3] = (length&0xff00)>>16;
    frame[4] = crc32&0xff;
    frame[5] = (crc32&0xff00)>>8;
    frame[6] = (crc32&0xff0000)>>16;
    frame[7] = (crc32&0xff000000)>>24;
    frame[8] = '\0'; // Pomoc dla strcat

    strcat(frame,compressed);
    *frameLength = length+8;
    free(compressed);

    return FS_OK;
}

Before calling this function I allocate memory for buffer named frame. All is ok, but assign instructions frame[x] = ... don't seem to write anything to buffer called frame and strcat concatenate compressed data to empty buffer without header I need.
Why assign instructions frame[x] = ... etc. don't give any result?
[EDIT:]
Can you suggest what function I have to use if I want to concatenate frame header with compressed data?
[EDIT2:]
Code presented below works just fine.
framingStatus compressToFrame(char* inputBuffer, size_t inputBufferLength, char* frame, size_t* frameLength)
{
    dword crc32 = GetMaskedCrc(inputBuffer,inputBufferLength);
    size_t length = snappy_max_compressed_length(inputBufferLength);
    char* compressed = (char*)malloc(length);
    snappy_status status = snappy_compress(inputBuffer,inputBufferLength,compressed,&length);
    if( status!=SNAPPY_OK )
        return FS_ERROR;
    frame[0] = 0x00; // Typ ramki skompresowany
    frame[1] = length;
    frame[2] = length >> 8;
    frame[3] = length >> 16;
    frame[4] = crc32;
    frame[5] = crc32 >>8;
    frame[6] = crc32 >>16;
    frame[7] = crc32 >>24;

    memcpy(&frame[8],compressed,length);
    *frameLength = length+8;
    free(compressed);

  return FS_OK;
}

A: You have
frame[0] = 0x00;

which is the same as
frame[0] = '\0';

No matter what you add after the first character, frame becomes a 0 length string.

A: strcat is for strings, not general binary bytes. Because frame first byte is zero, strcat will copy compressed starting at frame[0] and will stop copying when it sees a zero in compressed.
Try memcpy instead.
memcpy(&frame[8], compressed, length);

Also, since the length of frame is passed as an argument, you might want to be checking the total length you are copying to frame to make sure there's no illegal overwrite in that case.

A: As others already pointed out, you use binary data and not text strings. Therefore, strcat function is inappropriate here, use memcpy instead.
Furthermore, you should use unsigned char instead of plain char.
Additionally, you don't need to mask the values before shifting
frame[2] = (length&0xff00)>>8;

could be just
frame[2] = length >> 8;

And in this case, it is even buggy
frame[3] = (length&0xff00)>>16;

Same here
frame[5] = crc32 >> 8;
frame[6] = crc32 >> 16;
frame[7] = crc32 >> 24;

A: frame[0] = 0x00;

will make the first character as end of string character therefore your string frame is empty.
frame[0] = 0x00;

is same as writing,
frame[0] = '\0';


text:
Q: jQuery Bootgrid using ADO.Net with SQL Server 2012 I have read that jQuery Bootgrid is simple to use for sorting, paging and searching options and seen the demo's. Can anyone clarify me that can I use this jQuery Bootgrid for my C# ASP.Net application. I m using default GridView option binding with ADO.Net services.
I have read one article in this link, but it explained for php & MySQL. Is it applicable to use the same concept for ADO.Net.
Please some one throw some lights on this.

A: Bootgrid is a jQuery plugin, which can be populated with json data, or you can build html table by yourself (filling a tbody with tr's and td's).
Surely you can use it with a C# ASP.NET WebApplication, or WebForms, or anything which can receive a http request, but it won't work binding to an ADO.NET, SQL Server Connection out of the box, as do GridView, because a GridView is a server-side component which is compiled and translated to html by the server. So the client receives only the resulted html, whereas Bootgrid is client-side, which means you can make it work with any kind of server application by using ajax calls.
You should build an API to receive requests from bootgrid, for example, or fill the html table data manually, as I said. The table must have their structure, like this sample:

            ID
            Sender
            Received
            Link

In the sample above, they only configured the table header with column specifications, take note those data-column-id, data-type, data-anything attributes. They are bootgrid's common configurations.
In this example, we don't have a tbody with tr's and td's already populated, it's a sample to be loaded with json data.
Another option is to manually build rows with td's:

        10238
        eduardo@pingpong.com
        14.10.2013

    ...

...and bootgrid will work as well.
It's really simple to use bootgrid, just take a read in their examples here.


text:
Q: Pentaho Reporting with NODEJS and without TOMCAT I have a linux-based nodejs web application that I need to generate reports from and I have chosen Pentaho for this.
I have installed biserver-ce (5.4) which works, however this is an overkill as it uses tomcat which is a behemoth and uses huge amounts of CPU and memory (1.5GB+) which I don't have a lot of, and furthermore I do not require any user console, user management or security etc etc or any of the other features that biserver offers.
Currently the requests are sent to biserver:8080 by nodejs back-end and the resulting pdf report is then piped to the client's front-end browser using nodejs.
As far as I understand, tomcat is simply converting a http request and returning the rendered pdf, and since I already have a web server with nodejs this seems a bit redundant, and I want to bypass tomcat entirely.
So I am looking to eliminate tomcat and either have a server listening on a socket or simply send the report parameters via the command line, but having googled this for the last half day, I am still unable to find a definitive answer or example of how I can generate pentaho reports without using tomcat.
Can this be done ? I have good javascript skills but zero java programming abilities, Can I use just the parts of biserver that generate the reports and eliminate tomcat completely ?
I have moved the compiling issue to a different thread.

A: It does appear possible to at least embed the reporting engine into a standalone Java application. This does require you to have some knowledge about Java and the Pentaho SDK, but it may be your only non-Tomcat option. There is a complete example Java project here that shows you how to accomplish this (code is mostly in Sample1.java).


text:
Q: Filter selected list by variable I'm on cakePHP 2. I have a problem and I need your help. Here is some code of my controller (from StudentsController.php) specifically the "edit" function:
$students = $this -> Student -> find('list', array(
    'order' => 'Student.name ASC'
));
$this -> set('students', $students);

How can I filter the list by the current student's class so the list will contain all students that has the same student's class?
I need some code like this
$students = $this -> Student -> find('list', array(
    'conditions' => array('Student.class_id' => CURRENT-STUDENT'S-CLASS),
    'order' => 'Student.name ASC'
));
$this -> set('students', $students);

A: So according to your edit function, your find should look something like this.
$students = $this -> Student -> find('list', array(
'conditions' => array('Student.class_id' => $this->request->data['Student']['class_id']),
'order' => 'Student.name ASC'

));


text:
Q: zooming HTML contents with zoomooz I'd like to zoom a HTML Table with text in it. I am using zoomooz, which is a great tool for zooming:
http://janne.aukia.com/zoomooz/
The problem i am facing is that fonts are also zoomed, which makes the same contents appear just bigger. I want to have more content show up when i zoom, have text wrap around ,etc. probably you know what i mean.
I checked this out but it doesn't seem to have any effect when i apply it to the target divs:
-webkit-text-size-adjust: none;
Thank you
Angel

A: Maybe instead of zooming, you could just resize the element you want to zoom to. Then, the font size etc would stay the same but you would have more space content.
You can resize elements with jQuery.animate, see examples here:
http://api.jquery.com/animate/
I don't quite get what you are aiming at, so please give a more detailed explanation of your issue.


text:
Q: Propagation of exceptions in Spring Boot does Spring Boot wraps/hides/encapsulates exceptions one way or another ?
I get some strange behaviour when an exception is produced.
For instance, in a Spring Boot + JPA project, if i comment out the @Entity annotation :
@Table(name = "XXX")
//@Entity
public class Contract
{
...
}

i get the following exception (warning) :
2018-12-10 19:09:33.153 DEBUG DESKTOP-48HHHCD --- [ost-startStop-1] o.h.c.CollectionSecondPass               : Second pass for collection: cp.dmo.bean.ContribuablePar.listeContratMensu
2018-12-10 19:09:33.153 DEBUG DESKTOP-48HHHCD --- [ost-startStop-1] o.h.c.a.CollectionBinder                 : Binding a collection of element: cp.dmo.bean.ContribuablePar.listeContratMensu
2018-12-10 19:09:33.154  WARN DESKTOP-48HHHCD --- [ost-startStop-1] o.s.b.f.s.DefaultListableBeanFactory     : Bean creation exception on non-lazy FactoryBean type check: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testpopulationserviceso' defined in file [C:\Users\celfer\AppData\Local\Temp\1-dmo\WEB-INF\classes\conf\application\applicationContext-service.xml]: Cannot resolve reference to bean 'testpopulationserviceimpl' while setting bean property 'target'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testpopulationserviceimpl' defined in file [C:\Users\celfer\AppData\Local\Temp\1-dmo\WEB-INF\classes\conf\application\applicationContext-service.xml]: Cannot resolve reference to bean 'testpopulationdao' while setting bean property 'testpopulationdao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testpopulationdao' defined in file [C:\Users\celfer\AppData\Local\Temp\1-dmo\WEB-INF\classes\conf\application\applicationContext-dao.xml]: Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in URL [jar:file:/C:/Users/celfer/AppData/Local/Temp/1-dmo/WEB-INF/lib/lombok-jpa-24.0.6-SNAPSHOT.jar!/conf/applicationContext-datasources-jpa2.xml]: Cannot resolve reference to bean 'entityManager' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManager' defined in URL [jar:file:/C:/Users/celfer/AppData/Local/Temp/1-dmo/WEB-INF/lib/lombok-jpa-24.0.6-SNAPSHOT.jar!/conf/applicationContext-datasources-jpa2.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2018-12-10 19:09:33.155 DEBUG DESKTOP-48HHHCD --- [ost-  startStop-1] o.s.b.f.s.DefaultListableBeanFactory     : Creating shared instance of singleton bean 'lecturepersonneso'

So the exception says the application is unable to build a Hibernate SessionFactory but it does not point out precisely where the problem comes from.
Any clue ?
Thanks


text:
Q: java date parsing with GMT in it The published date String is returned as : Sun, 18 Nov 2012 06:50:02 GMT and my method to convertDate is returning me java.text.ParseException: Unparseable date: "Sun, 18 Nov 2012 06:50:02 GMT" (at offset 8).  I checked resources but couldn't find them much helpful like this one ... Parsing a String with a GMT timezone to Date using SimpleDateFormat
Would really appreciate if you can shed some light on it.  Here is my method ..
pubDate here is Sun, 18 Nov 2012 06:50:02 GMT
public Date convertDate(String pubDate){

    SimpleDateFormat sdf =  new SimpleDateFormat("EEE, dd MM yyyy hh:mm:ss Z",Locale.US);
    Date newsDate = new GregorianCalendar(0, 0, 0).getTime();
        try{
            newsDate  = sdf.parse(pubDate);
        }catch(ParseException e){
            Log.d(Tag, "Exception Parsing date" + pubDate);
        }
    return null;
}

A: Use MMM for the month field:
new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z",Locale.US);

Once this is fixed, don't forget to return newsDate as you're currently returning null.

A: Here is a little test I did:
@Test
public void testDate() throws ParseException {

    String pubDate = "Sun, 18 Nov 2012 06:50:02 GMT";

    SimpleDateFormat sdf = new SimpleDateFormat(
            "EEE, dd MMM yyyy hh:mm:ss z", Locale.US);
    Date newsDate = new GregorianCalendar(0, 0, 0).getTime();

    newsDate = sdf.parse(pubDate);

}

You need to set the month with MMM because you are using the first three letters of the month (and four M would mean the full month name). Also, the timezone must be z instead of Z because you have a ISO 8601 Time zone (GMT).


text:
Q: How does the Contours→{{f_1, g1}, {f_2, g_2}, …} setting work? I want to plot some wavefronts in Mathematica, and I'm having some trouble reining in one of the options for my ContourPlot3D.
More specifically, the documentation for ContourPlot3D says that the Contours option can be used in the form
ContourPlot3D[
  x^3 + y^2 - z^2
  , {x, -2, 2}, {y, -2, 2}, {z, -2, 2}
  , Contours -> {{-2, Red}, {2, Blue}}
  , Mesh -> None
]

to produce contours at those levels and with those colours, but when I try to implement that I get some pretty wonky behaviour. As a minimal example, consider the following plane wave:
L = π + 0.001;
ContourPlot3D[
 Arg[Exp[I z]]
 , {x, -L, L}, {y, -L, L}, {z, -L, L}
 , Contours -> Table[{ϕ, Hue[(ϕ + π)/(2 π)]}, {ϕ, -π, π, π/3}]
 , Mesh -> None
 ]

Unfortunately, it produces some pretty paltry output,

with a bunch of contours missing. Weirdly enough, these contours do appear if I give it numerical values for the contours:
ContourPlot3D[
 Arg[Exp[I z]]
 , {x, -L, L}, {y, -L, L}, {z, -L, L}
 , Contours -> Table[{N[ϕ], Hue[(ϕ + π)/(2 π)]}, {ϕ, -π, π, π/3}]
 , Mesh -> None
 ]

What's going on here? Is this a bug?


text:
Q: Rails / Stripe - taking multiple payments I'm building an events app using Rails and Stripe to handle payments. I've used javascript for my booking page in order to allow a user to book and pay for multiple spaces rather than just one at a time. The booking page allows for this as you can see here -

However on my Stripe dashboard only one payment has been taken for one space -

How do I solve this so it takes the full payment indicated on the booking view?
Here's my Controller and view code -
bookings_controller.rb
class BookingsController < ApplicationController

    before_action :authenticate_user!

    def new
        # booking form
        # I need to find the event that we're making a booking on
        @event = Event.find(params[:event_id])
        # and because the event "has_many :bookings"
        @booking = @event.bookings.new(quantity: params[:quantity])
        # which person is booking the event?
        @booking.user = current_user
        #@booking.quantity = @booking.quantity
        @total_amount = @booking.quantity.to_f * @event.price.to_f

    end

    def create
        # actually process the booking
        @event = Event.find(params[:event_id])
        @booking = @event.bookings.new(booking_params)
        @booking.user = current_user

        Booking.transaction do

            @event.reload
            if @event.bookings.count > @event.number_of_spaces
            flash[:warning] = "Sorry, this event is fully booked."
            raise ActiveRecord::Rollback, "event is fully booked"
            end
        end

        if @booking.save

            # CHARGE THE USER WHO'S BOOKED
            # #{} == puts a variable into a string
            Stripe::Charge.create(amount: @event.price_pennies, currency: "gbp",
                card: @booking.stripe_token, description: "Booking number #{@booking.id}")

            flash[:success] = "Your place on our event has been booked"
            redirect_to event_path(@event)
        else
            flash[:error] = "Payment unsuccessful"
            render "new"
        end

        if @event.is_free?

            @booking.save!
            flash[:success] = "Your place on our event has been booked"
            redirect_to event_path(@event)
        end
    end

    private

    def booking_params
        params.require(:booking).permit(:stripe_token, :quantity)
    end

end

booking.new.html.erb

Confirm Your Booking

                                  Confirm number of spaces you wish to book here:
                                    <input type="number" placeholder="1"  min="1" value="1" class="num-spaces">

                                    Total Amount
                                    £<span class="total" data-unit-cost="<%= @event.price %>">0

                <%= simple_form_for [@event, @booking], id: "new_booking" do |form| %>

                      Card Number
                      <input type="text" size="20" data-stripe="number"/>

                  CVC
                  <input type="text" size="4" data-stripe="cvc"/>

                        Expiration (MM/YYYY)
                        <input type="text" size="2" data-stripe="exp-month"/>

                     /
                    <input type="text" size="4" data-stripe="exp-year"/>

               <%= form.button :submit %>

<% end %>
<% end %>

Do I need to add 'price' to my booking_params? I already have 'quantity' in there?
Do I need to add a 'total_amount' column to my bookings table? Or is it related to my Stripe action in the controller and the amount?
Any help is appreciated.

A: You need to create Stripe.order and pass items: [], where you can pass quantity. In your case it will be one item.
Please check out Stripe API for more information
Update
Here step by step guide:

*

*Login to Stripe account, create a product and make it active. This will be your booking. Save it.

*When you inside the product, you'll see Inventory. Find + Add SKU. Click it.

*You'll see the popup window like this

*Fill in whatever you need to. In your case currency, price and inventory, perhaps image. ID will be generated automatically. Press Add SKU

*Now you'll have SKU for this product. As you probably guessed already, you can have many SKU's for the same product and the price can be different.

*Copy newly created SKU id

*Now you can create Stripe::Order like this:

response = Stripe::Order.create(
  currency: 'usd',
  items: [
    {
      type: 'sku',
      parent: 'sku_9AJ4OfKbdRuoGi', # SKU id
      quantity: 2
    }
  ],
  customer: nil,  # replace with customer id if needed
  email: 'michael.thompson@example.com'
)

This is how your response would look like:
#<Stripe::Order:0x3ff36d37e2b8 id=or_18ryyuBq3wgBfJrxa44Jzm3T> JSON: {
  "id": "or_18ryyuBq3wgBfJrxa44Jzm3T",
  "object": "order",
  "amount": 19998,
  "amount_returned": null,
  "application": null,
  "application_fee": null,
  "charge": null,
  "created": 1473465868,
  "currency": "usd",
  "customer": null,
  "email": "michael.thompson@example.com",
  "items": [
    {"object":"order_item","amount":19998,"currency":"usd","description":"booking","parent":"sku_9AJ4OfKbdRuoGi","quantity":2,"type":"sku"},
    {"object":"order_item","amount":0,"currency":"usd","description":"Taxes (included)","parent":null,"quantity":null,"type":"tax"},
    {"object":"order_item","amount":0,"currency":"usd","description":"Free shipping","parent":"ship_free-shipping","quantity":null,"type":"shipping"}
  ],
  "livemode": false,
  "metadata": {},
  "returns": {"object":"list","data":[],"has_more":false,"total_count":0,"url":"/v1/order_returns?order=or_18ryyuBq3wgBfJrxa44Jzm3T"},
  "selected_shipping_method": "ship_free-shipping",
  "shipping": null,
  "shipping_methods": [
    {"id":"ship_free-shipping","amount":0,"currency":"usd","delivery_estimate":null,"description":"Free shipping"}
  ],
  "status": "created",
  "status_transitions": null,
  "updated": 1473465868
}

When examining the response of any API call or webhook notification, use the Order object's status attribute to verify the current status of the order and respond accordingly.

*

*When an order is first requested, the resulting order object has an
  initial status of created.

*When an order is paid, status changes to paid. You should now fulfill
  the order.

*After fulfilling the order, update the Order object to change status
  to fulfilled. Only orders in the paid state can be marked as
  fulfilled.

*If the customer cancels the order (through your site) before it's
  been fulfilled, update status to canceled which will refund the
  payment.

*If the order has been fulfilled and the customer returns the
  purchased items, update status to returned which will refund the
  payment.

Read order guide for more details.
Now you should see new order in Stripe's dashboard
Hope this helps.


text:
Q: Using an automatically generated URL as a kind of a password Assume I want visitors of my site to be able to fill in a long form. That's not necessary for them to fill it in to use the site, but if they want to send a story to me, they need to fill it in. So, some of them will wish to do it, some won't. The form is quite large so visitor may want to leave it semi-filled to come back later and finish it. To make the process as easy as possible for the visitor, I want him just to click a link "Create a story" that will redirect the visitor to an automatically generated url, like www.mysurveys.com/7Bs3h4vSWEe. Here the visitor works with his form and clicks 'Save' when he wants to save it so that to return back later to finish it. The form data is kept in the database with its generated ID. When the visitor thinks the form is filled properly and is done, he clicks 'Send for review' and then the form goes to me.
The question is: how secure is to use this automatically generated URL as the only credential for the user? I suppose any sniffer could easily get the url visitor uses to fill in the form. How to make a process like this as simple as possible? What are ways to make it a little more safe? I know I can do it using standard user registration pattern but I want to make it simpler.

A: This ID is a lot like having a session id for the user and in that sense its not a compromise.  One difference is that session id's should always expire.  If security is a concern then HTTPS should be used to prevent eavesdropping.
This url value should be a Cryptographic Nonce.  You should also take brute force into consideration.  If someone is guessing a lot of keys that don't exist,  prompt them with a captcha.

A: It's not that secure, BUT sniffing is basically the only attack, AND unless the attacker doesn't care whose URL they get, they would have to target their victim quite specifically.
I wouldn't use this for, for example, financial information, or third-party-confidential information, but for low-risk information it might well be fine.
edit: I've ignored brute force, but much the same applies, and as other answers suggest, there are protections against that, like captcha.


text:
Q: Winapi : How do I for my button send different message according to the key pressed? I created a button, that when clicked, will open an .exe file and close the current application:
HWND Button = CreateWindowEx(0, L"Button", L"Exe Application", WS_BORDER | WS_VISIBLE | WS_CHILD, 500, 500, 200, 200, hWndParent, (HMENU)BUTTON_EXE, 0, 0);

And in the WindProc:
switch (uMsg)
{
    case WM_COMMAND:
        switch (wParam)
        {
        case BUTTON_EXE:
            ShellExecute(hwnd, NULL, L"Module 1.exe", NULL, NULL, SW_SHOW);
            PostQuitMessage(0);
            return 0;
        }
    return 0;
}

I want that when I click on the button with a key pressed (for example, "maj"), the current application doesn't close.
So, I want that according to the key pressed when clicking the button, it sends a different message, but I didn't find how. Is there a way to do that?

A: You can check whether a key is pressed while handling WM_COMMAND messages by calling the GetKeyState function. Depending on its return value you can then implement different logic.
It's important to call GetKeyState (as opposed to GetAsyncKeyState) to get the key state at the time the button was clicked.

A: You can do additional processing of the message. For example:

*

*your button will sent another message (WM_BUTTON_EXE_RAW).

*you catch that message and resend other message (BUTTON_EXE) if button maj pressed only.


text:
Q: What does it mean to integrate out fields from a theory? I've done a fair bit of reading on this subject and I'm still confused about the basic principle of integrating out fields in QFT. When we have a function of 2 fields a and b, f(a,b), and we integrate out the heavy b-fields to give f(a), by what mechanism does the b-field dependence disappear? Are we basically saying that integrating out the b-fields is tantamount to solving the probability amplitude of those fields appearing and that because they are heavy their contribution is vanishingly small?
Also I've seen the contraction of fields talked about with regards to integrating out, what is the role of these contractions when integrating out? Contracting fields seems the best means of making a particular field disappear from the equations we consider!

A: The "integration" we refer to when we "integrate heavy fields out" is nothing else than the Feynman path integral – a way to calculate amplitudes in a quantum field theory using the sums-over-histories. If you have been thinking about any other kind of "integral" or if you even replaced the integral by contractions or arbitrary different operations, you had to end up with confusing (or completely wrong) conclusions.
The Feynman path integral gives you a formula for Green's functions and other amplitudes
$$ A = \int {\mathcal D}\phi_{\rm light} \,{\mathcal D}\phi_{\rm heavy}\,\exp(iS)\prod_{i}V_i$$
where $V_i$ are some insertions in the integral that are chosen according to the choice of the quantity (amplitude) we want to quantify. We integrate over all configurations of all fields etc. To integrate out $\phi_{\rm heavy}$ means to divide the integration process to two steps and first integrate over some degrees of freedom, namely $\phi_{\rm heavy}$ – which may be many fields – for fixed values of the remaining fields, $\phi_{\rm light}$.
The resulting i.e. remaining integral which still waits to be integrated over the remaining light fields (without insertions) is interpreted as $\exp(iS_{\rm effective})$ where $S_{\rm effective}$ only depends on the light degrees of freedom $\phi_{\rm light}$.
$$ A_\text{after integrating out} = \int {\mathcal D}\phi_{\rm light} \,\exp(iS_{\rm effective})\prod_{i}V_i,\\
\exp(iS_{\rm effective} [\phi_{\rm light}]) = \int {\mathcal D}\phi_{\rm heavy}\,\exp(iS)
$$
In this way, we eliminate the heavy degrees of freedom and calculate the effective action that remembers all the loop effects that the now-forgotten heavy fields used to cause. However, this effective field theory with an effective action – a result of integrating out the heavy fields – is only good for asking low-energy questions, of course. The insertions $V_i$ we may insert into the simplified theory that only depends on $\phi_{\rm light}$ cannot depend on the heavy degrees of freedom anymore, of course: they have been disappeared.
But in principle, if you calculate the path integral over the heavy degrees of freedom "exactly", the effective action may give you completely accurate results for the scattering of the light fields, and so on. In practice, we integrate over the heavy degrees of freedom "approximately" – we assume that the effective action only contains some low-dimension operators (the renormalizable ones and perhaps one or two extra operators that are non-renormalizable) and we study what happens with their coefficient. If we wanted the effective action to give exactly the same result for observables depending on the remaining light fields as the original action, we would have to include everything and the effective action would contain arbitrarily high-dimension non-renormalizable operators – equivalently, it would be non-local.
If you need to avoid the Feynman path integral, then you should interpret "integrating out a set of fields" by "finding the dynamics for the remaining fields that produces the same interactions or Green's functions for them as in the original theory that did contain the now-integrated-out fields". Feynman's approach gives us a straightforward tool to do such a thing; it could be very hard to derive the right algorithm in a different computational approach to quantum field theory.


text: Q: Delphi 10 Seattle - little change in unit then all dcu file are recompiled I have large project written in XE3 (about 2200 units). I did update IDE Delphi XE3 to Delphi 10 Seattle. When I adds or deletes methods in any unit (without form, without dfm) and I want running (F9), all units of project are compiling, this continues very long time. In XE3 is absent this problem. I have dcu files in the same folder. I did even new project file (dpr and dproj) in Delphi 10 but it did not work.


text:
Q: Redux State Using Reselect To Derive Related Data I've been stuck on this for a while.
Here's a part of my redux-state
state: {

  teachers: [
    { teacherId: 'ttt1', teacherName: 'Susan', isCool: true, teachesAt: 'sss1'},
    { teacherId: 'ttt2', teacherName: 'Karen', isCool: false, teachesAt: 'sss2'},
    { teacherId: 'ttt3', teacherName: 'Bob', isCool: true, teachesAt: 'sss3'},
    { teacherId: 'ttt4', teacherName: 'Mike', isCool: false, teachesAt: 'sss1'},
  ],

  schools: [
    { schoolId: 'sss1', schoolName: 'Washington'},
    { schoolId: 'sss2', schoolName: 'Lincoln'},
    { schoolId: 'sss3', schoolName: 'Jefferson'},
  ],

  students: [
    { schoolIdEnrolled: 'sss1', studentName: 'Billy'},
    { schoolIdEnrolled: 'sss1', studentName: 'Steven'},
    { schoolIdEnrolled: 'sss2', studentName: 'Bobby'},
    { schoolIdEnrolled: 'sss3', studentName: 'Mikey'},
    { schoolIdEnrolled: 'sss3', studentName: 'Sally'},
    { schoolIdEnrolled: 'sss3', studentName: 'Cindy'},
    { schoolIdEnrolled: 'sss3', studentName: 'Mandy'},
  ],

  classes: [...],

}

Can anyone dream up a way so that in the render method of my
React Component I can loop through my schools and calculate the number
of 'coolTeachers' and 'studentCount' for each school?  Is this the
use-case for reselect?
My table needs to be like this:
SCHOOL______# OF COOL TEACHERS_______STUDENTS
Washington__________1_______________________2
Lincoln______________0_______________________1
Jefferson____________1_______________________4

A: This is classic usecase for Array.prototype.reduce:

const state = {
  teachers: [
    { teacherId: 'ttt1', teacherName: 'Susan', isCool: true, teachesAt: 'sss1'},
    { teacherId: 'ttt2', teacherName: 'Karen', isCool: false, teachesAt: 'sss2'},
    { teacherId: 'ttt3', teacherName: 'Bob', isCool: true, teachesAt: 'sss3'},
    { teacherId: 'ttt4', teacherName: 'Mike', isCool: false, teachesAt: 'sss1'},
  ],

  schools: [
    { schoolId: 'sss1', schoolName: 'Washington'},
    { schoolId: 'sss2', schoolName: 'Lincoln'},
    { schoolId: 'sss3', schoolName: 'Jefferson'},
  ],

  students: [
    { schoolIdEnrolled: 'sss1', studentName: 'Billy'},
    { schoolIdEnrolled: 'sss1', studentName: 'Steven'},
    { schoolIdEnrolled: 'sss2', studentName: 'Bobby'},
    { schoolIdEnrolled: 'sss3', studentName: 'Mikey'},
    { schoolIdEnrolled: 'sss3', studentName: 'Sally'},
    { schoolIdEnrolled: 'sss3', studentName: 'Cindy'},
    { schoolIdEnrolled: 'sss3', studentName: 'Mandy'},
  ],
}

const teachersReducer = (teachers, id) => {
  const numOfteachers = teachers.reduce((result, current) => {
    if (current.teachesAt === id && current.isCool) {
      result++;
    }
    return result;
  }, 0);
  return numOfteachers;
}

const studentsReducer = (students, id) => {
  const numOfstudents = students.reduce((result, current) => {
    if (current.schoolIdEnrolled === id) {
      result++;
    }
    return result;
  }, 0);
  return numOfstudents;
}

const resultData = state.schools.reduce((result, currentSchool) => {
  const currentId = currentSchool.schoolId;
  const numOfTeachers = teachersReducer(state.teachers, currentId);
  const numOfStudents = studentsReducer(state.students, currentId);
  return {
    ...result,
    [currentSchool.schoolName]: {
        ...result[currentSchool],
        numOfTeachers,
        numOfStudents
    }
  }
}, {});

console.log(resultData);

You can wrap the methods with reselect but keep in mind it will only cache the last input parameter.