text:
Q: What is an ultradrive spine? I've read the whole of A Fire Upon the Deep and I still can't figure out what an ultradrive spine is? Is it an engine or something else?

A: The Ultradrive technology

*

*Only works outside the 'slow zone'. The galaxy in Verne's universe consists of 'zones of thought', the level of technology available depends on which zone you are in.

*The closer you are to the galactic core, only rudimentary tech works and FTL is not possible... hence, the 'slow zone'.

*The further out from the core, more and more advanced tech becomes operable. The spines are merely an element of the jump propulsion system of the Ultradrive.

A Fire Upon the Deep: The novel posits that space around the Milky Way is divided into concentric layers called Zones, each being constrained by different laws of physics and each allowing for different degrees of biological and technological advancement.

*

*The innermost, the "Unthinking Depths", surrounds the galactic core and is incapable of supporting advanced life forms at all. The next layer, the "Slow Zone", is roughly equivalent to the real world in behavior and potential.

*Further out, the zone named the "Beyond" can support futuristic technologies such as AI and FTL travel. The outermost zone, the "Transcend", contains most of the galactic halo and is populated by incomprehensibly vast and powerful posthuman entities.

A: In A Fire Upon the Deep Vinge has a tendancy to throw ideas around with very little discussion. Personally I love this style of writing because it makes for wonderful scenery without the tedious expositions that hard Sci-Fi authors are prone to. However it does mean there is simply no answer to your question. It's clear from the book that the spines are just a component of the ultradrive - the ultradrive still works with some spines missing or damaged. My interpretation is that the spines couple the ultradrive to whatever facet of the universe the ultradrive interacts with.

A: It's certainly propulsion, but I'm not sure that "engine" is entirely accurate. In the Beyond and especially the Transcend, what would be normal physics goes haywire, and things that would be impossible here (the Slow Zone) are quite typical. As far as I understand the book, you don't even need reaction mass to move.

A: Vinge is quite hard on scifi and as John Rennie points, Vinge writes throwing big ideas and leaving fine tunning to the readers.
I got to the point where the drive spines where conducting the interaction between the ship and the medium/high Zones.
Remember there is a physics effect recalling the use of spin-like extensions - this is usually known as antenna - to concentrate electrons at its sharpest point, where space tends to zero (the last -metal- atom actually composing the antenna body) and charge or whatever desired physical effect takes place at its maximum expression (this is roughly valid, antenna structure may change this).
Long story short, yes, the ultradrive spines are kinda exhaust, or power transmission at least in a "normal" universe, which leads us to the undefined physics layered universe drawn by Vinge. Thus you can imagine the spines cover the entire ship isolating its local field from the outer field and producing motion through physical space at insane speed.


text:
Q: ZeroDivisionError in numpy.average I am calculating a weighted average value on numpy:
np.average(df['column1'], weights=df['column2'])

I received this error: Weights sum to zero, can't be normalized
Is there an argument I can use to solve this problem?

A: can you try:
(df['column1'].values*df['column2'].values).sum()/df['column2'].sum()

?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve fields of all documents in mongodb collection I am trying to retrieve all Fields of all Documents and embeded Documents in Mongo collection.
this is an example of one document:
{
   "_id": {
      "$oid": "53b309def468718462e0c390"
   },
   "customer": {
      "companyName": "Vins et alcools Chevalier",
      "contactName": "Paul Henriot",
   },
   "employee": {
      "employeeId": 5,
      "firstName": "Steven",
      "lastName": "Buchanan"
   },
   "orderItems": [
      {
         "productName": "Queso Cabrales",
         "unitPrice": 14,
         "quantity": 12
      },
      {
         "productName": "Singaporean Hokkien Fried Mee",
         "unitPrice": 9.8,
         "quantity": 10
      }
   ],
   "orderId": 10248,
   "orderDate": {
      "$date": "1996-07-04T07:00:00.000Z"
   },
   "requiredDate": {
      "$date": "1996-08-01T07:00:00.000Z"
   },
   "shippedDate": {
      "$date": "1996-07-16T07:00:00.000Z"
   },
   "shipVia": "Federal Shipping",
   "freightCost": 32.38
}

Here is my code and output:
MongoCursor<Document> cursor;
MongoCollection<Document> collection = database.getCollection("test");
cursor = collection.find().iterator();
try {
    while (cursor.hasNext()) {
         //System.out.println(cursor.next().toJson());
         System.out.println(cursor.next().get("key"));
    }
} finally {
    cursor.close();
}

And this is the out put :
null null null null null ...

i want only the Name part, but it's not working.

i'm using java driver 3.12.4 with mongodb v4.2

Tank you.

A: Try this:
private void printFields(){
    MongoCursor<Document> cursor;
    MongoCollection<Document> collection = database.getCollection("user");
    cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            //System.out.println(cursor.next().toJson());

            for (Map.Entry<String, Object> entry : cursor.next().entrySet())
            {
                System.out.println(entry.getKey() + "/" + entry.getValue());
            }
        }
    } finally {
        cursor.close();
    }
}


text:
Q: is it possible to run sails & nuxt on a single express instance? I understand that the intended setup is.
Seperate backend server (e.g. Sails, Laravel, ...)
plus frontend server with nuxt.js or prerendered static content generated with nuxt and statically hosted (e.g. AWS S3, now, ...)
I am wondering if it is also possible to run sails and nuxt within the same node/express instance.

A: Nuxt.js can be used as a middleware so i think you can. Check the docs: Using nuxt.js programmatically


text:
Q: Removing column in a list in linq I have a list I want to remove the column RiskRegisterEntryId and RiskRegisterTypeId how can I to do that..?
 SeriesNumber       RiskRegisterEntryId RiskRegisterTypeId  RiskRegisterType
 RCMSRA19111300001      1               1                   Site Risk Audit
 RCMSRA19111300002      2               1                   Site Risk Audit
 RCMSRA19111300003      3               1                   Site Risk Audit
 RCMSRA19111300004      4               1                   Site Risk Audit
 RCMSRA20111300016      16              1                   Site Risk Audit

A: You can just create a new list of an anonymous type without those columns:
var newList = myList.Select(l => new {
     l.SeriesNumber , l.RiskRegisterType
    }).ToList();

A: List.Select(x => new { x.SeriesNumber, x.RiskRegisterType});

This will create a list with an anonymous type containing only those two fields.


text:
Q: drop rows if the two columns have non-missing values but have different values I have the following df
sender_name receiver_name
NaN         Carl
Carl        Carl
Peter       Carl
Carlos      Matt
Julia       Bernard
Carlos      NaN
Peter       NaN
NaN         Matt
...

I want to drop if sender_name != receiver_name
If i do
df=df.drop(xfers_dex['name_sender'] != xfers_dex['name_receiver'])

It drops all rows with NaN values..
I only want to drop if both columns have non-missing values. so my desired df
sender_name receiver_name
NaN         Carl
Carl        Carl
Carlos      NaN
Peter       NaN
NaN         Matt
...

A: Another possible solution:
df[(df['sender_name'] == df['receiver_name']) | (df.isnull().any(axis=1))]

Output:
  sender_name receiver_name
0         NaN          Carl
1        Carl          Carl
5      Carlos           NaN
6       Peter           NaN
7         NaN          Matt

A: Extend the condition so it also checks that values are different than NaN:
df=df.drop((xfers_dex['name_sender'] != xfers_dex['name_receiver']) & (xfers_dex['name_receiver'] != 'NaN') & (xfers_dex['name_sender'] != 'NaN'))


text:
Q: Can 2D matrix be rotated with 90° in a better time complexity than O(n^2)? Here is an example input/output of a matrix rotation:
Input: [[1,2,3,],[4,5,6],[7,8,9]]
Output: [[7,4,1], [8,5,2], [9,6,3]]

I understand that a rotation can be performed with O(n^2) time complexity.
Is there a quicker solution possible? What would it be?

A: No, a matrix of width/height n cannot be rotated with a better time complexity than O(n²). This is because there are O(n²) values that need to be moved.
However, there is a way that you could get around this:
You could decide to not really perform the rotation, but just make note of the rotation, and translate any subsequent access to the matrix accordingly. If you do it like that, then a matrix rotation has O(1) time complexity.
Here is a simple demo of that idea in JavaScript. The class Matrix should be extended with all methods you want to support (like set, invert, determinant, ...etc), where each will have to take into account this particularity. But that wouldn't affect their own time complexities.

class Matrix {
    constructor(rows) {
        // Take a copy of the 2d-array passed as argument
        this.rows = [];
        for (let row of rows) {
            this.rows.push(Array.from(row));
        }
        this.rotation = 0;
        this.n = rows.length;
    }
    rotate90() {
        this.rotation = (this.rotation + 1) % 4;
    }
    get(rowIdx, colIdx) {
        switch (this.rotation) {
        case 0: return this.rows[rowIdx][colIdx];
        case 1: return this.rows[this.n-1-colIdx][rowIdx];
        case 2: return this.rows[this.n-1-rowIdx][this.n-1-colIdx];
        case 3: return this.rows[colIdx][this.n-1-rowIdx];
        }
    }
    toString() {
        let txt = "";
        for (let rowIdx = 0; rowIdx < this.n; rowIdx++) {
            txt += "\n";
            for (let colIdx = 0; colIdx < this.n; colIdx++) {
                txt += " " + this.get(rowIdx, colIdx);
            }
        }
        return txt.slice(1);
    }
}

// Demo
let m = new Matrix([[1,2,3],[4,5,6],[7,8,9]]);

console.log(m.toString());

for (let rot = 1; rot <= 4; rot++) {
    m.rotate90();
    console.log(m.toString());
}


text:
Q: using bash and rawdata, make a new data raw data corpus, and it is like below.
CT check
EPT check
Dental insurance.

and I have a prononciation file for corpus like below.
...
CT  kh eo t eu
CT  kh eo l2 t eu
CT  kh eo d2
CT  kh o t eu
CT  kh o l2 t eu
CT  kh o d2
check tʃ e k
...
...
EPT i p i t i
...
...

Now I want to make new prononciation file for original corpus like below.
CTcheck  kh eo t eu tʃ e k
CTcheck  kh eo l2 t eu tʃ e k
CTcheck  kh eo d2 tʃ e k
CTcheck  kh o t eu tʃ e k
CTcheck  kh o l2 t eu tʃ e k
CTcheck  kh o d2 tʃ e k
EPTcheck i p i t i tʃ e k
Dentalinsurance ...

I try to do it, but I am not good at bash,
its difficult.
could anybody please help me.
below is by trial, but its seemed not good.
mkdir -p $srcdir/temp
while read line; do
    echo $line | sed s/" "//g > $srcdir/temp/line.txt
    for word in $line; do
         echo -e `grep $word $srcdir/lexicon | grep -v "[[:graph:]]$word\|$word[[:graph:]]"` | wc -l >> $srcdir/temp/word.txt
         echo -e `grep $word $srcdir/lexicon | grep -v "[[:graph:]]$word\|$word[[:graph:]]"| cut -f2- ` >> $srcdir/temp/word.txt
    done

    #rm $srcdir/temp/word.txt
    exit 1
