text:
Q: Client-side XSLT I converted my whole site to XML/XSL and I would like to know all of the current issues with performing Client-side XSLT.
Here are the ones i already know of (from first-hand experience):

*

*Cross-domain XSL files (this is a security issue and not cross browser)

*disable-output-escaping (this does not work in FF... they consider it a security issue)

Also as for browser support this is all i know of:

*

*Opera 9+

*FF 1.0+

*SF 2.0 + (i may be wrong on this)

*Chrome

*IE 6.0 +

Any others would be helpful too :)
Edit:
As for the 2nd pitfall there is a decent workaround that lets you pass xhtml to your xsl. It works by actually converting and making sure your XHTML is valid XML and placing it into your XML as XML. Then in your XSL you copy the xml ;) and output it as XHTML.

A: On the performance front... consider that the majority of clients these days have 2 CPU's and 2 GB of RAM each, and that most servers don't... Have two CPU's + 2 GB per client that is. So it's certainly logical that offloading the XSLT transforms should improve scalability, and caching CSS + XSLT + JS should reduce overall traffic.
Having said that I've tried using XSLT to produce XHTML containing SVG in the past, and had an epic-fail. The largest page was simply too big (3,000+ entries in an index), and IE uses a DOM to do the XSLT transform, which causes it to start trashing. The same transforms done in xerces-j (on the server, on the same dev box) was about 1000 times faster.
It's high-time the browser-monkeys got with the program ;-)
An interesting discussion. Thanks for raising it.
Cheers. Keith.

A: I found passing parameters to xsltfiles difficult to keep crossbrowsing able.  I now support FF and IE but Chrome fell out because of it..

A: *

*Speed: The browser needs to apply the XSLT transformation before rendering the HTML, thus the user will have to wait longer to see the page. The XSLT engines used by the browsers might not be top-notch. On Mac OS X, the browser might freeze while the XML is transformed and cause the "spinning beach ball" cursor, thus the user might punch the screen and injure him or herself.

*Accessibility: What about the browsers not in that set, such as screen-readers? Do those users matter to you?

A: i have worked about 1 year at a project where we used xslt+xml-> html (although server-side only)
the major drawback i encountered: there are no good tools for xslt generation which lean towards web developement. no previewing of html. no validation.
the resulting xslt was a total mess noone could understand. that was not so much the xslt designers fault, but rather results from the xslt processing model.
the layering between xslt/xml/urls becomes more complicated than it should be. there is no way you could program component-oriented.
often multiple xslt files were needed, this would lead to many downloads on the client-side. otherwise it would lead to massive code duplication thoughout the project.
i would see this as a form of early optimisation. you shoud start by using a "normal" web framework like wicket, jsf, tapestry, gwt etc.., later if it turns out your servers preformance is cpu-bound you might ocnsider rewriting the most often used parts of the apllication that way.
otoh, it has real benefits if you need to provide both an xml api + a html interface.

A: The XSLT file is another object which needs to be downloaded and the browser will only fetch 2 or 3 items in parallel. My experience is that the overall performance (download and generation) is noticably slower.
Also, depending on the complexity and redundancy of the data, you might be downloading much more than you really need to - ie. if the HTML had already been rendered.


text:
Q: How to properly use sscanf in this context? I have a file which structure is the following:
var1 2921
var2 0.5
var3 12

I need a method that gets the name of the file and 3 empty variables. It should read the file and give a value for each variable. (This is what I have tried so far)
void get_input(char * filename, int * var1, double * var2, int * var3){
    FILE *file;
    char buf[1024];
    file=fopen(filename,"r");
    if(file == NULL){
        printf("ERROR");
        exit(0);
    }

    int i=0;

    if(file){
        while(fgets(buf,sizeof(buf),file)!=NULL){
            switch(i){
            case 0:
                sscanf(buf,"var1 %d",&var1);
                break;
            case 1:
                sscanf(buf,"var2 %f",&var2);
                break;
            case 2:
                sscanf(buf,"var3 %d",&var3);
                break;
            default:
                break;
            }

            i++;
        }
    }
}

And the main:
int main()
{
    char filename[256];
    int var1,var3;
    double var2;

    snprintf(filename,256,"file.txt");

    get_input(filename,&var1,&var2,&var3);

    printf("%s %d","var1: ",var1);
    printf("%s %f","\nvar2: ",var2);
    printf("%s %d","\nvar3: ",var3);

    return 0;
}

Output:

var1:  8
var2:  0.000000
var3:  2011837489

A: *

*For a double, you need to use %lf, not %f; in scanf as well as in printf. Alternatively, you could use float, that goes with %f.

*You are passing the addresses of var1, 2, 3; so taking the address again in scanf is duplicate - you will get the address of the address.
Use var1 instead of &var1 inside the scanf.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get Image from Video using Open CV and SimpleUploadedFile I have the following code to create an InMemoryUploadedFile. The reason I'm doing this is because I use firebase and save the images and videos there. It could be considered similar to S3 storage... In my test I have the following:
file = BASE_DIR + '/static/samy-assets/img/landing/small.mp4'
video = SimpleUploadedFile(file, open(file, 'rb').read(), content_type="video/mp4")
response = self.client.post('/media/upload/', {'file': video}, follow=True)

This works to upload the video to firebase, however now I need to get a frame from the video to show as the "preview". I have this code:
cap = cv2.VideoCapture(media)
cap.set(cv2.CAP_PROP_POS_MSEC, 1000)  # Go to the 1 sec. position
success, frame = cap.read()  # Retrieves the frame at the specified second
print(success)
cv2.imwrite("image.jpg", frame)  # Saves the frame as an image
cv2.waitKey()

However the error I receive is:
an integer is required (got type InMemoryUploadedFile)

Any help would be appreciated...


text:
Q: Tensorflow add new op slicing the output tensor I checked the file here:
// get the corresponding Eigen tensors for data access
auto input_tensor = input.matrix<double>();
auto weights_tensor = weights.matrix<double>();
auto biases_tensor = biases.matrix<double>();
auto output_tensor = output->matrix<double>();

for (int ix_sample = 0; ix_sample < batch_samples; ix_sample++) {
  for (int ix_unit = 0; ix_unit < units; ix_unit++) {
    output_tensor(ix_sample, ix_unit) = 0;
    for (int ix_input = 0; ix_input < input_feature_width; ix_input++) {
      output_tensor(ix_sample, ix_unit) += input_tensor(ix_sample, ix_input) * weights_tensor(ix_input, ix_unit );
    }
    output_tensor(ix_sample, ix_unit) += biases_tensor(0, ix_unit);
  }
}

And the one on Tensorflow tutorial:
// Create an output tensor
Tensor* output_tensor = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(),
                                                 &output_tensor));
auto output_flat = output_tensor->flat<int32>();

// Set all but the first element of the output tensor to 0.
const int N = input.size();
for (int i = 1; i < N; i++) {
  output_flat(i) = 0;
}

I am wondering if the output tensor is a 3d tensor, how could I slice it and assign its value vector-wise.
I find the slice method for Eigen:
Eigen::Tensor<int, 2> a(4, 3);
a.setValues({{0, 100, 200}, {300, 400, 500},
             {600, 700, 800}, {900, 1000, 1100}});
Eigen::array<int, 2> offsets = {1, 0};
Eigen::array<int, 2> extents = {2, 2};
Eigen::Tensor<int, 1> slice = a.slice(offsets, extents);
cout << "a" << endl << a << endl;
=>
a
   0   100   200
 300   400   500
 600   700   800
 900  1000  1100
cout << "slice" << endl << slice << endl;
=>
slice
 300   400
 600   700

But not clear how could I use it here.


text:
Q: JavaFX - JFoenix alternative for JDK 13 Unfortunately I have the problem that JFoenix does not run with my Java version (13). After a short research I found out that this problem probably exists for a while (link).
I don't know Java very well and I found the introduction to JFoenix very good through numerous tutorials. I also like the integration into Scene Builder. So I wanted to ask if you know a good alternative to JFoenix that is also suitable for less experienced Java developers?
If there is no alternative, would it be problematic to use Java 9? I saw here that someone is using JFoenix with JDK 13. Is there a workaround?

