Q: Injecting application level dependency into node module I'm trying to create package from higher order components that are currently in application.
The issue is that in some of those components application routes are being used ( through helper that imports all the routes and returns url based on route name ).
I have no idea how to inject those routes to my module from app level.
For example in Symfony ( PHP ) this issue would be fairly simple, due to dependency injection. But with imports inside each file I'm really lost here.
I'm using NextJS and here is code sample ( I would love to inject those routes instead of directly importing them ):
import { routes } from "../../routes";

export default (routeName, params) =>
  routes.find(route => route.name === routeName).toPath(params);

A: You could build your own dependency injection module.
Using NodeJs it's fairly simple to do.
This one for instance.


Q: Can I create an HTML list in a D3.js SVG container Here is the code I am working on. I want to plot events for a certain year as an unordered list.
Is it possible to do using d3.js?
Code-
var mevent = svg.append("text")
        .attr("class", "year mevent")
        .attr("text-anchor", "end")
        .attr("y", height - 450)
        .attr("x", width - 300)
        .attr("width", 1000)
        .attr("height", 200)
        .text("");

  // Updates the display to show the specified year.
  function displayYear(year) {
    dot.data(interpolateData(year), key).call(position).sort(order);
    year = Math.round(year);
    label.text(year);
    price.text("$ " + iacprices[year]);
    mevents_text = "";
    for (var i = 0; i < (mevents[year]).length; i++) {
        mevents_text = "*" + mevents_text
        + (mevents[year])[i];
    }
    mevent.text(mevents_text);

A: Yes, you can place HTML elements in a SVG with a foreignObject.
Example w/ d3


Q: SQL Server SMO script generation throwing deadlock error I have a huge database with nearly 16k tables. Some of these tables are transnational tables and always receive some insert/select/update queries.I am using SMO to transfer the definition of all these 16K tables to some test database. But my code is failing while scripting tables and throwing deadlock issue (especially while copying those transaction heavy tables). I was just wondering "why deadlock" as SMO internally use some SYS tables to extract definition and shouldn't be messing up with any other transaction.
Stack trace:
<SqlException>
          <Message>Transaction (Process ID 670) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.</Message>
          <Server>p01db107</Server>
          <Source>.Net SqlClient Data Provider</Source>
          <StackTrace>   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
   at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
   at System.Data.SqlClient.SqlDataReader.Read()
   at Microsoft.SqlServer.Management.Smo.DataProvider.ReadInternal()
   at Microsoft.SqlServer.Management.Smo.DataProvider.Read()
   at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitObjectsFromEnumResults(Urn levelFilter, IDataReader reader, Boolean forScripting, List`1 urnList, Int32 startLeafIdx, Boolean skipServer)
   at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitQueryUrns(Urn levelFilter, String[] queryFields, OrderBy[] orderByFields, String[] infrastructureFields, ScriptingPreferences sp, Urn initializeCollectionsFilter)
   at Microsoft.SqlServer.Management.Smo.DefaultDatabasePrefetch.PrefetchUsingIN(String idFilter, String initializeCollectionsFilter, String type, IEnumerable`1 prefetchingList)
   at Microsoft.SqlServer.Management.Smo.DatabasePrefetchBase.<PrefetchObjects>d__1.MoveNext()
   at Microsoft.SqlServer.Management.Smo.SmoDependencyDiscoverer.SfcChildrenDiscovery(HashSet`1 discoveredUrns)
   at Microsoft.SqlServer.Management.Smo.SmoDependencyDiscoverer.Discover(IEnumerable`1 urns)
   at Microsoft.SqlServer.Management.Smo.ScriptMaker.DiscoverOrderScript(IEnumerable`1 urns)
   at Microsoft.SqlServer.Management.Smo.ScriptMaker.ScriptWorker(List`1 urns, ISmoScriptWriter writer)
   at Microsoft.SqlServer.Management.Smo.Scripter.ScriptWithListWorker(DependencyCollection depList, SqlSmoObject[] objects, Boolean discoveryRequired)
   at Microsoft.SqlServer.Management.Smo.Scripter.ScriptWithList(DependencyCollection depList, SqlSmoObject[] objects, Boolean discoveryRequired)</StackTrace>


Q: How to calculate number of post which have particular meta_key? I am using repeatable meta boxes what i want to achieve is display number of post which have particular meta key such as
Country Pakistan
City Islamabad
Age 12
Age 12
Meta key "Age" is used in 2 posts.
No i want structure like Age in Post 2 , Islamabad in Post 1 , Pakistan in Post 1.
/**
* Display callback for the submenu page.
*/
function iif_register_submenu_form_details_callback() {

$id = get_current_user_id();

    $loop = new WP_Query( array(
    'post_type'         => 'iff-info-forms',
    'post_status'       => 'publish',
    'author'            => $id,
    'meta_query'        => array(
                        array(
                            'key'   => 'repeatable_fields',
                            //'value' => $user_data_new,
                            'compare'   => 'LIKE'
                        ))
     ) );
    //print_r($loop);
    while ( $loop->have_posts() ) : $loop->the_post();
    $info = get_post_meta(get_the_id(), 'repeatable_fields', true);

    if ( $info ) {
      //  echo 'Emergency Contacts:
';

        foreach ( $info as $emergency_contact_metas ) {
            echo '' . esc_html( $emergency_contact_metas['iif_label'] ) .' ' . esc_html( $emergency_contact_metas['iif_details'] ) . '
';
        }
    }

    endwhile;

}

OUTPUT SHOWING IS Below
Country Pakistan
City Islamabad
Age 12
Age 12


Q: Elliptic curve point comparison If Alice uses point doubling over a generator point P to create two new points and then hands them over to Bob, can Bob tell which of the two points is the greater point without having to bruteforce all possible integer multiples of P?
Assume Bob knows the elliptic curve used to generate the points as well as the generator point P from which the two other points are derived.
Example: Alice creates the points 32P and 64P and hands them over to Bob without showing the scalars used. Can Bob somehow determine the second point (64P) is greater than the first point (32P).
A solution would be to divide the first point by the second point to find out if the value is above or below 1, but as far as I know division only works with scalars; not points.


Q: How to display the IP address of the default Interface with Internet connection? I need to create a script that outputs the internal IP address, that is configured as the default Interface.

A: Here's another slightly terser method using procfs (assumes you're using Linux):
default_iface=$(awk '$2 == 00000000 { print $1 }' /proc/net/route)
ip addr show dev "$default_iface" | awk '$1 ~ /^inet/ { sub("/.*", "", $2); print $2 }'

This returns both the IPv4 and (if available) the IPv6 address of the interface. You can change the test if you only want one or the other (look for inet for IPv4, and inet6 for IPv6).

$ default_iface=$(awk '$2 == 00000000 { print $1 }' /proc/net/route)
$ ip addr show dev "$default_iface" | awk '$1 ~ /^inet/ { sub("/.*", "", $2); print $2 }'
10.0.2.15
fe80::a00:27ff:fe45:b085

$ ip addr show dev "$default_iface" | awk '$1 == "inet" { sub("/.*", "", $2); print $2 }'
10.0.2.15

$ ip addr show dev "$default_iface" | awk '$1 == "inet6" { sub("/.*", "", $2); print $2 }'
fe80::a00:27ff:fe45:b085

A: Lots of good answers here, but wanted to throw in my usual approach:
The simplest solution is to get the route for a public internet address:
$ ip route get 1.1.1.1 | grep -oP 'src \K\S+'
192.168.0.20

Another solution is to get the default gateway, and then get the IP addr used to communicate with that gateway:
$ ip route get $(ip route show 0.0.0.0/0 | grep -oP 'via \K\S+') | grep -oP 'src \K\S+'
192.168.0.20

A: Here's what I wrote:

*

*Get the default interface from the "route" command.

It will print out which interface is the "default". For my host, I need to get the last column of the default line.
[root@pppdc9prd3ga mdesales]# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.4.0     *               255.255.252.0   U     0      0        0 bridge0
10.132.60.0     *               255.255.252.0   U     0      0        0 eth4
link-local      *               255.255.0.0     U     1002   0        0 eth4
link-local      *               255.255.0.0     U     1003   0        0 bridge0
default         10.132.60.1     0.0.0.0         UG    0      0        0 eth4

*Use "ifconfig" to retrieve the IP address of that interface.

Just getting the addr: value.
[root@pppdc9prd3ga mdesales]# ifconfig eth4
eth4      Link encap:Ethernet  HWaddr 00:50:56:01:42:91
          inet addr:10.132.63.191  Bcast:10.132.63.255  Mask:255.255.252.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1346288 errors:0 dropped:0 overruns:0 frame:0
          TX packets:438844 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:276243478 (263.4 MiB)  TX bytes:116188062 (110.8 MiB)

So here's the script I came up with.
/app/myPublicIp.sh
defaultInterface=$(route | grep default | awk '{print $(NF)}')
ifconfig $defaultInterface | grep 'inet addr:' | cut -d: -f2 |  awk '{ print $1}'

Here's it executing:
/app/ipFor.sh
10.132.63.191

A: My favorite one is following.
Get the default interface:
$ ip r | grep -oP 'default .* \K.+'
eth0

Get the ip of an interface:
$ ip a show eth0 | grep -oP 'inet \K[\d\.]+'
10.33.44.135

Combined:
$ ip a show $(ip r | grep -oP 'default .* \K.+') | grep -oP 'inet \K[\d\.]+'
10.33.44.135

A: One other approach is:
ip a|awk /$(ip r|awk '/default/ { print $5 }')/|awk '/inet/ { print $2 }'| cut -f1 -d"/"

the benefit of this is that uses only ip a and ip r that is available by default at all linux systems

A: If what you want is the IP address assigned to the default interface (which is what I understood from the comments under the question), using the Swiss army knife of network setup (ip) should be enough:
$ ip route | grep '^default'
default via 10.176.143.1 dev eth1  metric 203
$ ip addr show eth1
4: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether c0:de:f1:72:30:48 brd ff:ff:ff:ff:ff:ff
    inet 10.176.143.71/24 brd 10.176.143.255 scope global eth1
       valid_lft forever preferred_lft forever

This shortens to
$ ip addr show \
    $( /sbin/ip route \
        | grep '^default'\
        | sed 's/^.*dev \([^ \t]*\) .*$/\1/' )

which is ugly, because it is parsing something that probably wasn't really meant to be parsed (output of ip route), but should work.

A: Simple Command with the default interface.
ip -o route get "8.8.8.8" 2>/dev/null | sed -e 's/^.* src \([^ ]*\) .*$/\1/'

or
ip route | grep src | awk -F 'src' '{print $NF; exit}' | awk '{print $1}'

or
ip route | sed -n 's/.* src \(.*\) metric .*/\1/p' | uniq

Tested on All Unix OS

A: This worked for me on Centos 7. Find default interface using ip
ifconfig $(ip route | awk '/default/ { print $5 }') | grep "inet " | awk '{print $2}'

