text:
Q: JAVASCRIPT Can someone fix my code? Can someone help me fix my code?
The function is like the Eval function but has a √ added but it doesn't work
function Eval(n) {
    var a = n.split("√").length - 1;
    var b = n.split("√").length;
    var c = a.replace("√" + d, e);
    var d = parseFloat(b[1]);
    var e = Math.sqrt(d);
    while (a != 0) {
        b();
        d();
        e();
        c();
        return;
    }
}
document.write(Eval("64+√68+32"));

A: There are some issues with your code and going by your approach, I have updated the code to following. Please see, whether it helps!
Please note, I am assuming as per the name of the function, that you want to evaluate the expression. Also, there are other assumptions as well, like there will be only one square root expression and all operations will be additive.

function Eval(n) {
  var b = n.split("√"); // you were expecting b to be an array
  var a = b.length - 1; // you can use b here
  var d = parseFloat(b[1]); // d should have been assigned before using in c
  var e = Math.sqrt(d);
  var c = n.replace("√" + d, e);
  return c.split("+").reduce(function(a, b) {
    return a + parseFloat(b); // sum up all the values
  }, 0);
}
console.log(Eval("64+√68+32"));

You can try tweaking here

A: function eval(n){
   var numbers = n.split('+'); // split the exepression with the + operator
   var result = 0; // initaliaze the result to 0
   for(number of numbers){ // for each number of numbers
       if(number.indexOf('√') !== -1){ // if the number contains sqrt
           number = +number.substring(1, number.length); // cast to int
           result += Math.sqrt(number);
       }else{
           number = +number; // cast string to int, NaN if not possible
           result += number;
       }
   }
   return result;
}

This function will work for you additions.
Not that this is just a point to start, and not the best way of doing it, I tried to be the more comprehensive seeing that you are a beginner in javascript


text:
Q: ERROR Cannot read properties of undefined (reading 'options') in Nuxt3 I am getting this error when trying to create a Nuxt 3 application.  I haven't done anything with Axios yet and the application is essentially empty other than the boiler plate code.
(base) app % npx nuxi build
Nuxi 3.0.0                                                                             14:32:27
Nuxt 3.0.0 with Nitro 1.0.0                                                            14:32:27

 ERROR  Cannot read properties of undefined (reading 'options')                        14:32:28

  at axiosModule (node_modules/@nuxtjs/axios/lib/module.js:12:13)
  at installModule (node_modules/@nuxt/kit/dist/index.mjs:416:9)
  at async initNuxt (node_modules/nuxt/dist/index.mjs:1825:7)
  at async loadNuxt (node_modules/nuxt/dist/index.mjs:1857:5)
  at async loadNuxt (node_modules/@nuxt/kit/dist/index.mjs:493:19)
  at async Object.invoke (node_modules/nuxi/dist/chunks/build.mjs:34:18)
  at async _main (node_modules/nuxi/dist/cli.mjs:50:20)

A: The axios module is not something to use anymore for Nuxt3 as explained here: https://stackoverflow.com/a/74679190/8816585
Use $fetch directly, which is basically a wrapper around ofetch.

A quick way to see if a module is compatible with a specific version of Nuxt is to use the module page, for example here is the one for axios.
As you can see, it is not compatible with Nuxt3 since the page is empty.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to access global constants inside a JSON file I have many JSON files in a Vue.js application, with numerous references to global constants. Is it possible to import constants into a json file, or to refer to .env constants from my .json files?
The following examples break my tests:
"href": process.env.SOME_EXTERNAL_LINK, or
"href": "$(process.env.SOME_EXTERNAL_LINK)", or
"href": `${process.env.SOME_EXTERNAL_LINK}`

Is there a "standard" way to do this?

A: The suggestion of Estus Flask is correct - this is the best way forward.


text:
Q: Prevent Nhibernate schemaexport from generating foreign key constraints on has many relationship I have a mapping like this:
HasMany(x => x.Orders).KeyColumn("CustomerID");

Which is causing a constraint like this to be generated by schemaexport:
alter table [CustomerOrder]
    add constraint FK45B3FB85AF01218D
    foreign key (CustomerID)
    references [Customer]

I have tried adding .NotFound.Ignore() like on a References() mapping to disable the constraint from being generated but this does not work.
Can a mapping be defined that will force SchemaExport to not generate the constraint?

A: Figured it out:
HasMany(x => x.Orders).KeyColumn("CustomerID").ForeignKeyConstraintName("none");

buried in the source is a check to ignore creation if the name is "none"


text:
Q: Y-axis of a graph with a common unit but different meanings I have a graph where the x-axis is time and y-axis is the density of two or more different organisms. So the graph shows how the densities change with time. Suppose the species are tunas and whales, and the plot shows the data for the both species together. Should the label for the y-axis Density or Densities? I have seen both ways...

A: Density. The axis is only a measurement scale. At any given time, each data set has only one value.

A: You should label it density unless you're doing something really peculiar.
At any given point of time, an animal (or group of animals, if this is an aggregation or population density) possesses a single density. They probably possess multiple units of density measurement - e.g. Wikipedia lists the average density of a human as 1062 kg/m3 - but only a single density*.
Your Y axis counts units of density measurement, not numbers of densities; it quantifies the quality rather than asking how many different instances of that quality exist. Unless you're using density as the metric for determine number of populations of animals (e.g. a density of 10 animals/km2 and another location having a density of 15 animals/km2 demarcates them as different populations). But that's a really crazy way to count population groups.
* - Yes, I realize the density will be different at different places in the body, but at that level we're talking about tissue densities, not human density. Even a heterogeneous body has only a single density when considered as a whole. I also realize this is most likely about population density, but it's a lot cooler to me to think of it in terms of physical body density, and that doesn't change the answer, or even the above asterisk (with appropriate terminological substitutions of course).