A: I was able to run JFoenix with java13, you need to do bit of figuring out. One more person asked a similar question just yesterday see this :  https://stackoverflow.com/a/61473762/2448015
And also you can see in comments 2 people gave you the correct solution. All I can additionally contribute is give you are working example.
If you are directly running, then you just need to add the relevant vm flags such as
--module-path=D:\[YOUR DIRECTOY\javafx-sdk-13\lib
--add-modules=javafx.base, javafx.controls, javafx.fxml, javafx.graphics, javafx.media, javafx.swing, javafx.web
--add-opens
javafx.base/com.sun.javafx.runtime=ALL-UNNAMED
--add-opens
javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED
--add-opens
javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED
--add-opens
javafx.base/com.sun.javafx.binding=ALL-UNNAMED
--add-opens
javafx.base/com.sun.javafx.event=ALL-UNNAMED
--add-opens
javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED

Refer : https://github.com/jfoenixadmin/JFoenix/issues/889#issuecomment-450744122
If you are using maven, you can refer to the following :
<option>--add-opens</option>
<option>javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED</option>

In the POM configuration for the javafx-maven-plugin
For this, you need to fix the pom, something like this
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>nu.sharabheshwara.A456B123</groupId>
    <artifactId>nu-sharabheshwara-A456B123-MyFx</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-web</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-media</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>com.jfoenix</groupId>
            <artifactId>jfoenix</artifactId>
            <version>9.0.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.4</version>
                <configuration>
                    <mainClass>application.Main</mainClass>
                    <options>
                        <option>--add-opens</option><option>javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED</option>
                        <option>--add-opens</option><option>javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED</option>
                        <option>--add-opens</option><option>javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED</option>
                        <option>--add-opens</option><option>javafx.base/com.sun.javafx.binding=ALL-UNNAMED</option>
                        <option>--add-opens</option><option>javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED</option>
                        <option>--add-opens</option><option>javafx.base/com.sun.javafx.event=ALL-UNNAMED</option>

                        <option>--add-exports</option><option>javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED</option>
                        <option>--add-exports</option><option>javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED</option>
                        <option>--add-exports</option><option>javafx.base/com.sun.javafx.binding=ALL-UNNAMED</option>
                        <option>--add-exports</option><option>javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED</option>
                        <option>--add-exports</option><option>javafx.base/com.sun.javafx.event=ALL-UNNAMED</option>
                    </options>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <compilerArgs>
                        <arg>--add-opens</arg><arg>javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED</arg>
                    </compilerArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

To run, use the command mvn javafx:run or mvn clean javafx:run . This will use javafx-maven-client instead of apache.
If this doesn't help, you can simply check this github sample maven project where you can put your existing jfoenix code and make it work
https://github.com/shashaanktulsyan/java-javafx-maven-learning-tips/tree/master/nu-sharabheshwara-jfoenix_maven_javafx11_fix_demo
This should surely 100% solve your problem.


text:
Q: How to execute Ant task in another thread My ant has two target A and B, target A copies a bunch of files to a location, and target checks the copied files in that location.
The problem is that, A needs sometime to complete its execution, but B should wait either blindly (e.g., 30 seconds) or wisely (e.g., check a var/property indicating the finish of task A) to continue its process.
I tried both sleep and wait, but it seems that both of them block the whole thread, so during the wait of target "execute_task", target A is also blocked, so the file copy is in sleep/wait mode.
How should I process, to let target A continues its copy mission, and hold B to wait for a while till A is complete?
thanks a lot!
<target name="execute_task">

    <antcall target="A_copy_files"></antcall>
    <antcall target="B_exam_files" ></antcall>

    <waitfor maxwait="30" maxwaitunit="second" timeoutproperty="signal_build_timeout1">
        <istrue value="${set_for_deploy_done}"/>
    </waitfor>
    <antcall target="B_exam_files" ></antcall>

</target>

A: did you checked this thread
Run ant from Java
http://thilosdevblog.wordpress.com/2010/08/30/calling-an-ant-target-via-java/
you can use the following to start another thread in java
Java: How to run thread separately from main program/class?


text:
Q: Install multiple exe with wix toolset I have three products which have their installers in .exe files.
Let us say the installers for the three three products are

*

*Product_A.exe

*Product_B.exe

*Product_C.exe

I want to create a msi file using wix toolset which will install these three exe installers.
What is the best way to do this?
I want to also fail my MSI in case any of the three exe fails to install.
I am new to these so please help.
Any example would be highly appreciated
I also plan to uninstall these products once I uninstall my msi.
Thanks in advance for any help

A: Tools: There are a number of tools available for MSI creation. Some commercial and WiX - the open source solution. Here is a quick summary of tools. The commercial tools are excellent but expensive, WiX (free, open source) is also excellent but has a learning curve (XML text sources). Remember that a setup consultant can help you make such packages pretty quickly in most cases, but you might need the knowledge in-house. Long review of tools.
Cohesion & Coupling: You might need to create 3 different MSIs to install these products, or you could put them all in the same MSI. Here are some considerations to decide what to do. Remember to not be dogmatic but practical - what will work best for your particular case? You can allow only some of the tools to be installed by exposing features in the MSI you make - allowing only some features to be installed from a single MSI. Feature sample screenshot.
Setup.exe: There is also functionality to allow a setup.exe bootstrapper / installer launcher to install multiple MSI files wrapped inside it in sequence. WiX has the Burn component, and commercial tools have various options for the same (InstallShield Suite Projects, prerequisites, etc... - info here).
Details: As to the actual setups. You need to determine what they actually install (bullet point 3) - prerequisites and all (COM, COM+, GAC, Java, VC++ runtime, etc...). That might or might not be available to you via 1) documentation of in-house expertise (developers). 2) You can extract files from the setup to look at (check if they are MSI files already coming out of the setup.exe!), 3) install the setups and inspect the application operation with dependency / profiling tools. 4) The best is to find the old setup scripts used to compile the old setup exes. 5) You can also "capture" old setup EXE files to auto-convert to MSI. This needs serious cleanup at times from experts and it requires expensive tools - generally. See more info here. There are probably further approaches too. Developers will dump files in place, start registering them and install runtimes and keep going until things (appear) to work in order to figure out what to do in the setup (have them jot down some good notes).

Packaging Team: Note that most big companies have whole teams to take care of such setup conversion to MSI - generally referred to as "application packaging". If you are in a big company, maybe try to locate them and see if they can help (or just get them to capture your setup for you - with the expensive tool - for you to clean up - it is no picnic to clean).

Links:

*

*A long answer on features, setup.exe launchers and how to decompose and bundle setups


text:
Q: Фон блока за пределами контейнера Есть такой макет

Блок о компании и новости должны быть в фиксированном контейнере, который всегда по центру.
А фон белый с тенью должен заканчиваться на границе блока о компании
Блок с тенью может иметь какую угодно высоту, в зависимости от контента. Как это правильно сверстать?

* {
  box-sizing: border-box;
}

.container {
  margin: 0 auto;
  width: 600px;
}

.row {
  margin: 0 -15px;
}

.col-lg-8 {
  float: left;
  width: 66%;
  background: silver;
  padding: 20px;
}

.col-lg-4 {
  float: left;
  width: 33%;
  background: #eee;
  padding: 20px;
}

body {
  background: #cfe0ff;
  width: 800px;
}

Основной контент c динамической высотой

Новости


text:
Q: Create a zip file and download all files using paperclip Rails 4 I am trying to download n number of images uploaded using paperclip as a zip.
def download
  require 'zip'
  @files = Upload.where(:request_id => params[:id])
  t = Tempfile.new('tmp-zip-' + request.remote_ip)
  Zip::OutputStream.open(t.path) do |zos|
    @files.each do |file|
      puts file.image.url(:original, false)
      zos.add(file.image, file.image.url(:original, false))
      zos.put_next_entry(file.image)
    end
  end
end

I am getting this error

undefined method 'add' for #<Zip::OutputStream:0x007f39508516d8>


text:
Q: List of people who have done one thing and gotten nice rep for it I was playing with StackQL and asked myself. Are there people who have as much rep as their highest voted question/answer (as in, they've only gotten rep from that one question/answer).
The query isn't that complicated but you have to filter out the people who have answered one question, gotten 1 upvote and have 10 rep. Since thats no fun. So I limited it to >= 100 rep.
SELECT Posts.Id, Posts.Score, Users.Id, Users.Reputation FROM Posts
LEFT JOIN Users ON Users.Id = Posts.OwnerUserId
WHERE (Posts.Score * 10) = Users.Reputation AND Users.Reputation >= 100
ORDER BY Users.Reputation DESC

These are the questions / answers.

*

*Answer to - Boxing when using generics in C# (230 rep)

*Question - Why would I want to use Interfaces? (220 rep)

*Question - What is the difference between an asp.net web method and a wcf service? (180 rep)

*Answer to - Can an element's CSS class be set via JavaScript? (160 rep)

*Answer to - Best Java book you have read so far (150 rep) (this might be a fluke though)

*Question - Computer science final year project ideas (150 rep)

*Question - Determining if ASP.Net is properly registered (150 rep)

*Question - How relevant is Win32 programming to modern professionals? (110 rep)

*Question - What would be a good sample project to ask a prospective programmer to code during the hiring process? (110 rep)
The questions are often interesting but generic but it's the answers that intrigue me. For example the top one. That user has not done anything but voted a few times and answered that one answer.
The fluke one might be because of CW not being enabled at the start of his answers. He has two, both CW answers.
The third answer is similar to the first one, although he has answered two questions but the other answer has 0 votes.
Even though the list isn't that exciting, it's still a bit interesting.
UPDATE:
I did a query with +100. I was worried that there would be to many cases where people had gotten upvotes from other places.
SELECT Posts.Id, Posts.Score, Users.Id, Users.Reputation FROM Posts
LEFT JOIN Users ON Users.Id = Posts.OwnerUserId
WHERE (Posts.Score * 10) + 100 = Users.Reputation AND Users.Reputation >= 200
ORDER BY Users.Reputation DESC

I did >= 200 because otherwise I got pages and pages of results. This is the breakdown of the query.

*

*Tim (309 rep). Got 210 from one question. Two account associations with SO. But no rep on SO from that.

*giltotherescue (270 rep).. Rep from other questions. No assoc.

*Mohit Ranka (240 rep). Most from one of his 28 questions. Matched query because he has one CW question with 14 votes. No assoc

*rofly (230 rep). Similar situation as Mohit. No assoc

*qrunchmonkey (210 rep). Rep from other stuff. No assoc.

*Daz (200 rep). Rep from other stuff. No assoc.

So account association has no effect here, we just get bad results.
UPDATE 2
Looks like I had forgotten the initial 1 rep. So I have fixed the query (I'll leave the original stuff intact) But what happened to the starting 1 rep is a good question.
So here is the same list but with a fixed query.
SELECT Posts.Id, Posts.Score, Users.Id, Users.Reputation FROM Posts
LEFT JOIN Users ON Users.Id = Posts.OwnerUserId
WHERE (Posts.Score * 10) + 1 = Users.Reputation AND Users.Reputation >= 300
ORDER BY Users.Reputation DESC

I limited this one to >= 300 since the list was pretty long.

*

*Scott Stanchfield (441 rep)

*Jay Kimble (411 rep)

*Hamster (331 rep)

*Long Time Smalltalker (321 rep)

*Mark (311 rep) (This one has more answers and rep for that)


text:
Q: How many "read"s does it cost to call get() function when fetching data from Firestore I have the following code piece in a function that I call when I need to fetch the user profile data.
  FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Future getUserProfile() async {
    try {
      DocumentSnapshot ds =
          await _firestore.collection('users').doc(_auth.currentUser.uid).get();

      return ds;
    } catch (e) {
      print(e);
      return null;
    }
  }

With the assumption that user's profile data does not change, does this call cost me 1 read each time I call the getUserProfile() function? If yes, how can I change this function so that my function only listens to changes and does not necessarily increase the number of reads in firestore?

A: Yes, each function call will cost you 1 read. If the data does not change through out the app you could fetch it at the start of your application and store it by creating a class say User, then add data to that User object. This method is very useful and would minimize the number of function calls made to fetch data.

A: Each time you call getUserProfile(), the read counter will increase by one.
Firestore offers an alternative to get() for listening to real time changes. It's called snapshots(), it returns a Stream<QuerySnapshot>. You can attach a listener and every time one of the documents you listen to, changes, it will be added to the stream. Initially all items matching your query (in your case it's only one) will be added to the stream. Your code should be then:
  Stream<QuerySnapshot> getUserProfile() {
    try {
      Stream<QuerySnapshot> stream = _firestore
          .collection('users')
          .doc(_auth.currentUser.uid)
          .snapshots();
      return stream;
    } catch (e) {
      print(e);
      return null;
    }
  }

Every time a change is added to the stream, the read will be increased by one.
More information can be found at the official Firestore Docs.


text:
Q: Are review audit pass/fail decisions ever triggered by Skip? I've argued passionately in the past that when reviewing edits, Skip is often a blatantly wrong choice. I also feel there should be edit honeypots, but I believe there are not.
For the remaining review queues, is Skip always a not-wrong choice? Are there audits out there that will tell someone "no, you should not have skipped this one?"
Here is a screenshot (from This audit looks completely obvious. Is it really needed? ) of an audit where upvoting would clearly be wrong:

I don't think you need technical expertise to act on this one. Skip would surely be wrong here - so I was wondering if it would be called out as wrong. Perhaps honeypots that are so awful they shouldn't even be skipped are really rare in the non-edit queues. (In the suggested edit queue, awful no-expertise-needed examples are not rare at all.)

A: No, they are not. "Skip" does one thing: It removes the page from that review queue for you. That's it. If you "Skip", you mean that "I don't wanna review this". Since "reviewing" includes reading the post, there's no need to punish you for not acting on a post you may not have read.
The audits are to stop robo-reviewers (who do it for the badges) from, well, robo-reviewing. Skipping doesn't put you closer to any badges, so no point in punishing that.

A: I often skip because I feel I can't judge if it is right or wrong without diving into Python, Haskell or Lisp... (you get my point) or search for similar answers/google.
When I click Skip I say to myself 'Somebody else with more knowledge on this topic should decide'.
So I see skip as an invitation to other reviewers to grab their chance.

A: The system cannot possibly know your areas of expertise. A post that was outrageously wrong in the eyes of a quorum of the qualified may look merely half-baked to someone else. Further, one of the points of the honeypot system is to encourage people to take reviewing seriously. One aspect of taking it seriously is to say to oneself: 'this is completely outside of my expertise. Badges or no badges, bad, good, or indifferent, I'm leaving this for someone else.'


text:
Q: Returning string from database as currency I have the following query
SELECT        SUM(Price) AS Sales
FROM            BarOrder
WHERE        (OrderDate <= @OrderDateEnds) AND  (OrderDate >= @OrderDateStarts)

My Price field is set up as Float so that is able to store cents. That part works fine. Now I want to retrieve the information in currency format using the following
   lblTodayAmount.Text = Cstr(BarOrderTableAdapter.TodaysSalesAmount(CDate(strEndDay), CDate(strBeginDay)))("C")

I get the following:
Conversion from string "C" to type 'Integer' is not valid.

if I do the following:
BarOrderTableAdapter.TodaysSalesAmount(CDate(strEndDay), CDate(strBeginDay))("C")

Then I get:
No default member found for type 'Double'.

A: Use ToString, not CStr
lblTodayAmount.Text = BarOrderTableAdapter.TodaysSalesAmount(CDate(strEndDay), CDate(strBeginDay)).ToString("C")


text:
Q: join audio file in specific time of the video ffmpeg i am trying to use the code bellow to merge an audio file at specific time (6th second of my input video) and create a new video autput file but i cant make it work.
<?php

exec("/usr/local/bin/ffmpeg -sameq -i /home/xxx/public_html/xxx/video/full.mp4 -itsoffet 6 -i /home/xxx/public_html/xxx/sounds/names/george.mp3 /home/xxx/public_html/xxx/upload/sample.mpg");

?>

Thank you a lot!

A: Firstly, you have a typo in your command: -itsoffet should be -itsoffset.
Secondly, it seems there's a bug affecting -itsoffset.
Take a look at these identical/similar questions:

*

*Add audio (with an offset) to video with FFMPEG

*delay audio with ffmpeg

*Add multiple audio files to video at specific points using FFMPEG


text:
Q: buttons inside listview don't work properly? in my list_item I have two buttons inside each item. the problem is that the buttons don't work unless I click the item then click the buttons.
Here for example I have to click on the item then click on the delete icon to delete the item.
ListView with two items
list_item :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    >

        <ImageView
            android:id="@+id/play_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:background="?attr/selectableItemBackgroundBorderless"
            android:clickable="true"
            android:focusable="true"
            android:padding="5dp"
            android:src="@drawable/ic_play_circle_black_24dp"
            android:tint="#4CAF50"
            android:layout_weight="1"
            />

        <ImageView
            android:id="@+id/delete_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="16dp"
            android:background="?attr/selectableItemBackgroundBorderless"
            android:clickable="true"
            android:focusable="true"
            android:padding="5dp"
            android:src="@drawable/ic_delete_black_24dp"
            android:tint="#FF0000"
            android:layout_weight="1"
            />

            </LinearLayout>

A: Sorry everyone for lateness!
I've got the solution; the problem was that I deleting the ListView item in the Activity instead of doing it in the Adapter ;)
the Code that doesn't work (MainActivity) :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {

                // delete button
                ImageView deleteBtn = view.findViewById(R.id.delete_btn);
                deleteBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mAdapter.remove(mAdapter.getItem(i));
                    }
                });

            }
        });