A: Any Linux OS-es using /proc (but without using iproute tools):
cat /proc/net/fib_trie|grep -A50 '\|-- 0\.0\.0\.0$'|grep -B50 -wm1 'LOCAL'|tail -n2|grep -oP '\|-- \K\S+'


Q: Using C++ to receive int inputs and displaying the larger and smaller number The instructions are to

*

*Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating 'I' is entered.

*Change the program to write out the smaller value is: followed by the smaller of the nwnbers and the larger value is: followed by the larger value.

I got the program to run but it terminates with a Range error: Can anybody correct my mistake in this code?
/*a drill in the Programming Principles
and Practice Using C++ by Bjarne Stroustrup*/
#include "std_lib_facilities.h"     /*standard library from the author's website*/
int main()
{
    vector<int>values;
    int a, b;       //ints declared
    while(cin>>a>>b){   //ints read
        values.push_back(a);    //ints put into vector
        values.push_back(b);    //********************
    }
    for(int i = 0; i < values.size(); ++i){     //loop
        if(values[i]>values[i+1]){
            cout << "The larger value is: " << values[i] << endl;   /*print larger value on screen*/
        }
        else
            cout << "The smaller value is: " << values[i] << endl;  /*prints smaller value on screen*/
    }
    return 0;
}

A: values[i+1] goes out of bounds for the last value, so you need to change your for loop condition
for(int i = 0; i < values.size() - 1; ++i){
                              // ^^^

A: 1.Write a program that consists of a while-loop that (each time around
    the loop) reads in two ints and then prints them. Exit the program
    when a terminating 'I' is entered.
int a, b = 0;
//  anything that isn't a int terminate the input e.g. 2 3 |
while (cin >> a >> b)
  cout << a << " " << b << "\n";

2.Change the program to write out the smaller value is: followed by the smaller of the nwnbers and the larger value is: followed by the larger value.
int a, b;
const string smaller = "smaller value is: ";
const string larger = "larger value is: ";

while (cin >> a >> b) {
    if (a < b)
        cout << smaller << a << larger << b << endl;
    else
        cout << smaller << b << larger << a << endl;
}

if (cin.fail()) {
    cin.clear();
    char ch;
    if (!(cin >> ch && ch == '|'))
        throw runtime_error(string {"Bad termination"});
}


Q: Get C Code Stack Trace in Go Program I'm using the rana/ora oracle driver in my Go program to query some Oracle tables.
The program somehow always gets SIGSEGV from a C library after running for a while and exits on segfault. It also gets a lot of query timeouts (context deadline exceeded) before it hits segfault error.
I'm using the driver in a pretty standard way:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Seconds)
defer cancel()
rows, err := initialedDb.QueryContext(ctx, "sql_query")

The stack trace from the 1st Goroutine is:
fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x70 pc=0x7fbb03e5d193]
runtime stack:
runtime.throw(0xa4a0a4, 0x2a)
    /usr/local/go/src/runtime/panic.go:596 +0x95
runtime.sigpanic()
    /usr/local/go/src/runtime/signal_unix.go:274 +0x2db
goroutine 5230 [syscall, locked to thread]:
runtime.cgocall(0x921850, 0xc421667348, 0xa495f1)
    /usr/local/go/src/runtime/cgocall.go:131 +0xe2 fp=0xc421667308 sp=0xc4216672c8
gopkg.in/rana/ora%2ev4._Cfunc_OCIAttrGet(0x2c92f08, 0x35, 0xc421cb8be4, 0xc421cb8be8, 0x5, 0x2b81930, 0xc400000000)
    gopkg.in/rana/ora.v4/_obj/_cgo_gotypes.go:347 +0x4d fp=0xc421667348 sp=0xc421667308
gopkg.in/rana/ora%2ev4.(*Rset).paramAttr.func1(0x2c92f08, 0xc400000035, 0xc421cb8be4, 0xc421cb8be8, 0x5, 0x2b81930, 0xf1ef01)
    /go/src/gopkg.in/rana/ora.v4/rset.go:970 +0xfc fp=0xc421667390 sp=0xc421667348
gopkg.in/rana/ora%2ev4.(*Rset).paramAttr(0xc4211f22d0, 0x2c92f08, 0xc421cb8be4, 0xc421cb8be8, 0xc400000005, 0x0, 0x0)
    /go/src/gopkg.in/rana/ora.v4/rset.go:976 +0x88 fp=0xc4216673e0 sp=0xc421667390
gopkg.in/rana/ora%2ev4.(*Rset).open(0xc4211f22d0, 0xc421358000, 0x7fbae405ed28, 0x0, 0x0)
    /go/src/gopkg.in/rana/ora.v4/rset.go:554 +0xd43 fp=0xc421667b98 sp=0xc4216673e0
gopkg.in/rana/ora%2ev4.(*Stmt).qryC(0xc421358000, 0xf1e940, 0xc421ace900, 0xc421cb8ad0, 0x1, 0x1, 0xc4211f22d0, 0x0, 0x0)
    /go/src/gopkg.in/rana/ora.v4/stmt.go:442 +0x3e0 fp=0xc421667f18 sp=0xc421667b98
gopkg.in/rana/ora%2ev4.(*DrvStmt).QueryContext.func1(0xc421b73260, 0xc420e789e8, 0xc420e789e0, 0xf1e940, 0xc421ace900, 0xc421cb8ad0, 0x1, 0x1)
    /go/src/gopkg.in/rana/ora.v4/drvStmt_go1_8.go:76 +0xa6 fp=0xc421667fa0 sp=0xc421667f18
runtime.goexit()
    /usr/local/go/src/runtime/asm_amd64.s:2197 +0x1 fp=0xc421667fa8 sp=0xc421667fa0
created by gopkg.in/rana/ora%2ev4.(*DrvStmt).QueryContext
    /go/src/gopkg.in/rana/ora.v4/drvStmt_go1_8.go:82 +0x30c

I checked my program many times and I don't think I'm causing any memory leaks, double frees or anything like that.
I wonder how I can debug this since Go doesn't give me C's stack trace. Will Valgrind's Memcheck tool help?


Q: Different effects of ORDER BY clause on two servers My query:
SELECT * FROM table GROUP BY id;

id field is a primary key, of course;
In 9.4.4 I get expected error:
column "table.name" must appear in the GROUP BY clause or be used in an aggregate function

BUT! In 9.4.5 it works, like in MySQL.
Can anybody tell me - why? :)

A: Postgres version does not matter here. The tables are not identical. Most likely in your 9.4.5 table the column id is a primary key, while in 9.4.4 is not.


Q: Google Apps Script - Use Column Name (not In row1) rather than column number I have an Apps Script linked to my Google Sheet which grabs a range from one sheet and copies it to another. The issue I face now (and one that cannot be reasoned with) is that users will add columns to the destination sheet.  What I am trying to do instead is look for the column names; to add another slight spanner in the works the column names are on row 7 instead of 1.
    function OPupdates() {

// I have tried looking at this but couldn't get it to work for me- https://stackoverflow.com/questions/45901162/refer-to-column-name-instead-of-number-in-google-app-script

//Copies Status From One Sheet To Another
  var sheetfrom2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Helper Sheet'); //this contains source info
  var sheetto2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Plan');//sheet into which the new source data is copied

  sheetfrom2.getRange(2, 2, sheetfrom2.getLastRow(), 1).copyTo(sheetto2.getRange(8,8, sheetfrom2.getLastRow()-2, 1), {
    contentsOnly: true
  });
//row 8 column 8.  This is what needs to be changes to reflect the column name regardless of where it sits in row 8

}

I have tried looking at a similar issue/solution (link in the code above) but try as I might I could not figure out how to get this to work for my particular issue.

A: Instead of copying the range you'll need to create a value array that matches the target structure.
In lieu of sample data I'll play with the following toy example:
Sheet "Source":

A
B
C

1
1
2

Sheet "Target":

_
A
B
C
D

1

2

3

4

5

6

7

8
B
E
C
A

function copyOver() {
  const source = SpreadsheetApp
      .getActiveSpreadsheet()
      .getSheetByName("Source")
      .getDataRange()
      .getValues();

  const target = SpreadsheetApp
      .getActiveSpreadsheet()
      .getSheetByName("Target");

  const headerRow = 8;
  const targetHeaders = target.getDataRange().getValues()[headerRow - 1];
  const sourceHeaders = source[0];
  const sourceValues = source.slice(1);
  const columnLookup = targetHeaders.map(h => sourceHeaders.indexOf(h));

  function buildRow(row) {
    return columnLookup.map(c => c == -1 ? "" : row[c]);
  }

  const output = sourceValues.map(buildRow);
  if (output.length > 0) {
    target
        .getRange(headerRow + 1, 1, output.length, output[0].length)
        .setValues(output);
  }
}