done < $srcdir/uniqWordList.mixed.normed > $srcdir/mixedlexicon

thanks and regard/

A: Could you please try following awk tested with provided samples only.
awk '
FNR==1{
  count++
}
count==1{
  a[$1]=$1 $2
  b[$2]=(b[$2]?b[$2] OFS:"")$1
  next
}
($1 in b) && count==2{
  val=$0
  sub(/[^ ]* +/,"",val)
  num=split(b[$1],array," ")
  for(i=1;i<=num;i++){
    c[array[i]]=val
  }
}
count==3 && !($1 in b){
  old=$1
  $1=a[$1]
  print $0,c[old]
}
'  Input_file1  Input_file2  Input_file2

Explanation: Adding detailed explanation for above code.
awk '                               ##Starting awk program from here.
FNR==1{                             ##Checking condition if it is first line then do following.
  count++                           ##incrementing variable count value with 1 whenever cursor comes here.
}                                   ##Closing BLOCK for FNR==1 condition here.
count==1{                           ##Checking condition if count==1 then do following.
  a[$1]=$1 $2                       ##Creating array a whose index is $1 and value is $1 $2 of current line.
  b[$2]=(b[$2]?b[$2] OFS:"")$1      ##Creating an array named b whose index is $2 and value is $1 and keep concatenating its own value here.
  next                              ##next will skip all further statements from here.
}                                   ##Closing BLOCK for count==1 condition here.
($1 in b) && count==2{              ##Checking condition ig $1 is NOT in array b and count value is 2 then do following.
  val=$0                            ##Creating variable val whose value is current line.
  sub(/[^ ]* +/,"",val)             ##Substituting everything till first space in variable val here.
  num=split(b[$1],array," ")        ##Using split of awk to split array b value with index $1 to array named array here.
  for(i=1;i<=num;i++){              ##Running a for loop from i=1 to till value of num.
    c[array[i]]=val                 ##Creating an array c whose index is array[i] and value is variable val here.
  }                                 ##Closing BLOCK for; for loop here.
}                                   ##Closing BLOCK for $1 in b condition here.
count==3 && !($1 in b){             ##Checking condition if count is 3 and $1 is NOT in array b then do following.
  old=$1                            ##Creating variable old whose value is $1 of current line.
  $1=a[$1]                          ##Setting $1 value as array a value with index $1 here.
  print $0,c[old]                   ##Printing current line with array c with index old here.
}                                   ##Closing BLOCK for count==3 && !($1 in b) condition here.
' file1 file2 file2                 ##Mentioning Input_file names here.

A: Type something like this:
#! /bin/bash

op=/tmp/old_prononciation

cat > $op <<EOF
...
CT  kh eo t eu
CT  kh eo l2 t eu
CT  kh eo d2
CT  kh o t eu
CT  kh o l2 t eu
CT  kh o d2
check tʃ e k
...
...
EPT i p i t i
...
...
EOF

check="$(sed -n 's/^check\(.*\)/\1/p' $op)"

for type in CT EPT; do
  sed -n "s/^$type \(.*\)/${type}check \1$check/p" $op
done


text:
Q: Error on gulp-uglify installation with npm I am new in nodejs and also gulp. I am going to start with node and gulp for some advancement in my development skills.
All thing are going good when installing the node js and gulp. I am checking both of this with checking there version on command prompt.
Here's the command:
node -v // for node version
npm -v // for npm

And installing the gulp with npm using command.
npm install -g gulp // gulp global

npm install --save-dev gulp // gulp in my project

After these steps, i am going to install gulp uglify.
npm install --save-dev gulp-uglify

Here's i am receiving the error. But i am not able to understand this error.

And also the path shown in command prompt for npm-debug.log. Here no file generated.
Thanks in advance.

A: You should start the installation when in the STATIC directory
 (ReactEnv) C:\Users\LUCKYPIUS\Desktop\REACT&DJANGO\APP\Reactify\static>

Do this first!
npm install --save-dev gulp

Still in the same static directory, run this..
npm install --save-dev gulp-uglify

It should be able to locate the previous files and install successfully.(meanwhile always use a virtual enviroment for your projects).
Goodluck.


text:
Q: Dynamically include a jsp file in a main view I try to include either a 'home.jsp' file or a 'error.jsp' file. This is my servlet file and my template:
// servlet
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

            // api access
        Api apix  = new Api(new ApiRequest(-1));

        // post params
        String email = request.getParameter("email");
        String password = request.getParameter("password");

        // exists?
        User user =  apix.userManager.authenticate(email, password);

        // template
        String address = "/main.jsp";

                // variable content
        String content_page = "/WEB-INF/user/home.jsp";

        if (user == null)
        {
            content_page = "/error.jsp";
        }

        request.setAttribute("content_page", content_page);
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);

        dispatcher.forward(request, response);

}

// main.jsp

<head>
    <jsp:include page="/head_includes.jsp"/>
</head>

<body>

    <%
        String content_page = request.getParameter("content_page");

        if (content_page == null)
        {
            content_page = "/error.html";
        }

    %>

            <!-- I get an error here -->
            **<jsp:include page="<%= content_page %>">**
</body>

I get this error on eclipse:
org.apache.jasper.JasperException: /main.jsp (line: 29, column: 1) Expecting "jsp:param" standard action with "name" and "value" attributes

A: Error is obvious.
main.jsp is expecting a parameter which you have to pass
either using jsp:param or querystring main.jsp?name=value


text:
Q: need angular response of post/get request out of scope, any suggestions? i am trying to get response of post/get requests , getting response successfully inside post/get,but unable to get result out of post/get .
when i print on console it is showing "undefined". any suggestions , here is my code
index.html:

{{ponies}}

Angular code:
var myApp = angular.module('myApp', []);

angular service:
myApp.factory('ponyService', function($http) {
  var getPonies = function() {
    return $http.get('https://www.w3schools.com/angular/customers.php');
  };

  return {
    getPonies: getPonies
  };
});

myApp.controller('customersCtrl', function($scope, ponyService) {

ponyService.getPonies().success(function(data) {
    $scope.ponies = data;
  });
console.log($scope.ponies); // here want to print data because want to use whole controller

});

A: That's because posts and gets are asynchronous.
Your console.log won't wait for the response.
Put your console inside success in order check it's data.
Try like this
ponyService.getPonies().success(function(data) {
    $scope.ponies = data;
    console.log($scope.ponies);
  });

or you can watch it's changes (but it's not recommended just for test purposes),
Like this
ponyService.getPonies().success(function(data) {
    $scope.ponies = data;
  });

$scope.$watch("ponies",function(val){
  if(val)
    console.log(val)
})

A: It is because a $http returns a promise (async request) so if you did something like this
ponyService.getPonies().success(function(data) {
    $scope.ponies = data;
  });
console.log($scope.ponies);

it will log undefined, as you are trying to log it before the request is finished.So you need to chain to that promise in any code that needs to access the resolved data.Like:
ponyService.getPonies().success(function(data) {
     $scope.ponies = data;
     console.log($scope.ponies);
     /* access data or $scope.ponies in here */
  });

or you can use promise like
  ponyService.getPonies().then(function (data) {
     $scope.ponies = data;
     console.log($scope.ponies);
    /* access data or $scope.data in here */
  });


text:
Q: How to debug CrashDump of ASP.NET 4.5 - symbols mismatch / missing? Having sporadic w3wp.exe crashes on productive system
Neither way of debugging the CrashDump using WinDbg or VisualStudio2012 was successful
VS2012:  Debugging information for w3wp.exe cannot be found or does not match.
No symbols loaded for System.Web.ni.dll - No matching binary found.
OurOwnCustom.dll: No matching binary found
WinDbg:  PSSCOR4 not supporting .NET 4.5
StackTraces not showing managed server code at all
How should we debug ASP.NET 4.5 CrashDumps successfully?
Or is this currently not possible due to missing public symbols for .NET 4.5?


text:
Q: In SQL Server, how do you determine the number of rows per page? In SQL Server, how do you determine the (average or expected) number of rows per page?
I know know how to determine the average and max row size, but I don't know how that relates to actual rows/page.

A: 8060 bytes per page, 8 pages per extent...remember that if you row is 4040 bytes then you can only fit one row on the page
DBCC SHOWCONTIG will give you how many pages your table is using

A: Pages are 8K in size including a 96byte header. So if you know the row size, you could make an estimate of how many rows would fit onto the data portion of a page.


text:
Q: implementation of c2dm in android I am developing android video application.In which i have to implement cloudtodevicecomputing.
Can anyone suggest me how should i pursue,,,,
Thanks in advance
Tushar

A: you need to register your application with the Google server and receive the respective registration token from the server in order to use c2dm in your application
this link will help you to follow the procedure to register your application


text:
Q: memset 'CortexA8' issue under iOS5 Since iOS5 hit the streets I have begun I have been receiving many (so many) crash reports like:
...
Exception Type:  SIGSEGV
Exception Codes: SEGV_ACCERR at 0x0
Crashed Thread:  0

Thread 0 Crashed:
0   libsystem_c.dylib  0x35ec4b3c memset$VARIANT$CortexA8 + 116
1   FooApp             0x0005ba25 -[FooViewController prepareShapes] (FooViewController.m:808)
...

Relevant details:

*

*XCode 4.2

*LLVM 3.0

*'armv6 armv7' architectures

*iOS 5 base SDK

*targeting iOS 4.0

*crashes under iOS5 only (all iOS5 iPhone models. No iPad crashes but app isn't universal)

*Can't reproduce the crash on any of my devices (of course)

Now [FooViewController prepareShapes] doesn't call memset directly, instead passes a struct (representing a shape) to a class method that attempts to realloc it. The fact that the stack trace skips over the class method is a bit weird but no doubt it's yet more compiler magic I don't understand. Within the class method, the block that invokes memset is as follows:
// class method invoked by [FooViewController prepareShapes]:808 (shape is coloured2DShape instance)
shape->maxVertexCount = maxVertexes;
if (shape->maxVertexBytes != 0)
{
    free(shape->vertices);
}
shape->maxVertexBytes = sizeof(vertex_2D_4byteColour) * shape->maxVertexCount;
shape->vertices = (vertex_2D_4byteColour *)malloc(shape->maxVertexBytes);
memset(shape->vertices, 0, shape->maxVertexBytes);

And here's the struct being manipulated
// coloured2DShape struct
typedef struct coloured2DShape
{
    vertex_2D_4byteColour* vertices;
    GLushort* indices;
    uint maxVertexBytes;
    uint maxIndexBytes;
    int vertexCount;
    int indexCount;
    int maxVertexCount;
    int maxIndexCount;
} coloured2DShape;

I recognise that this isn't anywhere close to the recommended way to do OpenGL, however the thing that really bamboozles me (and I am well and truly bamboozled here) is that memset is only blowing up under iOS5 (I'm using QuincyKit to collect crash reports and HockeyApp to aggregate them). This exact code had been cruising along under iOS4 (compiled with GCC) for months.
I hope this isn't interpreted as a 'do my homework' thing. I have spent months researching, tweaking (I've released several updates addressing this issue) and hair-pulling with no progress. I'm all out of ideas.