The correct code (Adapter) :
 deleteBtn.setTag(position);
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Integer index = (Integer) deleteBtn.getTag();
                remove(getItem(index));

            }
        });

Thank you so much everyone for helping :)


text:
Q: Why are $\vec{E } \cdot \hat{n}$ and $\vec{J} \cdot \hat{n}$ needed to prove the electric field is uniform in a wire Here is an excerpt from Griffith's Introduction to Electrodynamics third edition.

In the proof, what was the rationale in deciding to do the dot product of $\vec{J}$ with a unit vector and $\vec{E}$ with a unit vector? How does $J\cdot\hat{n}=0$ verify that there is no current density?

A: $\hat{n}$ is by convention the unit vector that is normal to a surface, in this case the curved surface of the conductor.  So $\hat{n}$ sticks perpendicularly out from every point on the curved surface of the conductor.
Since $\vec{J}$ is the vector field representing the current, if $\vec{J} \cdot \hat{n}$ were nonzero on the surface of the conductor, then the component of $\vec{J}$ in the direction of $\hat{n}$, which is directly out of the surface, would be nonzero, which means that current is moving out of the surface of the conductor.
Griffith points out that by defining one region as the "conductor", we are assuming that the region outside of the conductor is an insulator, which means there should be no movement of charge outside the conductor, so the current flowing out of the curved surface of the conductor should be zero, therefore $\vec{J} \cdot \hat{n}$ must be zero.
All that is just to establish the boundary condition for the current field $\vec{J} \cdot \hat{n} = 0$ on the curved surface, which allows him to find the solution to Laplace's equation for V.
Note that he is not saying that there is no current density, just that the current density is uniform, and in the $\hat{z}$ direction, throughout the conductor.


text:
Q: XMPP: can multiple users connect to a server over the same TCP connection? My clients speak with my servers over custom protocol. Now I'm adding chat system backed by XMPP server (ejabberd). My server will tunnel user messages to XMPP server by logging in XMPP server on behalf of all its clients.
Since a single server can have multiple clients it would be fine to have a single TCP connection from my server to XMPP server. Is this possible? If yes, how to do this? I'm not familiar with XMPP yet.
Seems like XML stream is opened at the beginning and closed at the end, and closing tag doesn't have any indication which stream to close. So I assume I cannot have multiple XML streams over the same TCP connection. Please correct.
I can try to login multiple times with different usernames and specify "from" anywhere it's allowed. I noticed that on many places "from" attribute is optional and ejabberd can assume it probably based on connection, so I worry if this is possible.

A: With normal client-to-server connections, each client must use a separate connection.  Clients normally don't send their JID in the from attribute of the opening tag of the XML stream, but identify themselves during SASL authentication.
ejabberd supports the protocol described in XEP-0114, whereby your system can connect to the ejabberd as a "component", and send and receive messages on behalf of many different users.  Depending on what you want to do, you may have to reimplement a lot of what ejabberd would do for you out of the box, e.g. presence subscriptions, roster management, routing of messages between users in your system.  The only things ejabberd does for you in this case is sending you all messages to recipients in a certain domain, and route any outbound messages you send.

A: legoscia gave you some information about how you might make your server use a single TCP connection. Allow me to suggest some reasons why you would want separate TCP connections.
First, TCP connections are not terribly expensive. There are some rare times when they're too heavy (and you use UDP), but this is not one. XMPP authentication is far more expensive than TCP setup/teardown.
It's also not too expensive in other system resources. In a normal XMPP conversation, the client connects to the listener port on the server, the server spins off a worker process with its own port, and the two talk. Both client and server are using system-assigned port numbers, so if all your client connections are coming from a single machine you can have about 65,000 connections to the server. You'll run out of other resources (CPU, network bandwidth, etc) long before you run out of ports to use.
Second, one TCP connection per conversation is a convenient mapping. Ejabberd uses the one-process-per-connection idiom to isolate clients. If you put all your clients in a single TCP conversation, it will be a pain to split them out into separate processes. If they're all in one process, then you don't get concurrency between clients or process safety.
Finally, when debugging network problems, Wireshark can parse a TCP conversation and make it easy to read. If you have all your clients in one conversation, you don't get any of that benefit.


text:
Q: Promises best practice with ExpressJS The problem is related to promises. I just started learning Express, and using to make HTTP requests.
The app relies heavily on making external requests to function, so for this reason, I am ending up with a very ugly app that is primarily a nested mess.
Example of a scenario (dummy code):
app.get('/v1/example', async function(req, res) {
    let bearer = null;
    try {bearer = req.header('authorization').split(' ')[1];}
    catch (e) {bearer = params.token;}
    checkUser(bearer).then(r => {
        res.json(r.data);

    res.json(r.data);
        action1(bearer).then(r => {
            action2(bearer).then(r => {
                res.json(r.data);
            }).catch(e => {
                try {
                    res.status(e.response.status);
                    res.send(e.response.data);
                }
                catch (e) {console.log('oops')}
            })
        }).catch(e => {
            try {
                res.status(e.response.status);
                res.send(e.response.data);
            }
            catch (e) {console.log('oops')}
        })

    }).catch(e => {
        try {
            res.status(e.response.status);
            res.send(e.response.data);
        }
        catch (e) {console.log('oops')}
    })
})

Is there a better way to do that? Knowing that in a more elegant fashion?
How can I properly wait for the above previous promise to complete before firing up the function below?
Is there anything that you can suggest?
Right now, I did a very dirty trick, and of course, this doesn't scale:
I am setting up an interval that checks if the variable that I need is defined or not, and when the variable is finally defined, it exits the interval and timeout.

            const intervalObj = setInterval(function() {
                let MIME = helpers.getMIME(image_response.extension)
                const file = image_response.image_path;
                const fileExists = fs.existsSync(file);

                if (fileExists) {
                    clearInterval(intervalObj);
                   // do the next task.

                }
            }, timeout);

Thank you.


text:
Q: Bootstrap - Force Div to Next Line when after Text area I have a feeling there is a quick solution to this but I'm stumped.
I have a simple layout, 2 col image, 4 col text, 2 col image, 4 col text.
https://codepen.io/brianpensinger/pen/GEbxxv