A: First of all try yelling at users and making them understand that they may not mess with sheets with active programming (This is successful 75% of the time). Otherwise, you'll want to check your columns before you copy.
function OPupdates() {
  var sheetfrom2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Helper Sheet'); //this contains source info
  var sheetto2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Plan');//sheet into which the new source data is copied

var statuscolumn = -1;
var headerWewant = "STATUS";//modify for the correct column name
var targetSheetHeader = sheetto2.getRange(1,1,1,sheetto2.getLastColumn().getValues();
for (var j=0; i<targetSheetHeader[0].length;i++)
    {
    if (data[0][j] == headerWeWant) statuscolumn = j+1;
    }
if (statuscolumn == -1) {console.error("Couldn't find the status column"; return;}

  sheetfrom2.getRange(2, 2, sheetfrom2.getLastRow(), 1).copyTo(sheetto2.getRange(8,statuscolumn, sheetfrom2.getLastRow()-2, 1), {
    contentsOnly: true
  });

}

But training the users to go in fear of your wroth is a better long term strategy ;).


Q: How prove $S_{k}(x)=\sum_{i=1}^{n}x^k_{i}$ this System of equations The only solution?
when I read a china book,I see this follow interesting problem (the author says it is clear have follow)
if give the  number $S_{k}(x),k=1,2,3,\cdots,n$ ,and such
  $$\begin{cases}
S_{1}(x)=x_{1}+x_{2}+\cdots+x_{n}\\
S_{2}(x)=x^2_{1}+x^2_{2}+\cdots+x^2_{n}\\
S_{3}(x)=x^3_{1}+x^3_{2}+\cdots+x^3_{n}\\
\cdots\cdots\cdots\cdots\cdots\cdots\cdots\cdots\cdots\\
S_{n}(x)=x^n_{1}+x^n_{2}+\cdots+x^n_{n}
\end{cases}$$
show that:
this system of equations has a unique solution.

we define $(x_{1},x_{2},x_{3})=(1,2,3),(x_{1},x_{2},x_{3})=(2,3,1),(x_{1},x_{2},x_{3})=(1,3,2),\cdots$ is same solution
why it is clear?
can you someone can  prove this?Thank you


Q: Insert contents of a file in middle of another file with Python? There is already a question on SO that explains how to insert a line into the middle of a python file at a specific line number.
But what if I have 2 files. inputfile.txt and outputfile.txt (which already has some text) and I want to insert all of inputfile.txt (with formatting preserved) into the middle of outputfile.txt?

A: Why do you think it is any different from this probable SO question you are referring to?
Its just that instead of inserting a line, you need to read your inputfile.txt into a variable as shown here
and insert that into the file, instead of the value as clearly shown in the question. (links provided above)

A: insert contents of "/inputFile.txt" into "/outputFile.txt" at line 90
with open("/inputFile.txt", "r") as f1:
    t1 = f1.readlines()
with open("/outputFile.txt", "r") as f2:
    t2 = f2.readlines()
t2.insert(90, t1)
with open("/outputFile.txt", "w") as f2:
    f2.writelines(t2)

That should do it


Q: Is SparseArray good for resource id keys? Is it advisable to use a SparseArray when the integer keys are resources id's? Or is it aimed at keys with lower numbers?
Yes, I know the definition of SparseArray, and the compiler always issues a warning when one uses ArrayList with integer keys, advising to use SparseArray.
But maybe when SparseArray was defined, they had in mind an array where you do have elements, but not all of them.
In my case, I want to use Resource IDs as keys, which are, for those of you who had a pick at the generated R.java file, very big numbers only. So I though that it may not fit, not only the intention, but also the implementation of SparseArray.

A: SparseArray is exactly for values which are of an unknown range.  So it seems to fit your need.

A: in R.java the resrource ids are all integer so there is no problem using sparse array.

A: Do not use the SparseArray together with the Resourse IDs as keys. SparseArraysorts keys in ascending order for efficient access. Since resource ids are generated automatically, you cannot guarantee their order within SparseArray. This means that when you iterate over the SparseArray, you will not follow the same order as you would when filling in the FW.
I think you should use LinkedHashMap instead.


Q: How Do I Ensure a Candidate Latin Square Is a Valid Damm Operation Table I am attempting to write a function in Scala that takes a valid Latin Square as input and then returns a Boolean value indicating whether the input Latin Square is a valid instance of an operation-table for the Damm Algorithm, or not. The Damm Algorithm appears to be of the "Check digit" class of error detection mechanisms.
The desired function is an implementation of the implication described in the Design section of the Wikipedia article for the Damm Algorithm. The implication is captured by the assertion of:

a weak totally anti-symmetric quasigroup with the property x ∗ x = 0

I'm insufficient in both the math skills to properly read and interpret Damm's paper, and then having enough German (the language within which the paper was written) reading skills to be able to confidently interpret how I would encode a correct validation function.
Given the following function definition:
def validate(latinSquare: List[List[Int]]): Boolean =
  ???

With what would I replace the ????
Within the paper, a single instance of a valid 10x10 Latin Square is provided. It is reproduced within the Wikipedia article and looks like this:
 |0 1 2 3 4 5 6 7 8 9
-+-------------------
0|0 3 1 7 5 9 8 6 4 2
1|7 0 9 2 1 5 4 8 6 3
2|4 2 0 6 8 7 1 3 5 9
3|1 7 5 0 9 8 3 4 2 6
4|6 1 2 3 0 4 5 9 7 8
5|3 6 7 4 2 0 9 5 8 1
6|5 8 6 9 7 2 0 1 3 4
7|8 9 4 5 3 6 2 0 1 7
8|9 4 3 8 6 1 7 2 0 5
9|2 5 8 1 4 3 6 7 9 0

I can see there are others who have sought an answer to this. However, no one has yet provided a requested code-based valid Latin Square solution.
I have coded up a generic Latin Square generator, but need the above validation function which will serve as the filter to eliminate each candidate Latin Square that does not meet the necessary condition(s) of the above implication.

A: In functional programming terms, the checksum algorithm is foldLeft with a carefully chosen binary operation. The requirements for this binary operation, in English:

*

*In every two-digit input, if we change one of the digits, then the checksum changes (Latin square…);

*In every three-digit input, if the latter two digits are distinct and we swap them, then the checksum changes (…with weak total antisymmetry);

*The Latin square has zeros on the diagonal.

In Python 3:
def validate(latinSquare):
    Q = range(len(latinSquare))
    return all(
        x == y
        for c in Q
        for x in Q
        for y in Q
        if latinSquare[latinSquare[c][x]][y] == latinSquare[latinSquare[c][y]][x]
    ) and all(latinSquare[x][x] == 0 for x in Q)

print(
    validate(
        [
            [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
            [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
            [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
            [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
            [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
            [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
            [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
            [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
            [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
            [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
        ]
    )
)

A: This is a conversion into Scala of the Python 3 Answer that was provided by David Eisenstat's answer.
View in Scastie:
def isValidDammOperationTable(validLatinSquare: List[List[Int]]): Boolean = {
  val indices = validLatinSquare.indices.toList
  (
        indices.forall(index => validLatinSquare(index)(index) == 0)
    &&  indices.forall(
          c =>
            indices.forall(
              x =>
                indices.forall(
                  y =>
                        (validLatinSquare(validLatinSquare(c)(x))(y) != validLatinSquare(validLatinSquare(c)(y))(x))
                    ||  (x == y)
                )
            )
        )
  )
}

val exampleLatinSquareX10: List[List[Int]] =
  List(
      List(0, 3, 1, 7, 5, 9, 8, 6, 4, 2)
    , List(7, 0, 9, 2, 1, 5, 4, 8, 6, 3)
    , List(4, 2, 0, 6, 8, 7, 1, 3, 5, 9)
    , List(1, 7, 5, 0, 9, 8, 3, 4, 2, 6)
    , List(6, 1, 2, 3, 0, 4, 5, 9, 7, 8)
    , List(3, 6, 7, 4, 2, 0, 9, 5, 8, 1)
    , List(5, 8, 6, 9, 7, 2, 0, 1, 3, 4)
    , List(8, 9, 4, 5, 3, 6, 2, 0, 1, 7)
    , List(9, 4, 3, 8, 6, 1, 7, 2, 0, 5)
    , List(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)
  )

println(isValidDammOperationTable(exampleLatinSquareX10)) //prints "true"


Q: Tabularx adding unnecessary pages My document is creating a {blank rest of page + empty page} before a tabularx table.
Checked this thread with no dice - I couldn't solve with typical figure/table placement controls.
This is my code:
\chapter{List of Symbols}
\label{ch:AE}
\begin{tabularx}{1\textwidth}{>{\hsize=.2\hsize$}l<{{}$}>{\hsize=28\hsize}X}[H]
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
...
\end{tabularx}

Pictures of results are below - you can see in the third pic that the [H] ends up being read as part of the first column.
I'm not that familiar with tabularx, any ideas??
Thanks for help
-DR

A: Just in case you didn't know it, there are specialized packages for printing such lists. They also add the possibility of referencing the symbols throughout the document.
One of them is glossaries. Here's an example with it:
\documentclass{book}

\usepackage[acronym,nonumberlist,numberedsection]{glossaries}

\renewcommand{\acronymname}{List of Symbols}
\newglossarystyle{mystyle}{%
  \setglossarystyle{long}%
  \renewenvironment{theglossary}%
     {\begin{longtable}[l]{@{}p{0.1\hsize}p{0.8\hsize}}}%
     {\end{longtable}}%
}

\newacronym{HA}{$[H]a$}{Semi-major axis of Earth}
\newacronym{ANT}{$Ant_k$}{Antenna number $k$}

\makeglossaries

\begin{document}

The symbol \acrshort{HA}

\glsaddall

\appendix
\printglossary[style=mystyle,type=\acronymtype]

\end{document}

Output:

To obtain the output, you have to run

pdflatex myfile
makeglossaries myfile
pdflatex myfile
pdflatex myfile

If you don't have Perl installed, replace the second step with

makeindex.exe -s myfile.ist -t myfile.alg -o myfile.acr myfile.acn

A: If you don't want to change to change much of your code, simply use a longtable instead of a tabularx.
MWE:
\documentclass{book}

\usepackage{array,longtable}

\begin{document}

\appendix
\chapter{List of Symbols}
\label{ch:AE}

\begin{longtable}[l]{@{}>{$}p{0.1\hsize}<{$}@{}p{0.9\hsize}@{}}
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
a & Semi-major axis of Earth \\
Ant_k & Antenna number \emph{k} \\
\end{longtable}

\end{document}

Output:

A: The problem is that the table is too large even for being contained in a page, so first of all LaTeX pushes it on the next page because it can't be contained in the chapter title.
Then it tries to set it in the next page which again doesn't have room for it, so it pushes it to the next page and finally it gives up.
You simply don't need tabularx.
\documentclass{book}
\usepackage{setspace}

\newcommand{\sym}[2]{%
  \noindent
  \makebox[4em][l]{$#1$}% <---- adjust to suit
  #2\par
}

\onehalfspacing % you seem to be using this (avoid it, if you can)

\begin{document}

\appendix
\chapter{List of Symbols}
\label{ch:AE}

\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}

\end{document}

If your descriptions are long and may end up into more than one line, you can modify the definition of \sym to ensure the description is not split across pages:
\documentclass{book}
\usepackage{setspace}

\newcommand{\sym}[2]{%
  \noindent
  \makebox[4em][l]{$#1$}% <---- adjust to suit
  \begin{minipage}[t]{\dimexpr\textwidth-4em\relax}
  #2\par\xdef\theprevdepth{\the\prevdepth}
  \end{minipage}\par\prevdepth\theprevdepth
}

\onehalfspacing % you seem to be using this (avoid it, if you can)

\begin{document}

\appendix
\chapter{List of Symbols}
\label{ch:AE}

\sym{a}{1 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{2 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{3 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{4 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{5 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{6 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{7 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{8 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{9 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{10 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{11 Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{12 Semi-major axis of Earth Semi-major axis of Earth Semi-major axis of Earth
  Semi-major axis of Earth Semi-major axis of Earth Semi-major axis of Earth
  Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}
\sym{a}{Semi-major axis of Earth}
\sym{Ant_k}{Antenna number $k$}

\end{document}


Q: Unable to set full-text index to 'active' in table-designer In SQL Server 2008 R2 Management Studio, I have set my database to be full-text indexed and ran the command
EXEC sp_fulltext_database 'enable'

along with creating a catalog. When I open the table design mode, and right click the Primary Key, then click Full-Text Indexes in the context menu, I add my columns under the 'General' section, but when I go to set it to Active = Yes, it's grayed out.
How can I change this?  Here is a screen-shot of what it's looking like.
http://snag.gy/2QSDN.jpg

A: For some reason you can't enable or disable the full text index from that screen. Instead you have to right-click the table in Object Explorer, then choose Full-Text index > Enable Full-Text index.


Q: It gives this error while running: undefined is not a function (evaluating '_reactNativr.default.createElement') This section of code is not running it always return en error saying undefined or not a function in the render function().

Heading
'use strict';
import React, {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    AlertIOS,
    Dimensions,
    BackHandler,
    PropTypes,
    Component,
} from 'react-native';

import NavigationExperimental from 'react-native-deprecated-custom-
components';

var _navigator;
//var Navipanel=require('./App/Navigation/Navipanel.js');
var Dashboard= require('./App/Dashboard/dashboard.js');
//var Sample= require('./App/Navigation/sample.js');
var Matches = require('./App/Components/Matches.js');
var Users = require('./App/Components/Users.js');
var SCREEN_WIDTH =require('Dimensions').get('window').width;
var BaseConfig=NavigationExperimental.Navigator.SceneConfigs.FloatFromRight;

var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop,
    {
        snapVelocity: 8,
        edgeHitWidth: SCREEN_WIDTH,
    });

BackHandler.addEventListener('hardwareBackPress', () => {
     if (_navigator.getCurrentRoutes().length === 1) {
         return false;
     }

     _navigator.pop();
     return true;
});

var CustomSceneConfig = Object.assign({}, BaseConfig, {
    // A very tighly wound spring will make this transition fast
    springTension: 100,
    springFriction: 1,
    // Use our custom gesture defined above
    gestures: {
        pop: CustomLeftToRightGesture,
    }
});

//var createReactElement = require('create-react-element');
var createReactClass = require('create-react-class');
var test = createReactClass({
    _renderScene(route,navigator) {
        _navigator = navigator;

        if (route.id === 1) {
            return <Dashboard navigator={navigator}/>;
        }
        else if(route.id === 2) {
            return <Sample navigator={navigator} /> ;
        }
        else if(route.id === 3) {
            return <Navipanel navigator={navigator} /> ;
        }
        else if(route.id === 4){
            return <Matches navigator={navigator} /> ;
        }
        else if(route.id === 5) {
            return <Users navigator={navigator} />
        }
    },

    _configureScene(route) {
        return CustomSceneConfig;
    },

    render:function() {
        return (
            <NavigationExperimental.Navigator  [//error in this line]
            initialRoute = {{id:1}}
            renderScene = {this._renderScene}
            configureScene = {this._configureScene} />
        );
    }
});

Undefined error _reactNative.default.createElement

A: You imported React from "react-native";
import React, {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  Dimensions,
  BackHandler,
  PropTypes,
  Component,
} from 'react-native';

instead of this, you need to import React from "react";
import React from 'react';

When we use JSX in our render functions, in the background JSX runs React.createElement(...). And in your code, React is not defined. Because of this, it gives that error.


Q: Wordpress SQL query different results I added a custom Visual Composer element and want to output a result of a query. However when I output this query(1) it gives other results then when I output this query(2).
// declared vars
global $wpdb;
$nn = '{{ post_data:ID }}';
$nn1 = (string)$nn;

 1)   $results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = 526 AND guid like '%pdf'", OBJECT );
 2)  $results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn1." AND guid like '%pdf'", OBJECT );

When I output the 526 string(query 1) it gives the right result however I want the output to be with the var because every post has its unique ID.
I've also tried to put the var in a string so it isn't being seen as a POST_ID
$nn = '{{ post_data:ID }}';
$nn1 = (string)$nn;

Any ideas to where this is failing?
What i've tried in the meantime:
$nn1 = (string)$nn;
$nn2 = strval($nn);
$nn3 = settype($nn, "string");

$results1 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn1." AND guid like '%pdf'", OBJECT );
$results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn2." AND guid like '%pdf'", OBJECT );
$results3 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn3." AND guid like '%pdf'", OBJECT );
$results4 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = %d AND guid like '%pdf'", $nn3, OBJECT );

All of the above are returning an empty string which means there is still something wrong with the var
When I echo the whole string it returns the right mysql query:
echo ("SELECT guid FROM wp_posts WHERE post_parent = ".$nn."");
//output
SELECT guid FROM wp_posts WHERE post_parent = 526;

When I execute that query, it gives me the right solution:
$results6 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = 526", OBJECT );
// output
[6]=>object(stdClass)#8030 (1) {
["guid"]=>
string(69) "http://blabla.pdf"}

Greetz

A: None of your tests seem to include the one query you've shown to be working:
$GLOBALS['wpdb']->get_results(
    "SELECT guid FROM wp_posts WHERE post_parent = $nn",
    OBJECT
);

There's no need to do any type conversions, especially not to string. $nn should contain int 526.
full disclosure: I'm not a WP dev and I have no idea how you got from '{{ post_data:ID }}' to 256, also string(18) "526" seems like a very weird output to me. (groetjes aan de daddykaters!)


Q: How to Solve PHP7.2 use of undefined constant priority warning In trying the next PHP 7.2 release out on my site (previously we've been on 7.1 with no problems) I noticed that one of our older scripts suddenly began throwing up this warning.
Warning: Use of undefined constant priority - assumed 'priority' (this will throw an Error in a future version of PHP) in /../plugins.inc.php on line 146
Of course I could hide this as it's only a warning but I'd rather figure out the problem than store them up for PHP8.0. The code it relates to is this block and nothing else in the file appears to be related to it.
function SortByActionPriority($a, $b) {
    return $a[priority] > $b[priority] ? 1 : -1;
}

Sadly this is not a system I'm familiar with (it's an older one) and it has thousands of PHP files, so I'm not entirely sure where else in the program this is being used for full context.


Q: ERLANG - Pattern Matching specifc pattern in unknown size list Ok now I think Im getting warmer, I have to pattern match whatever comes in.
So if I had say
Message = = [[<<>>],
 [<<"10">>,<<"171">>],
 [<<"112">>,<<"Gen20267">>],
 [<<"52">>,<<"20100812-06:32:30.687">>]]

And I was looking to pattern match the field <<"112">>
Such as the 112 is always going to say 112, but the Gen2067 can change whenever to whatever.. its the data, it will be stored in a variable.
Also the fields can be in any order, whatever function im trying to do has to be able to find the field and parse it.
This is the code I am using right now:
loop() ->
receive
    [_,[<<"112">>, Data], _] when is_list(X) -> %% Just dosen't work in anyway..
        ?DEBUG("Got a list ~p~n", [X]),
        loop();
    _Other ->
        ?DEBUG("I don't understand ~p~n", [_Other]),
        loop()
end.

I feel im close, but not 100%
-B

A: You can extract your data this way:
1> Message = [[<<>>],
1>  [<<"10">>,<<"171">>],
1>  [<<"112">>,<<"Gen20267">>],
1>  [<<"52">>,<<"20100812-06:32:30.687">>]] .
[[<<>>],
 [<<"10">>,<<"171">>],
 [<<"112">>,<<"Gen20267">>],
 [<<"52">>,<<"20100812-06:32:30.687">>]]
2> [Data] = [X || [<<"112">>, X] <- Message ].
[<<"Gen20267">>]
3> Data.
<<"Gen20267">>

Another way:
4> [_, Data] = hd(lists:dropwhile(fun([<<"112">>|_]) -> false; (_)->true end, Message)).
[<<"112">>,<<"Gen20267">>]
5> Data.
<<"Gen20267">>

And another one as function in module (probably fastest):
% take_data(Message) -> Data | not_found
take_data([]) -> not_found;
take_data([[<<"112">>, Data]|_]) -> Data;
take_data([_|T]) -> take_data(T).


Q: AutoCAD Map 3D does not show panels and icons? I have some problems with autocad 2014, 3D map, this not show me de icons on the top, I use windows 10.

A: Sounds like you are missing you quick access toolbar.

If you open your Custom User Interface (type CUI at the command line) and set the current workspace to "current" even if it is already current, that should help. See other ways you could try to get it back here:
You can also click on the small triangle to the right of the big blue"A" in the upper left corner of the image for to the same menus.


Q: Getting multiple ints from string I have a string:
"3, V, 11, H, 21, H"

and I am trying to get
int first = 3
int second = 11
int third = 21

I'm not exactly sure how to do this since the numbers could be one or two digits, there are non-digit characters between the numbers, and I have to capture multiple numbers. I tried regex but then I'm left with "31121" which does not indicate what the three numbers are.

A: Try this code. Should get you the job done.
public static void main(String[] args){
    String s = "3, V, 11, H, 21, H";
    String[] t = s.split(" [ ,]*|,[ ,]*");
    int first = Integer.parseInt(t[0]);
    int second = Integer.parseInt(t[2]);
    int third = Integer.parseInt(t[4]);
    System.out.println(first);
    System.out.println(second);
    System.out.println(third);
}

A: You can split your String by "," and check if it's a number using  NumberUtils.isNumber (String str) from org.apache.commons.lang.math.NumberUtils :

Checks whether the String a valid Java number.
Valid numbers include hexadecimal marked with the 0x qualifier,
  scientific notation and numbers marked with a type qualifier (e.g.
  123L).
Null and empty String will return false.

String s = "3, V, 11, H, 21, H";
for(String st : s.split(",")){
    if(NumberUtils.isNumber(st.trim()))
        System.out.println(st);
}

If you want to check that the String contains only digits, you can use NumberUtils.isDigits(String str)

A: public static void main(String[] args) {

    String in = "3, V, 11, H, 21, H";

    List<String> storage = Arrays.asList(in.split(","));
    List<Integer> output = new ArrayList<Integer>();

    int first = 0;
    int second = 0;
    int third = 0;

    for(String str : storage){
        if(str.trim().matches("[0-9]+") ){ // or if(NumberUtils.isNumber(str) )
            output.add(Integer.parseInt(str.trim()));
        }
    }

    if(output.size() == 3){
         first = output.get(0);
         second = output.get(1);
         third = output.get(2);
    }

    System.out.print("first: "); System.out.println(first);
    System.out.print("second: "); System.out.println(second);
    System.out.print("third: "); System.out.println(third);

}

Output:
first: 3
second: 11
third: 21

A: You can split this string by , and then check if every part is a number like this :
import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        String str = "3, V, 11, H, 21, H";
        String[] parts = str.split(", ");
        ArrayList<Integer> listNumbers = new ArrayList<Integer>();
        for(String x : parts){
         try{
           listNumbers.add( Integer.parseInt(x) );
         }
         catch(Exception e){}
        }

        for(int i=0;i<listNumbers.size();i++) System.out.println("Number "+(i+1)+" : "+listNumbers.get(i));
    }

}


Q: simple question in sentence with a prepostion
I want to use a pencil to drawing a picture.

is it a correct sentence?
If not, please, change it into a right sentence.
I want native speakers what to think about the sentence.

A: The correct form is

I want to use a pencil to draw a picture.

The addition of does not change the verb form

I want to draw a picture.

However, neither of these are questions.
A question related to the original sentence might be:

Do you want to use a pencil to draw a picture?

The form "drawing" could be used in such sentences as:

*

*I am drawing a picture.

*I saw him drawing a picture.

*I saw him drawing a picture with a pencil.


Q: Facebook api shows only statuses of the last year i'm working with a facebook app that  aims to show all user statuses, after a couple of questions here on stackoverflow ,  i got this (almost )working.
The problem is that graph api show only statuses of last year.
Is not a script problem because if i use the Graph Api explorer tool , the json output is the same (now - october 2013).
tested with several facebook account, same problem.
Any idea / help? thanks
UPDATE:
Basically i get data from : https://graph.facebook.com/v2.1/me?fields=statuses (this is from Explorer api tool), script code is
" $request = new FacebookRequest( $session, 'GET', '/me/statuses' ); "

In both ways i got same result. (using explorer tool or by script). few statuses and i cant go back untill very old statuses.
But the problem is not my code , i'm asking because maybe there are some limitation , not listed in docs. As Wizkid suggest i've filed a bug.

A: Is a Bug.
https://developers.facebook.com/bugs/298184123723116/

We have managed to reproduce this issue and it appears to be a valid
  bug. We are assigning this to the appropriate team.


Q: How to set the background of a custom shaped ImageButton in a RecyclerView? In a recyclerView I have list of imageButtons with a custom shape applied as the background of all ImageButtons. Each ImageButton currently has a solid color from a colorlist: colors[]
This is how it looks right now:

I want to put a icon.png in the place of index 0 (brown colored button) instead of the solid color. So far I have used many days of trying to find a solution myself but without any succses.
Here is all relevant code:
This is the code in the recyclerView adapter that sets the colors:
Resources resources = App.getAppContext().getResources();
String colors[] = resources.getStringArray(R.array.backgroundcolors);

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    Drawable drawable = holder.colorButton.getBackground();

    //This is here where each ImageButton gets a color from the colorlist colors[]

    if (drawable instanceof GradientDrawable) {
        GradientDrawable gd = (GradientDrawable) drawable.getCurrent();
        gd.setColor(Color.parseColor(colors[position]));

        //This does nothing
    } else if (drawable instanceof RippleDrawable) {
        RippleDrawable rd = (RippleDrawable) drawable;
        int color = Color.parseColor(colors[position]);
        rd.setColor(newColorStateList(color));
    }
}

The colorStatList code for each imageButton:
 private static ColorStateList newColorStateList(int color) {
    int[][] states = new int[][]{

            new int[]{android.R.attr.state_enabled}, // enabled
            new int[]{-android.R.attr.state_enabled}, // disabled
    };

    int[] colors = new int[]{
            color, color
    };
    return new ColorStateList(states, colors);
}

My Custom button for the recyclerView Adapter:
public class ColorButton{

private ImageButton button;
private String color;
public static List<ColorButton> colorButtonList;

public ColorButton(ImageButton button, String color) {
    this.button = button;
    this.color = color;
}

static ColorButton colorButton = new ColorButton(new ImageButton(App.getAppContext()), null);

public static List<ColorButton> initColorButtons(){
    colorButtonList = new ArrayList<>();

    Resources resources = App.getAppContext().getResources();
    String colors[] = resources.getStringArray(R.array.backgroundcolors);

    for(int i=0; i<colors.length; i++){

        colorButtonList.add(new ColorButton(new ImageButton(App.getAppContext()), colors[i]));
    }

    return colorButtonList;
}

You may wonder why I have String color;
This is for setting the background color of my app when the user clicks on a colorbutton:mEditText.setBackgroundColor(Color.parseColor((mColorButtons.get(position).getColor())));

A: Try this:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position ==0){
holder.colorButton.setBackgroundResource(R.drawable.colorpicker2);
}
else
{
GradientDrawable gd = context.getResources().getDrawable(R.drawable.bbshape);
gd.setColor(Color.parseColor(colors[position]));
holder.colorButton.setBackGroundDrawable(gd);
}
}


Q: How to clean JVM heap memory in spark scala or pyspark How to clean my JVM occupied memory in spark scala streaming application. I am running streaming job which is in 60 sec interval of time. For my first six hours no issue after that, I am facing JVM heap memory issue. Is there any way programmatically I can clean my GC or JVM memory in spark scala.
In my application, I am using Dataframe, registertemptable also end of my program I am writing the result into HDFS. Presently in my application spark SQL context level, I am uncaching, like this any other way we can release the memory?
Error msg: Exception in thread "dag-scheduler-event-loop" java.lang.outofmemoryError: Java heap space
Thanks
Venkat

A: I would suggest you to see if there is any thread leak in the application.
You can look at the thread dump in the application master near the executor logs.
Try to set this parameter. --conf spark.cleaner.ttl=10000.
If you are using cache I would suggest you to use persist() it in both memory and disc


Q: How override view on custom tab?
I want to make report section for view in custom tab. I d'nt understand how override view.  There is visual page for this but  i can't use View filter for my tab. For example, there are 2 views: sales, marketing. For each view i want to show appropriate Report list.

A: Probably you are mixing a few things up here. The View mechanism is limited to filtering lists of records. The capabilities are those you see when you press "Edit" or "Create New View" beside the picklist - that's it.
It is not possible, to integrate Reports in the List(views) picklist.
The option to override the View by a visualforce page is something entirely different and I would possibly call it a naming-clash. This "View" there means the view of a single record. You can open each record in salesforce either in "View" or "Edit-Mode" - both can be overridden by VF-Pages.
To get things clear in your mind think about the views in your screenshot as list-views and the overridable ones as record-views.
Another thing what you can do is to override the entire tab. And with that you might come a bit closer to what you want, since you could write there you own titlepage for your tab. As a tradeoff, you loose all the default mechanisms for listviews and you have to (re)create the picklist and all the logic you need on your own.


Q: Wolfram alpha and floating point arithmetic (loss of significance) I'm studying floating point aritmetic. Suppose we are in double precision. We know that when we  subtract two numbers which has "almost" the same magnitude, the relative error is large.
In MatLab command window, for instance, if I compute
2.0000001-2.0
I obtain 9.99999998363421e-08
and with a relative error errRel =  1.63657882716964e-09 which is not negligible.
But If I do that in Wolfram alpha (or with the calculator of my laptop), I actually obtain the right result, which is 1e-7.
So, my question is: why is that? I thought that both MatLab and the calculator of my laptop used the floating point arithmetic in the same way

A: There are two possible causes of seeing exactly 1e-7 on subtracting 2.0000001-2.0.
One is that many systems round to a reasonable number of digits on output. The exact conversion to decimal of IEEE 64-bit binary 2.0000001-2.0 is 9.9999999836342112757847644388675689697265625E-8. Some systems round to a limited number of significant digits, and might print that as 1e-7. On the other hand, Java, for example, delivers by default enough digits to distinguish the original value from any other double, and prints 9.999999983634211E-8
The other possible cause is if the arithmetic is being done in decimal, in which case the real numbers 2.0000001, 2, and their difference are all exactly representable because they are all decimal fractions. You would need to calculate something like 1/3 to see rounding error.


Q: ChildrenRect always returns 0 I have a Flickable item in where I want to put a customized flow component, so I created the Flickable like this:
import QtQuick 2.0
import UICore.Layouts 1.0 as Layouts
Flickable{
    anchors.fill: parent;
    contentWidth: parent.width;
    contentHeight: flow.childrenRect.height;

    Component.onCompleted: {
        console.log("The content height is: " + contentHeight);
    }

}

Then in my main.qml I have this (The file above is MyFlickable, and the MyFlow is a flow with specific properties):
 MyFlickable{
        ....
        MyFlow{
            id: flow
         ...
        }
  }

This works great but the problem is that I want to be able to reuse this item with as little overhead as possible. Setting the id inside of my MyFlow doesn't work, and I tried this
contentHeight: contentItem.childrenRect.height

as suggested in here under contentWidth section: http://doc.qt.io/qt-5/qml-qtquick-flickable.html#contentItem-prop
but that always returns 0. I've tried a couple of other ways to receive onCompleted signals but I get the same luck. This doesn't work for example:
contentHeight: children[0].childrenRect.height

Which in my mind should be the same as accessing the item through the id, bu apparently not.
So my question is: how do I get to height of my flow after all the components have been added?
Thanks in advance!

A: This wlil achieve what you want:
contentHeight: contentItem.children[0].childrenRect.height

From Qt docs

Items declared as children of a Flickable are automatically parented to the Flickable's contentItem. This should be taken into account when operating on the children of the Flickable; it is usually the children of contentItem that are relevant.

But I must say it is bad practice for a component to make assumptions about things outside its own QML file, as it makes the component difficult to reuse. Specifically in this case the Flickable is making the assumption that its first child is of a Component type that makes use of the childrenRect property. Your MyFlow component does, but many other components do not, for example an Image.


Q: Python 3 Multiprocessing and openCV problem with dictionary sharing between processor I would like to use multiprocessing to compute the SIFT extraction and SIFT matching for object detection.
For now, I have a problem with the return value of the function that does not insert data in the dictionary.
I'm using Manager class and image that are open inside the function. But does not work.
Finally, my idea is:
Computer the keypoint for every reference image, use this keypoint as a parameter of a second function that compares and match with the keypoint and descriptors of the test image.
My code is:
# %% Import Section
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
from datetime import datetime
from multiprocessing import Process, cpu_count, Manager, Lock
import argparse
# %% path section
tests_path = 'TestImages/'
references_path = 'ReferenceImages2/'
result_path = 'ResultParametrizer/'
#%% Number of processor
cpus = cpu_count()
# %% parameter section
eps = 1e-7
useTwo = False  # using the m and n keypoint better with False
# good point parameters
distanca_coefficient = 0.75
# gms parameter
gms_thresholdFactor = 3
gms_withRotation = True
gms_withScale = True
# flann parameter
flann_trees = 5
flann_checks = 50

#%% Locker
lock = Lock()

# %% function definition
def keypointToDictionaries(keypoint):
    x, y = keypoint.pt
    pt = float(x), float(y)
    angle = float(keypoint.angle) if keypoint.angle is not None else None
    size = float(keypoint.size) if keypoint.size is not None else None
    response = float(keypoint.response) if keypoint.response is not None else None
    class_id = int(keypoint.class_id) if keypoint.class_id is not None else None
    octave = int(keypoint.octave) if keypoint.octave is not None else None
    return {
        'point': pt,
        'angle': angle,
        'size': size,
        'response': response,
        'class_id': class_id,
        'octave': octave
    }

def dictionariesToKeypoint(dictionary):
    kp = cv2.KeyPoint()
    kp.pt = dictionary['pt']
    kp.angle = dictionary['angle']
    kp.size = dictionary['size']
    kp.response = dictionary['response']
    kp.octave = dictionary['octave']
    kp.class_id = dictionary['class_id']
    return kp

def rootSIFT(dictionary, image_name, image_path,eps=eps):
    # SIFT init
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    sift = cv2.xfeatures2d.SIFT_create()
    keypoints, descriptors = sift.detectAndCompute(image, None)
    descriptors /= (descriptors.sum(axis=1, keepdims=True) + eps)
    descriptors = np.sqrt(descriptors)
    print('Finito di calcolare, PID: ', os.getpid())
    lock.acquire()
    dictionary[image_name]['keypoints'] = keypoints
    dictionary[image_name]['descriptors'] = descriptors
    lock.release()

def featureMatching(reference_image, reference_descriptors, reference_keypoints, test_image, test_descriptors,
                    test_keypoints, flann_trees=flann_trees, flann_checks=flann_checks):
    # FLANN parameter
    FLANN_INDEX_KDTREE = 1
    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=flann_trees)
    search_params = dict(checks=flann_checks)  # or pass empty dictionary
    flann = cv2.FlannBasedMatcher(index_params, search_params)
    flann_matches = flann.knnMatch(reference_descriptors, test_descriptors, k=2)
    matches_copy = []
    for i, (m, n) in enumerate(flann_matches):
        if m.distance < distanca_coefficient * n.distance:
            matches_copy.append(m)
    gsm_matches = cv2.xfeatures2d.matchGMS(reference_image.shape, test_image.shape, keypoints1=reference_keypoints,
                                           keypoints2=test_keypoints, matches1to2=matches_copy,
                                           withRotation=gms_withRotation, withScale=gms_withScale,
                                           thresholdFactor=gms_thresholdFactor)
#%% Starting reference list file creation
reference_init = datetime.now()
print('Start reference file list creation')
reference_image_process_list = []
manager = Manager()
reference_image_dictionary = manager.dict()
reference_image_list = manager.list()
for root, directories, files in os.walk(references_path):
    for file in files:
        if file.endswith('.DS_Store'):
            continue
        reference_image_path = os.path.join(root, file)
        reference_name = file.split('.')[0]
        image = cv2.imread(reference_image_path, cv2.IMREAD_GRAYSCALE)
        reference_image_dictionary[reference_name] = {
            'image': image,
            'keypoints': None,
            'descriptors': None
        }
        proc = Process(target=rootSIFT, args=(reference_image_list, reference_name, reference_image_path))
        reference_image_process_list.append(proc)
        proc.start()

for proc in reference_image_process_list:
    proc.join()

reference_end = datetime.now()
reference_time = reference_end - reference_init
print('End reference file list creation, time required: ', reference_time)

A: I faced pretty much the same error. It seems that the code hangs at detectAndCompute in my case, not when creating the dictionary. For some reason, sift feature extraction is not multi-processing safe (to my understanding, it is the case in Macs but I am not totally sure.)
I found this in a github thread. Many people say it works but I couldn't get it worked. (Edit: I tried this later which works fine)
Instead I used multithreading which is pretty much the same code and works perfectly. Of course you need to take multithreading vs multiprocessing into account


Q: Ionic android app works fine on mobile data but failed to send http request on wifi I am developing app on ionic and angularjs.
Webservices deployed on cloud based server.
My android app is working fine on mobile data but not in wifi.
App Permissions
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="${applicationId}.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.INTERNET" />


Q: How to sort a collected based on descending order in laravel? I am very new to the laravel , i have one collection i want to sort the collection based on the id by using sortBy() method but it's not working,please help me to achieve this thing ..
 $new=collect($transformed['data']);
       $v= $new->sortByDesc(function($prod,$key){
            return count($prod['id']);
        });
        dd($v->all());

error:- count(): Parameter must be an array or an object that implements Countable


Q: Why does this `while` loop not process all records when it changes the data? I have a PHP while loop in a WordPress script that only seems to process half of the records it's supposed to when it modifies the data, and I'm struggling to see why this is happening.
I'm writing a WP-CLI script that will set a meta with key reviewed and value 1 on all comments that don't already have it. My script looks like this:
class Mark_Comments_Reviewed {

    public function __invoke() {

        $limit  = 100;
        $offset = 0;

        while ( $comment_ids = $this->get_unreviewed_comments( $limit, $offset ) ) {

            array_walk(
                $comment_ids,
                function ( $comment_id ) {
                    $comment_id = (int) $comment_id;
                    $this->process_comment( $comment_id );
                }
            );

            $offset += $limit;
        }
    }

    protected function get_unreviewed_comments( int $limit, int $offset ): array {

        global $wpdb;

        return $wpdb->get_col(
            $wpdb->prepare(
                "SELECT DISTINCT comments.comment_ID
                        FROM wp_comments AS comments
                        AND comments.comment_ID NOT IN (
                            SELECT meta.comment_id
                            FROM wp_commentmeta AS meta
                            WHERE meta.meta_key = 'reviewed'
                        )
                        LIMIT %d
                        OFFSET %d",
                $limit,
                $offset
            )
        );
    }

    protected function process_comment( int $comment_id ): bool {
        return ! ! update_comment_meta( $comment_id, 'reviewed', (int) true );
    }

}

(The wp_commentmeta table has fields meta_id, meta_key,meta_valueandcomment_id, and the last field relates to the ID of a comment record in thewp_comments` table.)
I have 810 comments without the meta. When I run the script like this, it finishes having processed 410. When I replace the $this->process_comment( $comment_id ); line with return true, the script "processes" all 810.
With the process_comment call restored, I have to run the script four times to process all 810 records.

*

*The first time, the script loops 6 times and processes 410 records. The database confirms 400 remain. Apart from the fact the loop finishes early, this is weird because 6 batches of 100 should be 600.

*The second time, it loops 3 times and processes 200 records, leaving 200. So it's done 200 instead of 300.

*The third time, it loops 2 times and processes 100 records, leaving 100.

*The fourth time it loops once and leaves no unchanged records.

Clearly something in the updating of the comment metas is causing the loop to finish before it should. Am I missing something obvious?

EDIT
I've found the script is only processing every other batch of 100 records.

A: Aaaargh! It was the offset! When I remove it, the script processes all the records as intended.
The first iteration of the loop processed the first 100 records, removing them from the set of records that didn't have the meta value. This left 710. But the next iteration started from offset 100, which meant the first 100 of those 710 weren't processed. I didn't need an offset – I just needed to select the first batch of remaining records each time.
The corrected script is
class Mark_Comments_Reviewed {

    public function __invoke() {

        $limit  = 100;

        while ( $comment_ids = $this->get_unreviewed_comments( $limit ) ) {
            array_walk(
                $comment_ids,
                function ( $comment_id ) {
                    $comment_id = (int) $comment_id;
                    $this->process_comment( $comment_id );
                }
            );
        }
    }

    protected function get_unreviewed_comments( int $limit ): array {

        global $wpdb;

        return $wpdb->get_col(
            $wpdb->prepare(
                "SELECT DISTINCT comments.comment_ID
                    FROM wp_comments AS comments
                    AND comments.comment_ID NOT IN (
                        SELECT meta.comment_id
                        FROM wp_commentmeta AS meta
                        WHERE meta.meta_key = 'reviewed'
                    )
                    LIMIT %d"
                $limit
            )
        );
    }

    protected function process_comment( int $comment_id ): bool {
        return ! ! update_comment_meta( $comment_id, 'reviewed', (int) true );
    }

}


Q: Instantiating class with parameterized constructor from COM Is it possible to call the parameterized constructor with COM?
I am going to create an instance of C# class which has parameterized constructor with COM.
Now it raises the Memory Excpetion. so I am not sure about instantiation of C# class carrying the  parameterized constructor with COM. So Please let me know about the same.
My C# constructor is
public GetNumberFromClass(NumberClass number)
{
}

C++ Constructor:
NumberFromC#::NumberFromC#
{
    getNumberFromClassPtr.CreateInstance(__uuidof(GetNumberFromClass));
}

and the pointer getNumberFromClassPtr throws memory exception as it comes NULL .

A: That's not possible, COM doesn't have a mechanism to pass arguments to a constructor.  This is most visible in your C++ snippet, you specified the GUID of the class with the __uuidof keyword as required but you didn't pass a NumberClass argument.  You can't.
What goes wrong next is that you didn't check for an error, CreateInstance() returns an HRESULT.  Which would have told you that the method failed.  The embedded interface pointer is still NULL and that's going to blow your program with an access violation when you just keep motoring on.
Start fixing this by first getting rid of that constructor in your C# class, it must have a default constructor to be usable by COM.  Add a property of type NumberClass so you can set that value after the object is created.  And of course improve the error handling in your C++ code, these kind of failures just become completely undiagnosable if you don't have any.  You must check the return value of CreateInstance() and you must add try/catch blocks in the code that uses the object so you can catch the _com_error exceptions that will be thrown when a method call fails.


Q: How can I use Google Chrome as a node.js server? I copy/pasted a node js hello world example into an html file
<html>
<head>
<script>
var http = require("http");

http.createServer(function (request, response) {

   // Send the HTTP header
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

</script>

</head>
</html>

I'm using a Chrome app called OK 200! Server to make this page available at http://127.0.0.1:8887/
The ideal solution would work on a Google Chromebook.
When I run this it gives error:

Uncaught ReferenceError: require is not defined(…)

So that implies several features unique to node won't be embedded in Chrome. Is there an extension, chrome app, or native client app that would make those features available and still leverage the v8 engine already embedded in Chrome?

A: I'm not really sure about your goal ? Are you trying to run a server from a client web browser ? I'm not sure this is possible for many reason (as security for example)... I think you need to read this !
If you're just trying to run a node server on your localhost (127.0.0.1), you need to install nodejs on your computer Node.js, then you need to save your nodejs example in javascript file (named "myServer.js" for example) and run node in CLI using:
node path/to/myServer.js

And about:
Uncaught ReferenceError: require is not defined

you should see #19059580
Best regards,
Tristan

A: You could use something like electron.
It basically gives you node.js and chromium and enables you to build cross-platform desktop apps.


Q: Efficient way to store SKLearn Birch model in Snowflake (and bypass 8MB binary limit) my code is exactly that on the answer by @SimonD in this post Store and retrieve pickled python objects to/from snowflake.  However I am now running into an error

Programming Error: 100145 (22000): Binary value '800.....' is too long and would be truncated.

The object I am trying to persist is a clustering model (Birch) from skLearn. I am wondering if there is a better method for storing sklearn models in snowflake.
Thanks.


Q: How do I enter data in array from a text file in JavaScript? I would like to populate an array using the data in text file in JavaScript. The data in text file is in the following format:
0.1 0.5
0.2 0.8
0.3 0.7
0.4 0.9
0.5 0.2
and so on..

A: Some browsers support opening files in JavaScript through the FileAPI. If you want a more cross-browser solution, you'll have to use a java/swf applet, or you'll need to pass the file to a PHP server and get back its content through AJAX.
Yes, it's that complex to do something as simple as opening a file in JS. It wasn't made for this purpose, and it would be a security issue if JS could easily access any file in your PC.
As for how to parse the data, look at String.split like Blazemonger suggested, or learn how to do regular expressions.
Finally, you could store the file in this format:
[0.1, 0.5, 0.2, 0.8]

And call JSON.parse(filecontent) and it would return an array with the values. JSON is the standard way to store JS objects in files.


Q: Calling powershell script in VBA with return value Let's say I have a powershell script sorta like this:
'Hey'

Which I want to call in VBA sorta like this:
Sub CallPowerShell()

    Call Shell("powershell.exe -ExecutionPolicy Bypass C:\Users\chm\Documents\5.ps1")

End Sub

I know this works as a console window briefly pops up with the word 'Hey' in it. What I really want however, is to use this string in my VBA code.
Is there a simple way how to get a return value from a powershell script through VBA?
Ideally it would be something like this:
Dim x As String

Sub CallPowerShell()

    x = Shell("powershell.exe -ExecutionPolicy Bypass C:\Users\chm\Documents\5.ps1")

End Sub

But that just sets x to seemingly random numbers like 70640 or 30960.
I could have the powershell script write the value I want to a file and then read the file in VBA but it'd be really nice if I could skip that so I figured I'd ask here.


Q: Change File Permission in Python File System I want to change permission of file inside python file system (pyfilesystem).
Here's the code I have:
fslocal = fs.osfs.OSFS(localdir, create=True, thread_synchronize=True)
fslocal.setcontents('/file1', b'This is file 1')

Now I want to change file permission of file 1. I am using os.chmod for this
os.chmod(localdir + '/file1', stat.S_IWOTH)

However, I get this error:
Traceback (most recent call last):
File "/Users/user/.conda/envs/scram/lib/python3.4/site-packages/fs/errors.py", line 257, in wrapper

return func(self,*args,**kwds)

File "/Users/user/.conda/envs/scram/lib/python3.4/site-packages/fs/osfs/__init__.py", line 251, in listdir

listing = os.listdir(sys_path)

PermissionError: [Errno 13] Permission denied: '/Users/user/Documents/tests/function/arwan/localfs/file1

Can you please tell me if it is possible to do it and how?
Thanks.

A: One problem is that it appears you're calling chmod with the intent of adding a single permission bit.  In fact, you are setting all of the permission bits, so the call is trying to clear all of them except the one you want set.  Assuming you're on a Unix system, you will presumably want to set the user and group bits as well, including the read and execute bits.
You can do the following:
st = os.stat(path)
old_mode = st.st_mode
new_mode = old_mode | stat.S_IWOTH
os.chmod(path, new_mode)

Hopefully that will help you.


Q: Crime mapping symbology Are there any standard, publicly available symbol sets for crime mapping?  What are their intended applications and their strengths and weaknesses?

A: Not a Standard but possible the nearest to it:
But ESRI have re-vamped symbol sets and crime mapping has been added.
http://mappingcenter.esri.com/index.cfm?fa=arcgisResources.gateway
Application: ESRI, Web Mapping
http://blogs.esri.com/Support/blogs/mappingcenter/archive/2010/07/05/New-Crime-Mapping-Symbols-Available.aspx
Strengths - Freely available
Weakness - not defined - too general
Types (Homicide, Narcotics, Misdemeanor, Felony  is US based - it doesn't exist in European/UK law Murder, Manslaughter, Drug, Serious Crime is)
*Not a lawyer/solicitor/barrister

A: In the US there is a Homeland Security Standard - some of my colleagues have discussed it in an AAG paper (PDF) last year.

A: Another publicly available symbology set for crime mapping applications is the Crime Mapping Symbology (CMS).
http://emsymbology.org/Police_CAD-RMS/index.html
Intended Applications
The Crime Mapping Symbology (CMS) was created to be used in a web mapping environment.
The use of PNGs also allows for many desktop mapping applications to import the symbols for use in a non web environment.
Strengths

*

*The symbol set has been created in PNG format to allow for a broad range of software platforms.

*The symbols are intended to utilize simple intuitive pictograms that require little training to become familiar with their representations.

*The symbols are designed to be highly visible against a wide range of vector and raster based backgrounds.
Weaknesses

*

*The symbols were designed to meet the specific needs for the police forces in Pierce County, Washington rather than the overall crime mapping community.  While it was designed to meet the specific needs a particular organization those needs are also shared by many other organizations which might find value in this symbol set.

*The use of letters as modifiers are based on English words which might be limiting to Non-English based applications.


Q: Simulation of an exponentially distributed variable A one-period jump diffusion model of a stock is the following: given the stock value at $T0$, $S(T0)$, the stock value at time $T$, $S(T) = S(T0)exp(x)exp(y)$. Given the inputs $m$, $s$, $pup$, $pdown$ and $\lambda$, and:

*

*x is normally distributed with mean m and standard deviation s

*y equals 0 with probability 1 – pup – pdown (i.e. no jump).

*y is positive with probability pup; if it is positive , y is exponentially distributed with density p(y) = λexp(-λy) for y > 0.

*y is negative with probability pdown; if it is negative, y is exponentially distributed with p(y) = λexp(λy) for y < 0.

*x and y are uncorrelated & independent.

I am to write a MATLAB program that siumulates the stock prices. Two random numbers per trial are required:

*

*A uniformly distributed random number that determines if a jump has occurred

*An exponentially distributed random number that determines the size of the jump

I've transormed a uniform random variable to an exponential variable using $-ln(1 - U(a, b)) / \lambda$.
Where I'm confused is how we're using the uniformly distributed random number that determines if a jump has occurred given I am given pup and pdown. Also, why do I need an exponentially distributed random number for the jump size. I thought I just integrate the pdf? For some reason I struggle mightily with the exponential distribution.

A: Let $B$ be the indicator of what type of jump occurs, if any; $B=-1$ when there's a negative jump, $B=1$ when there's a positive jump and $B=0$ if there is no jump. Then to determine the jump, you just need to generate $B$. According to your formulation,
$$ P(B=-1) = p_{down} $$
$$P(B=1) = p_{up} $$
$$P(B=0) = 1-p_{up}-p_{down} $$
You can generate $B$ by generating a Uniform(0,1) variable $U$ and letting
$$B=-1 \ \ \ {\rm if} \ \ \ U \leq p_{down}, $$
$$B=1 \ \ \ {\rm if} \ \ \ p_{down} \leq U \leq p_{down}+p_{up} $$
and
$$B=0 \ \ \ {\rm if} \ \ \ U \geq p_{down}+p_{up}$$
Examining the Uniform(0,1) CDF will make it clear why the probabilities work out correctly.
You could integrate out $Y$ if the question were to determine the distribution of $S(T)$ analytically but I think the point is to determine its distribution by simulation.
Note: Assuming you don't have a function to generate normally distributed variables, you will also have to generate more uniforms to simulate $X$. If you use the Box-Muller transform method of generating normals, you can simulate two normals for every two uniformly distributed variables.


Q: Access store in ember.view How we can access this.store in Ember.view ?
I tried inject method , but it doesn't work for me . Is there any way to do this ?

A: This is an antipattern you want to send an action to the controller and do you work with the store in the controller.
However if you have to inject the store into the view you would do this.
Ember.onLoad('Ember.Application', function(Application) {
  Application.initializer({
    name: "store",

    initialize: function(container, application) {
      application.register('store:main', application.Store);
      ...
    }

    container.lookup('store:main');
  }
});

Application.initializer({
  name: "injectingTheStore",

  initialize: function(container, application) {
    application.inject('view', 'store', 'store:main');
  }
});


Q: How to sort MongoDB results by element in array that matches a condition? I have a collection of places which is like this :
{
"_id" : ObjectId("575014da6b028f07bef51d10"),
"name" : "MooD",
.
.
.
"categories" : [
    {
        "categoryList" : [Nightlife, Bar],
        "weight" : 8
    },
    {
        "categoryList" : [Restaurant, Italian Restaurant],
        "weight" : 4
    }
]
}

I want to search in places by a category, for example "Bar".
So, I look into categories' categoryList if there is "Bar".
After that, I want to sort by the weight of the matched category's weight,
so that the above place (where Bar weight is 8) appears before another place where Bar weight is 5.

A: You have to use aggregation framework.
Check this:
db.mongo.aggregate(
    { $unwind: '$scores' },
    { $match: {
        'scores.categoryList': 'Bar'
    }},
    { $sort: {
        'scores.weight': -1
    }}
)


Q: Generate string from table cells I am using Excel 2008 for Mac. I would like to have a cell generate a string based on the contents of the other cells on the same row.
For example, say I have the following table headers:
bob, weave, nip, tuck
And the next row (or could be any subsequent row) are multiplier numbers, for example:
2, 3, 1, 2
I would like the last cell on that row to generate a string based on the counts in each cell, the result would be:
"bob, bob, weave, weave, weave, nip, tuck, tuck"

A: With data like:

pick a cell and enter:
=REPT(A1 & ", ",A2) & REPT(B1 & ", ",B2) & REPT(C1 & ", ",C2) & REPT(D1 & ", ",D2)


Q: Unable to repair boot with Windows 8 and Ubuntu 13.04 I have a Samsung laptop NP350E7C. It comes with Windows 8 and I'm trying to install Ubuntu 13.04. The first time I installed it with the live USB, it worked, but windows stopped working. I repaired windows and now there is not way to reboot on Ubuntu. I even tried to use windows' boot manager instead of GRUB2 with no success.
I then followed the instructions at http://doc.ubuntu-fr.org/uefi?redirect=1 (disabled fastboot and secureboot in the BIOS) and re-installed ubuntu. I then had the windows blue screen as predicted by this tutorial and I could repair it with the instructions from their link.
Than, I needed to repair ubuntu's boot with boot-repair. Using the recommended options, I always get to this error:

An error occurred during the repair.
Locked-ESP detected. You may want to retry after creating a /boot/efi
  partition (FAT32, 100MB~250MB, start of the disk, boot flag). This can
  be performed via tools such as gParted. Then select this partition via
  the [Separate /boot/efi partition:] option of [Boot Repair].

According to this thread http://ubuntuforums.org/showthread.php?t=2112273 the problem is that the file /EFI/ubuntu/grubx64.efi is corrupted and then if we can remove it and run boot repair again, everything should work fine. I then removed the file using the instructions at How can I remove Ubuntu from the UEFI boot options? but every time, I run boot repair I still get the same error.
My logs are at http://paste.ubuntu.com/6081052/
Any help is very appreciated.
Thanks again

A: See this bug report. It includes a workaround, which I quote:

*

*via Gparted create another EFI partition (FAT32, 200MB, located in the first 100GB of the disk)

*move the 'boot' flag on it

*make Ubuntu use this new ESP (eg via Boot-Repair --> Recommended Repair).

See also the error message that you quoted in your question.

A: In my case (using Boot-Repair from within a Ubuntu Live USB, as explained in the 2nd option of the Boot-Repair wiki), the Locked-ESP error was caused by my partitions being mounted.
I unmounted them using gParted (right-click on each partition -> unmount), and then Boot-Repair succeeded in repairing my system (using Recommended Repair).
See also this article.


Q: Some special characters are not appearing in Text Field of Android In my app user is asked to input text. But some special characters are not appearing
User input :  test{ "@","\" }
Actual result : test{"",""}
How can I fix this ?    is there anything special required with text.setText() code ?

A: use text watcher and Input Filter interface implemetation


Q: NVD3 tooltip change event I have a nvd3 chart and a html table. I need to update table values as the user moves the mouse over the chart. Is there an event I can use to catch a nvd3 tooltip change and get the date value at the current mouse position?
My first idea was to get the nv.tooltip values on mousemove over the chart element. Not of much help.
$('#chart').mousemove(function(e) {
    console.log(nv.tooltip);
});


Q: Angular CLI 7 installed angular material 9 My pc has installed angular cli version 7.3.10 & ts 3.2.4
then i have hit below command for installing angular material>
npm install --save @angular/material @angular/cdk @angular/animations hammerjs
Now i can see angular material version 9 has installed

"@angular/animations": "^7.2.16",
"@angular/cdk": "^9.2.3",
"@angular/common": "~7.2.0",
"@angular/compiler": "~7.2.0",
"@angular/core": "~7.2.0",
"@angular/forms": "~7.2.0",
"@angular/material": "^9.2.3",

My problem is when i add material like progress bar then application could not compile and showing below errors:

*ERROR in node_modules/@angular/cdk/coercion/array.d.ts(10,60): error TS1005: ',' expected.

*node_modules/@angular/cdk/coercion/array.d.ts(10,61): error TS1005: ',' expected.

*node_modules/@angular/cdk/coercion/array.d.ts(10,75): error TS1144: '{' or ';' expected.

*node_modules/@angular/cdk/coercion/array.d.ts(10,77): error TS1011: An element access expression should take an argument.
Can anyone please help. why angular cli 7 has installed 9 material , i could not understand.

A: It appears the @angular/core is version ~7.2.0 but the @angular/material is ^9.2.3. You either need to upgrade the Angular or downgrade the Angular Material library. I'd rather downgrade the Material library. Try the following commands in order
npm uninstall @angular/material
npm uninstall @angular/cdk
npm install @angular/material@7.2.0
npm install @angular/cdk@7.2.0

A: I'm not sure why this happened (normally the dependencies of material 9 are set to angular 9), but you can delete it and resintall the correct version again
npm un -S @angular/material @angular/cdk
npm add -S @angular/material@7 @angular/cdk@7


Q: Field calculator: generate n fields reporting n-largest values I have a polygon shapefile and I need to generate n new fields reporting the n largest values across k variables. In this particular case n = 3, so that I would like to create three new fields: "max_area_1", "max_area_2", "max_area_3", with the highest, the second and third largest, values across variables x1, x2, ..., xk.
To make things clearer, consider this simpliefied version of my data:
x1  x2  x3  x4
10  31  73  14
 7  69  55   2
91   9  87  13

What I would like to get is:
x1  x2  x3  x4  max_area_1  max_area_2  max_area_3
10  31  73  14      73          31          14
 7  69  55   2      69          55           7
91   9  87  13      91          87          13

Using the field calculator in Python console of QGIS, I can compute the highest value using the max function. My code is:
crops = [x1, ..., xk]
processing.run("qgis:fieldcalculator", {
    "INPUT": input_layer,
    "FIELD_NAME": "max_area_1",
    "FIELD_TYPE": 0,
    "NEW_FIELD": True,
    "FORMULA": 'max(crops)',
    "OUTPUT":  output_layer})

Any idea on how I can compute, in PyQGIS, three new fields reporting the three largest values across the relevant variables?

A: You can also use the following script without any Processing tool. The script doesn't create any layer, it adds fields to the active layer and assigns values.
from PyQt5.QtCore import QVariant

lyr = iface.activeLayer()

# crops fields
cfs = ["x1","x2","x3","x4"]

# new fields list
nf = [QgsField("max_area_1", QVariant.Int),
      QgsField("max_area_2", QVariant.Int),
      QgsField("max_area_3", QVariant.Int)]

# add fields to layer
lyr.dataProvider().addAttributes(nf)
lyr.updateFields()

# new field indices
idx = [lyr.fields().indexOf(f.name()) for f in nf]

attr_map = {} # {id: {index: value}, id: {index: value}, ...}
for f in lyr.getFeatures():
    vals = sorted([f[c] for c in cfs], reverse=True)
    attr_map[f.id()] = {idx[0]: vals[0],
                        idx[1]: vals[1],
                        idx[2]: vals[2]}

lyr.dataProvider().changeAttributeValues(attr_map)

A: You can use this script. First, select a the layer, then run the script. It adds the result as a memory layer. You should save the result as a new file manually or using a code.
input_layer = iface.activeLayer()
max_area_x = ["max_area_1", "max_area_2", "max_area_3"]

for i in range(len(max_area_x)): # OR for i in [0, 1, 2]
    input_layer = processing.run("qgis:fieldcalculator",
        {"INPUT": input_layer,
        "FIELD_NAME": max_area_x[i],
        "FIELD_TYPE": 0,
        "NEW_FIELD": True,
        "FORMULA": 'array_sort(array("x1", "x2", "x3", "x4"), False)[' + str(i) + ']',
        "OUTPUT": "TEMPORARY_OUTPUT"})["OUTPUT"]

QgsProject.instance().addMapLayer(input_layer)

It works in QGIS 3.8. I have not tested in other versions.


Q: Any way to make Project References work without loading them in the solution in Expression Blend? We have a Solution with 25 projects in it referencing each other and it builds successfully in  Visual Studio 2012.
But when it comes to Expression Blend (Blend for Visual Studio 2012), I am having the following issues :
1) The solution fails to build. Gives me missing references, missing resource dictionary errors.
2) Takes long time to load or perform any operation.
I am wondering if there is any way to just load my main project in to a solution and still make the project references work.
Does the order in which the individual projects are compiled in a solution matter in Expression Blend? I am not sure why the blend is unable to find the resource dictionaries when it is seen clearly in Visual Studio 2012.


Q: operator << in c# i couldn't understand this code in c#
int i=4
int[] s =new int [1<<i];
Console.WriteLine(s.length);

the ouput is 16
i don't know why the output like that?

A: bit shift operator

A: From documentation

If first operand is an int or uint
  (32-bit quantity), the shift count is
  given by the low-order five bits of
  second operand.
If first operand is a long or ulong
  (64-bit quantity), the shift count is
  given by the low-order six bits of
  second operand.
Note that i<<1 and i<<33 give the same
  result, because 1 and 33 have the same
  low-order five bits.

This will be the same as 2^( the actual value of the lower 5 bits ).
So in your case it would be 2^4=16.

A: I'm assuming you mean i in place of r...
<<n means "shift left by n* bits". Since you start with 1=binary 00...00001, if you shift left 4 times you get binary 00...10000 = 16 (it helps if you are familiar with binary arithmetic - otherwise "calc.exe" has a binary converter).
Each bit moves left n places, filling (on the right) with 0s. *=note that n is actually "mod 32" for int, so (as a corner case) 1 << 33 = 2, not 0 which you might expect.
There is also >> (right shift), which moves for the right, filling with 0 for uints and +ve ints, and 1 for -ve ints.

A: << is the left shift operator
x << y

means shift x to the left by y bits.
3 is 0011, 3<<1 is 0110 which 6.
It's usually used to multiply by 2 (shifting to the left is multiplying by 2)

A: As already mentioned, << is the left shift operator.  In your particular example, the array size is being defined as a power of 2.  The value 1 shifted left by some number is going to be 1, 2, 4, 8, 16, ...


Q: Running git on shared host I have a non-sudo account on a shared host. I want to be able to run the git-core for version control.
I have another server that I am using for the git-repo.
How can I install a version of git inside of my user folder and execute that.
I have shell access and the server is CentOS/Redhat/Fedora.

A: If you have access to the compiler, you should be able to download the source archive, build it, and install it in your home directory.
You can get a source archive from http://www.kernel.org/pub/software/scm/git/. The most recent release is 1.7.4.2, so you would get git-1.7.4.2.tar.bz2. You may also want git-manpages-1.7.4.2.tar.bz2 and/or git-htmldocs-1.7.4.2.tar.bz2. There are .gz versions available if you can not uncompress .bz2 files.
Git’s Makefile actually defaults to installing in your home directory. If you already have a well populated ~/bin (etc.) and you want to install Git separately, then you can have it install everything under a some other “prefix” in your home directory. Using a unique prefix also makes it easy to uninstall or wipe and upgrade.
make install prefix="$HOME/git"

The Makefile has many comments describing the variables that control the build process. It also includes reasonable defaults for most platforms. You can tweak any of the settings by editing the file itself or putting your customizations in a config.mak file (it is automatically included if it exists).
Unless you are on an exotic system, you can skip using ./configure. The autoconf stuff works, but sometimes it rusts a bit since most of Git’s developers just use the Makefile directly.

If you do not have access to the compiler on your target machine, then you will need access to a machine with a similar OS installation. Build with prefix set to the path that will be used on the target machine and set DESTDIR to a temporary location (on the build machine).
# On the "build" machine:
make install prefix=/home/dir/on/target/git DESTDIR=/tmp/git-dest
cd /tmp/git-dest/home/dir/on/target && tar cjf git-for-target.tar.bz2 git
# transfer the file to "target" machine

# On the "target" machine:
cd /home/dir/on/target && tar xjf git-for-target.tar.bz2


Q: Upload to YouTube directly from stdin via Data API? As the title says, I want to pipe the output of a commandline encoder (that's recording a livestream) directly to YouTube via stdin.
Does the YouTube Data API have this functionality or is there some other little trick in order to accomplish this?


Q: How can we give a color with specific color code in the styles.xml in Android Studio? I want to change the status bar color to a specific color with a color code. Only the default colors can be specified in the code as given below, is there any way to give a specific color code to get that color?
<item name="android:statusBarColor">@color/dark_blue_Shade1</item>

A: create a color.xml into values folder
code for color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
        <color name="dark_blue_Shade1">#000080</color>
</resources>

if the color.xml already exists there then just put the
<color name="dark_blue_Shade1">#000080</color>

inside <resources>   </resources>  tag

A: create color.xml file inside values folder
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ColorPrimary">#8E67E0</color>
    <color name="ColorPrimaryDark">#59419B</color>
    <color name="LightPrimaryColor">@android:color/holo_blue_bright</color>
    <color name="AccentColor">#ff4081</color>
    <color name="PrimaryText">#212121</color>
    <color name="SecondarText">#727272</color>
</resources>

and then in style.xml file change like this
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/ColorPrimaryDark</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <item name="colorAccent">@color/AccentColor</item>
    </style>
</resources>

From this your entire project will take this colors.

ColorPrimaryDark

is your status bar color you dont want to apply it manually system will get colorPrimaryDark as your status bar color