A: I'd think that memset is working fine, but the call to malloc failed for some reason, returning 0.

A: I'm gonna publish the soution of similar crash I found after hour of debugging, maybe it would be useful for somebody...
The reason was in so stupid thing.
I had two placeholders in NSLog and only one real variable.
NSLog(@"lastItemDate = %@ unixtime = %@", lastItemDate);


text:
Q: RabbitMQ / Celery with Django hangs on delay/ready/etc - No useful log info So I just setup celery and rabbitmq, created my user, setup the vhost, mapped the user to the vhost, and ran the celery daemon succesfully (or so I assume)
(queuetest)corky@corky-server:~/projects/queuetest$ ./manage.py celeryd
 celery@corky-server v0.9.5 is starting.
 Configuration ->
. broker -> amqp://celery@localhost:5672/
. queues ->
. celery -> exchange:celery (direct) binding:celery
. concurrency -> 2
. loader -> celery.loaders.djangoapp
. logfile -> [stderr]@WARNING
. events -> OFF
. beat -> OFF

Celery has started.

I created a user of "celery" because I wasn't feeling very inventive in this case.
When I try to do one of the simple examples within the celery docs:
>>> from tasks import add
>>> r = add.delay(2, 2)
>>> r
<AsyncResult: 16235ea3-c7d6-4cce-9387-5c6285312c7c>
>>> r.ready()
(hangs for eternity.)

So I checked the FAQ wondering what else could be up and it told me this is a common bug due to user permissions, so I triple checked those, nothing, made another new user, still nothing. If I import DjangoBrokerConnection from carrot.connection and get the information, it matches up with what's in my celery settings. The FAQ stated to check your log file.
My rabbit.log file isn't very helpful in this situation, simply showing:
=INFO REPORT==== 26-Jan-2010::11:58:22 ===
accepted TCP connection on 0.0.0.0:5672 from 127.0.0.1:60572

=INFO REPORT==== 26-Jan-2010::11:58:22 ===
starting TCP connection <0.1120.0> from 127.0.0.1:60572

And so forth. At this point, I'm at a loss as to what else my problem could be. I'm running Ubuntu Jaunty and installed RabbitMQ from apt-get.
Thanks in advance for any help.

A: I just fixed a really ugly bug that would only show up for new users that would have caused this. (http://github.com/ask/celery/commit/a9c1316b15055b67ee3c38d294461fa82ed6d2b5)
Please pull from the master branch at github. If it still doesn't work you
probably have to stop rabbitmq, remove the rabbitmq database directory (usually /var/lib/rabbitmq) and start rabbitmq again)
Really sorry for the inconvenience.
The bug happened because we recently changed the name of the consumers routing key option to "binding key", but the amqp libraries still use routing_key and we forgot to rewrite the option.

A: For anyone stumbling upon this: it really does seem to help to remove your /var/lib/rabbitmq, even if the problem seems to go away with updating celery. I was seeing lots of unreliability and unpredictability until I did so.


text:
Q: Split nested array into multiple arrays I have a string that looks like this:
str = {1|2|3|4|5}{a|b|c|d|e}

I want to split it into multiple arrays. One containing all the first elements in each {}, one containing the second element, etc. Like this:
arr_0 = [1,a]
arr_1 = [2,b]
arr_2 = [3,c]

.....
The best I can come up with is:
var str_array = str.split(/}{/);

for(var i = 0; i < str_array.length; i++){
    var str_row = str_array[i];
    var str_row_array = str_row.split('|');
    arr_0.push(str_row_array[0]);
    arr_1.push(str_row_array[1]);
    arr_2.push(str_row_array[2]);
    arr_3.push(str_row_array[3]);
    arr_4.push(str_row_array[4]);
}

Is there a better way to accomplish this?

A: Try the following:
var zip = function(xs, ys) {
  var out = []
  for (var i = 0; i < xs.length; i++) {
    out[i] = [xs[i], ys[i]]
  }
  return out
}

var res = str
  .split(/\{|\}/) // ['', '1|2|3|4|5', '', 'a|b|c|d|e', '']
  .filter(Boolean) // ['1|2|3|4|5', 'a|b|c|d|e']
  .map(function(x){return x.split('|')}) // [['1','2','3','4','5'], ['a','b','c','d','e']]
  .reduce(zip)
/*^
[['1','a'],
 ['2','b'],
 ['3','c'],
 ['4','d'],
 ['5','e']]
*/

A: Solution
var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) {
       return a.match(/[^|]+/g);
    }),
    i,
    result = {};

for (i = 0; i < str[0].length; i += 1) {
  result["arr_" + i] = [+str[0][i], str[1][i]];
}

How it works
The first part, takes the string, and splits it into the two halves. The map will return an array after splitting them after the |. So str is left equal to:
[
    [1,2,3,4,5],
    ['a', 'b', 'c', 'd', 'e']
]

The for loop will iterate over the [1,2,3,4,5] array and make the array with the appropriate values. The array's are stored in a object. The object we are using is called result. If you don't wish for it to be kept in result, read Other
Other
Because you can't make variable names from another variable, feel free to change result to window or maybe even this (I don't know if that'll work) You can also make this an array
Alternate
var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) { return a.match(/[^|]+/g); }),
    result = [];

for (var i = 0; i < str[0].length; i += 1) {
  result[i] = [+str[0][i], str[1][i]];
}

This is very similar except will generate an Array containing arrays like the other answers,


text:
Q: How a detached node could merge into a git branch? I am using GitKraken on Windows. While I was pulling remote branch into local, I saw this wired log graph, circled in the image. It looks like there's a detached node, a node without parent, but it is able to merge with another branch...not sure what does this means, any idea?

Update after @VonC's comment
In this image, the commit with hash prefix 52a66d2 is the problematic one, and it looks like it had a parent in this view.
So maybe it is GitKraken's fault?

A:
I found out commit 52a66d2 is committed almost 3 hours earlier than its parent which commit 3058015

That means 52a66d2 has a parent (3058015), and its parent link is shown.
But the display order might not be topological (the parents are not always shown before the children) but using --date=relative.
(see also git show-branch, which defines the two orders)


text:
Q: Url Rewrite in apache I am trying to rewrite urls so that whenever I type say /foo.html, I want the extension of the file to be hidden, so that on the address bar i get to see only /foo . I have tried searching and used rewritecond expressions in .htaccess file of apache server but the url is not getting changed in the address bar.
One more thing I have observed is the browser displays the content of my foo.html file when i type either /foo or /foo.html even when I remove .htaccess file.
I am using apache2 on ubuntu 12.10.

A: Add the following rule to your /.htaccess
RewriteRule ^(.*?)\.html$ $1 [R=301,L]

To remove multiple file extensions use
RewriteRule ^(.*?)\.(php|html?)$ $1 [R=301,L]


text:
Q: Include a location header in Django Rest Framework I read in a post that it is ideal to put that it is a good standard to include a Location header that points to the URL of the new resource (newly created via POST). My problem is I do not know how to include it.
I am using a class-based views using the APIView and my code in the view is:
class ListArtists(APIView):
    serializer_class = ArtistSerializer
    def get(self, request, format=None):
        _array = Artist.objects.filter()
        serializer = self.serializer_class(_array, many=True)
        if serializer.data:
            _status = status.HTTP_200_OK
        else:
            _status = status.HTTP_204_NO_CONTENT
        return Response(standardResponse(data=serializer.data), status=_status)

    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(standardResponse(data=serializer.data), status=status.HTTP_201_CREATED)
        else:
            return Response(standardResponse(errors=serializer.errors))
artist = ListArtists.as_view()

urls.py
from django.conf.urls import url, include

from store import views

urlpatterns = [
    url(r'^artists/', views.artist, name='artists-list'),
]

P.S.
Every time I throw a request using my Advanced REST Client this is the response that I receive:
Date: Sat, 23 Jul 2016 10:54:23 GMT
Server: WSGIServer/0.1 Python/2.7.10
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Allow: GET, POST, HEAD, OPTIONS

A: You can add arbitrary headers to a Response object, like so:
def post(self, request, format=None):
    serializer = self.serializer_class(data=request.data)
    if serializer.is_valid():
        obj = serializer.save()
        response = Response(standardResponse(data=serializer.data),
                            status=status.HTTP_201_CREATED)
        # If you have defined a get_absolute_url method on your model, then
        # you can use that to get a URL for the new object
        response['Location'] = obj.get_absolute_url()
        return response

A: For those using the drf CreateModelMixin the view has to look something like that:
In case you do want an empty body in the response:
class MyView(mixins.CreateModelMixin, generics.GenericAPIView):

    serializer_class = MySerializer

    def post(self, request, *args, **kwargs):
        default_response = self.create(request, *args, **kwargs)
        return Response(headers={'Location': reverse("get_enpoint_name", args=[default_response.data['id']], request=self.request)})

In case the response body has to include the objects data as specified in the serializer:
class MyView(mixins.CreateModelMixin, generics.GenericAPIView):

    serializer_class = MySerializer

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def get_success_headers(self, data):
        try:
            return {'Location': reverse("customer", args=[data['id']], request=self.request)}
        except (TypeError, KeyError):
            return {}

Always open for improvements!


text:
Q: sending smtp mail with PHPMailer I am using phpmailer to send email from a contact form. using the following code, I get the message "message sent" yet nothing ever arrives. I've tried both with my AOL account and Gmail account.
<?php
$mail = new PHPMailer();

    // ---------- adjust these lines ---------------------------------------
    $mail->Username = "account@aol.com"; // your user name
    $mail->Password = "password";  // your Password
    $mail->AddAddress("recipient@company.com"); // recipients email
    $mail->FromName = "My name"; // readable name

    $mail->Subject = "Message from BeaverMjr.info";
    $mail->Body    = $body;

    $mail->Host = "smtp.aol.com";
    $mail->Port = 587; //465 or 587
    $mail->IsSMTP(); // use SMTP
    $mail->SMTPAuth = true; // turn on SMTP authentication
    $mail->From = $mail->Username;

    //----------------------------------------------------------------------

    if(!$mail->Send())
    {
        echo "mail sent";
    }
?>

I've been scratching my head as I search the net and am getting no where. can someone show me what I'm doing wrong?

A: If you're getting the mail sent message it actually did not send because your if statement has the NOT operator in front of it.
I'd advise you set $mail->SMTPDebug = SMTP::DEBUG_SERVER; and then update your code to see what the error message is:
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';
}

A: I corrected my code and found that I had a connection error. After further review, I figured out that the port number needed to be 25. Thanks for the help.