text:
Q: The sum of series I have the series
$x_{2n-1}:=1+\frac{1}{2}+\frac{1}{2^3}+...+\frac{1}{2^{2n-1}}=1+\frac{2}{3}\cdot(1-\frac{1}{4^n}).$ But why?
I found that the sum of odds power can be so calculate:
$x+x^3+x^5...=x(1+(x^2)^1+(x^2)^2..=\frac{x}{1-x^2}$. If I apply this to my series, then I get $\frac{4}{3}$ because $1+\frac{1}{2} \cdot(1+(\frac{1}{2^2})^1+(\frac{1}{2^2})^2...+(\frac{1}{2^{2}})^{n-2}=\frac{\frac{1}{2}}{1-\frac{1}{2^2}}=1+\frac{1}{2} \cdot(\frac{4}{6})=1+\frac{1}{3}=\frac{4}{3}$
So something doesn't work! I will be grateful for help!

A: You have
$$
\begin{array}{l}
 x_{2n - 1}  = 1 + \frac{1}{{2^1 }} + \frac{1}{{2^3 }} + \frac{1}{{2^5 }} +  \cdots \frac{1}{{2^{2n - 1} }} =  \\
  = 1 + \frac{1}{{2^1 }}\left( {1 + \frac{1}{{2^2 }} + \frac{1}{{2^4 }} +  \cdots \frac{1}{{2^{2n - 2} }}} \right) \\
 \end{array}
$$
Now
$$
1 + \frac{1}{{2^2 }} + \frac{1}{{2^4 }} +  \cdots \frac{1}{{2^{2n - 2} }} = 1 + \frac{1}{{2^2 }} + \frac{1}{{\left( {2^2 } \right)^2 }} +  \cdots \frac{1}{{\left( {2^2 } \right)^{n - 1} }}
$$
Hence
$$
\begin{array}{l}
 x_{2n - 1}  = 1 + \frac{1}{2}\left( {1 + \frac{1}{4} + \frac{1}{{4^2 }} +  \cdots \frac{1}{{4^{n - 1} }}} \right) =  \\
  = 1 + \frac{1}{2}\left( {\frac{{1 - \frac{1}{{4^{n - 1 + 1} }}}}{{1 - \frac{1}{4}}}} \right) =  \\
  = 1 + \frac{2}{3}\left( {1 - \frac{1}{{4^n }}} \right) \\
 \end{array}
$$


text:
Q: Comparison Between SPICE Simulators I've recently realized that I can't do everything easily in ngspice, mainly because analysis has to be performed through the interpreter. I'm considering switching to a new SPICE simulator.
I'd like a list the advantages and disadvantages of the following SPICE simulators as well as experiences with the various simulators:
HSPICE
LTspice
ngspice
PSpice

I'm well aware HSPICE is an expensive proprietary simulator, but I am able to get access to it, problem is I'd have to access it on a sever via SSH.
LTspice is already free, but not installed on my Windows 7 machine.
Already using ngspice in Fedora Linux.
PSpice available to me on my university's computers. I refuse to install it on my own computer, because it messes with the registry a bit too much.

A: My short answer is to just go with LTSpice, it is one of the best simulators on the market and it is free. You can't really beat that. But if you would like a breakdown feel free to read my personal opinions.
HSPICE:

*

*Advantages: HSPICE is widely considered one of the most accurate simulators on the market. However I have no actual experience using it.

*Disadvantages: As you said, it is expensive, proprietary, and as far as I know has no schematic capture features.

*Overall: If you REQUIRE reliable results (Military or high end industrial) then HSPICE is the way to go. Otherwise, I would avoid it.

LTSpice:

*

*Advantages: If you are doing power electronics this simulator is tuned for simulating switching events, as well as some other things which make it perfect for this field. Additionally, it has (IMO) an intuitive interface and doesn't try to hide the netlist from you. Plus, it is FREE.

*Disadvantages: ? I haven't been made aware of any, it isn't considered quite as accurate as HSPICE, but it isn't inaccurate by any means.

*Overall: This is the simulator I would suggest. It is easy to use, it is free, and it is supported by a much larger company. (Linear Technology)

ngspice:

*

*Overall: I don't know enough about ngspice to give a full overview. I only recently downloaded it and am still working on compiling it for my system. Obviously you have found one of the drawbacks is being limited to the command line.

PSPICE:

*

*Advantages: Well this is as close as you can get to the original SPICE. PSPICE is powerful, has a well established simulator, built in results viewer, and an extensive model library.

*Disadvantages: Unfortunately it has become so bloated in recent years that it is difficult to recommend. And as you would probably like to have it on your computer, I would bet this one is out of your price range unless you have $20,000 laying around.

*Overall: Powerful and well established, but going downhill fast. Expensive.

A: I would say that depends heavily on what you need it for. Often the expensive spices are part of some e.g PCB design tool. I'm just trying out MultiSIm from NI (expensive orcad type tool), and it has lots of pretty virtual instruments (e.g scope, distortion analyser, etc) and monte carlo analysis (which LTspice does not have a "convenient" version of - it does have some functions you can use though as Vlad points out, here is a link on using them) but to be honest I find that 99% of things I could do on LTspice.
I find the LTspice setup is by far the quickest out of any spice I have tried, once you get used to the key commands. R for resistor, D for diode, is much easier than clicking the picture (or even selecting from a pop up box in MultiSims case, arghh) and dragging to the right place every time.
You can have a circuit done in seconds this way.
The manual is not as pretty either, but all the info you need is there regarding how to use, eg. the .param, .step and .measure commands for doing things like running an analysis many times and varying parameters. I just tried to run a transfer function analysis in MultiSim in this manner (i.e. run may times and vary a parameter then plot results) but despite reading/wrestling for hours with it, I couldn't manage it, but a quick addition of .step V2 -15 15 1 to the sheet made it possible in LTspice.
I'm sure some of the above is simply as I'm new to MultiSim, and no doubt I am missing something (as the above example simply must be possible in a tool like that) and no I don't work for LT :-) but it has been the only spice that I have used regularly for the last few years. The main point is that it will do all the normal stuff as good (and probably faster) than the expensive tools, but if you need the extras (e.g. monte carle, PCB level anaysis based on actual routing/IBIS models - Altium does this excellently) and all wrapped up in one design tool then you may need more than if can offer.
In my view it can't hurt much to have around even if you do need a more powerful tool anyway.

A: I recently fought with the same battle as you trying to get a decent spice package and being on a Linux machine definitely does not help matters.
I used NI Multisim in school and its a fantastic interactive SPICE package. I love the fact you can watch a virtual scope and turn pot's to see real responses. The downside with it is I found it to be less than accurate when dealing with small signals and waveform performance in general. I still use it when coming up with circuit ideas until I have a pretty good idea of the design then I move to a better package for fine tuning things.
The best package I have used for hardcore SPICE has been SIMetrix. They have a free version that works on Linux too. Its the most accurate package I have used so far and has all the complicated options that require reading the manual quite a few times over to understand.
Here are examples of how I use both packages.  In Multisim, I was making a transistor tester and needed to create a square wave with 0deg, 120deg, 240deg output via a schmitt hex buffer. Multisim did a swell job and visually lit up LED's like it would in real life when a transistor was put in the circuit. I used SIMetrix when I was making an amp for sound system that required a noise floor of >100dB.

A: I don't have experience with HSPICE, but use LTspice and NGSPICE very frequently. In my field (power electronics), I have observed fellow engineers actively refuse to work with the company-supplied Pspice after being exposed to LTspice.
Unfortunately, LTspice is closed source, has no scripting possibility, and you can't add (your own) code models to it. When you need these more advanced options (not many people do or care) NGSPICE is the way to go. It's open source, incorporates XSPICE, KLU, open-mp and CUA, and has a C-shell type interpreter with very advanced possibilities (but IMHO a horrible user interface). It does not have
schematic entry but there are solutions for that (e.g. LTspice). NGSPICE can be used with gnuplot for very nice, programmable, graphical output.

A: As an addition to the previous answers, LTspice is a great freeware with limited possibilities on the digital parts: ibis models are not considered at the exception if you own/develop/find a software.
ngspice handles ibis file as well as mixed mode simulation (Verilog-AMS + Spice) if you install ADMSXml components. Unfortunately, this extension is tough to install and use (create a component/compile it/refresh/use it).
Pspice as a daughter of Cadence is very powerful and well known. Nevertheless, the free version allows a limited number of component, and quite slow in everyday use.
XSpice is ngspice like with multi threaded and shared processes possibilities to speed up simulations.
Then you can also use TINA from Texas Instrument which is free and allows as LTspice a bit of extra digital and ibis model. As a designer you should oftenly pay attention to the noise of your circuit and sadly only commercial one support well the noise consideration (Cadence, HSpice, UltraSim, ... and Xspice).

A: Ngspice is not limited to the command line.  One may include a scripting block in the netlist which is quite powerful.

A: The Ltspice display is inferior to orcad.  The parameter steps are hard to distinguish from different voltages.
On the good side, the hierarchy navigation is straightforward.  LTspice uses an old system, which is easy to understand and gives you fairly good flexibility.
Making a part from a schematic is very quick in LT spice.


text:
Q: Using a pipe in C I am trying to use a single pipe which creates 3 child processes, where each child procss shouold prompt the user to enter an int and then writes it to the pipe. The parent process should read the pipe and display the largest int.
Here is what I have with my limited knowledge:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

main(int argc, char argv[]) {
    int input[3];
    int i;
    int fd[2];
    int result;

    if(pipe(fd) == (-1))
        fprintf(stderr, "pipe failed\n");

        for(i = 0; i < 3; i++) {
            if(fork() == 0){//child
                printf("Enter a number: ");
                scanf("%d", &input[i]);
                printf("\n");
            }
        }
        if(input[0] >= input[1]){
            if(input[0] >= input[2])
                result = input[0];
            else
                result = input[2];
        }
        else if(input[1] >= input[2]){
            if(input[1] >= input[0])
                result = input[1];
            else
                result = input[0];
        }
        else if(input[2] >= input[0]){
            if(input[2] >= input[1])
                result = input[2];
            else
                result = input[1];
        }
        printf("The max of the three is: %d", result);
    }

When I try running this in terminal I get this:
The max of the three is: 4195760Enter a number: $ Enter a number:
Enter a number:
The max of the three is: 4195760The max of the three is: 4195760Enter a number:
The max of the three is: 4195760

Please shed some light on me.


text:
Q: Concatenation tchar variables I work with WinAPI and I have a function get_disk_drives() for retrieves available disk drives and a helper function get_current_disk_drive() for retrieves the full path and file name of the specified file.
void get_current_disk_drive(TCHAR dirname[]) {
  TCHAR *fileExt = NULL;
  TCHAR szDir[MAX_PATH];
  GetFullPathName(dirname, MAX_PATH, szDir, &fileExt);
  _tprintf(_T("Full path: %s \nFilename: %s\n"), szDir, fileExt);
}

void get_disk_drives() {
  DWORD drives_bitmask = GetLogicalDrives();

  for (int i = 0; i < 26; i++) {
    if ((drives_bitmask >> i) & 1) {
      TCHAR drive_name = (char)(65 + i);
      TCHAR drive_path[] = drive_name + "\\";
      get_current_disk_drive(drive_path);
    }
  }
}

int _tmain(int argc, _TCHAR* argv[]) {
  get_disk_drives();
  return 0;
}

Here I can't make concatenation:
TCHAR drive_name = (char)(65 + i);
TCHAR drive_path[] = drive_name + "\\";
get_current_disk_drive(drive_path);

Why? Where is my mistake?

A: operator+ cannot be used for C-strings, string literals, or characters. The effect (for legal expressions anyway) is pointer arithmetic. For concatenation you have to either explicitly call one of the strcat functions, or use std::basic_string instead:
typedef std::basic_string<TCHAR> tstring;

tstring drive_name;
drive_name += TCHAR( 65 + i );
tstring drive_path = drive_name + _T( '\\' );

You can access a C-string from a std::basic_string by invoking its c_str() member. Since this is a C-string represented as a pointer, you would have to change the signature of get_current_disk_drive to void get_current_disk_drive(const TCHAR* dirname), or pass a const tstring&.
It's also a good idea to stop using Code::Blocks. Defaulting to MBCS character encoding in 2015 is a crime.


text:
Q: Unable to create new jupyter notebook. Getting error '_xsrf' argument missing from POST When trying to create new jupyter notebook. Following error is popping
'_xsrf' argument missing from POST

A: The problem probably arose from having an open notebook idle for too long.
Try this:
Copy the changes you have made in that notebook, and restart Jupyter.
Then reopen, paste your changes, and you should be good to go!

A: Check with another browser (or newer version of it). I started to get that error on Opera (might be an old version) but worked well using Chrome.

A: for me restarting the kernel worked. Give it a try!


text:
Q: Mean field approximation I am a Japanese student studying machine learning and stuff like that. When I have studied Mean Field Approximation HERE, I got question.
In that post, equation (14) is as follows:
$$
L[q_1,...,q_m] - \sum_{j=1}^{m}\lambda_j\int_{z_j}q_j(z_j)dz_j = 0 $$
But I think it should be like:
$$
L[q_1,...,q_m] - \sum_{j=1}^{m}\lambda_j\left[\int_{z_j}q_j(z_j)dz_j - 1 \right]
$$
Because we construct the Lagrangian with careful the following constraint:
$$
\int_{z_j}q_j(z_j)dz_j = 1 ~~~~~\textrm{for all }j
$$
It means that each $q_j$ is probabilistic density function.
Please help me.

A: Strictly speaking, you're right. If you want to construct the Lagrangian such that you can recover the constraints by setting the derivatives with respect to the Lagrangian multipliers to zero, you need to do it the way you say. However, since the constraints are already known, there's usually no need to recover them from the Lagrangian, and the Lagrangian is usually only used to derive the equations of motion by differentiating with respect to the $q_i$ (and $\dot q_i$). Since a constant in a constraint doesn't make a difference in the derivatives with respect to $q_i$, constants in constraints are often dropped in the Lagrangian for simplicity.


text:
Q: Evaluate math expression in c# that should handle whitespace if it exists I am trying to use the following code to evaluate math expression. currently, the expression parser only works if there is a whitespace between every character. ex: (x + y) *2.... if the expression is (x+y)*2, the expression does not evaluate. Trying to use regex so the expression evaluates with or without spaces,but still unable to meet the goal. Any direction/help is greatly appreciated.
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "(x + y)*2";
      string pattern = "\\s+";
      string replacement = " ";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);

      Console.WriteLine("Original String: {0}", input);
      Console.WriteLine("Replacement String: {0}", result);
   }
}

A: If extra spaces between the terms is fine, please try this code:
public static void Main()
{
  string input = "(x + y)*2";
  string pattern = "";
  string replacement = " ";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);

  Console.WriteLine("Original String: {0}", input);
  Console.WriteLine("Replacement String: {0}", result);
}

A: public static void Main()
{
  string input = "(x + y)*2";
  string pattern = "";
  string replacement = " ";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);

  pattern = "  ";
  replacement = " ";
  rgx = new Regex(pattern);
  result = rgx.Replace(result, replacement);
  Console.WriteLine("Original String: {0}", input);
  Console.WriteLine("Replacement String: {0}", result);
 }


text:
Q: macOS: How to open a local HTML file with URL parameters I want to start a Kantu web macro from the command line on Mac. Essentially this is as simple as opening the Chrome or Firefox browser with a local HTML page (which contains the macro code). All works fine on Windows. But on macOS, when I use
mac:~ open 'file:////Users/fabrice/Kantu/demoautofill.html?direct=1&close=1&savelog=demotestlog.txt'

Chrome starts, and the file URL gets opened, but the '?direct=1&close=1&savelog=demotestlog.txt' GET parameter part is lost.
So the question is: How to launch a local html file with GET parameters?
I found this post: https://stackoverflow.com/questions/7710803/open-a-local-html-file-with-url-params-through-applescript which uses AppleScript as a workaround, but it is for Safari, I need Chrome. Plus I would like to avoid using AppleScript, if possible.

A: open just handles files, it doesn't know about GET parameters. So the AppleScript approach is probably the way to go here:
osascript -e 'tell application "Google Chrome" to
    open location "file:///Users/YOU/path/to.html?foo=bar"'


text:
Q: How to solve jars conflict with different libraries? i am using Repast Simphony in my project and its library contains many jars. meantime, i am using GeoTools and they are conflict because Repast Simphony employ geotools 2.3.3 and i want to use geotools 2.7.
the problem is i don't know how to remove some jars from the Repast Simphony. To add it, i just right click the project and have a option of Repast Simphony > Add Repast Simphony to this project
in the build path i can't edit that library. under the bulid path, after i press edit the only thing i can change is the name of the library. and in the .project file i found
<buildSpec>
.
.
.
<buildCommand>          <name>repast.simphony.eclipse.repast_simphony_builder</name>            <arguments>             </arguments>        </buildCommand>
</buildSpec>
<natures>
.
.
.
<nature>repast.simphony.eclipse.repast_simphony_nature</nature>
</natures>

and in the .classpath file it looks like this:
<classpathentry kind="con" path="REPAST_SIMPHONY_SUPPORT"/>