Nulla porttitor accumsan tincidunt. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Nulla quis lorem ut libero malesuada feugiat. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Nulla porttitor accumsan tincidunt. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Nulla quis lorem ut libero malesuada feugiat. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

When on the SM breakpoint, I want to switch to 6 col each. However, my second image sits underneath the text instead of going to a new line.
Screenshot
How can I force it down to the next line?
Thanks,
Brian

A: It's because of cleafix issue caused due to float:left on cols. You can do it manually by writing a CSS for that specific SM viewport or simply add HTML for clearfix which only works in SM viewport.
Check the snippet.

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

Nulla porttitor accumsan tincidunt. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui.
      Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Nulla quis lorem ut libero malesuada feugiat. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Curabitur non nulla sit amet nisl tempus convallis
      quis ac lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Nulla porttitor accumsan tincidunt. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui.
      Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Nulla quis lorem ut libero malesuada feugiat. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Curabitur non nulla sit amet nisl tempus convallis
      quis ac lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

A: Hi there!

Text here

Text here

This will do what you require :) By giving defining the first row you have told it to be one block. By defining the cols inside you have told to take up 50% of the page in md/lg. After that they will automatically go to full width which is where you were ultimately having the problem.
To combat that you could define another row. By defining another row you have told bootstrap to take up 100% of the containers width... since the col above is no longer valid past md size it then has full reign over the 100%. This will give you 6/6, one below the other.


text:
Q: Removing the maximize button from a window created using glfw How do you remove the maximize button from a window created usingg the glfwopenWindow functionn call ?
Currently, what I'm doing is:
windowHandle = GetForegroundWindow();
long Style = GetWindowLong(windowHandle, GWL_STYLE);
Style ^= WS_MAXIMIZEBOX;
SetWindowLong(windowHandle, GWL_STYLE, WS_MAXIMIZEBOX);

Where, I get the window handle and then toggle the maximize bit. Then I re-apply the window style. But this doesn't work an it makes the window completely blank without any buttons or title bar. is there anyway to remove the maximize button. I dont want to change the window size whenever the resize function is called

A: you code is bugged, as you don't pass back the old style, thus clearing all the style flags except WS_MAXIMIZEBOX, it should read:
windowHandle = GetForegroundWindow();
long Style = GetWindowLong(windowHandle, GWL_STYLE);
Style &= ~WS_MAXIMIZEBOX; //this makes it still work when WS_MAXIMIZEBOX is actually already toggled off
SetWindowLong(windowHandle, GWL_STYLE, Style);

also, you should really use the GetWindowlongPtr based functions if you plan on any future x64 compatability


text:
Q: Nested Subclass Instantiation Declaration Java Coming from a JavaScript background, I find the following code a bit too robust, containing multiple statements; and am wondering how I can simply the code, and do everything in a single statement.

Student is the superclass and Friend and Schedule are the subclasses aggregated into a superclass ArrayList public member (these are not nested classes). Here is my current code:
public static void main(String[] args) {

  // Subclass1 instantiation and declaration
  Friend friend_of_andy_1 = new Friend(1002, "Bob");
  ArrayList<Friend> andys_friends = new ArrayList<>();
  andys_friends.add(friend_of_andy_1);    // superclass member

  // Subclass1 instantiation and declaration
  Schedule schedule_of_andy_1 = new Schedule(1, "Yoga practice");
  ArrayList<Schedule> andys_schedule = new ArrayList<>();
  andys_schedule.add(schedule_of_andy_1); // superclass member

  // Superclass instantiation declaration with subclass objects in constructor argument
  Student student_andy = new Student(1001, "Andy", andys_friends, andys_schedule);

}

I'm wondering if I can do something like this instead, where I declare/instantiate the superclass and subclasses in a single statement; is this possible?
public static void main(String[] args) {

  Student student_andy = new Student(
    1001,
    "Andy",
    // instantiation of subclass
    ArrayList<Friend>[
      Friend(
        {
          1002,
          "Bob"
        }
      )
    ],
    ArrayList<Schedule>[
      Schedule(
        {
          1,
          "Yoga practice"
        }
      )
    ]
  )

};

A: First, you only use friend_of_andy_1 in one place, so you can eliminate it:
List<Friend> andys_friends = new ArrayList<>();
andys_friends.add(new Friend(1002, "Bob"));

Second, if you're ok with the list having fixed size, i.e. you cannot add more elements to it, you can use Arrays.asList(), instead of creating an ArrayList:
List<Friend> andys_friends = Arrays.asList(new Friend(1002, "Bob"));

Then you can do the same for Schedule and inline that in the creation of Student:
Student student_andy = new Student(1001, "Andy",
                                   Arrays.asList(new Friend(1002, "Bob")),
                                   Arrays.asList(new Schedule(1, "Yoga practice")));

If the lists must be resizable, then use the ArrayList(Collection<? extends E> c) constructor:
Student student_andy = new Student(
        1001,
        "Andy",
        new ArrayList<>(Arrays.asList(
                new Friend(1002, "Bob")
        )),
        new ArrayList<>(Arrays.asList(
                new Schedule(1, "Yoga practice")
        ))
);

And of course format that however you want, if you prefer the exploded style that takes up way too many lines of code:
Student student_andy = new Student(
    1001,
    "Andy",
    new ArrayList<>(
        Arrays.asList(
            new Friend(
                1002,
                "Bob"
            )
        )
    ),
    new ArrayList<>(
        Arrays.asList(
            new Schedule(
                1,
                "Yoga practice"
            )
        )
    )
);

A: Ok, so, essentially, you are missing JSON [footnote-1] too much? Understandable.
Below is a loose collection of methods for creation of instances in Java so that it looks like JSON as much as possible.
1) Arrays: Use inline array literals
They are slightly more verbose in Java, but almost as good as [ ... ] in JSON, e.g. :
new int[]{1, 2, 3}

is a literal for an array of integers.
2) Objects: Define proper constructors
If your Friend has a constructor public Friend(int id, String name), then initializing Friends is really easy and pleasant:
new Friend(1234, "Bob")

3) More objects, faster use factory methods
If you define factory methods, you can get rid of new. E.g. if you have
class Friend {
    ...
    static Friend friend(int id, String name) { return new Friend(id, name); }
}

then you can even get rid of new. This is useful in those seldom cases where you are defining some kind of embedded-DSL, and really need this constructor thousand times.
4) Lists: Use asList
You can import static methods using static imports in Java:
import static java.util.Arrays.asList;

now you have the handy asList available, so that
asList(friend(2, "John"), friend(3, "Bob"))

gives you a list of friends.
5) Maps: Use anonymous subclasses with initializer blocks.
This seemingly crazy thing works in java:
HashMap<String, Integer> hm = new HashMap<>{{
  put("foo", 10);
  put("bar", 20);
}};

this is because the inner pair of curly braces encloses an initializer block, in which you can call methods on this.
Ok, now you can easily create:

*

*Primitive stuff: Strings, ints, doubles

*User-defined objects (using constructors and factory methods)

*Arrays

*Lists

*Maps

This should be enough to create ad-hoc json-esque data structures in Java.

Now, assuming that all constructors are in place, your code becomes this:
import static java.util.Arrays.asList;

...

Student student_andy = new Student(
  1001,
  "Andy",
  asList(new Friend(1002, "Bob")),
  asList(new Schedule(1, "Yoga practice"))
)

We didn't use maps here, so the hint with initializer block is just a bonus.
[footnote-1] To be more precise: it seems as if you are missing the fragment of JavaScript which allows to easily initialize those objects which canonically map to JSON objects. JSON is of course not JavaScript. Thanks @Andreas for pointing that out.


text:
Q: Rails instance variables in .js.erb file I have a controller action like this.
itineraries_controller.rb
def delete_city
  @new_itinerary = params[:new_itinerary] if params[:new_itinerary].present?
  @step = params[:step]
  if @step == 'two'
    @city = City.find(params[:id])
    @delete_rec = true
  else
    @city_item = CityItem.find(params[:id]) rescue nil
  end
  if @city_item.present?
    @itinerary = @city_item.country_item.itinerary rescue nil
    @itinerary = Itinerary.unscoped.find(params[:data_id])
    if (@itinerary.present? and @itinerary.user_id == current_user.id) or (current_user.moderator?)
      @country_item = @city_item.country_item
      @city_item.destroy
      @country_item.update_column('city_ids', @country_item.city_items.order(:sequence).pluck(:city_id))
      @delete_rec = true
    end
  end
  respond_to do |format|
    if @delete_rec && @step != 'two'
      format.js {render 'step_two.js.erb'}
    elsif @delete_rec && @step == "two"
      format.js {render 'delete_city_step_2.js.erb'}
    else
      format.js {render :text => 'fail'}
    end
  end
end

And js.erb like this:
delete_city_step_2.js.erb
a = $('a.cityCrossBtn[for='+"<%= @city %>"+']')
li = a.closest('.token-input-token-facebook')
li.hide();

I am not able to find a element. What is the correct syntax?

A: @city will give you an instance of ActiveRecord::Base class, and I think it's something you aren't expecting in your .js.erb file. You may be wanting an attribute related to that instance like id or name, and you can accomplish that by writing the following code:
a = $('a.cityCrossBtn[for='+"<%= @city.id  %>"+']')


text:
Q: NHibernate Search with inheritance  I have a Client class like that:
public class Client
{
    public Person Pers { get; set; }
}

And I have 2 Person´s child class :
public class PersonType1 : Person
{
   protected string att1;
   protected string att2;
}

public class PersonType2 : Person
{
     protected string att3;
     protected string att4;
}

public class Person
{
     protected string attx;
     protected string atty;
}

So, my Client could be PersonType1 or PersonType2...
I need execute a Client search ... The parameters to that search are att1,att2,att3,att4,attx,atty... But all those are optional...
I´m trying to execute that search with ICriteria, but I dont know how specify that inheritance scheme...

A: You really cannot do this because at the criteria level the Person class is agnostic of any derived classes. The result set will be an IList<Person> even though iterating through the collection will show you that the elements will also comprise of PersonType1 and PersonType2 types (assume that we just fetch the whole set from the DB without any restrictions).
That said, you can achieve the desired effect with a workaround:
Define each derived type as a new subquery
var dc1 = DetachedCriteria.For(typeof(PersonType1)).SetProjection(Projections.Property("id")).Add(Expression.Eq("att1", "foo"));

var dc2 = DetachedCriteria.For(typeof(PersonType2)).SetProjection(Projections.Property("id")).Add(Expression.Eq("att3", "bar"));