text:
Q: How do I get Google Chrome on (Android) work with JQM? I can't make the Google Chrome (Mobile) browser scroll down the page Basically I developed a webapp using Jquery Mobile and am having problems when looking at this web app on google chrome on my Android phone. For some reason I can click buttons but when I go to a page that has to be scrolled down to see data, the google chrome browser refuses to scroll. However, when I test this app on Firefox i do not have this problem, Anybody have any ideas?? Anything would be greatly appreciated!
The link to my web app is http://testgroundwebapp.appspot.com


text:
Q: problem with frameset in Safari I am facing one problem with Frames .
when i am trying to redirect one page from the another framset then its giving "Undefined" error .
Let say i have a frameset which i have divide into 2 horizontal frame, and again the lower the frame, i have again divide into 2 vertical frmaes and now i want to reload the right side of frame page from "left side " frmae , i mean i ll redirect the pages to Right side of Frame from left navigation.
while redirection i am getting exception as "Undefined".
Please help me out . this is creating lots of probelm for me.
thanks in Advance
Regards
Bijay

A: You have to give your link or form a target attribute, that would hold the name of the frame you are trying to reload.


text:
Q: Change table data in 2nd table in same view upon selecting the row in 1st table I wanted to know how can we change the cell.textLabel.text of the second table, when we select the row of the first table.. P.S : Both the tables are in the same View..so i cant push another view controller to cover up the present view.
Example : I have some 10 rows of data in the first table, upon selecting 1st row in table 1 it should display "table1, row1 " or any other string.. in the first row of the second table., when I select 2nd row of first table.., the first row of the second table should now display as "table1,row2"
Thanks in advance

A: Try something likethis....
Have a string NSString *str=[[NSString alloc]init];

    for the first table

         didSelectRowAtindexPath
            {
            if(indexpath.row==1)
            str=@"1 row 1 table";
            if(indexpath.row==2)
            str=@"2 row 1 table");
            [table2 reloadData];
            }
        In table2
        cellforRowAtindexPath
        {
        cell.textLabel.text=str;
        }


text:
Q: Fixing truth value error in pandas dataframe I have a pandas dataframe df. I'm trying to create a new column 'Activity' and give it a string variable based on condition.
I'm getting

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I checked several places it mentions that I should have comparison operator as & vs 'and'. But even that does not work.
if ((df['%Deliverble'] > df['Deliverble_mean']) & (df['Action'] > df['Action_mean'])):
    df['Activity']='Jackpot'
elif ((df['%Deliverble'] > df['Deliverble_mean']) & (df['Action'] < df['Action_mean'])):
    df['Activity'] = 'Accumalation'
elif ((df['%Deliverble'] < df['Deliverble_mean']) & (df['Action'] > df['Action_mean'])):
    df['Activity'] = 'Action'
elif ((df['%Deliverble'] < df['Deliverble_mean']) & (df['Action'] < df['Action_mean'])):
        df['Activity'] = 'No Interest'

A: You could use Pandas apply and pass the function you just described to be executed along the row axis (axis=1).
def generate_activity(x):
    if ((x['%Deliverble'] > x['Deliverble_mean']) & (x['Action'] > x['Action_mean'])):
        return 'Jackpot'
    elif ((x['%Deliverble'] > x['Deliverble_mean']) & (x['Action'] < x['Action_mean'])):
        return 'Accumalation'
    elif ((x['%Deliverble'] < x['Deliverble_mean']) & (x['Action'] > x['Action_mean'])):
        return 'Action'
    elif ((x['%Deliverble'] < x['Deliverble_mean']) & (x['Action'] < x['Action_mean'])):
        return 'No Interest'
    return ''

df['Activity'] = df.apply(generate_activity, axis=1)


text:
Q: Replicate the Visual Studio 2005 interface I was wondering how to replicate the Visual Studio 2005 graphical user interface to create a LOB application. I have tried DevExpress controls but they cannot provide the System render mode. Then there is DockPanelSuite which I like but when I'm using DevExpress it seems rather obvious that I would not use the DockPanelSuite. When I'm using DevExpress with UseWindowsXPTheme option to true the menubar,toolbar seems to use the ManagedRenderMode which I don't want. I want to replicate the Visual Studio 2005 as closely as possible. Can anyone please guide me to some project which already uses this. It'll be very helpful. Also I'm willing to use the MVP pattern for the development of this software.

A: Look at the SharpDevelop open source IDE which does this already.


text:
Q: Uncaught TypeError: deleteConfirmation is not a function at HTMLAnchorElement.onclick i got error and when i try to delete a record from my categories page i want to open a modal pop-up for delete confirmation i got error when i click on delete button i didn't show the Modal even i error when instpact the console error is Uncaught TypeError: deleteConfirmation is not a function at HTMLAnchorElement.onclick
categories.blade.php file

    @php
      $serial_no = ($categories->currentPage()-1)*$categories->perPage();
    @endphp
    @foreach ($categories as $category)

          {{ ++$serial_no }}
          {{ $category->name }}
          {{ $category->slug }}

              $category->id]) }}">Edit
              id }})">Delete

   @endforeach

This my Modal on same page

Are you sure want to delete record?

                        <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#deleteConfirmation">Cancel</button>
                        <button type="button" class="btn btn-danger">Delete</button>

#Here is the JS on same page
@push('scripts')

@endpush

i want that popup show


text:
Q: Nginx - Reverse proxy for 4 domain names, each pointing to different content I have four different domain names (we'll call them aaa.com, aaa.co.za, bbb.com and bbb.co.za). What I'm trying (and failing) to do is point both the aaa domains to regular old HTML content while both the bbb domains act as a reverse proxy to a tomcat server. As it stands the reverse proxy to tomcat works fine while I'm pointing all four the domains to it, the trouble starts once I try to update it to point half the domain names to different content. Keep in mind that I've only attempted changes on the file /etc/nginx/sites-enabled/default so all the examples you're about to see are in this file.
Here's what I currently have (which works fine):
server {
  listen 80 default_server;
  server_name 123.123.123.123;  # using fake IP for this question
  root /usr/share/nginx/html;

  location / {
          proxy_set_header X-Forwarded-Host $host;
          proxy_set_header X-Forwarded-Server $host;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_pass http://bbb;  # this is the substitute for my actual url minus the .com/.co.za at the end
  }

  location ~ \.php$ {
          try_files $uri =404;
          fastcgi_split_path_info ^(.+\.php)(/.+)$;
          fastcgi_pass unix:/var/run/php5-fpm.sock;
          fastcgi_index index.php;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          include fastcgi_params;
  }

  location /phpmyadmin/ { }

  location /anextraproject/ { }
}

Notice that the above has some additional location statements, which successfully point to regular HTML/PHP resources by doing bbb.com/anextraproject/, for instance. I don't know how or why it works but it currently does, so if your answer could include preserving these extra locations or making it more efficient I'd really appreciate it.
Here's what I'm currently trying in order to split up the domain names (it doesn't work at all):
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    root /usr/share/nginx/html/htmlproject;
    index index.html index.html;

    server_name aaa.com www.aaa.com aaa.co.za www.aaa.co.za;

    location / {
            try_files $uri $uri/ =404;
    }
}

server {
    listen 80;
    listen [::]:80;
    root /usr/share/nginx/html;

    server_name 123.123.123.123;

    location / {
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://bbb;
    }
}

Both the above server statements are in the same file, one after the other but when I try to run sudo service nginx restart I get the following in my error logs:
2017/12/31 15:14:39 [emerg] 42033#0: a duplicate default server for 0.0.0.0:80 in /etc/nginx/sites-enabled/default.save.2:4

If I need to supply any additional info please let me know.
EDIT: The above error was caused by the sites-enabled directory also having multiple files called default.save.1, default.save.2, etc. After deleting them and restarting the server it didn't throw the error again but what's now happening is when I go to any of the domain names it directs me to aaa's content so the second server statement in my second example above seems to be not working.


text:
Q: Constructions like "A good shot" Is anyone aware of a rule behind which nouns can be combined with a preceding "a good" to become an adjectival phrase. For example "He's a good shot" meaning he has good aim.  How many more examples of this construction can EL&U think of?

A: Disclaimer: Most of this is rambling and thinking in type.
The over-arching principle here is a transformation from:

He shoots well

To:

He is a good shot

Obviously these variations don't work well:

He is a shot
He is a good run

The problem with "run" seems to be that it is a continuous activity. Discrete actions seem to fit much better:

He is a good poke
He is a good steal
He is a good sell
He is a good kiss

These don't seem to mean anything in particular but they don't sound funny to me. But lots of examples suddenly appear when we use "has" instead of "is":

He has a good jump
He has a good run
He has a good shot

The possession of "a good [verb]" again implies "he [verb]s well." Why some verbs get to see the form "he is a good" instead of "he has a good" is not clear to me. The form "he is a good shooter" makes perfect sense; why "shot" gets to have both may simply be idiomatic.
The examples I can find for "he is a good [verb]" can all be rearranged as "he has a good [verb]" and "he is a good [verb]er". The opposite is untrue: You cannot automatically take "he is a good [verb]er" or "he has a good [verb]" and make "he is a good [verb]".

A: I think it has to do more with development of idioms rather than any grammatical rule.
As for examples, only one that comes to mind at the moment is the risque "a good lay" and some more vulgar variants.

A: This is probably too open-ended of a question. "A good X" is possible for nearly any noun where the noun stands for a skill, profession, sports person, etc.: (painter, writer, goalie, resp.).
Any verb that can take "-er" is thinkable here. "A good runner, climber, dealer," etc.

A: A good deal: a rewarding exchange of goods/services/cash from the buyer's or the seller's POV, as "Oh, Man! I just made a wicked1 good deal on that 1996 Toyota I've been [ yearning for | trying to unload]," as the new owner or the poor struggling salesman might say. "I took that sucker right to the cleaners!2 Pissah!"3
A good deal: a not-insignificant amount, as "I [sic] already dumped a good deal o' cash on that POS Toyota!" or "I spent a good deal o' time dumping that POS Toyota."
A good deal: some better-than-mediocre pine lumber; Oliver Twist might say "At least this refectory table's made of a good deal. Maybe just a nibble ..."
A good deal: my opponent's poker hand.

1 wicked: pissah (South Boston only)
2 to take to the cleaners: to extract the last possible sou from
3 pissah: wicked (q.v.)


text:
Q: What is the difference between `e1` and `&e2` when used as the for-loop variable? The compiler says that e1: &i32 and e2: i32. Having read the docs for slice::Iter and the book chapter on loops, I'm still confused.
More generally, can a particular element in a slice be owned? It seems like in case 2, e2 is owning an element, is it?
fn main() {
    let slice = &[1, 2, 3];
    for e1 in slice.iter() {
        println!("{}", e1); // case 1
    }

    for &e2 in slice.iter() {
        println!("{}", e2); // case 2
    }
}

A: When used in a destructuring pattern binding, the ampersand & is used to dereference a value:
let a_number: i32 = 42;
let a_reference_to_a_number: &i32 = &a_number;

let another_reference = a_reference_to_a_number;
let &another_number = a_reference_to_a_number;

let () = another_reference; // expected type `&i32`
let () = another_number;    // expected type `i32`

This applies anywhere a pattern is accepted, such as in a let or if let, as a function argument, the for-loop variable, or a match arm.

While initially confusing to many people, this is actually the language being consistent with how enums and structs are pattern matched and thus removed from the inner variable binding:
let a_value: Option<&i32> = Some(&42);

if let Some(&val) = a_value {
    let () = val; // expected type `i32`
}

Note how val is no longer "wrapped" by the Some, just like it is no longer "wrapped" by the reference.
This behavior of & in patterns is why the ref keyword is needed. The ref keyword is used to unambiguously introduce a reference in a pattern match.


text:
Q: How can I align my paragraph content and heading content to be underneath the date? float:right doesn't work My aim is to align the heading and the content underneath the date. I tried using float:right and play with margins and padding but it doesn't seem to work

This is a heading

This is the content

This is my css any idea what could've caused this?/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
.content {
  background-color: #3d4b5b;
}

#list-content li img {
  list-style-type: none;
  margin-left: -50px;
  width: 300px;
  height: 200px;
  padding-top: 2em;
  list-style-type: none;
}