then i suspend all validators and remove the confilcted jars from the Repast library, however, it's not working. i can't build project due to lack of jars. so i am think about to edit some files to cross those conflict jars from the repast library, but i don't know how?
There is a "C:\Program Files\eclipse\plugins\repast.simphony.core_2.0.0\plugin_jpf.xml" file and "C:\Program Files\eclipse\plugins\repast.simphony.core_2.0.0\META-INF\ MANIFEST.MF" file. In above 2 files, all included files are list. I remove some of jars path but no difference.

A: If the Repath library is written in a clean way, you could simply use in your code full names.and.paths for all conflicting include operators. If the Repath does it, too, there will be no conflicts thereafter.


text:
Q: Entity Framework Core retrieving related entities I'm new to EFC and was hoping to get some help with a problem I ran into.
Suppose I have two tables:
Tool table:
Version  FeatureId

1         1

1         2

1         4

2         1

Feature Table:
FeatureId Name

1         feature1

2         feature2

3         feature3

4         feature4

and based on these two tables I have the following:
public class Tool
{

public int Id {get; set;}

public int Version { get; set; }

public List<Feature> Features { get; set; }

}

public class Feature
{

public string FeatureId { get; set; }

public string Name { get; set; }
}

so a tool version may include more than one features and a feature may be included in more than one version. When I tried to retrieve a tool based on the version number like this:
_context.Tool.Where(x => x.Version == versionID)
           .Include(i => i.Features)
           .ToList()

I ran into an error asking for a ToolId. Why is that?

A:
a tool version may include more than one features and a feature may be included in more than one version.

So you have many-to-many relashionship, and your tables must look like below:
public class Tool
{
    public int Id {get; set;}
    public int Version { get; set; }
    public ICollection<Feature> Features { get; set; }
}

public class Feature
{
    public string FeatureId { get; set; }
    public string Name { get; set; }
    public ICollection<Tool> Tools { get; set; }
}

And the missed one:
public class ToolsFeatures
{
    public int ToolId { get; set; }
    public Tool Tool { get; set; }

    public int FeatureId { get; set; }
    public Feature Feature { get; set; }
}

Then configure the relashions the dbcontext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ToolsFeatures>()
        .HasKey(t => new { t.ToolId, t.FeatureId});

        modelBuilder.Entity<ToolsFeatures>()
            .HasOne(t => t.Tool)
            .WithMany(f => f.Features)
            .HasForeignKey(t => t.ToolId);

        modelBuilder.Entity<ToolsFeatures>()
            .HasOne(f => f.Feature)
            .WithMany(t => t.Tools)
            .HasForeignKey(f => f.FeatureId);
    }

See Many-to-Many relashions

Notice: You have FeatureId defined as string but it has int values! is there any mistake here?


text:
Q: Is it possible to make Spark UDF working with Array that could be None? How to make this code working when array could be None :
def stringInArrayContains = udf((array: collection.mutable.WrappedArray[String], str: String) => array.filter(x => x.contains(str)).mkString(";"))

A: This UDF will just work fine, just make sure it's only called for inputs which are non null :
.withColumn("result",when($"arr".isNotNull and $"string".isNotNull, stringInArrayContains($"arr","string"))))

otherwise handle nulls inside UDF:
def stringInArrayContains = udf((array: collection.mutable.WrappedArray[String], str: String) => if(array==null || str==null)  null else array.filter(x => x.contains(str)).mkString(";"))


text:
Q: Orthogonal Block Matrix Given $A \in \mathbb{R^{\text{nxn}}}$, $B \in \mathbb{R^{n\text{x}m}}$ and $C \in \mathbb{R^{m\text{x}m}}$ such that
$$ M = \begin{bmatrix}
    A & B \\
    0 & C
\end{bmatrix} \in \mathbb{R^{(n+m)\text{x}(n+m)}} $$
a block Matrix.
Prove that: $M$ is orthogonal $\iff$ $A$ and $C$ are orthogonal and $B = 0$
My solution idea:
$\Longleftarrow$
Since $A$ is orthogonal, its columns form a linearly independent orthonormal set of vectors. It follows that the first $n$ columns of $M$ are orthonormal, because a vector $v_{i}$ of the form $(a_{1,i},a_{2,i},...a_{n,i},0,..,0)$ for $i = 1,..n$ still has Norm equal to $1$ and $\langle\ v_{i},v_{j} \rangle = 0$ for $j = 1,..,n$ given $i \neq j$
Same logic applies to columns vectors of $M$ from $n+1$ to $m$ since $C$ is orthogonal. So, taken together $\{v_{1},...,v_{n},v_{n+1},...,v_{m}\}$ they build an orthonormal Basis for $\mathbb{R^{(n+m)}}$ and it follows that $M$ is orthogonal.
$\Longrightarrow$
Reversing the argument:
Since $M$ is an orthogonal Matrix, its columns vectors build an orthonormal Basis for $\mathbb{R^{(n+m)}}$
Given that $a_{i,j} = 0$ for $i = m,..,n+m$ and $j =1,..,n$ It follows that the columns vectors of $A$ build an orthonormal Basis for $\mathbb{R^{n}}$ and $A$ is orthogonal.
Now to prove $B = 0$ confuses me. Because the columns vectors of $M$ are orthonormal, it has to be that the inner product of each column vector of $A$ with the columns vectors of $B$ is zero. Is this enough to follow that $B= 0$?
If $B = 0$ then it's easy to follow that $C$ is orthogonal.
Any help/comments would be great!

A: The $n+i$-th column of $M$ must be orthogonal to all the first $n$ columns of $M$. If you write the dot product, it's clear that the dot product of the $n+i$-th column of $M$ and the $k$-th column of $M$ (for $k\leq n$) is equal to the dot product of the $i$-th column of $B$ and the $k$-th column of $A$.
Therefore, the above demand is equivalent to demanding that the $i$-th column of $B$ must be orthogonal to all the $n$ columns of $A$.
Since the columns of $A$ span $\mathbb R^n$ (orthogonal nonzero vectors are always linearly independent), the only vector orthogonal to all the columns of $A$ is the zero vector.


text:
Q: Sending POST request in ESB mule I try to send the post request to API using ESB mule. Hence i have created flow like this.
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd">
    <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8110" doc:name="HTTP Listener Configuration"/>
    <http:request-config name="HTTP_Request_Configuration" protocol="HTTPS" host="api.bonanza.com" port="443" doc:name="HTTP Request Configuration"/>
    <flow name="bonanza_fetchtoken_ceFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/fetchtoken" allowedMethods="GET" doc:name="HTTP"/>
        <message-properties-transformer doc:name="Message Properties">
            <add-message-property key="X-BONANZLE-API-DEV-NAME" value="t*****I"/>
            <add-message-property key="X-BONANZLE-API-CERT-NAME" value="l*****F"/>
        </message-properties-transformer>
        <set-payload value="fetchTokenRequest" doc:name="Set Payload"/>
        <set-property propertyName="Content-Type" value="application/json" doc:name="Property"/>
        <json:object-to-json-transformer doc:name="Object to JSON"/>
        <http:request config-ref="HTTP_Request_Configuration" path="/api_requests/secure_request" method="POST" doc:name="HTTP">
            <http:success-status-code-validator values="0..599"/>
        </http:request>
    </flow>
</mule>

In the API documentation, they have provided the sample code for java to send and receive response and it is working in my local too. The java code snippet is  below.
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.HttpURLConnection;

public class FetchToken {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String devId = "t******I";
            String certId = "l*******F";

            URL url = new URL("https://api.bonanza.com/api_requests/secure_request");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("X-BONANZLE-API-DEV-NAME", devId);
            connection.setRequestProperty("X-BONANZLE-API-CERT-NAME", certId);

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

            String requestName = "fetchTokenRequest";

            writer.write(requestName);
            writer.flush();
            writer.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = in.readLine();

            JSONObject jsonResponse = new JSONObject(response);