for N derived types and then on your main Criteria query just do
CreateCriteria(typeof(Person)).Add(Subqueries.PropertyIn("Id", dc1) || Subqueries.PropertyIn("Id", dc2));

alternatively, an ISQLQuery has not such limitations.
EDIT i'm adding below the necessary adjustments to find Client
i will re-write the criteria to be a <Client> criteria and express the subquery restriction on the joined <Person>s.
var crit = ses.CreateCriteria(typeof(Client)).CreateCriteria("Person","per").Add(Subqueries.PropertyIn("per.Id", dc1) || Subqueries.PropertyIn("per.Id", dc2));


text:
Q: How to get the user name using a Microsoft user id? Am working on a windows store javascript application. I have used the microsoft login authentication from azure as follows.
client.login("microsoftaccount").done(function (results) {;
userId = results.userId;
refreshTodoItems();
var message = "You are now logged in as: " + userId;

var dialog = new Windows.UI.Popups.MessageDialog(message);
dialog.showAsync().done(complete);
}

Am able to retreive the userid such as "Microsoftaccount:c2892313bla...."
How am I supposed to retreive the associated UserName for that Microsoft account ID?

A: When you're logged on, on any scripts on the server side you can query for the identities of the user (via the user.getIdentities() function), which will give you an object with access tokens which you can use to talk to the authentication providers. The post at http://blogs.msdn.com/b/carlosfigueira/archive/2012/10/25/getting-user-information-on-azure-mobile-services.aspx has an example on how to get the user name for MS account (and other providers as well).


text:
Q: Sitecore: how to move a Field to one of my Base Templates without losing data Let's say that my "Toyota" template has "Car" as its Base Template.
I want to move the field "Windshield" from "Toyota" to "Car", but I don't want all instances of Toyota to have it reset to null.
Is there a safe way to go about doing this?

A: Yes.
In the content editor you can move the item that represents the "Windshield" field to your Car template. The ID of the field will stay the same, so you will not loose that data.
The field item can be found in the children of your template item..


text:
Q: Intellij does not build JavaFX with libraries I am developing a JavaFX application that has a lot of libs. If i run it inside intellij it works ok, but when i build the JavaFX application it only builds the .JAR of the project files, it doesn't even copy the libraries to the OUT folder.
How can i solve this?

A: The sequence below worked for me on a Mac with Idea 13.1, no guarantees it will work on anything else (it's all one big continuous process of button clicks):

File Menu | Project Structure | Artifacts | + Button |
JavaFx Application | From module... | Choose Module |
Output Layout Tab | + Button | Library Files |
Choose Libraries |  JavaFX Tab | Choose an Application Class |
Make any changes needed |  Apply | OK | Build Menu |
Build Artifacts | Choose your new artifact | Choose Build

Built artifact including any libraries will end up in your project out/artifacts directory.
If you want to make it so that others who don't use Idea could also build your project then you could investigate usage of a 3rd party JavaFX build tool, such as the JavaFX Gradle plugin or the Oracle JavaFX deployment toolkit.


text:
Q: What is causing this 'Uncaught TypeError: Cannot call method 'animate' of undefined' error? All,
See the code below:
function menu() {
    this.menuitem=[];
    this.submenu=[];
    this.menuitem[0] = $('div#sivname1');
    this.menuitem[1] = $('div#divname2');
    this.submenu[0] = $('div#submenu1');
    this.submenu[1] = $('div#submenu2');
    this.active = false;
    this.timeout;
}

menu.prototype = {
    animatedown: function(submenu) {
        submenu.animate({top: '99px'}, 200);
    },
    animateup: function(submenu) {
        submenu.animate({top: '-4px'}, 200);
    }
}

var menu = new menu();
z=2;
while(z--) {
    console.log(z);
    menu.menuitem[z].hover(
    function() { //mouseover
        if(menu.active) {
            clearTimeout(menu.submenu[z].data("timeout"));
        }
        else {
            menu.animatedown(menu.submenu[z])
        };
    },
    function() { //mouseleave
        $(this).data("timeout", setTimeout(function({
            menu.animateup(menu.submenu[z])
        },200));
        menu.active = false;
    }),

    menu.submenu[z].hover(
    function() { //mouseover
        menu.active = true;
        if (menu.menuitem[z].data("timeout")) {
            clearTimeout(menu.menuitem[z].data("timeout"));
        };
    },
    function() { //mouseleave
        $(this).data("timeout", setTimeout(function() {
            menu.animateup(menu.submenu[z]);menu.active = false;
        },200));
    });
}

This code gives the following error:

Uncaught TypeError: Cannot call method 'animate' of undefined

And the strange this is that is I add:
z=0;

to the bottom of the code it will work properly. I would expect it to work without z=0 and I have no idea why it does when I add that. Can anyone please explain?
The problem was in the closures, the following code works:
z=1;
while(z--){
  (function(z) {
    console.log(z);
      menu.menuitem[z].hover(
        function(){ //mouseover
          if(menu.active){clearTimeout(menu.submenu[z].data("timeout"));}
          else{menu.animatedown(menu.submenu[z])};
        },
        function(){ //mouseleave
          $(this).data("timeout", setTimeout(function(){menu.animateup(menu.submenu[z])},200));
          menu.active = false;
        }
      )

      menu.submenu[z].hover(
        function(){ //mouseover
          menu.active = true;
          if(menu.menuitem[z].data("timeout")){clearTimeout(menu.menuitem[z].data("timeout"));};
        },
        function(){ //mouseleave
          $(this).data("timeout", setTimeout(function(){menu.animateup(menu.submenu[z]);menu.active = false;},200));
        }
      );
  })(z); //this is to enable closures http://bonsaiden.github.com/JavaScript-Garden/#function.closures
}

A: First of all, you have an error in the code:
$(this).data("timeout", setTimeout(function({
    menu.animateup(menu.submenu[z])
},200));

Should be:
$(this).data("timeout", setTimeout(function() {
    menu.animateup(menu.submenu[z]);
},200);

Second: z is global, and your callbacks will use it's last value after the initialization. You should create a local copy of z for your callbacks with a closure in the loop, like this:
while (z--) {
    (function(z) {
        /* your code */
    })(z);
}

This way you enclose the value of z for that while cycle, and the callbacks in it.
The strange thing with z=0 is that, when the loop dies (since z is 0) the decrementing operator will run one more time, and z will be -1. The -1 index will be used in all your callbacks, indexing a non-object which don't have animate ofc. But (!) if you set it z=0, than it will index an object, but always the one with the 0 index. You have to use the above correction to get the good result in every menuitem.

A: This is because your submenu item is most probably not a jQuery object.
You have no submenu[2] which is where your z variable starts at.
You might want to switch it to:
while(--z) ...

Which should start your z at 1.


text:
Q: How to use twig object variable with at-sign @ inside I send from Symfony object which contains at-sign @ in variable.
Object name is invoice and with {{ dump(invoice) }} in twig template I see object and parameter with path:
invoice[0].banSpojDod@showAs

But I dont know how to get value of this banSpojDod@showAs because there is at-sign @.
Could you help me someone please?

A: You could try with The attribute function can be used to access a "dynamic" attribute of a variable:
{{ attribute(invoice[0], 'banSpojDod@showAs') }}

Hope this help

A: Ok thanks. Problem was that I used it in loop, and some parameters not exists. I needed to add exist conditions. So my final code works:
{% for f in invoice %}
    {% if attribute(f,'banSpojDod@showAs') is defined %}
       {{ attribute(f,'banSpojDod@showAs')  }}
    {% endif %}
 {% endfor %}


text:
Q: ruflin elastica how to use _source to get certain fields how to use _source  to get certain fields in ruflin elastica.
please suggest how to use it.
For Ex:
{
"_source": {"user", "message"},
"query" : {
    "term" : { "user" : "kimchy" }
}
}

How can i convert this to ruflin elastica.
Please help.
Thanks

A: Query class provides a setSource method to add the list of fields, as an array, you want to retrieve.
Some code I use to make a query by using ruflin/elastica v3.2 and ElasticSearch 2.4 can be:
$search = new Search(new Elastica\Client());
$query = new Elastica\Query();
$query->setSource(['user', 'message']

$boolQuery = new Elastica\Query\BoolQuery();
$boolQuery->addMust(new Term(['user' => 'kimchy']));

$query->setQuery((new BoolQuery())->addMust(new MatchAll())->addFilter($boolQuery));
$search->setQuery($query);

try {
        $resultSet = $search->search();
} catch (ResponseException $exception) {
    // code
}

$results = $resultSet->getResults();


text:
Q: Writing a matrix as multiplication of orthogonal and diagonal matrices Given is the matrix A = \begin{pmatrix}
  5 & 3  \\
  0 & -4 \\
  \end{pmatrix}
I would like to write this matrix as the product A = $U S V^T$
whereas U and V both are orthogonal matrices and S is a diagonal matrix. What is the approach to find suitable matrices?

A: Given:
$$A = \begin{pmatrix}
  5 & 3  \\
  0 & -4 \\
  \end{pmatrix}$$
We want to find the Singular Value Decomposition (SVD) where $U$ and $V$ both are orthogonal matrices and $\Sigma$ is a diagonal matrix, such that:
$$A = U \cdot \Sigma \cdot V^T$$
We arrive at:
$$A = U \cdot \Sigma \cdot V^T = \begin{pmatrix} 5 & 3  \\  0 & -4 \\ \end{pmatrix} = \begin{pmatrix} \frac{2}{\sqrt{5}} & -\frac{1}{\sqrt{5}}  \\  -\frac{1}{\sqrt{5}} & -\frac{2}{\sqrt{5}} \\ \end{pmatrix} \cdot \begin{pmatrix} 2\sqrt{10} & 0 \\  0 & \sqrt{10} \\ \end{pmatrix} \cdot \begin{pmatrix} \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}}  \\  \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\ \end{pmatrix} $$


text:
Q: If $\hat{F}$ - estimated empirical CDF, then what does $(\hat{F}) \ll F_{empirical}$ mean? (Absolutely continuous on $F_{emp}$) Here is the part of the definition I don't get: Given $X^n$, let $\hat{F}$ be a CDF that is absolutely continuous on $F_e \ \ (\hat{F}\ll F_e)$. What does it mean?

A: Consider a probability measure $\hat{\mu}_n$ with distribution function $\hat{F}$ and a probability measure $\mu_e$  with distribution function $F_e$. Then $\hat{\mu}_n$ should be absolutely continious with respect to measure $\mu_e$.


text:
Q: Why is the provided Python script not printing all of the lines of the by it traced code? While using sligthly modified code provided in a 5-years old but only today by me answered question  How print every line of a python script as its being executed (including the console)? I run into problems with understanding in detail how the code works and especially why the tracing is skipping to mention running the lines 5 and 8?
I am aware of the existence of another way to trace execution of a script with
python3 -m trace --trace --ignore-module sys,time --ignore-dir /sys:/usr tmp.py

but I would like to have the option of adapting the printed output content and format to my needs and to understand how the code works in detail in order to have an explanation why not all lines of the executed code appear in the trace.
Please feel encouraged by my question to provide another answer with better code (not being a dirty hack as this one that follows) as response to the other question my question here started with.
Below the code:
import subprocess
tracerCode = """
import sys
import inspect

class SetTrace(object):
    '''Although, this produces the desired result, it is
    a very bad hack since it will most likely break depending on what
        python_string_base   is'''

    def __init__(self, func):
        self.func = func

    def __enter__(self):
        sys.settrace(self.func)
        return self

    def __exit__(self, ext_type, exc_value, traceback):
        sys.settrace(None)

def monitor(frame, event, arg):
    if event == "line":
        file_dict = dict(enumerate("{}".split("|")))
        line_number = frame.f_lineno-30 # Amount of lines in THIS string
        if line_number > 0:
           print( "line " + str(line_number)+ ": " + file_dict[line_number] )
           sys.stdout.flush()
    return monitor

def run():
    {}

with SetTrace(monitor):
    run()

"""

codeToRun = """
    import time
    for _ in range(1):
        print(
'hello'
             )
        time.sleep(
5
                  )
    print ( 'goodbye')
"""

tracerCode = tracerCode.format("|".join([i.strip() for i in codeToRun.split("\n")]), codeToRun)
#print(tracerCode)

proc = subprocess.Popen(['python3.11', '-'], stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc.stdin.write(bytes(tracerCode,"utf-8"))
proc.stdin.close()
for line in proc.stdout:
    print( '{}'.format(line.strip()) )
proc.wait()

printing
b'line 1: import time'
b'line 2: for _ in range(1):'
b'line 3: print('
b"line 4: 'hello'"
b'line 3: print('
b'hello'
b'line 6: time.sleep('
b'line 7: 5'
b'line 6: time.sleep('
b'line 2: for _ in range(1):'
b"line 9: print ( 'goodbye')"
b'goodbye'

where lines 5 and 8 are not covered in the output.

A: The simplest explanation is that lines 5 and 8 are not executed as they are continuations of a previously executed line.  The closing ')' is simply part of lines 3 or 6 respectively and has nothing to execute on it.  Likewise, any extra lines in your code to execute don't get traced as empty lines.
As a demo, I've made some tweaks to your example to include the following:

*

*For the initial print statement I extended the string to be printed over multiple lines using both implicit concatenation and the + operator.  The implicit joins are not traced, while the line with the + operator is traced.

*I also added an f-string callout to a function, which does get its own trace line.

*I also added the sep and end arguments on their own lines

*I changed the input parameter for the "goodbye" line to a multi-line string.  Only the start of the multi-line string is traced

*I added an additional print call at the end with multiple input args, and the end and sep arguments. It only gets traced once, not once per arg.

import subprocess
tracerCode = """
import sys
import inspect

class SetTrace(object):
    '''Although, this produces the desired result, it is
    a very bad hack since it will most likely break depending on what
        python_string_base   is'''

    def __init__(self, func):
        self.func = func

    def __enter__(self):
        sys.settrace(self.func)
        return self

    def __exit__(self, ext_type, exc_value, traceback):
        sys.settrace(None)

def monitor(frame, event, arg):
    if event == "line":
        file_dict = dict(enumerate("{}".split("|")))
        line_number = frame.f_lineno-30 # Amount of lines in THIS string
        if line_number > 0:
           print( "line " + str(line_number)+ ": " + file_dict[line_number] )
           sys.stdout.flush()
    return monitor

def run():
    {}

with SetTrace(monitor):
    run()

"""

codeToRun = """
    import time

    def word():
        return 'today'

    for _ in range(1):
        print(
          'hello '
          'world '
          'how ' + 'are ' +  'you '
          f'{word()}?',
          end=';\\n',
          sep='--'
          )
        time.sleep(
5
                  )
    print ( '''
    goodbye
    cruel
    world
    '''
    )

    print('Testing1', 'testing2', 'testing3', sep=' - ', end='FIN')
"""

tracerCode = tracerCode.format("|".join([i.strip() for i in codeToRun.split("\n")]), codeToRun)
#print(tracerCode)

proc = subprocess.Popen(['python3.11', '-'], stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc.stdin.write(bytes(tracerCode,"utf-8"))
proc.stdin.close()
for line in proc.stdout:
    print( '{}'.format(line.strip()) )
proc.wait()

Gives the output:
b'line 1: import time'
b'line 3: def word():'
b'line 6: for _ in range(1):'
b'line 7: print('
b"line 8: 'hello '"
b"line 10: 'how ' + 'are ' +  'you '"
b"line 11: f'{word()}?',"
b"line 4: return 'today'"
b"line 10: 'how ' + 'are ' +  'you '"
b"line 8: 'hello '"
b"line 12: end=';"
b"',"
b"line 13: sep='--'"
b'line 7: print('
b'hello world how are you today?;'
b'line 15: time.sleep('
b'line 16: 5'
b'line 15: time.sleep('
b'line 6: for _ in range(1):'
b"line 18: print ( '''"
b''
b'goodbye'
b'cruel'
b'world'
b''
b"line 25: print('Testing1', 'testing2', 'testing3', sep=' - ', end='FIN')"
b'Testing1 - testing2 - testing3FIN'


text:
Q: Access a web server located in a VirtualBox virtual machine from the Host operating system I have a Mac OS X installation and a Ubuntu Virtual Box inside them. I use the Debian Virtual Box as a development machine for several rails and php web projects, but I want to access them from the Mac OS so I can tested on Safari, it is possible do this? how?
Thanks in advance

A: The simplest way is to set the virtual machine to use bridged networking, it will get an IP address on your network; this IP address should then be accessible from your host machine.
From Chapter 6 of VirtualBox's manual:

With bridged networking, VirtualBox uses a device driver on your host system that filters data from your physical network adapter. This driver is therefore called a "net filter" driver. This allows VirtualBox to intercept data from the physical network and inject data into it, effectively creating a new network interface in software. When a guest is using such a new software interface, it looks to the host system as though the guest were physically connected to the interface using a network cable: the host can send data to the guest through that interface and receive data from it. This means that you can set up routing or bridging between the guest and the rest of your network.

It is also possible to use the NAT networking mode, but it will require tinkering with port forwards (not worth the trouble, in my opinion).

A: The way I would do this (especially if you are on a home network) is to set the networking adapter to a bridged adapter. This way the guest VM is assigned it's own IP, and is accessible from any machine on the local network. It's the most convenient, and the won't have to mess around with port forwarding (which can get complicated).
A good reference for all the VBox networking modes is: http://www.virtualbox.org/manual/ch06.html


text:
Q: PL/SQL Check constraint: value on one column depends on another column Using PL/SQL, I'm building a table containing config which defines the distribution of samples into 2 different sets based on ratio. It has 4 columns: sample_type, set_1, set_2, ratio (percentage of samples going to set_1). For example, if a row is ('walk', 'left', 'right', 50), it means for samples whose type is 'walk', 50% of them goes 'left' while the rest goes 'right'.
I want to add a check constraint which makes sure that set_2 is null if only ratio is 100, i.e. 100% of sample goes to set_1. I try something like:
ALTER TABLE CONFIG
ADD CONSTRAINT CHK
CHECK (
    NOT EXISTS (SELECT 1 FROM CONFIG WHERE SET_2 IS NULL AND RATIO <> 0)
)

However, Oracle doesn't allow sub-query in check. So, is there another way to add a check constraint for this situation?
Thank you

A: ALTER TABLE CONFIG
ADD CONSTRAINT CHK
CHECK (
    (RATIO = 100) OR (SET_2 IS NOT NULL AND RATIO != 100)
)

and I wasn't completely sure if it was a requirement, but if SET_2 needs to be null in the case of 100, then you would want this:
ALTER TABLE CONFIG
ADD CONSTRAINT CHK
CHECK (
    (SET_2 IS NULL AND RATIO = 100) OR (SET_2 IS NOT NULL AND RATIO != 100)
)

A: Would
ALTER TABLE CONFIG
ADD CONSTRAINT CHK
CHECK (
    SET_2 IS NULL AND RATIO <> 0
)

work?


text:
Q: Prove using Taylor's Theorem: $1-\cos(\frac{x}{n})=\frac{x^2}{n^2}-\cos\theta(x_n,n)\frac{x^3}{6n^3}$ let $F_n(x)=n^2(1-\cos(\frac{x}{n}))$. I am asked to prove that this converges pointwise to limit function $F$ on a set $S$. In this case using geogebra, I see that it converges to $F=x^2$ where $x\in \mathbb{R}$.
From the solutions manual, I found they got this using Taylor's theorem,
$1-\cos(\frac{x}{n})=\frac{x^2}{n^2}-\cos\theta(x_n,n)\frac{x^3}{6n^3}$
where $\theta(x_n,n)$ is between $0$ and $\frac{x}{n}$
Furthermore, they state that $|F_n(x)-x^2|\leq \frac{x^4}{24n^2}$.
How can I show,
$1-\cos(\frac{x}{n})=\frac{x^2}{n^2}-\cos\theta(x_n,n)\frac{x^3}{6n^3}$
and $|F_n(x)-x^2|\leq \frac{x^4}{24n^2}$.
What I have so far:
$1-\cos(\frac{x}{n})=1-\cos(\frac{a}{n})+\sin(\frac{a}{n})*(\frac{1}{n})*(\frac{x}{n}-\frac{a}{n})^2+\cos(\frac{a}{n})*(\frac{1}{n})*(\frac{x}{n}-\frac{a}{n})^3$....
How would I proceed.

A: Hint. Assume $h>0$. Integrating by parts three times, one has
$$
\begin{align}
\cos h-1&=\int_0^h-\sin t\:dt
\\&=\left[(h-t) \frac{}{}\sin t\right]_0^h-\int_0^h (h-t)\cos t\:dt
\\&=\color{red}{0}+\left[\frac{(t-h)^2}{2}\cdot\cos t\right]_0^h+\int_0^h \frac{(t-h)^2}{2}\cdot\sin t\:dt
\\&=-\frac{h^2}{2}+\frac12\int_0^h (t-h)^2\cdot\sin t\:dt
\\&=-\frac{h^2}{2}+\left[\frac{(t-h)^3}{6}\cdot\sin t\right]_0^h-\int_0^h \frac{(t-h)^3}{6}\cdot\cos t\:dt
\\&=-\frac{h^2}{2}+\color{red}{0}-\int_0^h \frac{(t-h)^3}{6}\cdot\cos t\:dt
\end{align}
$$ or

$$
\cos h=1-\frac{h^2}{2}+\int_0^h \frac{(h-t)^3}{6}\cdot\cos t\:dt
$$

then one may use the mean value theorem for definite integrals to conclude.


text:
Q: Child div 100% height A more convoluted example of this question is here: child div height of 100% being ignored (a working solution is yet to be found)
Validating test case for my question: http://www.elucidatedbinary.com/tmp/layouttest_100percentheight.html. I want the #main div (yellow background) to expand to 100% of the height of it's parent div (#container).
My question is simple, can this be done without

*

*Reverting to jQuery (yucky!) or

*Reverting to tables (yuckier!)

I am yet to find a single example of how this can be done using the CSS layout model.
Thankyou.
EDIT: When I say "expand to 100% of the height of it's parent div" I mean expand all the way to beneath the footer. The header is supposed to leave a pink gap at the top.

A: try:
#main { position: absolute; top: 0px; bottom: 0px; }


text:
Q: Excel: Creating a macro to copy&paste active selection into another worksheet This is my first question on here, so please be kind.
Disclaimer: I'm also very new to macro building in Excel, so don't be upset if I ask for clarification.
I set out to make a project tracker and ran into the following problem:
I would like to have a button that would allow me to copy an active selection (a single cell or a row) on one worksheet and paste it into another worksheet within one workbook.
What I'm essentially trying to do is to have a possibility to just select a certain task, click the button and copy/paste it into a different worksheet. Therefore, as far as I understand, the code needs to be a loop (?) and it also needs to offset so that I can paste multiple tasks and they don't overwrite each other.
The code I managed to scrounge up right now gives me the runtime error 1004 on the line Activecell.Offset, and I can't figure out why.
Sub MoveToWeekly()
Sheets("Test1").Select
    Selection.Copy

    Sheets("Test2").Select

    Sheets("Test2").Range("A1:A4").Select
    Selection.End(xlDown).Select
    ActiveCell.Offset(1).Select

    Selection.PasteSpecial _
        Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

End Sub

I'd be incredibly glad for some help and I'm sorry that I'm not being awfully specific.

A: Here's one approach
Sub MoveToWeekly()

    'make sure a range is selected
    If typeName(selection)<>"Range" Then
         Msgbox "First select a range"
         Exit sub
    End If

    'you can assign the value between the two ranges directly, without copy/paste
    'Note: assumes there's always a value in ColA on the destination sheet
    with Selection
        'Starting at the bottom of the sheet and using xlUp is
        '    typically safer than using xlDown
        Sheets("Test2").Cells(rows.count,1).end(xlup).offset(1,0) _
              .resize(.rows.count, .columns.count).value = .value
    End with

End Sub


text:
Q: EmbeddedResourceVirtualPathProvider and @Html.TextBoxFor(Linq expression) In my .cshtml file, I'm getting an error wherever I use @Html.TextBoxFor
here's a sample code:
@model WebComposite.Models.CompositeModel

<label for="name">Name</label>
@Html.TextBoxFor(m => m.name)

Error:
Error #1:
'System.Web.Mvc.Html.InputExtensions.TextBoxFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Error #2:
One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?

any ideas?

A: in case anyone else is wondering, here's how I resolved it:
1. right click on the project -> select properties
2. select Application
3. change "target framework" (I was at 4.5, so I changed it to 4)
4. change "target framework" to whatever it was before step 3

web.config is cleaned up, appropriate references are added, do a build and everything should be back to normal


text:
Q: Alter Table in MySQL is using only one core Is there a way to enable all CPU cores for "Alter Table" query?
All other queries use 100% cores available, just "Alter Table" uses only one core.
Here are some my.cnf settings:
join_buffer_size = 32M
read_buffer_size = 32M
read_rnd_buffer_size = 32M
tmp_table_size = 1G
max_heap_table_size = 1G
#net_buffer_length = 1M
sort_buffer_size = 32M
key_buffer_size = 32M

innodb_buffer_pool_size = 5G
innodb_thread_concurrency = 0
innodb_read_io_threads = 64
innodb_write_io_threads = 64
innodb_flush_method = O_DIRECT
innodb_flush_log_at_trx_commit = 2

We're using MySQL server 5.6.33 on Ubuntu Server 14.04

A: No you can't use more than one core for an ALTER TABLE, even in MySQL-8.0.
5.7+ has significant improvements to the time of queries that can be done online.
For background ALTER TABLE, use the tools gh-ost or pt-online-schema-change are usable with 5.6.


text:
Q: Is there an equation like Jacobi-Anger expansion for the Bessel function of the second kind The Jacobi-Anger expansion is represented as $$ e^{ix \cos\theta} = \sum_{n=-\infty}^{\infty} i^{n}J_{n}(x)e^{in \theta} $$  then is there an expression for the Bessel function of the second kind $Y_n$ without summing
$$\sum_{n=-\infty}^{\infty} i^{n}Y_{n}(x)e^{in \theta} = ?$$

A: The Neumann functions at integer order cannot have a Jacobi-Anger type expansion due to their asymptotic behavior at large order $n$. They grow at a super-exponential rate $\propto n^n$ (also see here) which implies that multiplying them by powers of some number $a$ cannot possibly describe a convergent infinite sum.
The best one can do is define the exponential generating function
$$G(a,z)=\sum_{n=0}^\infty \frac{a^nY_n(z)}{n!}$$
since the factorial in the denominator cancels out the bulk of the asymptotic behavior and hence the series should have at least a bounded region of convergence in the $z-$plane. Then by using the integral representation 10.9.7 and  after a few manipulations (I can provide more details upon request) one can write down the following integral expression for the generating function:
$$G(a,z)=\frac{1}{\pi}\int_0^\pi e^{a\cos\theta}\sin[(z-a)\sin\theta]d\theta-\frac{1}{\pi}\int_0^\infty e^{-(z-a)\sinh t}\cosh(a\cosh t)dt ,\\ \text{Re}(z)>\max(0,2\text{Re}(a))$$
It doesn't look like there is a simple analytic form for this integral representation.


text:
Q: Запрос пароля администратора во время выполнения программы на C++ (WinAPI) В манифесте приложения на C++ указаны параметры для запуска с правами администратора (<requestedExecutionLevel level="requireAdministrator" uiAccess="false"></requestedExecutionLevel>). По непонятным мне причинам такой подход породил следующую проблему:
функция SHGetFolderPath с флагом CSIDL_APPDATA возвращает путь админа, который введёт пароль, а не пользователя, который запустил приложение. Это критично, поскольку приложение является установщиком ПО, и писать конфиги и прочие рабочие установки должно именно в папку запустившего его пользователя, которым может быть и гость. К сожалению использование CSIDL_COMMON_APPDATA не решает проблему, так как распаковываемые установщиком сторонние приложения ищут свои конфиги именно в папке пользователя, и общая APPDATA их не "интересует".
Подскажите пожалуйста выход из данной ситуации - как назначить запрос прав администратора только на кнопку "Установить", чтобы при старте установщик успел подхватить правильные пути?
PS: Путь получается так:
case WM_COMMAND:
    switch(wParam){
        case 1:
            ...
            //Получение ключевых путей в глобальные переменные
            SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, AppDataRoaming);
            SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, AppDataLocal);
            SHGetFolderPath(NULL, CSIDL_PROGRAMS, NULL, 0, StartMenu);
            SHGetFolderPath(NULL, CSIDL_DESKTOP, NULL, 0, DeskTop);

            ...
            //Запуск извлечения файлов.
            DWORD dwThreadId;
            InstallThread = CreateThread(NULL, 0, DataProcessing, NULL, 0, &dwThreadId);
            ...
            break;
        ...

Естественно получение путей можно вынести до кнопки установить, но надо решить проблему с доступом администратора, который запрашивается сразу при старте (иконка приложения с "щитом")

A: Всё работает согласно документации.
SHGetFolderPath является обёрткой к SHGetKnownFolderPath.
Из документации к SHGetKnownFolderPath:

hToken [in, optional]
Type: HANDLE
An access token that represents a particular user. If this parameter is NULL, which is the most common usage, the function requests the known folder for the current user.

Поскольку ваш текущий пользователь — админ, вы получаете то, что запрашивали.

Для того, чтобы отдельно получить нужные пути, и отдельно запуститься из-под админа, вам нужно сделать следующее:

*

*Убрать манифест, запускать программу без него. В ней у вас есть данные текущего юзера.

*После диалога с пользователем нужно запустить свой же собственный процесс параллельно, затребовав при этом админские права. Пример кода здесь.

*Администраторский экземпляр процесса инсталлятора по-хорошему не должен создавать файлы для текущего пользователя, т. к. они будут созданы с администраторскими правами (если не позаботиться об ином специально). Поэтому имеет смысл дождаться окончания работы администраторского процесса в неадминистраторском процессе, и с правами текущего пользователя создать нужные файлы.

A: В различных источниках написано, что в таком вот (вашем) случае для функции SHGetFolderPath() третий параметр hToken нужно заполнять реальным значением, а не NULL. Гляньте в сторону WTSQuerySessionInformation() потом WTSQueryUserToken().


text:
Q: How Linux handles the case when multiple processes try to replace the same file at the same time? I know this is a bit of theoretical question but haven't got any satisfactory answer yet. So thought to put this question here.
I have multiple C++ processes (would also like to know thread behaviour) which contend to replace the same file at the same time. How much is it safe to do in Linux (Using Ubuntu 14.04 and Centos 7)? Do I need to put locks?
Thanks in advance.

A: The filesystems of Unix-based OS's like Linux are designed around the notion of inodes, which are internal records describing various metadata about the file.  Normally these aren't interacted with directly by users or programs, but their presence gives these filesystems a level of indirection that allows them to provide some useful semantics that other OS's (read: Windows) cannot.
filename --> inode --> data

In particular, when a file gets deleted, what's actually happening is the separation of the file's inode from its filename; not (necessarily) the deletion of the file's data itself.  That is, the file and its contents can continue to exist (albeit invisibly, from the user's point of view) until all processes have closed their file-handles that were open on that file; once the inode is no longer accessible to any process, only then will the filesystem actually mark the file's data-blocks as free and available-for-reuse.  In the meantime, the filename becomes available for another file's inode (and data) to be associated with, even though the old file's inode/data still technically exists.
The upshot of that is that under Linux it's perfectly valid to delete (or rename) a file at any time, even if other threads/processes are in the middle of using it; your delete will succeed, and any other programs that have that file open at that instant can simply continue reading/writing/using it, exactly as if it hadn't been deleted.  The only thing that is different is that the filename will no longer appear in its directory, and when they call fclose() (or close() or etc) on the file, the file's data will go away.
Since doing mv new.txt old.txt is essentially the same as doing a rm old.txt ; mv new.txt old.txt, there should be no problems with doing this from multiple threads without any synchronization.  (note that the slightly different situation of having multiple threads or processes opening the same file simultaneously and writing into it at the same time is a bit more perilous; nothing will crash, but it would be easy for them to overwrite each other's data and corrupt the file, if they aren't careful)

A: It depends a lot on exactly what you're going to be doing and how you're using the files. In general, in Unix/Posix systems like Linux, all file calls will succeed if multiple processes make them, and the general way the OS handles contention is "the last one to do something wins". Essentially, all modifications to the filesystem are serialized, so the filesystem is always in a consistent state. But otherwise it's a free-for-all.
There are a lot of details here though. There's flags used in opening a file like O_EXCL that can result in failure if another process did it first (a sort of lock). There's advisory (aka, nobody is forced by the OS to pay attention to them) locking systems like flock (try typing man 2 flock to learn more) for file contents. There are more Linux specific mandatory locking system.
And there are also details like "What happens if someone deleted a file I have open?" that the other answer explains correctly and well.
And lastly, there's a whole mess of detail surrounding whether it's guaranteed that any particular change to the filesystem is recorded for all eternity, or whether it has a chance of disappearing if someone flicks the power switch. And that's a mess-and-a-half once you really dive into it, between dodgy hardware that lies to the OS about things to the confusing morass of different Linux system calls covering different aspects of this problem, often entering Linux from different eras of Unix/Posix history and interacting with each other in strange and arcane ways.
So, an answer to your very general and open-ended question is going to have to necessarily be vague, abstract, and hand-wavey.


text:
Q: How to fix "cannot access file because it is being used by another process" I'm running a program that will call a code based on a condition.
    if (charCount >= 152) {
        new InformixToPDF().createPdflandscape( DESTINATION +
                "\\" + new_file_name + "_" + df.format(new Date()) + ".pdf",source);
        }
    //function to call for portrait conversion
    else {
        new InformixToPDF().createPdfportrait( DESTINATION +
                "\\" + new_file_name + "_" + df.format(new Date()) + ".pdf",source);
         }

Here the code that's called if else condition are met.
  public void createPdfportrait(String dest,String source) throws DocumentException, IOException {
   File myfile = new File(source);
   Document document = new Document(PageSize.A4);

   document.setMargins (20, 0, 50, 80);
   PdfWriter.getInstance(document, new FileOutputStream(dest));
   document.open();

   br = new BufferedReader(new FileReader(source));
   String line;
   Paragraph p;

   //PDF font configuration
   Font normal = new Font(FontFamily.COURIER, 7);
   Font bold = new Font(FontFamily.COURIER, 7, Font.BOLD);

   //add page into PDF
   boolean title = true;
       while ((line = br.readLine()) != null) {
       p = new Paragraph(line.length() == 0 ? " ": line, title ? bold : normal);
       document.add(p);
       }
       document.close();

       System.out.println("Informix4gl report file " + source + " has been converted to PDF");
       Path sourcePath = Paths.get(source);
       Path destinationPath = Paths.get(MOVE);
       try {
           Files.move(sourcePath, destinationPath,
                   StandardCopyOption.REPLACE_EXISTING);
       } catch (IOException e) {
           e.printStackTrace();
       }
    }

After conversion has been done the current file. it need to be move to another folder using this code where "source" is the current file and "MOVE" is destination folder.
   Path sourcePath = Paths.get(source);
   Path destinationPath = Paths.get(MOVE);
   try {
       Files.move(sourcePath, destinationPath,
               StandardCopyOption.REPLACE_EXISTING);
   } catch (IOException e) {
       e.printStackTrace();
   }

The codes is executed and pdf is created successfully but error "java.nio.file.FileSystemException: O:\xx\yy\zz\test -> O:\xx\yy\zz\FOLDER C: The process cannot access the file because it is being used by another process." appear.
How do I fix this and what change should I make to the code to avoid this error?
I know these question was asked a lot but none of that fixed my problem. However I may have missed some.


text:
Q: How can i handle the multiple click action to single button for api calling and get the true response from api i just want to know the method to handle multiple click event on single button.(e.g FACEBOOK like button if i tapped multiple time then it may work perfect)
below code give you some idea and if there is any appropriate solution then give me as soon as possible.
class LikeViewController: UIViewController {
//MARK:- Outlets
@IBOutlet weak var btnLike: UIButton!
@IBOutlet weak var lblDescription: UILabel!

//MARK:- Variables
var objModelWatchList:WatchListModel?
var objUser = WatchListModel()

//MARK:- Lifecycle methods
override func viewDidLoad() {
    super.viewDidLoad()
    getWatchList()

}

//MARK:- Functions

//Function for prepare UI
func prepareUI() {
    btnLike.isSelected = isLike()
}

//Function for prepare data from api
func getWatchList() {
    objUser.videoId = 216
    objUser.type = "VIDEO"
    APIService.sharedInstance.getWatchList(parameters: objUser.toDictionary() as [String : AnyObject], success: { (dataSuccess) -> (Void) in
        self.objModelWatchList = dataSuccess
        DispatchQueue.main.async {
            self.prepareUI()
            self.lblDescription.text = self.objModelWatchList?.message
        }
    }) { (resultFailure) -> (Void) in
        print(resultFailure)
    }
}

//Function to varify the status of like
func isLike() -> Bool {
    return objModelWatchList!.status == 1 ? true : false
}

//MARK:- Actions
@IBAction func btnLikeClicked(_ sender: UIButton) {
            sender.isSelected = !sender.isSelected
            self.getWatchList()
}

}
Thank You.

A: You have to disable your button when API call and when u will get right response after the processing on that response you have to enable it.
Its works for me. I have a same issue.

A: if you refer to manage several events taps...I  recommend that use tapGestureRecognizer or variants, these can manage events that you comment for example...:

*

*Single tap,double tap or more taps to trigger function event

*Hold tap [UILongPressGestureRecognizer]

if you refer to same button called severals function in diferents situations i recommend the use un tag button for example:
function examplefunctionA(){
  //Another Proccess
  //Another Proccess
  self.button.tag = 2
}

function examplefunctionB(){
  //Another Proccess
  //Another Proccess
  self.button.tag = 1
}

func buttonclicked(sender: UIButton) {
    if sender.tag == 1 {
       examplefunctionA()
    }else if sender.tag == 2 {
       examplefunctionB()
    }
}


text:
Q: Checking for a factor change by group I have a data.table as follows:
library(data.table)
DT <- fread(
"Event_Type  country year
A   NLD   2005
B   NLD   2004
A   GBR   2006
B   GBR   2003
A   GRC   2002
A   GRC   2007",
header = TRUE)

From this post, I know I can see if there is a change in event type as follows:
ind <- with(DT, c(FALSE, Event_Type  [-1L]!= Event_Type  [-length(Event_Type  )]) & Event_Type  !='NULL')
DT$switch <- ifelse(ind, 1, '')

But I would like to be able to do this by group as well, in this case the country. How can I do this?

A: If you're using data.table, you can use the shift function to create a lagged variable and check if event is equal to its lagged value.
DT[, switch := Event_Type != shift(Event_Type, fill = Event_Type[1]), country]

That creates the ind part of your code, if you want something other than TRUE/FALSE you can put it in an ifelse (or fifelse if you're on a recent data.table version).


text:
Q: Printing strings and arguments of functions in R I've two questions about R. There are quite simple, but unfortunately I don't find something in the web.

*

*Is it possible to write a function in R, fun1<-function(place) such that the argument "place" is the filename which I want to import in my case, i.e.
fun1 <- function(place)
data <- read.table(/home/place.csv, header=TRUE, sep=",")

*Suppose the variable c is assigned to a number for example age of a person. Then I want to print out a string like this: "hello my age is c". How do you do this in R?

A: *

*You can use sprintf, paste0, etc for the first part.
fun1 <- function(place) read.table(sprintf('/home/%s.csv', place),
                                   header=TRUE, sep=",")

fun2 <- function(place) read.table(paste0('/home/', place, '.csv'),
                                   header=TRUE, sep=",")
# paste0 only works in recent versions of R

fun3 <- function(place) read.table(paste('/home/', place, '.csv', sep=''),
                                   header=TRUE, sep=",")

# Now call the functions
fun1('test.csv')
fun2('test.csv')
fun3('test.csv')

*sapply isn't needed since paste is vectorized.
ages <- 10:20
paste('Hello my name is', ages)

A: I'm not sure what you're trying to achieve in the first part of your question. Can you explain that further?
For the second part, what about something like this:
> ages = c(40, 23, 13, 42, 53)
> sapply(ages, function(x) paste("Hello, my age is", x))
[1] "Hello, my age is 40" "Hello, my age is 23" "Hello, my age is 13" "Hello, my age is 42"
[5] "Hello, my age is 53"


text:
Q: iOS NSURLConnection incorrect call My program register users through URL-requests, but before registration there is existence userlogin or his e-mail  checking in remote database. If this data not exist program should add user data in database or (if user or e-mail exist) program should return error.
I wrote this code:
 - (IBAction)buttonRegister:(id)sender {
    NSString *getDataURL = [NSString stringWithFormat:@"https://*********/********.php?chklogin=%@&chkemail=%@",login.text,email.text];
    NSURL *url = [NSURL URLWithString:getDataURL];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection)
       urlDataCheckUser = [NSMutableData data];
    else NSLog(@"Connection failed!");
    }

  - (void) msgtitle: (NSString*) title msgtext: (NSString*) msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
}

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
       [urlDataCheckUser appendData:data];
    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
       NSString *strResult = [[NSString alloc] initWithData:urlDataCheckUser encoding:NSUTF8StringEncoding];
       if ([strResult isEqualToString:@"1"])
       {
           [self msgtitle:@"Error" msgtext:@"E-mail or Login already use!"];
       }
       if ([strResult isEqualToString:@""])
       {
           NSString *getDataURL = [NSString stringWithFormat:@"https://**********/**********.php?reglogin=%@&regemail=%@&regpass=%@",login.text,email.text,password.text];
           NSURL *url = [NSURL URLWithString:getDataURL];

           NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];

           NSURLConnection *conn =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
           theRequest = nil;
           if (conn)
           {
               [self msgtitle:@"Success!" msgtext:@"Please login"];
           }

           UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
           UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"loginView"];
           [self presentViewController:vc animated:YES completion:nil];
       }
    }

    - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
    {
       return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
    {
       [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
       [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
    }

It is work, but i get message about successful registration  more then once.
What is wrong?