.text-content{
  float: right;
  margin:0;
}

.header-content {
    font-size: 1.5em;
    -webkit-margin-before: 0;
    -webkit-margin-after: 0;
    -webkit-margin-start: 0px;
    -webkit-margin-end: 0px;
    font-weight: bold;
    margin:0;
}

.paragraph-content{
  float: right;
}

time{
  padding-top:40px;
  padding-right: 40px;
  margin:0;
}

A: According to your expected behaviour image, here is the code snippet to implement what you want. Basically, you need to:

*

*wrap heading & time & paragraph into one container (.desc).

*float image to left and float .desc to right (I guess this is what you want, but if you want to put image and .desc near each other, you can float .desc to left).

*use clear:both on :after pseudo element of li, to give li element height.

* {
  margin: 0;
}
.content {
  background-color: #3d4b5b;
}
#list-content li {
  list-style-type: none;
  padding-top: 2em;
}
#list-content li img {
  width: 200px;
  float: left;
}
#list-content li .desc {
  float: right;
}
#list-content li .desc .text-content {
  margin-bottom: 5px;
  display: block;
}
#list-content li:after {
  content: "";
  clear: both;
  display: block;
}

This is a heading

                    <time datetime="2017-01-01" class="text-content">Game Updates | January 1st, 2017</time>

This is the content

This is a heading

                    <time datetime="2017-01-01" class="text-content">Game Updates | January 1st, 2017</time>

This is the content

This is a heading

                    <time datetime="2017-01-01" class="text-content">Game Updates | January 1st, 2017</time>

This is the content

A jsfiddle is also made for reference.


text:
Q: ¿Cuál es la diferencia entre px, dip. dp, y sp en Android? En android hay diferentes unidades de medición de pixeles. ¿Cuál es la diferencia entre las siguientes?

*

*px

*dp

*dip

*sp

A: Las 4 son unidades relacionadas a los pixeles:

px: podría mencionar que es únicamente un "píxel", pero que es un píxel, es la menor unidad homogénea en color que forma parte de una
  imagen digital.
dp:  La densidad de Píxeles independientes - un resumen de la unidad que se basa en la densidad física de la pantalla. Estas
  unidades son relativas a un 160 dpi de la pantalla, por lo que un dp
  es un píxel en una extensión de 160 dpi de la pantalla. La relación de
  dp-a-pixel va a cambiar con la densidad de pantalla, pero no
  necesariamente en proporción directa.
dip: es lo mismo que dp.
sp: Independiente de la escala de Píxeles, esto es como el dp de la unidad, pero también es escalado por el usuario tamaño de la fuente
  preferencia. Se recomienda el uso de esta unidad al especificar los
  tamaños de fuente, por lo que se ajustará para que tanto la densidad
  de pantalla y la preferencia del usuario.

Revisa:
Compatibilidad entre diferentes densidades.
Compatibilidad con diferentes tamaños de pantalla

A: De acuerdo con las especificaciones de unidades y medidas de Google:
La densidad de pixeles
Es la cantidad de pixeles que cabe en una pulgada. Las pantallas de alta densidad tienen más pixeles por pulgada que los de baja densidad. Esto da como resultado que algunos elementos gráficos (como los botones) se vean más grandes en una pantalla de baja densidad y más pequeños en una de alta densidad.
En Android:

*

*px es un pixel.

*dip o dp son pixeles de densidad independiente (density-independent pixels).

*sp son pixels de escala independiente (scaleable pixels).

Los pixeles de densidad independiente (dp or dip)
Son unidades flexibles que se escalan a dimensiones uniformes en cualquier pantalla. Cuando desarrolle aplicaciones para Android, utilice dp para mostrar los elementos uniformemente en pantallas con diferentes densidades.
Un dp es igual a un pixel en una pantalla de densidad de 160.
Para calcular dp:
dp = (ancho en pixeles * 160) / densidad de la pantalla
Los pixeles de escala independiente (sp)
Tienen la misma función que los dp, pero se utilizan para las fuentes. El valor por defecto de un sp es el mismo que el valor por defecto de un dp.
La diferencia principal entre un sp y un dp es que el sp preserva los ajustes del usuario respecto a la fuente. Los usuarios que tengan ajustes para agrandar el texto verán que el tamaño del texto concuerda con sus preferencias.
Como conclusión:

*

*dp y dip es lo mismo y se usa para objetos tipo view (aunque también puede ser usado para texto, no se recomienda).

*sp se utiliza sólo para texto.


text:
Q: Where can I find the task manager in Mac OS X Lion? Where can I find a task manager in Mac OS X Lion? I want to see the processes that are currently being run, and I can kill any process I like.

A: It's called Activity Monitor. You can find it in this folder: /Applications/Utilities/

A: A short way to do this is using the cmd + space to open Spotlight and then type in Activity Monitor (you should get the right suggestion very quick). I like this, because it's very fast.
You can also use this to start other apps or open files.

A: Look for the apple/Mac icon (perhaps top left). There will be an option for "Force Quit." Use that.

A: There are many ways to find mac task manager.
Easiest one is to use spotlight. Just type Activity monitor i.e mac task manager.
If you wish to just force quit an app or process. You can just use this shortcut: Alt + Command (⌘) + Esc
Source: Mac Activity Monitor


text:
Q: Is it possible to map through an array and fetch data from a server for each item gotten from the mapped array? Data consists of an array of posts made by different users in the database. Each post holds the _id of the user who made the post. I want to map through each post, get the _id of the post and fetch the user data for each post. this is how far I've gotten. is there a proper way to do this or a better way? I'm running into errors.
    const getUsers = () => {
    data.map(async () => {
        await axios({
        method: "POST",
        withCredentials: true,  url:`https://droplikebackend.herokuapp.com/api/user/get/${id}`,
        data: {
            userId: data.userId,
        },
      })
        .then((res) => {
          console.log(res.data);
        })
        .catch((err) => {
          console.log(err);
        });
    });
  };

A: What will work best is to extract the exact getUser logic in a separate function. What im not sure about is why method is "POST" and why id of the user is in both, the URL and in data property in axios.
No need for .then and .catch as you can see, but if you want to catch something - just use a normal try/catch block, dont mix async/await with .then.catch:
const getUser = async (userId) => {
  const response = await axios({
    method: "POST",
    withCredentials: true,
    url: `https://droplikebackend.herokuapp.com/api/user/get/${userId}`,
    data: { userId: userId }
  });
  return response.data;
};

Now about usage - the map function in this case will return an array of Promises, as you can see, and you can use Promise.all() method to await them all and get the results. All the promises will fire simulateously and not one by one if it was a for loop with awaits. Cons: if your API has rate-limiter - you can get banned for a while, Because for 100 posts 100 getUser requests will be fired in a less than a second.
const getUsers = async () => {
  const uniqueUserIds = [...new Set(data.map((x) => x.userId))];
  const promises = uniqueUserIds.map(getUser);
  const users = await Promise.all(promises);
  return users;
};

A:
app.js

const axios = require("axios");
const getUsers = async (id) => {
  const data = await axios({
    method: "get",
    url: id // if exist id search for id, if not exist map of restult
      ? `https://jsonplaceholder.typicode.com/posts/${id}`
      : "https://jsonplaceholder.typicode.com/posts"
  });

  if (id) {
    // if exist an id return a object and not array
    return console.log(data.data.id);
  } else {
    // map the array
    data.data.map((post) => console.log(post.id));
  }
};

getUsers(); // all post
// getUser(1) only bring the post with id 1

You can´t use data.map because data is not defined before, you can validated if the function bring an id or not and come all post or only one post.
I used JsonPlaceHolder becuase your api is an post. but is the same.
In my example with only find on post is and object, you can pass an array and with hat isn't necessary validated if is a object or array and the data.map will work fine
You don't can use data.map because data is not defined before, you can validated if the function bring an id or not and come all post or only one post.
I used JsonPlaceHolder becuase your api is an post. but is the same.
In my example with only find on post is and object, you can pass an array and with hat isn't necessary validated if is a object or array and the data.map will work fine

A: [
    {
        "_id": "62f45046a763042f5f35ba06",
        "userId": "62eb470392306d95ed89d964",
        "Image": "",
        "caption": "Monday!",
        "likes": [],
        "comments": []
    },
    {
        "_id": "62f4504ea763042f5f35ba08",
        "userId": "62eb470392306d95ed89d964",
        "Image": "",
        "caption": "Tuesday!",
        "likes": [],
        "comments": []
    }
]

This is what the data looks like. I want to display the username of the users who made these posts and I can only do that by fetching their individual data from the userId attached to the post.


text:
Q: how change active class on a listItem using jquery please see the demo below :
http://www.templateaccess.com/demos/walkin/
i bought this template and really really could n't find a way how does active class on menu_nav li work?
that menu_nav html is like this :

Home

Blog

Support

About Us

Contact Us