            if (jsonResponse.optString("ack").equals("Success")
                    && jsonResponse.optJSONObject("fetchTokenResponse") != null) {
                // Success! Now read more keys from the json object
                JSONObject fetchTokenJson = jsonResponse.optJSONObject("fetchTokenResponse");

                System.out.println("Your token: " + fetchTokenJson.optString("authToken"));
                System.out.println("Token expiration time: " + fetchTokenJson.optString("hardExpirationTime"));
                System.out.println("Authentication URL: " + fetchTokenJson.optString("authenticationURL"));
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

I am not java expertise. How they are sending post payload (fetchTokenRequest) in Java in the above sample. How can i send same payload in the mule ESB.
If it is stream post payload, how can i send stream post payload in ESB mule ?

A: In your sample, whatever payload your http listener is listening to will be your payload for post request. To use a different payload, use <set-payload doc:name="Set Payload" value="your_value"/> before outbound http.
Set Content-Type to application/json
After set-payload, use <json:object-to-json-transformer/>


text:
Q: Finding new standard deviation and mean after adding an element Say I have a mean and standard deviation for a dataset of 5 elements.
I now add a sixth element. Is there a way to calculate the new mean and standard deviation using the information we had prior (i.e. not just recalculating the whole thing from scratch)?
For the mean, I see that I can just multiply the old one by $5$, add the new element, and divide by $6$.
I'm not sure if there's something I can do with the standard deviation, however.
$$\sigma_{old} = \sqrt{\sum_i (X_i - \mu_{old})^2}$$
$$\sigma_{new} = \sqrt{\sum_i (X_i - \mu_{new})^2 + (X_{new} - \mu_{new})^2}$$
$$\mu_{new} = \frac{\mu_{old}*N + X_{new}}{N+1}$$
$$\sigma^2_{new} = \sigma^2_{old} + \sum_i \left( (X_i - \mu_{new})^2 - (X_i - \mu_{old})^2 \right) + (X_{new} - \mu_{new})^2$$
After putting it in terms of the old stats, this becomes (I think)
$$\sigma^2_{new} = \sigma^2_{old} + \sum_i \left(2 X_i + \frac{(2N+1) \mu_{old} + X_{new}}{N+1} \right) \left(\frac{X_{new} - \mu_{old}}{N+1}\right) + (X_{new} - \frac{\mu_{old}*N + X_{new}}{N+1})^2$$
Is there anything better than this monstrosity?

A: Let's say you started with n points and have added an $(n+1)^{st}$.  To handle the variance write $\mu_{new} = \mu_{old} + \delta$ .  We see that we need to compute $$\sum_{i=1}^{n} (x_i - \mu_{new})^2$$  Where the sum is just taken over the old $x_i$'s (the contribution from the $(n+1)^{st}$ sample being easily incorporated. But $$(x_i - \mu_{new})^2 = (x_i - \mu_{old} - \delta)^2$$ So our sum becomes $$\sum_{i=1}^{n} (x_i - \mu_{new})^2 = \sum_{i}^{n} (x_i - \mu_{old})^2 - 2 \delta \sum_{1}^{n} (x_i - \mu_{old}) + n \delta^2 = \sum_{i}^{n} (x_i - \mu_{old})^2 + n \delta^2$$  Where the middle sum vanishes as the old x's sum to the old mean.
Combining all this (and trusting that no algebraic error has been made!) we see that $$Var_{new} = \frac{(x_{n+1}-\mu_{new})^2}{n+1}+ \frac{n}{n+1}Var_{old} + \frac{n}{n+1}\delta^2$$
Not too terrible!

A: If $\mu_n = \frac1n \sum_{i=1}^n x_i$,
$$\mu_{n+1} = \frac{1}{n+1}\sum_{i=1}^{n+1}x_i = \frac{1}{n+1}\big[x_{n+1} + \sum_{i=1}^nx_i\big] = \frac{x_{n+1}}{n+1} + \frac{n}{n+1}\mu_n$$
As you stated, the running sample standard deviation is much trickier. Check this link out: Incremental Mean and Standard Deviation Calculation
They provide derivations for the following incremental variance formula:
$$\sigma_{n+1}^2 = \frac{1}{n+1}\big[n\sigma_n^2 + n(n-1)(\mu_{n+1} - \mu_n)^2\big]$$


text:
Q: How to rendering to html in the viewsets in Django Rest Framework models.py
class MyVideo(models.Model):
    title = models.CharField(max_length=100, null=True, default='')
    seotitle = models.CharField(max_length=100, null=True, default='')
    keywords = models.CharField(max_length=150, null=True, default='')
    status = models.IntegerField(default=1)

serializers.py
class MyVideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyVideo
        fields = '__all__'

views.py
class My(viewsets.ModelViewSet):
    queryset = MyVideo.objects.all()
    serializer_class = MyVideoSerializer

    renderer_classes = (JSONRenderer, TemplateHTMLRenderer,)
    template_name = "my.html"

    def get(self, request, *args, **kwargs):
        # ??????

    def get_query(self):
        # ??????

urls.py
urlpatterns = [
    path('my/', views.My), # ???????? anything wrong here?
]

my.html

My video

    {% for d in data %}

{{ d.title }}
  # ?????? anything wrong here?

{{ d.seotitle }}

{{ d.keywords }}

    {% endfor %}

I have a MyVideo model which store several videos record in the database. What I wanna implement is that to display the information of those videos through the my.html.
e.g. http://127.0.0.1:8000/my/103 can access the video which id=103, and on this page display its fields (title, seotitle, keywords, etc.).
Any nice implementation or suggestion? Thanks!
**UPDATE

My video

    {{ data }}

A:    from django.shortcuts import render
    class My(viewsets.ModelViewSet):
        queryset = MyVideo.objects.all()
        serializeddata = MyVideoSerializer(queryset,many=true)

    renderer_classes = (JSONRenderer, TemplateHTMLRenderer,)
    template_name = "my.html"

    def get(self, request, *args, **kwargs):
        return render_to_response(template_name, {'data': serializeddata.data})
    #or use below
      #return render(
    #request,
    #template_name=template_name,
    #{'data': serializeddata}
#)

    def get_query(self):
        # ??????

UPDATE
models.py
"""
Definition of models.
"""

from django.db import models

# Create your models here.
class MyVideo(models.Model):
    title = models.CharField(max_length=100, null=True, default='')
    seotitle = models.CharField(max_length=100, null=True, default='')
    keywords = models.CharField(max_length=150, null=True, default='')
    status = models.IntegerField(default=1)

serializers.py
from rest_framework import serializers
from app.models import MyVideo

class MyVideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyVideo
        fields = '__all__'

my.html

My video

    {% for d in data %}

Title: {{ d.title }}

SEO Title:{{ d.seotitle }}

KeyWords {{ d.keywords }}

    {% endfor %}

views.py
def my(request):
    """Renders the contact page."""
    assert isinstance(request, HttpRequest)
    queryset = MyVideo.objects.all()
    serializer_class = MyVideoSerializer(queryset,many=True)
    #datan = {"title":"Test Title"}
    return render(
        request,
        'app/my.html',
        {
            'data':serializer_class.data,
        }
    )

NOTE: You can add if(request.method == GET): elif(request.method == POST)
OUTPUT:


text:
Q: How to use IR leds that is not working on Pi camera For a night vision camera, I bought NoIR Pi camera and IR leds(Can be attached to both sides of the camera).
But I found that my Pi camera doesn't have metal part on the attaching part. So I cannot use my IR leds with pi camera. Can I use it with pi's gpio? Actually I only need to turn on the leds, so I wonder if I can supply power to leds with raspberry pi or arduino's pins.
Additionally If I connect the leds with jumper cable or something, should I solder it or is it okay just tying it.

A: You can connect your leds to any DC power source, just be sure to limit the current by using a suitable series resistor to avoid destroying your leds. And don't look into them to prevent eye damage, as your eyes will not accomodate to invisible light.
In good approximation:
I = U / R
with:

*

*I is maximum allowed current trough LED (ampere)

*U is power supply voltage (volt)

*R is value of resistor (ohm)

Or more exact:
https://www.sparkfun.com/tutorials/219


text:
Q: Efeitos em links através do hover Galera, alguém sabe me dizer como faço esse efeito com hover?
Ao passar o mouse sobre o link do menu ele aparecer aquela linha vertical sobre o nome, só consegui com a linha horizontal abaixo do nome.
Ou então me dizer onde encontro exemplos, não encontrei nada sobre isso.

A: Você pode colocar um span invisível dentro de cada link que só vai aparecer quando o mouse passar sobre o link.
CSS:
body{ background: #000;}
a{ color: #fff;}
li{ padding: 0px; margin: 0px; list-style: none; display: inline-block; float: left; margin: 10px; position: relative;}
ul{ padding: 0px; margin: 0px;}
li span{
    display: none; width: 1px; background: #fff; position:absolute; bottom: 100%; height: 1000px; left: 50%; margin-left: -1px;
}

li:hover span{ display: inline-block;}

HTML:

        Link1

        Link2

Fiddle: https://jsfiddle.net/vqfr54w4/


text:
Q: how to execute multiple async queries in google app engine? I want to execute multiple queries asynchronously. Now for that I have searched but nothing special I found.
Ya one thing I found is of Asynctools at http://code.google.com/p/asynctools/
but in the code given i am getting the error
NameError: global name 'AsyncMultiTask' is not defined
and I dont kn what to import for that. so please anyone can help me for this

A: A couple of months ago Guido announced a new experimental datastore API, which allows asynchronous calls:
http://neopythonic.blogspot.com/2011/01/new-app-engine-datastore-api.html


text:
Q: Deploy a monthly job by add_interval_job() In APScheduler, I know I can deploy a montly job by using add_cron_job(): add_cron_job(my_job, day="2", kwargs=None), then the task will get executed on every 2nd of the month (1/2, 2/2, 3/2,...etc.)
My questions is: is it possible to achieve it by using add_interval_job()?

add_interval_job(func, weeks=0, days=0, hours=0, minutes=0, seconds=0,
  start_date=None, repeat=0, args=None, kwargs=None)

Based on the signature, looks like I can only have it execute every 4 weeks: add_interval_job(my_job, weeks=4) or every 30 days: add_interval_job(my_job, days=30), any ideas?


text:
Q: Django: more efficient to calculate in views or templates? This has almost certainly been asked here before, so apologies if it's a duplicate. I can't find the answer though :)
In Django, in general, is it more efficient to do calculations in the view, or in the template?
Here's a simple example. I want to put a particular string in the template, dependent on the value of an integer. I could do it in views.py:
# in views.py
description = "small"
if count > 10:
    description = "large"
elif count > 5:
    description = "medium"

Or I could do it this way in the template:
# in template.html
{{ count }}
({% if count > 10 %}large
{% else %}
{% if count > 5 %}medium{% else %}small{% endif %}
{% endif %})

In this case, the code is noticeably simpler in views, so perhaps that answers my question: but what I really want to know is, does it make a difference to efficiency to do it in either the template or the view?

A: I wouldn't say that this is a question of efficiency, but more of where the code fits using a MVC like pattern. If this is all about how to display something and not what the template is a suitable place for sure. If you'd say you modify what is displayed the view is the more suitable place!
If you'd say that this values are bound deeply to the model, you could also make a method on the model that you call from within the template. If you need the same functionality at other places it could also make sense to make a custom template tag for this purpose!
But keep in consideration that django isn't so strict about dealing with the original MVC pattern, and eg. templatetags pull a lot of functionality inside the template!

A: It depends what you mean by efficient.
The former version involves fewer function calls, because when logic is contained in a template, the strings must first be parsed into nodes and tokenized, before being executed.
However, the performance of both of those will be identical in a real-world context, as they are both very simple.
A broader interpretation of efficiency would include the maintainability of code, which is generally more readable and more easy to refactor when contained in the view (or model, where appropriate).
In either interpretation, it's best to move as much logic as possible out of the template and into view, controllers, or templatetags.


text:
Q: What is accessibility.AOM.enabled in Firefox about:config and Chrome chrome://flags? I counldn't find any clear explanation about accessibility.AOM.enabled
I have searched chrome and Firefox websites.

A: 'accessibility.AOM.enabled' is a preference in the Chrome browser that enables or disables the Accessibility Object Model (AOM). When the preference is set to true, the AOM is enabled and accessible to web pages. When it is set to false, the AOM is disabled and not accessible to web pages.
The Accessibility Object Model is a web standard that allows web developers to create web content that is more accessible to users with disabilities. It provides a way for web developers to programmatically modify the accessibility information of a webpage, such as the text labels and descriptions of elements, the focus order, and the relationships between elements. This can make it easier for users with disabilities to navigate and interact with web pages using assistive technologies, such as screen readers or keyboard-only navigation.
You can find the accessibility.AOM.enabled preference in the Chrome browser by going to chrome://flags in the address bar and searching for "Accessibility Object Model". You can then use the dropdown menu to enable or disable the preference.

A: To add on to @morteza's answer, the AOM (Accessibility Object Model) is a proposed structure, see https://wicg.github.io/aom/spec/.
It's similar to the DOM (document object model) in that it will allow to you access objects and change properties on them. The AOM will give you direct access to the accessibility tree.
Currently, you have to use setAttribute to change the value of ARIA attributes, for example:
acc1 = document.getElementById('accordionHeader1');
acc1.setAttribute("aria-expanded","true");

With the AOM, you'd be able to write more "object oriented" looking code:
acc1 = document.getElementById('accordionHeader1');
acc1.ariaExpanded = "true";

The reason you have to turn a flag on in Chrome/Firefox in order to access the AOM is because the AOM is still a work in progress/experimental.
I wouldn't write any production code that depends on the AOM.  For now, you have to add/set/change ARIA attributes using setAttribute() and removeAttribute().


text:
Q: SonarQube: how to revert the automatic author assignment made based on the SCM info The property sonar.scm.enabled was enabled by default and during the analysis a lot of issues were assigned to the same author, though this was not the real author of those issues.
This is because that git user was the responsible to migrate the code from a previous version control.
I want to know if is there any way to unassign all issues assigned to a specific author, using some kind of bulk change or a specific configuration during an analysis.
Sonar version: 5.1.2

A: You haven't mentioned your version of the SonarQube platform, so I'll assume 5.1.*.
In the Issues page, do an Assignee search, and then use Bulk Change to re/un-assign the results.


text:
Q: iPhone submission - The binary you uploaded was invalid Having gone through all the steps of submitting my app to the iStore by the book (and other manuals around), I get a 'not so funny' response after uploading my binary:
'The binary you uploaded was invalid. Fat binaries require a MinimumOSVersion of at least 3.0'
Now, I set the device deplyment to be 2.2.1 and the Base SDK the same.   My build SDK is 3.0 and I'm pretty sure I do not use anything which is in 3.0 but not in the 2.2.1 API (I built and ran on both and tested).
It might be nothing, or not - I do use XML parsing and some XML files in my application, again, I'm not even sure that it is connected ot the problem.
If you have any experience with that or have a clue it's be great,

A: Check the Info.plist of the binary that is produced. The file should have the following setting somewhere in it:
MinimumOSVersion XYZ

...where XYZ is the Deployment Target OS version you are trying to build for.
I have noticed in my own binaries that this line does not exist for binaries built for the iPhone Simulator. Given that, my suspicion is that you are trying to upload a binary built for the simulator instead of the device. Try changing the Active SDK to "iPhone Device 2.2.1" and submitting that binary to the App Store.

A: I had a similar issue and it was due to me zipping the file up (or trying to upload it) from a PC. I used 'compress' on the mac and uploaded using firefox for mac os and it worked fine.

A: This window becomes visible upon clicking on the root project name in the Xcode directory /groups tree, where you can change the:
! Deployment Target OS 8.1 and SDK declarations
Also, under the General tab is the Asset Catalog where the Icon migration and Launch screen file conversion takes place.


text:
Q: Can someone give me a push in the right direction? Java XML and ResultSet I am learning Java, and we have this task at school:
"XMLDecode this XML with the following class.."

Heres the XML-code:
https://www.dropbox.com/s/9nedam40v2q8wbr/XML.xml

Okey, I'll try to explain simply what my problem is:
I don't know how to get these contructors to "talk". If I set the ResultSet to null, theres a NullpointerException, but I don't know how to get a resultset from this.
This is how I have started..
    URL url;
    try {
        url = new URL("THE URL TO THE XML");
        XMLDecoder ois = new XMLDecoder(url.openStream());
                    // Can also do:
                    // XMLDecoder ois = new XMLDecoder(url.openStream(), new CachingResultSetTableModel());
        ois2.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

This is connecting fine
As I am trying my best to ask, is how to "connect" what I have just made, into a working Table-making code.
The code is located here:
https://www.dropbox.com/s/7xqkp6pb6zqyc21/CachingResultSetTableModel.java

A: ResultSet has nothing to do with your problem.
The XML you posted has a fixed, not self describing grammer.  Fixed means that there is a finite set of tags that are valid.  Not self describing means that the tags have implied meanings.

*

*Identify the grammar of the xml in question.  Clearly this will include "array", "object" and "void".  Probably other tags as well.

*Identify the meaning of each tag.

*Identify the properties of each tag.  For example, the "object" tag can have a property named "class"

*Identify the meaning of each property.  For example, the array tag has a property named "class".  This appears to indicate the type of element stored in the array.

*Write a SAX parser for the XML (check out this old tutorial: SAX Parser Tutorial).  Initially just print out the xml so you know it is parsing the XML correctly.  After the parser works, add the functionality for the tags and properties.

*Unless specifically instructed to do so, don't bother reading the XML from a url.  just get the file from the dropbox then store it to a local file.


text:
Q: Create equal groups of timings Pretty tricky one here. I have a data warehouse that runs different load jobs. I have all the load jobs in batches. I have the timings for all the load jobs and want a way to programmatically work out the best way to arrange the load jobs into separate batches to make them all finish around the same time.
My data looks like this:
NAME    TIME
AA_1    13:52.9
AA_2    10:37.8
AA_3    10:10.6
AA_4    09:07.7
AA_5    08:22.9
AA_6    04:29.3
AA_7    04:14.4
AA_8    03:56.3
AA_9    03:11.4
AA_10   02:59.3

As an example if I take AA_1 and AA_2 then their run time will be around 24 minutes. If I think take AA_3, AA_4 and AA_6 it'll be around 24 minutes too.
So basically I want to be able to specify that I want this to be split up into an n number of batches and then have the program work out the best groupings.
Any thoughts? I'm happy to do it in Python or SQL.
Thanks


text:
Q: CSS styles not getting applied I have a bootstrap project and I want to quickly change the span. So I have a span like that with my inline css:

                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                                Toggle navigation

                        </button>
                        Title

But the thing is that style is not getting applied, however I can see the styles using dev tools:

Moreover then if I disable/enable any tickbox like that:

Then all styles gets applied.
Any ideas is what is going on and how to fix that?

A: when I tried it, everything is working except padding-top. To apply padding-top, use
display: block

or
display: inline-block

Edit:
Not sure if you know this already but span is an inline element which means, margin and padding will not take effect. Hence, you need to explicitly add display:block or inline-block


text:
Q: Windows Explorer crashes whenever I view a folder with an MP4 (H.264) video file in 'Large Icons' view (shows thumbnails) Whenever I view a folder which contains .MP4 (H.264) video files in large icon view (shows thumbnails), Windows 7's Explorer crashes. Explorer loads for a few seconds, the green progress bar shows up, and then boom!, Explorer crashes. The thumbnails are not shown before crashing. Does anyone know how to fix this?
I tried setting Folder options to 'Always show icons, never thumbnails' (disables thumbnails) on the same folder with MP4 (H.264) video files and Explorer doesn't crash if the MP4 thumbnails aren't shown. I tried testing in other folders containing other video formats (with 'Always show icons, never thumbnails' set to off) like .AVI/Xvid, without an MP4/H.264 file, and Windows Explorer shows the thumbnails fine without crashing.
I have not currently experienced problems with other formats, only MP4/H.264. The only media players that I have installed are KMPlayer and VLC Media Player which both do not install external codecs, AFAIK. The only external codec I have installed is CoreAVC, but I have been using CoreAVC for months (KMPlayer+CoreAVC is one of the first things I installed in Windows 7) without any problems (this issue just arose a few days ago).
I am using Windows 7 Ultimate 32-bit.
Note: I prefer a solution that will not end up disabling video thumbnails for MP4 files. I still would like to see MP4 video thumbnails, if possible. If the video files themselves are problematic, I reckon Explorer should not crash and just not show the thumbnails.
Event Viewer log and HiJackThis log here:
Event Viewer log:

Faulting application name: Explorer.EXE, version: 6.1.7600.16450, time stamp: 0x4aeba271
Faulting module name: qedit.dll, version: 6.6.7600.16385, time stamp: 0x4a5bdad4
Exception code: 0xc0000005
Fault offset: 0x0005c832
Faulting process id: 0x600
Faulting application start time: 0x01cb917247cbd5d2
Faulting application path: C:\Windows\Explorer.EXE
Faulting module path: C:\Windows\System32\qedit.dll

Friendly view:

+ System

  - Provider

   [ Name]  Application Error

  - EventID 1000

   [ Qualifiers]  0

   Level 2

   Task 100

   Keywords 0x80000000000000

  - TimeCreated

   [ SystemTime]  2010-12-01T16:14:00.000000000Z

   EventRecordID 11098

   Channel Application

   Computer

   Security

- EventData

   Explorer.EXE
   6.1.7600.16450
   4aeba271
   qedit.dll
   6.6.7600.16385
   4a5bdad4
   c0000005
   0005c832
   600
   01cb917247cbd5d2
   C:\Windows\Explorer.EXE
   C:\Windows\System32\qedit.dll
   014e27a9-fd66-11df-a275-0015f2ac57c8

_______
HiJackThis log:

Logfile of Trend Micro HijackThis v2.0.4
Scan saved at 5:48:45 AM, on 12/2/2010
Platform: Windows 7  (WinNT 6.00.3504)
MSIE: Internet Explorer v8.00 (8.00.7600.16671)
Boot mode: Normal

Running processes:
C:\Program Files\Soluto\soluto.exe
C:\Windows\system32\Dwm.exe
C:\Windows\system32\taskhost.exe
C:\Program Files\Avira\AntiVir Desktop\avgnt.exe
C:\Program Files\NetWorx\networx.exe
C:\Program Files\cFosSpeed\cfosspeed.exe
C:\Program Files\Common Files\Java\Java Update\jusched.exe
C:\Program Files\Windows Sidebar\sidebar.exe
C:\Program Files\ATI Tray Tools\atitray.exe
C:\Program Files\DVD Tools\DAEMON Tools Lite\DTLite.exe
C:\Program Files\Launchy\Launchy.exe
C:\Program Files\Sizer\sizer.exe
C:\Program Files\Rainlendar\Rainlendar.exe
C:\Program Files\ObjectDock\ObjectDock.exe
C:\Program Files\Opera\opera.exe
C:\Program Files\TrueCrypt\TrueCrypt.exe
C:\Program Files\Common Files\Java\Java Update\jucheck.exe
C:\Program Files\System Utilities\PerfectDisk\PDAgentS1.exe
C:\Windows\system32\DllHost.exe
C:\Windows\explorer.exe
C:\Program Files\Notepad2\Notepad2.exe
C:\Windows\system32\SearchFilterHost.exe
C:\Program Files\HiJackThis\Trend Micro\HiJackThis\HiJackThis.exe

R1 - HKCU\Software\Microsoft\Internet Explorer\Main,Search Page = http://go.microsoft.com/fwlink/?LinkId=54896
R0 - HKCU\Software\Microsoft\Internet Explorer\Main,Start Page = http://go.microsoft.com/fwlink/?LinkId=69157
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Default_Page_URL = http://go.microsoft.com/fwlink/?LinkId=69157
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Default_Search_URL = http://go.microsoft.com/fwlink/?LinkId=54896
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Search Page = http://go.microsoft.com/fwlink/?LinkId=54896
R0 - HKLM\Software\Microsoft\Internet Explorer\Main,Start Page = http://go.microsoft.com/fwlink/?LinkId=69157
R0 - HKLM\Software\Microsoft\Internet Explorer\Search,SearchAssistant =
R0 - HKLM\Software\Microsoft\Internet Explorer\Search,CustomizeSearch =
R0 - HKCU\Software\Microsoft\Internet Explorer\Toolbar,LinksFolderName =
F2 - REG:system.ini: UserInit=C:\Windows\system32\userinit.exe,C:\Program Files\Soluto\soluto.exe /userinit
O2 - BHO: AcroIEHelperStub - {18DF081C-E8AD-4283-A596-FA578C2EBDC3} - C:\Program Files\Common Files\Adobe\Acrobat\ActiveX\AcroIEHelperShim.dll
O2 - BHO: Advertising Cookie Opt-out - {8E425EB4-ADBD-4816-B1E8-49BB9DECF034} - C:\Program Files\Google\Advertising Cookie Opt-out\opt_out.dll
O2 - BHO: Java(tm) Plug-In 2 SSV Helper - {DBC80044-A445-435b-BC74-9C25C1C588A9} - C:\Program Files\Java\jre6\bin\jp2ssv.dll
O3 - Toolbar: &NetWorx Desk Band - {FEEA54B4-D80F-41C7-87B9-DC08E6D3255F} - C:\PROGRA~1\NetWorx\deskband.dll
O4 - HKLM\..\Run: [avgnt] "C:\Program Files\Avira\AntiVir Desktop\avgnt.exe" /min
O4 - HKLM\..\Run: [NetWorx] "C:\Program Files\NetWorx\networx.exe" /auto
O4 - HKLM\..\Run: [cFosSpeed] C:\Program Files\cFosSpeed\cFosSpeed.exe
O4 - HKCU\..\Run: [Sidebar] C:\Program Files\Windows Sidebar\sidebar.exe /autoRun
O4 - HKCU\..\Run: [AtiTrayTools] "C:\Program Files\ATI Tray Tools\atitray.exe"
O4 - HKCU\..\Run: [DAEMON Tools Lite] "C:\Program Files\DVD Tools\DAEMON Tools Lite\DTLite.exe" -autorun
O4 - HKUS\S-1-5-19\..\Run: [Sidebar] %ProgramFiles%\Windows Sidebar\Sidebar.exe /autoRun (User 'LOCAL SERVICE')
O4 - HKUS\S-1-5-19\..\RunOnce: [mctadmin] C:\Windows\System32\mctadmin.exe (User 'LOCAL SERVICE')
O4 - HKUS\S-1-5-20\..\Run: [Sidebar] %ProgramFiles%\Windows Sidebar\Sidebar.exe /autoRun (User 'NETWORK SERVICE')
O4 - HKUS\S-1-5-20\..\RunOnce: [mctadmin] C:\Windows\System32\mctadmin.exe (User 'NETWORK SERVICE')
O4 - Startup: Rainlendar.lnk = C:\Program Files\Rainlendar\Rainlendar.exe
O4 - Startup: Stardock ObjectDock.lnk = C:\Program Files\ObjectDock\ObjectDock.exe
O4 - Global Startup: Launchy.lnk = C:\Program Files\Launchy\Launchy.exe
O4 - Global Startup: Sizer.lnk = C:\Program Files\Sizer\sizer.exe
O17 - HKLM\System\CCS\Services\Tcpip\..\{617D9698-114A-4664-B162-496A5CC7BECE}: NameServer = 8.8.8.8,8.8.4.4
O17 - HKLM\System\CS1\Services\Tcpip\..\{617D9698-114A-4664-B162-496A5CC7BECE}: NameServer = 8.8.8.8,8.8.4.4
O17 - HKLM\System\CS2\Services\Tcpip\..\{617D9698-114A-4664-B162-496A5CC7BECE}: NameServer = 8.8.8.8,8.8.4.4
O20 - Winlogon Notify: !SASWinLogon - C:\Program Files\SUPERAntiSpyware\SASWINLO.dll
O22 - SharedTaskScheduler: ObjectDockShellExt - {1984D045-52CF-49cd-DB77-08F378FEA4DB} - C:\Program Files\ObjectDock\ODMenu.dll
O23 - Service: Avira AntiVir Scheduler (AntiVirSchedulerService) - Avira GmbH - C:\Program Files\Avira\AntiVir Desktop\sched.exe
O23 - Service: Avira AntiVir Guard (AntiVirService) - Avira GmbH - C:\Program Files\Avira\AntiVir Desktop\avguard.exe
O23 - Service: Ati External Event Utility - ATI Technologies Inc. - C:\Windows\system32\Ati2evxx.exe
O23 - Service: cFosSpeed System Service (cFosSpeedS) - cFos Software GmbH - C:\Program Files\cFosSpeed\spd.exe
O23 - Service: Google Update Service (gupdate) (gupdate) - Google Inc. - C:\Program Files\Google\Update\GoogleUpdate.exe
O23 - Service: PDAgent - Raxco Software, Inc. - C:\Program Files\System Utilities\PerfectDisk\PDAgent.exe
O23 - Service: PDEngine - Raxco Software, Inc. - C:\Program Files\System Utilities\PerfectDisk\PDEngine.exe
O23 - Service: Remote Packet Capture Protocol v.0 (experimental) (rpcapd) - CACE Technologies, Inc. - C:\Program Files\WinPcap\rpcapd.exe
O23 - Service: Soluto PCGenome Core Service (SolutoService) - Soluto - C:\Program Files\Soluto\SolutoService.exe

A: Two options:

*

*Remove media preview, by typing in:
regsvr32 /u shmedia.dll

*From this page:

Click Start>Run, type REGEDIT and
  click Ok. Then make your way to this
  InProcServer32 key:
HKEY_LOCAL_MACHINE >SOFTWARE >Classes

CLSID > {87D62D94-71B3-4b9a-9489-5FE6850DC73E}>
    InProcServer32

Right click the InProcServer32 key and
  choose Delete. And that's all there is
  to it. This will prevent Windows from
  loading shmedia.dll when you work with
  video files and thus you should no
  longer have problems deleting or
  moving any video files. Also if you
  have a video file you can't delete
  now, deleting this key will allow you
  to do so. If not, log out and log in
  again to delete the file.

A: This problem seems to be caused by Haali Media Splitter (checked by default to be included with CoreAVC's installer). I've uninstalled it and I get no crashes so far.
Edit:
I'd like to add that this could be caused by other types of splitters installed in Windows 7. To troubleshoot this, try uninstalling the splitters and see if this fixes the issue.

A: It might be RealPlayer. IF you have it, uninstall it.
Nirsoft's ShellExView helped me find it (sort by thumbnail and see which extension are associated with it)

A: The solution for me was to set the folder properties to "Optimize for Documents". It was set for "General Items" which is probably like an "Automatic" feature where Windows detects what type of files are in it. If it is set for "Video" or "General Items", Windows will try to analyze the videos for durations, etc, etc which can take a long time if you have large or numerous videos. If you set it to "Documents" it treats it like a DOC folder. Once you change the properties be sure and back out and reselect the folder to see the change.
To set the properties of a folder simply right click anywhere in the folder window and select properties->Customize and under "What kind of folder do you want?" change it to "documents".

A: Try stop Windows Search Service as "@Stephen Rauch" suggested.

*

*Type: services

*Enter

*Browse for "Windows Search"

*Right click mouse then select "Stop"

My explorer work properly again

A: Try stopping Windows Search under Services in the Admin Console. You'd be amazed how that simple step makes Windows Explorer work properly again.


text:
Q: Boundary of subset of the space of continuous functions Let $T>0$ and $\Omega = (0,1) \times (0,2)$ and consider the set $X = C([0,T];C(\overline \Omega)) \sim C([0,T]\times \overline \Omega)$ which is the set of continuous functions $f: [0,T] \times \overline \Omega \to \mathbb{R}.$ I work in the uniform convergence norm, i.e., $$\|f\| = \sup\limits_{(t,x) \in [0,T] \times \overline \Omega} |f(t,x)|$$
Now, let $r, R \in \mathbb{R}$, $r < R$ and define $$K = \{ f \in X; r \leqslant f(t,x) \leqslant R, \forall (t,x) \in [0,T] \times \overline \Omega\}.$$
I am trying to compute $\partial K.$ I know that $f \equiv r$ and $f \equiv R$ belong to $\partial K$, but they are not the only ones, are they?

A: Let $$U = \{ f \in X; r < f(t,x) < R, \forall (t,x) \in [0,T] \times \overline \Omega\}.$$ Consider any $f\in U$.
Then, since $f$ has a minimum and maximum, we can define
$$
m:=\min\{ f(t,x):t,x\in [0,t]\times\overline\Omega\},
\quad
M:=\max\{ f(t,x):t,x\in [0,t]\times\overline\Omega\}.
$$
We get $r<m\leq M<R$. If $g$ is a function satisfying $\|f-g\|<\rho$, where $\rho=\min\{m-r,R-M\}$ then $g\in U$. This shows that $U$ is open.
Similarly one can prove that $K$ is closed.
This shows that $\partial K\subset K\setminus U$. Let's prove the converse. Consider $f\in K\setminus U$, i.e.
$r \leq f(t,x) \leq R$, for all  $(t,x) \in [0,T] \times \overline \Omega$ but for some $(t,x)$ we get the equality $f(t,x)=R$ or $f(t,x)=r$.

*

*If $f(t,x)=R$ then the function $f_n(x)=f(x)+\frac 1n$ is very close to $f$ but it doesn't belong to $K$. Therefore $f\in\partial K$.

*If $f(t,x)=r$ then the function $f_n(x)=f(x)-\frac 1n$ is very close to $f$ but it doesn't belong to $K$. Therefore $f\in\partial K$.

We got that $$\partial K = K\setminus U = \{ f \in K; f(t,x)\in\{r,R\}\text{ for some } (t,x) \in [0,T] \times \overline \Omega\}.$$


text:
Q: Some formula related with factor of (a+b+c+d) I am looking for some math formula
For example
\begin{align}
& a^2 -b^2 = (a+b)(a-b) \\
&a^3 +b^3 + c^3 - 3abc = (a+b+c)(a^2+b^2+c^2 - ab-bc-ca)
\end{align}
First one related with factor a+b and the second one related with factor a+b+c
then
How about some formula related with a,b,c,d
i.e., is there are some equation factors into (a+b+c+d)?

A: It will be probably
$$a^4+b^4+c^4+d^4-b^2a^2-c^2a^2-d^2a^2-b^2c^2-b^2d^2-d^2c^2+16abcd=(a+b+c+d)(a^3+b^3+c^3+d^3-ba^2-ca^2-da^2-ac^2-bc^2-dc^2-ab^2-cb^2-db^2-ad^2-bd^2-cd^2+4bca+4bda+4cad+4bcd)$$
OR

$$\sum a^4 -\sum a^2b^2 +16abcd=(\sum a)(\sum a^3-\sum ab^2 +4\sum abc)$$
  $$$$
  $$\sum \text{ represents cyclic summation}$$

A:
$$\begin{align}
& a^2 -b^2 = (a+b)(a-b) \\
&a^3 +b^3 + c^3 - 3abc = (a+b+c)(a^2+b^2+c^2 - ab-bc-ca)
\end{align}$$

The two relations are not quite "alike" since the second one is symmetric in $\,a,b,c\,$ (i.e. stays invariant if you permute the variables), while the first one is not (both sides change sign). Maybe a better analog would be for the first relation to be written as $\,a^2+b^2+2ab=(a+b)^2\,$.
With that note, the two equalities duplicate the Newton's identities for $\,n=2\,$ and $\,n=3\,$, respectively (where $p_k$ are the $k^{th}$ power sums, and $e_k$ the elementary symmetric polynomials):
$$
\begin{align}
p_2 + 2 e_2 &= e_1 p_1 \\
p_3 - 3 e_3 &= e_1 p_2 - e_2 p_1 = e_1(p_2-e_2)
\end{align}
$$
The next identity for $\,n=4\,$ would then be:
$$
p_4 + 4 e_4 = e_1 p_3 - e_2 p_2 + e_3 p_1 = e_1(p_3+e_3) - e_2 p_2
$$
$$
\begin{align}
\iff a^4+b^4+c^4+d^4 + 4 abcd &=  (a+b+c+d)(a^3+b^3+c^3+d^3+abc+abd+acd+bcd) \\ &\quad - (a^2+b^2+c^2+d^2)(ab+ac+ad+bc+bd+cd)
\end{align}
$$


text:
Q: Selecting rows in a DataFrame based on Time of the day? I have a DataFrame with Datetime as my index_col. This data is for 14 days. I want to create two different DataFrames based on the time of day:  data between 6 am and 18 pm of all days as one df and data between 18 pm and 6 am of all days in another df. How to extract?
Below is my Dataframe screenshot

A: try using
for df1
df1=df.between_time('06:00', '18:00')

for df2
df2=df.between_time('18:00', '06:00')

more about it here


text:
Q: C++ If ("Char" == "value") { do I'm trying to get the html code of webpage and check the value of this code.
I have this code, it not have errors but it not works, I want that if the code of the web its for example "test", the program do an action. But now the program don do anything.
There is my code:
void GetPage()
{
   std::string check_command_link = ("test.php?HWID=" + name());
    HINTERNET hInternet = InternetOpenA("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    HINTERNET hConnection = InternetConnectA(hInternet, "127.0.0.1", 80, " ", " ", INTERNET_SERVICE_HTTP, 0, 0);
    HINTERNET hData = HttpOpenRequestA(hConnection, "GET", check_command_link.c_str(), NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0);
    char buf[2048];
    string lol;
    HttpSendRequestA(hData, NULL, 0, NULL, 0);

    DWORD bytesRead = 0;
    DWORD totalBytesRead = 0;
    while (InternetReadFile(hData, buf, 2000, &bytesRead) && bytesRead != 0)
    {
        buf[bytesRead] = 0;
        lol = lol + buf;
        if (buf == "test") {
            //DO AN ACTION
            printf("Content;Test");
       }
        totalBytesRead += bytesRead;
    }

    InternetCloseHandle(hData);
    InternetCloseHandle(hConnection);
    InternetCloseHandle(hInternet);
}

Thanks!


text:
Q: Select data attribute within object tags for an SVG I have a relatively large SVG file, so much so that I would not like to put the entire XML code into my html file. As such, I have been using the object tags to refer to it and implement effects such as changing the transparency within css.
However, I would now like to use some javascript to select this object element and when clicked, change the data attribute to load a different SVG file (essentially alternating between images).
This is a trivial operation using normal img tags but the same approach doesn't seem to work using the object tags.
Here's what I have so far:

A Gathering of ...

        <object id="trooper" data="images/trooper.svg" type="image/svg+xml"></object>

For the html, and for the javascript:
addEventListener("load", start);
// else { attachEvent("onload", start); }

function start(){
    var logo = document.querySelector("#trooper");
    logo.addEventListener("click", logoChange);
}

function logoChange(){
    console.log("Clicked");
    var src = this.getAttribute("data");

    if(src === "images/trooper.svg"){
        this.setAttribute("data", "images/rebel.svg");
    } else {
        this.setAttribute("data", "images/trooper.svg");
    }
}

Thanks

A: the problem is you are using this inside of the logoChange function.
you will have to use the logo variable for getting and setting values.

A: I would just use the img Tag and avoid the object (don't know the current status, but when I messed around it with Flash some years ago ... strange things happened quite too often):

An then just change the source like you used to do ...
(but you can't have JS inside you SVG with img)


text:
Q: UIToolbar goes under status bar in iOS7 I have a UIView and I have a UIToolbar and UIWebView.
I want to show toolbar at top of UIView and after that the rest of page covered with webView.
But toolbar goes under status bar like this

How can I correct it in iOS7.

A: Set up toolbar delegate to your view controller and implement method:
- (UIBarPosition)positionForBar:(id <UIBarPositioning>)bar {
    return UIBarPositionTopAttached;
}

A: 1) Set the toolbar Y position to 20 (in the interface builder or in the code)
2) Set the toolbar delegate
3) In your toolbar delegate implement:
- (UIBarPosition)positionForBar:(id <UIBarPositioning>)bar
{
    return UIBarPositionTopAttached;
}

A: The only correct solution in 2k17 is to attach your toolbar/navigationBar to leading/trailing of your superview, top to topLayoutGuideBottom and to implement positionForBar:. This will produce correct result on all devices.


text:
Q: Why the moon doesn't fall down to earth? Why the moon doesn't fall down to the earth?
We know that the moon travels in speed perpendicular to the gravity of the earth so that it doesn't fall down to earth. But what if we supposed that the moon is stationary and the earth is stationary also but rotating around its axis?
I drawn the attached two charts to explain my question:

A: If the earth and moon were both stationary initially, the moon would fall into the earth as you said. But they were not. Earth was moving around the sun when the moon was formed from the earth. And so the moon also started revolving around the earth. Infact even now the moon is falling towards the earth, but the earth is continually moving away so that the moon has to continually change the direction of it's fall.


text:
Q: Samba: connecting to a DFS share using smbclient I have a problem connecting to a DFS share using smbclient. It does work using mount -t cifs.
Namely, when I do
sudo mount -t cifs //<dfs-url>/<service> ~/mountpoint/ -o username=<username>

things work perfectly. However, doing
smbclient //<dfs-url>/<service> -U <username> -W <workgroup>
Enter <username>'s password:
Domain=[<domain>] OS=[Windows Server 2012 R2 Datacenter 9600] Server=[Windows Server 2012 R2 Datacenter 6.3]
tree connect failed: NT_STATUS_BAD_NETWORK_NAME

I would expect that if I can connect using a cifs mount, I should be able to connect using smbclient.
Am I doing something wrong with the smbclient invokation?
Has anbody managed to connect to a DFS share using smbclient?

A: The error "tree connect failed: NT_STATUS_BAD_NETWORK_NAME" is because the path is not correct.
Example:
Path = //<dfs-url>/data/share1
Path = //<dfs-url>/data/share2
When mounting cifs, you can mount //<dfs-url>/data and see both shares.
With smbclient you only can use //<dfs-url>/data/share1 or share2


text:
Q: Swift: Why does UInt.max == -1 As the title states, lldb reports the value of UInt.max to be a UInt of -1, which seems highly illogical. Considering that let uint: UInt = -1 doesn't even compile, how is this even possible? I don't see any way to have a negative value of UInt at runtime because the initializer will crash if given a negative value. I want to know the actual maximum value of UInt.

A: The Int value of -1 and the UInt value UInt.max have the same bit representation in memory.
You can see that if you do:
let i = Int(bitPattern: UInt.max)  // i == -1

and in the opposite direction:
if UInt(bitPattern: Int(-1)) == UInt.max {
    print("same")
}

Output:

same

The debugger is incorrectly displaying UInt.max as a signed Int. They have the same bit representation in memory (0xffffffffffffffff on a 64-bit system such as iPhone 6 and 0xffffffff on a 32-bit system such as iPhone 5), and the debugger apparently chooses to show that value as an Int.
You can see the same issue if you do:
print(String(format: "%d", UInt.max))  // prints "-1"

It doesn't mean UInt.max is -1, just that both have the same representation in memory.

To see the maximum value of UInt, do the following in an app or on a Swift Playground:
print(UInt.max)

This will print 18446744073709551615 on a 64-bit system (such as a Macintosh or iPhone 6) and 4294967295 on a 32-bit system (such as an iPhone 5).
In lldb:
(lldb) p String(UInt.max)
(String) $R0 = "18446744073709551615"
(lldb)

A: This sounds like an instance of transitioning between interpreting a literal value under Two's Complement and Unsigned representations.
In the unsigned world, a binary number is just a binary number, so the more digits that are 1, the bigger the number, since there is no need to encode the sign somehow. In order to represent the largest number of signed values, the Two's Complement encoding scheme encodes positive values as normal provided the most extreme bit is not a 1. If the most extreme bit is a 1, then the bits are reinterpreted as described at https://en.wikipedia.org/wiki/Two%27s_complement.
As shown on Wikipedia, the Two's Complement representation of -1 has all bits set to 1, or the maximal unsigned value.


text:
Q: JAXB Unmarshal List of Interfaces I am trying to wrap 2 Classes, that are built following the Composite pattern, with JAXB.
The whole thing i built like this:
public interface ICriterion {String somemethod(String arg);}

@XmlRootElement(name = "criterion")
@XmlAccessorType(XmlAccessType.FIELD)
public class Criterion implements ICriterion {
    @XmlElement String name;
    @XmlElement String data;
    //getter, setter, somemethod(), Criterion(), Criterion(String, String)
}

@XmlRootElement(name = "criteria")
@XmlAccessorType(XmlAccessType.FIELD)
public class Criteria implements ICriterion {
    @XmlAnyElement(lax=true)
    private final List<ICriterion> criteria;
    //getter, setter, somemethod(),
    Criteria(){criteria = new ArrayList<>();}
    Criteria(List<ICriterion>)...
}

i took this solution from this answer
It works fine for marshalling - i can provide a Criteria, which contain a list of Criteria and Criterions, it gets marshaled to xml correctly.
What does not work however is unmarshaling a string to an Object
String request =
<criteria>
    <criteria>
        <criterion>
            <name>number1</value>
            <data>123123</token>
        </criterion>
        <criterion>
            <name>number2</value>
            <data>1223323</token>
        </criterion>
    </criteria>
    <criterion>
        <name>number3</value>
        <data>1212</token>
    </criterion>
</criteria>

JAXBContext ctx = JAXBContext.newInstance(Criteria.class, Criterion.class);
    StringReader reader = new StringReader(request);
    Criteria wrapped = (Criteria) ctx.createUnmarshaller().unmarshal(reader);

gives:
java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)

I've tried other ways that are avaiable through online sources like:
@XmlElementRefs({ @XmlElementRef(type=Criterion.class), @XmlElementRef(type=Criteria.class)})

@XmlElements({@XmlElement(type=Criteria.class),@XmlElement(type=Criterion.class)})

which do not give an error, but result in the List being empty instead. The solution to this problem, is using @XmlAnyElement(lax=true), which does not work for me.
My first guess was, that somehow the List is not initialized correctly in my Constructor and JAXB uses some kind of fixed size list.
My countermeasure was to explicitly initialize the list in the no-Args constructor
Criteria(){criteria = new ArrayList<>();}

The problem also is not solved by explicitly making "critera" an ArrayList<> instead of List<>.
What am I missing?


text:
Q: delete a property of object using Vue attribute given by DOM I am using v-for with node variable that runs on all properties in TreeObject object.
How can I delete one of the properties having only this node in my hand? (assume the function can't access TreeObject)
HTML:

{{ node.name }}

  <button @click="Delete(node)">delete</button>

Script:
[...]
methods: {
  Delete(node) {
    // somehow I want to delete node from TreeObject
  }
}

A: Assuming TreeObject is an Array of Objects and their only defining identifier is their name property - use that property to filter out the node-in-question.
If TreeObject is a prop on the Component (read-only) - Make a copy of TreeObject and set it to a data property of say DynamicTreeObject and use that property in the template
Or use a callback prop like onDelete to pass the node-in-question out to the parent Component that has access to the original TreeObject and make your deletions there, then the data will trickle down to your child Component.

Delete (node) {
  this.TreeObject = this.TreeObject.filter(n => n.name !== node.name)
}


text:
Q: The Set of integer multiples of two irrational numbers is dense in reals? Let $\alpha , \beta $ be the linearly independent irrational numbers over $\mathbb Q$ with $\alpha > \beta > 0 $ , and $\mathrm A=\{n\alpha-m\beta \mid  n,m  \text{ are nonnegative integers}  \}$
How to prove that $\mathrm A$ is dense in $\mathbb R$ ? Is it true?

A: Note that

*

*$A$ is closed under addition

*$\inf A=-\infty$

*$\sup \{\,x\in A\mid x>0\,\}=0$.

The first is trivial, the second follows from $\beta>0$, and only the third involves the $\Bbb Q$-linear independence of $\alpha,\beta$.


text:
Q: Preload an entire Bootstrap carousel Long time reader, first time poster.
I have recently started learning to use bootstrap.
I am stuck trying to get the a Bootstrap carousel to preload showing a spinning wheel (or similar effect).
I have pieced together the effect I'm going for, my first four images 'flick through' and the carrousel stops on my final image – but what I can't manage is to have the entire carousel content load behind a spinning wheel before the carousel starts.
This is my work in progress – http://maxsendak.com/test/pu_v2/max.html – so you can see, it is the whole header tag that needs to load with a 'load in progress' before it fires the carousel script and starts flicking through the slides.

Max Wilson

Creative

See More

Script to fire carousel needs to fire after everything is loaded.

As is often the case when I'm learning my way around these things, I think it might be that I am missing something simple – is this the case?

A: Remove the data-ride="carousel" - this is what triggers the carousel to start moving at page load. Instead you can start the carousel manually with javascript whenever you are ready with
$('.carousel').carousel()

Note - if you want to wait till your images have all loaded. You'd put this manual start in a window load like so
$(window).load(function() {
     // + any other carousel related stuff that has to wait for the images to complete loading
     $('.carousel').carousel()
})

A: jQuery solution would be adding d-block to all .carousel-item elements, and placing this at the bottom, after  tag:
$(window).on("load",function() {
     $('.carousel-item').removeClass("d-block");
})


text: Q: Sonar Quality Profile for JavaScript is Empty Quick question with regards to Sonar and JavaScript.  I was able to get examples of JsTestDriver and Jasmine working with Maven - Hudson - Sonar (code coverage and tests).  The only piece I am missing is the rules violations report.  When I look at sonarsource's doc/post on the JavaScript plugin, it says that it comes with 60 default rules.  But when I install the SonarQube JavaScript plugin and then go into my Quality Profiles (selecting the "Sonar way"), there are no rules within this profile.  I assume this is why I am not seeing metrics produced within my project and so I was wondering does the SonarQube JavaScript plugin come with the 60 default rules described within the sonarsource site?  Or do I need to create all my JavaScript rules?


text:
Q: Leaflet legend colours not showing in Chrome I am having trouble with Chrome
In Chrome, this example works for me
http://leafletjs.com/examples/choropleth/
When I apply this code to a custom map and open it with google chrome, the first colour gets applied and then all remaining colours are classed as colour #2. The HTML/CSS is correct, but it is not applying. It works fine on Firefox, Safari & Chrome on mobile, and it even works fine on other peoples Chrome, but the legend is not working on my chrome in development environment (running on virtual box) or production.
I have tried deleting cookies, application data and chrome is up to date and same version but the code is not being applied properly.
Anyone have a suggestion?
Thanks!

A: Yes, this worked for me. Turning hardware accelaration off brings back the colorscale in the legend.


text:
Q: can not update the actual quantity value in asp.net core 2.2 I am trying to update the quantity in the index method. but the index view's input submit button cannot work for that data can not bind. still, quantity no update and I show the value of quantity which I already used. but I want to update this.
Here Is My Code
namespace Amazon.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class ShopController : Controller
    {
        private ApplicationDbContext _db;
        private IHostingEnvironment _he;

        public ShopController(ApplicationDbContext db, IHostingEnvironment he) //input parameter
        {
            _db = db;
            _he = he;
        }

        public IActionResult Index()
        {
            return View(_db.Shop.Include(c => c.Category).Include(f => f.SubCategory).ToList());
        }

        [HttpPost]
        public async Task<IActionResult> Index(Shop shop)
        {
            _db.Shop.Update(shop);
            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

    @using Amazon.Models
    @model IEnumerable<Shop>
    @{
        ViewData["Title"] = "Index";
    }

Product List

             Add New Product

    <form asp-action="Create" method="post" enctype="multipart/form-data">

                            @Html.DisplayNameFor(c => c.Name)

                            @Html.DisplayNameFor(c => c.Price)

                            @Html.DisplayNameFor(c => c.PreviousPrice)

                            @Html.DisplayNameFor(c => c.Quantity)

                            @Html.DisplayNameFor(c => c.Description)

                            @Html.DisplayNameFor(c => c.Size)

                            @Html.DisplayNameFor(c => c.CategoryTypeId)

                            @Html.DisplayNameFor(c => c.SubCategoryTypeId)

                    @foreach (var item in Model)
                    {

                              @item.Name
                              @item.Price
                              @item.PreviousPrice
                            @*@item.Quantity	*@

                                    <input type="submit" value="-" class="button-minus" data-field="quantity">
                                    <input type="submit" step="1" max="" value="@item.Quantity"  name="quantity" asp-for="@item.Quantity" class="quantity-field">
                                    <input type="submit" value="+" class="button-plus" data-field="quantity">

                              @item.Description
                              @item.Size
                              @item.Category.CategoryName
                              @item.SubCategory.SubCategoryName

                                <partial name="_DeletePartial" model="@item.Id" />

                    }

    </form>

    @section scripts{

    }

my output is

when I update quantity these using spinner then it does not update the actual value of the quantity.
I am beginner, please help anyone.

A: If you want to save the value changed by your click on the button to the database, I think you can do so.
View.cshtml:

                        <input type="submit" value="-" class="button-minus" data-field="quantity">
                        <input type="submit" step="1" max="" value="@item.Quantity" name="quantity" asp-for="@item.Quantity"class="quantity-field">
                        <input type="submit" value="+" class="button-plus" data-field="quantity">
                        <input type="hidden" name="Id" value="@item.Id" data-field="quantity"/>

js in view:
 $('.input-group').on('click', '.button-plus', function (e) {
            incrementValue(e);
            var fieldName = $(e.target).data('field');
            var parent = $(e.target).closest('div');
            var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
            var id = parseInt(parent.find('input[name=Id ]').val());
            $.ajax({ url: 'blogs/test', type: 'get', data: { "value": currentVal ,"id":id}, dataType: 'json', success: function (data) { console.log(data) } })
        });

        $('.input-group').on('click', '.button-minus', function (e) {
            decrementValue(e);
            var fieldName = $(e.target).data('field');
            var parent = $(e.target).closest('div');
            var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
            var id = parseInt(parent.find('input[name=Id ]').val());
            $.ajax({ url: 'blogs/test', type: 'get', data: { "value": currentVal, "id": id}, dataType: 'json', success: function (data) { console.log(data) } })
        });

controller:
public IActionResult  Test(int id,int value)
        {
            var blog=_context.Blogs.Find(id);
            blog.Quantity = value;
            _context.SaveChanges();
            return Json("ok");
        }
        public async Task<IActionResult> Index()
        {
           return View(await _context.Blogs.ToListAsync());
        }

result:


text:
Q: [UITableViewSectionElement release]: message sent to deallocated instance I have spent a great deal of time trying to debug this error. When Zombie is enabled, this is printed on the console. I am very careful to not release things when I shouldn't. The main issues with debugging this is that:

*

*It happens seemingly randomly

*I don't know what a UITableViewSectionElement is and can't find any resources on the internet to tell me

*The stack traces in zombie or just running with zombie enabled don't include any part of my code

Does anyone know what UITableViewSectionElement's are? Has anyone seen this and may know how to fix it?
Replies are greatly appreciated.


text:
Q: Fenster FensterVideoView Android is only playing sound, no video I'm trying to display a video in Android using Fenster and i only get audio so far.  The video does not play but i can hear the audio.
My xml file is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/llShowDrop"
    android:background="#FFF">

    <com.malmstein.fenster.view.FensterVideoView
        android:id="@+id/play_video_texture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:keepScreenOn="true"
        android:fitsSystemWindows="true"
        android:visibility="visible" />

    <com.malmstein.fenster.controller.SimpleMediaFensterPlayerController
        android:id="@+id/play_video_controller"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:animateLayoutChanges="true"
        android:fitsSystemWindows="true"
        android:visibility="visible"
        android:layout_above="@+id/llLastComment" />

</RelativeLayout>

My .java file is:
final FensterVideoView textureView = (FensterVideoView) llShowDrop.findViewById(R.id.play_video_texture);
final SimpleMediaFensterPlayerController playerController = (SimpleMediaFensterPlayerController) llShowDrop.findViewById(R.id.play_video_controller);

textureView.setMediaController(playerController);
textureView.setVideo("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4", playerController.DEFAULT_VIDEO_START);
textureView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
     @Override
     public void onPrepared(MediaPlayer mp) {
           textureView.start();
     }
});

playerController.setVisibilityListener(new FensterPlayerControllerVisibilityListener() {
     @Override
     public void onControlsVisibilityChange(boolean value) {
           setSystemUiVisibility(value, playerController);
     }
});;

Does anyone know why this isn't playing video and only playing audio?
Thanks in advance for the help!

A: Turns out the emulator has trouble playing videos.  I tested it on my Samsung and it worked perfectly.


text:
Q: How can an if code block continue from where while loop left off in such cases? I don't have any experience with coding at all and I have just started learning Python.
In John Guttag's book "Introduction to Computation and Programming Using Python With Application to Understanding Data", at the beginning of chapter 3, there is a code example:
#Find the cube root of a perfect cube
x = int(input('Enter an integer: '))
ans = 0
while ans**3 < abs(x):
    ans = ans + 1
if ans**3 != abs(x):
    print(x, 'is not a perfect cube')
else:
    if x < 0:
        ans = -ans
    print('Cube root of ' + str(x) + ' is ' + str(ans))

What I have a hard time understanding is how "if" outside of "while" can pick up from where the loop left off with the iteration? If it is because of the last iteration of ans which gets it out of the loop and also satisfies the if condition, how does the if condition work for the values of ans and thus x inside the loop?(ans^3 is not equal to x only inside the while loop, how come can this part work:
 if ans**3 != abs(x):
     print(x, 'is not a perfect cube')

I really don't know how else to ask this but this is the code that I came up with before I peeked at the code in the book, it worked, and maybe it wil help to clarify what I am exactly asking:
x=int(input('Enter an integer: '))
crx=0

while True:
    if crx**3<abs(x):
        crx=crx+1
    elif crx**3==x:
        print('The cube root of',x,'is',str(crx)+'.')
        break
    elif crx**3==-x:
        print('The cube root of',x,'is',str(-crx)+'.')
        break
    else:
        print(x,'is not a perfect cube.')
        break

In my mind, somehow, I had to insert the if code blocks inside the while loop...
Thank you in advance.

A: This is not a consequence of if going back to the while loop. Let's examine the control flow:
x is being set as an integer from string input
ans is initialized with value 0, an int
x = int(input('Enter an integer: '))
ans = 0

To check if something has a cube root, the while loop takes every integer greater than 0 and cubes it, if the cube is less than x, then we increase ans by 1, otherwise, ans is saved and the while loop exits. Note, the otherwise covers if the cube is greater than or equal to x.
while ans**3 < abs(x):
    ans = ans + 1

If the resulting ans is equal to x, then x has a cube root. If it is not, then x is not a cube root.
if ans**3 != abs(x):
    print(x, 'is not a perfect cube')
else:
    if x < 0:
        ans = -ans
    print('Cube root of ' + str(x) + ' is ' + str(ans))

A: In simple terms - the loop makes sure the value of ans is the lowest (non-negative) integer whose cube is greater than or equal to x. Note the following consequence:

*

*if x is a perfect cube, then the final value of ans will be exactly that cube root (because we know that ans**3 must be equal to x.

*If x is not a perfect cube, then the final value of ans must be such that ans**3 is strictly greater than x. In particular, it will not be equal to it.

So the calculation is purely done in the while loop - and after this, the if checks if you calculated an exact cube root, or whether you don't (in which case this was never possible, because x was not a perfect cube). And of course it prints an appropriate message to the user in either case.
(I just saw the edit with your own solution - yes, as you observed, that also works fine. There is rarely only one way to solve a problem with code.)


text:
Q: The stateSave in jQuery DataTables is not working when loading data table for the first time The stateSave in jQuery DataTables is not working when loading data table for the first time, it loads filter data of previous state. It works fine after first load.
For example- If I have performed filter search and logout & login again in the application or update the cache and load this data table again then filter value of previous search will be visible and if there was nothing in previous search then value of filter will be blank. And next search onwards the filter works fine.
jQuery('#tableName').dataTable( {
    "Destroy": true,
    "Paginate": true,
    "StateSave": true,
    "StateDuration": 0.1
});

A: stateDuration defines the mode of storage as well as the duration in seconds after which the saved state will be invalidated. This should be an integer (see https://datatables.net/reference/option/stateDuration), so the behaviour with provided value 0.1 is undefined.
All the options are named in camelCase. Paginate does not exist, you probably mean paging.
jQuery('#tableName').dataTable( {
    destroy: true,
    paging: true,
    stateSave: true,
    stateDuration: -1
});

Fiddle
For an overview of all the options see https://datatables.net/reference/option/.