and it's css :
/* menu */
.menu_nav { margin:0; padding:50px 0 0; float:right; width:auto; height:43px;}
.menu_nav ul { list-style:none; padding:0; height:43px;}
.menu_nav ul li { margin:0; padding:0 0 0 2px; float:left;}
.menu_nav ul li a { display:block; margin:0; padding:0 0 0 20px; font-size:16px; line-height:19px; font-weight:normal; color:#fff; text-decoration:none; text-transform:none; text-align:center;}
.menu_nav ul li a span { display:block; padding:12px 20px 12px 0; height:19px;}
.menu_nav ul li.active a, .menu_nav ul li a:hover { color:#fff; background:url(images/menu_a_l.png) no-repeat left top;}
.menu_nav ul li.active a span, .menu_nav ul li a:hover span { background:url(images/menu_a_r.png) no-repeat right top;}

as you see there is a class named 'active' that moves by clicking on every menu and never jumps to home menu during postbacks.
there is no jquery or javascript about that.
how does it work?
in my asp.net that active class does not work, so i add the jquery below :

but during postbacks i lose active class on selected item.
any idea?

A: HTML:

Home

Blog

Support

About Us

Contact Us

jQuery:
$(function() {
    var location = window.location.href,
    nav = $('.menu_nav');
    $('li', nav).each(function() {
        var index = location.indexOf($(this).prop('class'));
        if (index != -1) {
            $(this).addClass('active');
            return false;
        }
    });
});

A: That active class is set manually on each page for the menu items. So you don't need JavaScript to set it unless you are using AJAX to get the new page and display it.
Your menu seemed to work fine for me, every-page has it's menu item properly styled.

A: You are adding the '.active' class on the client-side, so as soon as your page does a full postback everything is being re-created on the server-side. If you want to prevent that from happening, use an UpdatePanel and only refresh the page content (leaving the navigation menu intact).


text:
Q: Group by formula field in report To start from the beginning I had a long memo line that I needed to strip down to only show me a specific name in the string.  Here is an example of the original memo line my report was giving me:
Ex. PLUMBERS-ACH distribution from share suffix 9 [2] 19.00 01DEC2017
I created three different formulas to strip down the memo line to only show me text before the "-".  Here are those formulas:
Formula 1:
Left({SH_HIST.trn_memo}, instr(1,{SH_HIST.trn_memo},"-")-1)

Formula 2:
replace({Formula 1}, "-", " ")

Formula 3:
If instr({SH_HIST.trn_memo}, "-")>0 then {@Formula 2} else {SH_HIST.trn_memo}

I then placed Formula 3 into the report to give me the desired output from the memo line (this returns output successfully).  Now I need to sort by that field because I need to be able to group all like items and sum them.  When I click on "Insert Group" and select Formula 3 then try to preview the report I get the following message:

string length is less than 0 or not an integer

Can anyone lead me in the right direction to fix this, please?  I've googled my heart out.

A: Instead of 3 formulas why don't you try this:
Split(Column,"-")[1] //Provided the format you gave applies for all records

Now group by this formula


text:
Q: get Id out of an array and toggle it I am trying to build an "auto toggle". My plan was it to do it with an loop. The array[i].onclick works so far but I can't get further to the toggle animation.
function setContentBox() {
  for (var i = 0; i < jArrayText.length; i++)
    document.getElementById(textWord[i]).onclick = function() {
      var x = document.getElementById(textWord[i] + "commentB");
      if (x.style.display === 'none') {
        x.style.display = 'block';
      } else {
        x.style.display = 'none';
      }
    };
}

$(document).ready(function(){
  setContentBox();
});

    {{text + " "}}

{{text}}

        <textarea class="form-control" id="exampleTextarea" rows="3"></textarea>

A: Your logic here is a lot more complicated than it needs to be. As you're already using jQuery you can simply use classes on the repeated elements to identify them, then use DOM traversal within the click handler to find and amend the related elements. Try this:

    {{text + " "}}

{{text}}

        <textarea class="form-control" id="exampleTextarea" rows="3"></textarea>

$(document).ready(function() {
  $('.container').click(function() {
    $(this).find('.comment-box').toggle();
  });
});


text:
Q: Как добавить кнопку в основное оконное меню? Есть ли какой  то способ в QML добавить кнопку в основное оконное меню (то, где кнопки свернуть-закрыть-переместить окно, собственно рядом с ними)
UPD:
Подойдут также любые решения по отрисовке новой панели.  Главное условие: получившаяся панель должна выглядеть как основная панель окна. То есть при смене темы windows должа принимать вид этой темы (в том числе прозрачный)

A: Убирать стандартные кнопки гораздо проще, чем их добавлять (см. пример). А вот с добавлением своих новых элементов всё непросто.
Сразу обратим внимание, что приложение делается только под Windows (судя по тексту вопроса). Ничего специального в Qt для поддержки этих кнопок я не знаю, поэтому придётся погружаться в WIN API. До эпохи Aero задача решалась легко - мы могли самостоятельно рисовать что угодно: просто ловим WM_NCPAINT (перерисовку вне клиентской области), реагируем на события заголовка окна (WM_NCHITTEST, WM_NCLBUTTONDOWN и т.д).
Это примерно как обработка WM_PAINT, только рисуем не внутри окна, а во всём окне.
А вот с начала эпохи визуальных схем всё стало гораздо сложнее. Насколько я понимаю, единственный нормальный способ - это своими ручками повторить стили рисования кнопок. То есть, в своём коде надо посмотреть, какая версия Windows у пользователя и включена ли Aero, чтобы выбрать, какой ширины рамочки использовать и т.д. Подход плохой (буду рад, если кто-то укажет более человеческое решение), поэтому лучше трезво подумать, точно ли надо добавлять новые кнопки.
Но поскольку заниматься этим никто не хочет, то обычно просто игнорируют стили Windows (например, Google Chrome использует полностью свой стиль окон, поэтому смело пихает какие хочет кнопки в любые части заголовка окна).


text:
Q: How to list all the files in commits that haven't been pushed? I want to have a hook that will check for linting issues. The problem is that I don't want to check all the files in the project, I want to check only the files that have actually changed.
Lets say I have 3 commits locally that I havent pushed to remote. How can I list (or even better, pipe them to another process)?


text:
Q: C# Compiler command in VS2019 (Net Core) exceed 32767 chars (1) Net core installer have not tuning of location NET Core SDK

(2) VS2019 (MS Build) generate in this environment the same compilation command (with length 37153 chars)

If I understand, this command too long for CMD.EXE

then any Net Core site in this environment  not compiling, even examples from MS documentation and repository

How is possible to overcome this issue?


text:
Q: How can I look and search for a key inside a heavily nested hash? I am trying to check if a BIG hash has any keys from small hash and see if they exist, and if they do modify the BigHash with updated values from small hash.
So the lookup hash would look like this :
configure =(
    CommonParameter => {
        'SibSendOverride' => 'true',
        'SibOverrideEnabledFlag' => 'true',
        'SiPosition' => '8',
        'Period' => '11'
    }
)

But the BigHash is very very nested.. The key/hash CommonParameter from the small hash configure is there in the BigHash.
Can somebody help/suggest some ideas for me please?
Here is an example BigHash :
%BigHash = (

'SibConfig' => {
                'CELL' => {
                            'Sib9' => {
                                        'HnbName' => 'HnbName',
                                        'CommonParameter' => {
                                                                'SibSendOverride' => 'false',
                                                                'SibMaskOverrideEnabledFlag' => 'false',
                                                                'SiPosition' => '0',
                                                                'Period' => '8'
                                                         }
                                 }
                          }
                },
)

I hope I was clear in my question. Trying to modify values of heavily nested BigHash based on Lookup Hash if those keys exist.
Can somebody help me? I am not approaching this in the right way. Is there a neat little key lookup fucntion or something available perhaps?

A: Give Data::Search a try.
use Data::Search;
@results = Data::Search::datasearch(
   data => $BigHash, search => 'keys',
   find => 'CommonParameter',
   return => 'hashcontainer');

foreach $result (@results) {
    # result is a hashref that has 'CommonParameter' as a key
    if ($result->{CommonParameter}{AnotherKey} ne $AnotherValue) {
        print STDERR "AnotherKey was ", $result->{CommonParameter}{AnotherKey},
             " ... fixing\n";
        $result->{CommonParameter}{AnotherKey} = $AnotherValue;
    }
}


text:
Q: Pseudo code for a greedy algorithm for the influence maximization under the independent cascade mode I understand the concept behind a greedy algorithm but am still confused about the influence maximization under the independent cascade model and how I would implement the greedy algorithm.

*

*read in the data in a loop

*stick it into a data structure (i.e. arrays for nodes & edges, variables for the node count, edge count, probability, etc),

*loop through the nodes and edges using the algorithm storing the output values into another array, and finally

*loop to print out the results of your output array.

I am looking for pseudo code to understand the overall approach to creating this program.
I had found pseudo code for a greedy algorithm but I'm not sure I'm hoping to be able to create a working project once I am pushed in the right direction.
Link to prompt
Link to Greedy Algorithm Pseudo code
I have this as far as the greedy algorithm goes:
{
Open file (graph.txt)
Readln (n, m, k)
i = 1
while (i <= n)

     Readln(nodes[i], vert[i], probability[i])
end
}


text:
Q: Show that $f$ is a polynomial if it's the uniform limit of polynomais Let $f:\Bbb R\to \Bbb R$ be a function which is the uniform limit of polynomials. I want to show that $f$ is a polynomial.
I mean this seems a bit trivial...
If it's the uniform limit of the set of polynomials doesn't that guarantee it's a polynomial?
If I define $f$ to be the set of all polynomial do I define a uniform limit $L$ s.t $d(f,L)<\epsilon$?  or approach via contradiction?
any help would be great

A: Hint: if $f$ is a non-constant polynomial, then $f$ is unbounded.  What does this say about $f_n(z) - f_m(z)$, if $f_n$ is a sequence of polynomials that converges uniformly on $\mathbb R$?


text:
Q: How to Pipeline File Lines in NodeJS I am new to programming NodeJS and want to load multi-line sections from a file into MongoDB. I have seen simple solution that reads the file into memory and parses into lines. This will fill my need but doesn't seem the "NodeJS" way of doing it. If I just wanted to quickly load the file, I would load IntelliJ and do it in Java. I want to learn asynchronous and pipelines.
I see the the basic steps are stream the file in chunks, parse the chunks into lines, group lines into sections, convert sections into JSON, and insert JSON into MongoDB.
I like the idea of pipelines since I can easily replace parts and reuse others. It also helps in this case since the slowest step is the last and the whole input file could be loaded into memory before the first MongoDB document is written.
I have searched for a good example but they seem to be missing parts and explanations of what I need to modify. I have seen you can easily pipe a file stream in chunks but I need lines. I have seen you can easily stream a file to a line parser but that is not a pipeline.
Any ideas on how to do this or good examples?
Thanks,
Wes.


text:
Q: What are good practices for granting database permissions to a web service connection? I have been searching for articles and SQL script examples that would demonstrate how to securely and conveniently solve one of the most common scenarios - connecting from a .Net Core Entity Framework based web application to an SQL database.
But somehow I could not find any coherent step-by-step guide from a reputable source.
Let's assume the following:

*

*I cannot use integrated Windows auth in the connection string and must use username and password based auth (because hosting on a Linux server and the DB is on a different Windows server)

*the web service will need your usual minimum set of permissions - connect to the database, read data, write data, delete data, execute stored procedures
While reading many tutorials, I find there are multiple ways to manage the connection permissions. To avoid this question being too broad, I'll list my current choices as I understand them (please correct me if I'm missing something).
Users and logins:

*

*create a login and a user for the database

*create a database-only user without a login (not sure if this is applicable to a web app and connection string, but still it's a feature that I've seen being used)

Assigning permissions:

*

*assign the user to some fixed SQL role (db_datareader, db_datawriter AND also will have to grant EXECUTE permission)

*grant all fixed permissions

*create a custom role (let's say, db_web_apps) with required permissions

Which choices are better (more secure and easier to manage in general) and recommended by SQL DBAs?
I think every database administrator should have a template script handy for quickly adding a new user with minimum required permissions every time when developers ask for a new connection for their shiny new web app.
If you know a good, reliable tutorial or GitHub / Gist example that explains what and why is being done that way or a script that you yourself have used for years without any issues in production environments, I'll really appreciate if you could share it.

A: Create a role in the database and assign the required privileges to the role.  Don't use the fixed database roles.  Instead grant permissions directly to objects, schemas, or the entire database if necessary.  Like this:
create role trusted_app_role
grant select, insert, update, delete, execute
  on schema::dbo to trusted_app_role

That will grant the role full DML permissions on all the objects in the default dbo schema.  So if you have any tables or procedures you don't want the app to have access to, just create them in a different schema, say, admin.  This way you never have to fiddle with permissions as you add objects.  The fixed database roles predate schema-based permissions, and aren't really needed any more.
For your application's identity, add Active Directory or Azure Active Directory (Azure SQL) identities to this role, or, if you can't, add SQL Users to the role.
If you are on Azure SQL, you should normally use a database user without a login.  On SQL Server you can only add "contained database users" if you enable Partial Database Containment.  Which you can do, but is incompatible with Change Tracking and Change Data Capture, so it's a tradeoff.
So normally for SQL Server you still create a login and map the user to the login. EG:
create login web_service_user with password = '5X+jeuAB6kmhw85R/AxAg'
create user web_service_user for login web_service_user

And then add that user to your role
alter role trusted_app_role add member web_service_user


text:
Q: Recommendations to handle development and deployment of php web apps using shared project code I am wondering what the best way (for a lone developer) is to

*

*develop a project that depends on code of other projects

*deploy the resulting project to the server

I am planning to put my code in svn, and have shared code as a separate project. There are problems with svn:externals which I cannot fully estimate.
I've read

*

*subversion:externals considered to be an anti-pattern, and

*How do you organize your version control repository,

but there is one special thing with php-projects (and other interpreted source code): there is no final executable resulting from your libraries. External dependencies are thus always on raw source code.
Ideally I really want to be able to develop simultaneously on one project and the projects it dependends on.
Possible way:
Check out a projects' dependency in a sub folder as a working copy of the trunk. Problems I foresee:

*

*When you want to deploy a project, you might want to freeze its dependencies, right?

*The dependency code should not end up as a duplicate in the projects repository, I think.
*(update1: I additionally assume svn:ignore will pose problems if I cannot fall back on symlinks, see my comment)
I am still looking for suggestions that do not require the use junction points. They are a sort of unsupported hack in winxp, which may break some programs*
This leads me to the last part of the question (as one has influence on the other): how do you deploy apps whith such dependencies?
I've looked into BuildOut for Python, but it seems to be tightly related to the python ecosystem (resolving and fetching python modules from the web etc).
I am very eager to learn about your best practices.

A: One approach might be:

*

*one repository per dependency

*a requirements configuration file for your project which documents the dependencies and their versions (probably even your own versions of the dependencies)

*automation scripts that handle setup of the development, testing and deployment environments (can be as simple as documenting the setup procedure once and making it configurable and executable)

This has several benefits:

*

*you can easily (or even automatically) check whether your dependencies have become outdated (another better library is available), or have known security vulnerabilities.

*more awareness about dependencies

*easier to debug/fix/patch problems caused by dependencies

*ignoring svn:externals might also ease the pain when you switch to distributed version control like git, bzr, hg in the future.

*if you want to set up your environment on another machine (or eventually another developer takes over or joins) it will save you tons of time

Some KISS automation tools that are popular in web-development and server administration:

*

*fabric (python)

*buildout (python)

*capistrano (ruby)

Summary:
Document your requirements (preferably machine readable -> yaml, ini, json, xml) and handle dependencies outside of your project. It provides you with a bit of indirection which makes automated setup and deployment easier and less dependent on your version control system (separation of concerns, best tool for the job, etc).

A: This may sound cheap but I think I have a answer for you in this questions thread: svn folder structure organization
As long as you stay within your own repository I wouldnt consider svn:externals as harmful as stated. Just don't overdo it.
Deployment with this strategy is also a piece of cake since it is ALL in one tag (checkout, run it, profit). Your directory structure remains the same on all layers, branches, tags, trunk.
By directing externals to tags (and making tags read-only on the svn server) you can be 100% sure you get the library you expect.


text:
Q: How can I play the Mask of the Betrayer expansion natively on my Mac? I'm reliving all games and I would like to play the mask of the betrayer expansion on my Mac, but although the initial campaign has been ported, Mask of the Betrayer seems it hasn't.
Please, no parallels, VMs or similar.
How can I play the Mask of the Betrayer expansion natively on my Mac?

A: Take a look at this blog post.
It looks like you need Bootcamp anyway, with a Windows version of NwN installed there to transfer files.
There's also a torrent somewhere on the Internet that lets you play MoB and SoZ on the Mac, but I don't think it can be linked here.


text:
Q: OpenLayers 3 retrieve view's altitude I'm developing a web application that uses OpenLayers 3 and I've a service that receive 2 inputs parameters: altitude and bbox.
From the layer I can retrieve my Extent (bbox) in this way:
var extent = layerMap.getExtent();

But how can I retrieve my view's altitude?

Thanks

A: There is no method (not yet) to retrieve an altitude with OpenLayers 3.
The only altitude that you can get is from geolocation.
(API : http://openlayers.org/en/v3.4.0/apidoc/ol.Geolocation.html?unstable=true#getAltitude)
But if you want altitude of the center of your extent, you have the coordinates.
Then you can use an external service like this (with AngularJS, for example) :
        // metric system
        var altitude = 0;
        var url = 'http://open.mapquestapi.com/elevation/v1/profile?key=YOURKEY&latLngCollection=' + latitude + ',' + longitude;

        $http.get(url)
            .success(function (data, status) {
                altitude = data.elevationProfile[0].height;
            })
            .error(function (data, status) {
            });


text:
Q: openSUSE: Switch from Tumbleweed to standard distribution? Is there a way to go back to the standard openSUSE distribution from Tumbleweed (the rolling release)? If so, how?
I am using openSUSE Tumbleweed, and I am pretty pleased with it. But because of occasional issues (stability problems, and some programs malfunctioning with newest updates), I would like to go back to the standard distribution.
I do not necessarily want to revert all packages to earlier versions (and my OS seems to be working nicely at the moment), just no longer get the updates from Tumbleweed, but the standard distribution when they become available. (Maybe it is as simple as changing the repositories to those of the standard distribution?)
I have done quite a few Google searches on the topic, but so far I haven't found anything relevant. I appreciate your help!

A: Here is a better answer that not using tumbleweed.

*

*Uninstall new version

*Download and install the old version under http://download.opensuse.org/

*Launch the Software Manager (Yast sw_single)

*Find each package that malfunctions and then under Actions select Lock now the old version will not be upgraded unless you unlock them.

It maybe fine to revert some packages, but reverting them all generates too many security vulnerabilities.
This is one way of adding the original 13.2 repos back
zypper ar "http://download.opensuse.org/distribution/13.2/repo/non-oss/" OpenSuse13-2-nonoss
zypper ar "http://download.opensuse.org/distribution/13.2/repo/oss/" OpenSuse13-2-oss

Open yast or yast2 and launch repository manager and enable these and disable the other ones.  Install and lock the packages you need to.  Then disable these and enable the old ones.


text:
Q: Notifying message (Fade Out ) is disappearing instantly due to page reload behvaiour I am doing a ajax call and  notifying the User as shown below
$( document ).ready(function() {
    var response = true ;
        if(response)
        {
$(".success").html('Success!Value Updated Successfully  !!!').fadeIn(800).delay(1500).fadeOut(800);
window.location.reload();
        }
});

The problem is that the notfying message is disapperaing instantly
Is it possible to reload the page only after the fadeOut has been completed successfully
http://jsfiddle.net/cod7ceho/430/

A: Change
$(".success").html('Success!Value Updated Successfully  !!!').fadeIn(800).delay(1500).fadeOut(800);
window.location.reload();

to
$(".success").html('Success!Value Updated Successfully  !!!').fadeIn(800).delay(1500).fadeOut(800, function () {
    window.location.reload();
});

In the jQuery Documentation you can find your case:

.fadeOut([duration], [complete])
complete
A function to call once the animation is complete (...)

This is called a "callback function". You'll find it's being used a lot in jQuery.

A: .fadeOut() has a callback function so you change your code to this:
$(document).ready(function () {
    var response = true;
    if (response) {
        $(".success").html('Success!Value Updated Successfully  !!!').fadeIn(800).delay(1500).fadeOut(800, function () {
            window.location.reload();
        });
    }
});

A: The fadeOut function as well as the other fade animation functions, provides a callback that is triggered when the animation is finished.
Here is an example that was take from the documentation -
$( "#clickme" ).click(function() {
  $( "#book" ).fadeOut( "slow", function() {
    // Animation complete.
  });
});

So for your case, using this callback would look something like this -
$(".success").html(...).fadeIn(800).delay(1500).fadeOut(800, function() {
  window.location.reload();
});

Since the action you want to take is actually calling an existing function, you can pass the window.location.reload function as the callback itself to allow your code to be a little cleaner -
...fadeOut(800, window.location.reload);

You only need to define your own callback function if there are more actions that you want to perform.


text:
Q: Infinite sequencing number generator not work in python? I am trying to implement a nature number generator which can generator infinite numbers, my code:
def nature():
    s = 0
    while True:
        yield s
        s += 1

when I use next(nature()), I get a sequence of 0s, why this? and how to fix it?
>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0

A: Every time you call nature() you create a new generator.
Instead do this:
n = nature()
next(n)
next(n)
next(n)

A: You create a new generator every time you recall it like so; so it starts from the initial value. What you want is:
>>> n = nature()
>>> next(n)
0
>>> next(n)
1
>>> next(n)
2
>>> next(n)
3

A: You are creating a new generator each time, try creating it once and passing it to each next call

A: Don't instance your generator over and over, for example, instance one and use it several times like this:
def nature():
    s = 0
    while True:
        yield s
        s += 1

n = nature()
for i in range(10):
    print next(n)

print "Doing another stuff... Resuming the counting"

for i in range(10):
    print next(n)


text:
Q: Back button(google chrome) need to put two times for go back, how to remove this problem? I have a news list page and when i enter in some news-post and put (google chrome back arrow) i go again to news list, But when i put back arrow again i be back in news-post where just returned from. If you repeat the process again, it will normally go to where they were before the page of the news-list.
How to remove this problem?
This is news list page


text:
Q: How to show loading while moving between pages I would like to have in my jsp when the user clicks on the submit button, a loading message or an image is shown while moving between the pages. So, how can I do that?
I tried to use some javascripts, but I did not success.
Thanx

A: If it is a complete page change, the loading indicator is already here in every browser.
If you update only a part of a page through AJAX, you may use AJAX progress indicator. According to the JavaScript framework you use, implementations may be different, so see the documentation or complete your question by specifying the framework you use.


text:
Q: Application_OnError not always working I experience strange problem. We have error handling in global.asax  that would redirect user on special page in case if error happened:
void Application_Error(object sender, EventArgs e)
{
    .......
    string pageError = "~/LastError.aspx?AfterNextClick=" + afterNextClick.ToString();
    if (Request["guid"] != null)
        pageError += "&guid=" + Request["guid"];
    Server.Transfer(pageError);
}

Custom errors are turned off.
<customErrors mode="Off"/>

Most of the times the Application_OnError works perfectly and redirects users to the specific page, but sometimes, users are not redirected anywhere and an ASP.NET exception page is displayed.

So is there any situations in which Application_OnError in global.asax wouldn't fire?

A: Probably an exception is ocurring inside the Apllication_Error method. Take a closer look at the code you place in this method (where you placed ...... ).
Try placing a try/catch block in this method to debug what's going on...


text:
Q: How to change VBA code to work with cells under the first one? This code (an answer provided by the previous question I had in another post and have to ask another question in a separate post) works for A1, B1, D1, and E1. What exactly do I change to make it work for either 1) all the cell under them or 2) a select range of cells under them. In other words, make it work for A2, B2, D2, E2, and A3, B3, D3, E3. If you need anymore information or questions, please ask and I'll do my best to make it more clear. Thank you in advance!
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Target.Row = 1 And (Target.Column = 1 Or Target.Column = 2) Then
    'new val
    a1 = Range("A1").Value
    b1 = Range("B1").Value
    newVal = Range("D1").Value

    'disable events and undo
    Application.EnableEvents = False
    Application.Undo
    'old val
    oldVal = Range("D1").Value

    'diff between new and old val
    diff = newVal - oldVal

    Range("A1").Value = a1
    Range("B1").Value = b1
    Range("E1").Value = diff

    're-enable events
    Application.EnableEvents = True
End If
End Sub

A: You would just take the same incoming target and assign a variable by the ROW property of the target.  Then every Range(A1) you have, you replace the 1 with the variable.  "lRow".  You change the initial IF statement to allow ANY row, and still check to make sure it's column 1 or 2.
I also renamed the a1, b1, to aVal and bVal.
Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim lRow As Long

    If Target.column = 1 Or Target.column = 2 Then
        'new val
        lRow = Target.row
        aVal = Range("A" & lRow).Value
        bVal = Range("B" & lRow).Value
        newVal = Range("D" & lRow).Value

        'disable events and undo
        Application.EnableEvents = False
        Application.Undo
        'old val
        oldVal = Range("D" & lRow).Value

        'diff between new and old val
        diff = newVal - oldVal

        Range("A" & lRow).Value = aVal
        Range("B" & lRow).Value = bVal
        Range("E" & lRow).Value = diff

        're-enable events
        Application.EnableEvents = True
    End If
End Sub


text:
Q: Why are some HtmlHelper methods implemented as extension methods I'm currently creating some custom helper classes, similar to ASP.NET MVC's standard HtmlHelper. When I looked at the implementation of HtmlHelper, I noticed that most/all of the HTML generating methods (such as ActionLink(), BeginForm(), TextBox(), and so on) are not implemented directly inside the HtmlHelper class, but as extension methods in separate classes (e.g. in class LinkExtensions).
Apart from a nicer source-code organisation, is there any advantage when implementing such methods as extension methods instead of normal methods?
When creating my own helper classes, should I also follow that pattern?
Update: when I wrote that I wanted to create my own helper class, then I did mean to extend the existing HtmlHelper class. Instead I created a custom base class for my views (derived from ViewPage) and I want to add there an additional helper class similar to the Html and Url helper classes of ViewPage.

A: I suppose it might be because the Framework Design Guidelines mentions (4.1):

Avoid having types designed for advanced scenarios in the same namespace as types intended for common programming tasks.

and later on (5.6) about extension methods:

Do not put extension methods in the same namespace as the extended type, unless it is for adding methods to interfaces or for dependency management.

Phil Haack himself mentions on the same page that they put "more advanced" funcionality in a separate namespace in order not to "pollute" the API of the extended type.
I agree that the methods that actually are more useful (ActionLink and so on) are less discoverable, but they are all implemented using the core API of HtmlHelper (GenerateLink, etc.) which is part of the main namespace.
If you intend to follow the official design guidelines and it makes sense in your specific case, I think you should adhere to this pattern.

A: The reason is: we wanted to provide you with the ability to opt-out to any of the built-in HTML helpers in case you preferred to write your own or use some other 3rd party helpers instead. If they weren't extension methods in a special namespace, you wouldn't be able to ignore them.

A: I tend to follow that pattern by having core classes, and then extension classes for each one where needed.
Regarding advantages... I'm not aware of anything apart from separating the actual classes themselves from their extensions.


text:
Q: Mousemove event wrong target javascript In what cases can mousemove give incorrect target?
I have two elements and event.target shows me one div, when in fact the mouse is on another.
Here is the code.

var o = document.getElementById('container');
var inner = document.getElementById('inner');
var ox = 100;
var oy = 100;

function onMouseDown(event) {
    if (event.stopPropagation) event.stopPropagation();
    if (event.preventDefault) event.preventDefault();
    event.cancelBubble = true;
    event.returnValue = false;
    var size = {x: o.offsetWidth, y: o.offsetHeight};
    var curX = event.pageX;
    var curY = event.pageY;
    var previousInside = event.target === inner;

    function onMouseMove(event) {
        var x = event.pageX;
        var y = event.pageY;
        var dx = x - curX;
        var dy = y - curY;

        var p1 = {x: ox, y: oy};
        var p2 = {x: ox + 50, y: oy + 50};
        p1.x += dx;
        p2.x += dx;
        p1.y += dy;
        p2.y += dy;
        var currentInside = event.target === inner;
        console.log('Was '+ (previousInside? 'inside': 'outside'), 'Now ' + (currentInside?'inside': 'outside'))
        if (p1.x < 40 || p2.x > size.x - 40 || p1.y < 40 || p2.y > size.y - 40) {
            if (currentInside) {
                curX = x;
                curY = y;

            }
            previousInside = currentInside;
            return;

        } else {
            if (currentInside && !previousInside) {
                curX = x;
                curY = y;
                previousInside = currentInside;
                return;
            }

        }
        previousInside = currentInside;
        curX = x;
        curY = y;
        ox = p1.x;
        oy = p1.y;
        inner.style.top = oy +'px';
        inner.style.left = ox+'px';
        return false
    }

    o.addEventListener("mousemove", onMouseMove);
    o.addEventListener("mouseup", function () {
        o.removeEventListener('mousemove', onMouseMove);
    });
}
o.addEventListener("mousedown", onMouseDown);

To see a weird behavior, mousedown on the red square and drag it until it stops moving. Drag a bit higher so you are far enough from the red square. Now drag to the right far away from the square. Now drag down and when mouseX will equal red box x, the console will show that Was outside and Now insinde, when in fact it should be Was outside and now inside.
Thank you.


text:
Q: Node js, piping pdfkit to a memory stream I am using pdfkit on my node server, typically creating pdf files, and then uploading them to s3.
The problem is that pdfkit examples pipe the pdf doc into a node write stream, which writes the file to the disk, I followed the example and worked correctly, however my requirement now is to pipe the pdf doc to a memory stream rather than save it on the disk (I am uploading to s3 anyway).
I've followed some node memory streams procedures but none of them seem to work with pdf pipe with me, I could just write strings to memory streams.
So my question is: How to pipe the pdf kit output to a memory stream (or something alike) and then read it as an object to upload to s3?
var fsStream = fs.createWriteStream(outputPath + fileName);
doc.pipe(fsStream);

A: There's no need to use an intermediate memory stream1 – just pipe the pdfkit output stream directly into a HTTP upload stream.
In my experience, the AWS SDK is garbage when it comes to working with streams, so I usually use request.
var upload = request({
    method: 'PUT',
    url: 'https://bucket.s3.amazonaws.com/doc.pdf',
    aws: { bucket: 'bucket', key: ..., secret: ... }
});

doc.pipe(upload);

1 - in fact, it is usually undesirable to use a memory stream because that means buffering the entire thing in RAM, which is exactly what streams are supposed to avoid!

A: You could try something like this, and upload it to S3 inside the end event.
var doc = new pdfkit();

var MemoryStream = require('memorystream');
var memStream = new MemoryStream(null, {
   readable : false
});

doc.pipe(memStream);

doc.on('end', function () {
   var buffer = Buffer.concat(memStream.queue);
   awsservice.putS3Object(buffer, fileName, fileType, folder).then(function () { }, reject);
})

A: An updated answer for 2020. There is no need to introduce a new memory stream because "PDFDocument instances are readable Node streams".
You can use the get-stream package to make it easy to wait for the document to finish before passing the result back to your caller.
https://www.npmjs.com/package/get-stream
const PDFDocument = require('pdfkit')
const getStream = require('get-stream')

const pdf = () => {
  const doc = new PDFDocument()
  doc.text('Hello, World!')
  doc.end()
  return await getStream.buffer(doc)
}

// Caller could do this:
const pdfBuffer = await pdf()
const pdfBase64string = pdfBuffer.toString('base64')

You don't have to return a buffer if your needs are different. The get-stream readme offers other examples.

A: A tweak of @bolav's answer worked for me trying to work with pdfmake and not pdfkit. First you need to have memorystream added to  your project using npm or yarn.
const MemoryStream = require('memorystream');
const PdfPrinter = require('pdfmake');
const pdfPrinter = new PdfPrinter();
const docDef = {};
const pdfDoc = pdfPrinter.createPdfKitDocument(docDef);
const memStream = new MemoryStream(null, {readable: false});
const pdfDocStream = pdfDoc.pipe(memStream);
pdfDoc.end();
pdfDocStream.on('finish', () => {
  console.log(Buffer.concat(memStream.queue);
});

A: My code to return a base64 for pdfkit:
import * as PDFDocument from 'pdfkit'
import getStream from 'get-stream'

const pdf = {
  createPdf: async (text: string) => {
    const doc = new PDFDocument()
    doc.fontSize(10).text(text, 50, 50)
    doc.end()

    const data = await getStream.buffer(doc)
    let b64 = Buffer.from(data).toString('base64')
    return b64
  }
}

export default pdf

A: Thanks to Troy's answer, mine worked with get-stream as well. The difference was I did not convert it to base64string, but rather uploaded it to AWS S3 as a buffer.
Here is my code:

import PDFDocument from 'pdfkit'
import getStream from 'get-stream';
import s3Client from 'your s3 config file';

const pdfGenerator = () => {
  const doc = new PDFDocument();
  doc.text('Hello, World!');
  doc.end();
  return doc;
}

const uploadFile = async () => {
  const pdf = pdfGenerator();
  const pdfBuffer = await getStream.buffer(pdf)

  await s3Client.send(
    new PutObjectCommand({
      Bucket: 'bucket-name',
      Key: 'filename.pdf',
      Body: pdfBuffer,
      ContentType: 'application/pdf',
    })
  );
}

uploadFile()