text:
Q: Load Firestore documents descending order by time from bottom to top I am paginating data into a tableview for a messaging app. This is my query function and then I handle the response, data, and error:
func getMessages(userId: String, scrolled: Bool) {
        var query: Query!
        if scrolled {
            guard let lastDocument = lastDocument else { return }
            query = db.collection("Customer_Data").document(userId).collection("Contact_Messages").order(by: "sent", descending: true).limit(to: 10).start(afterDocument: lastDocument)
        } else {
            lastDocument = nil
            query = db.collection("Customer_Data").document(userId).collection("Contact_Messages").order(by: "sent", descending: true).limit(to: 10)
        }
        handleResponse(query: query)
    }

func handleResponse(query: Query) {
        query.getDocuments { (querySnapshot, error) in
            if let error = error {
                self.messageReceived?(nil, error.localizedDescription, .error)
            } else if querySnapshot!.isEmpty {
                self.messageReceived?(nil, nil, .end)
            } else if !querySnapshot!.isEmpty {
                let polledMessages = querySnapshot?.documents.compactMap { querySnapshot -> Message? in
                    return try? querySnapshot.data(as: Message.self)
                }
                guard let availableMessages = polledMessages else { return }
                var messageArray = [Message]()
                messageArray.append(contentsOf: availableMessages)
                self.lastDocument = querySnapshot!.documents.last
                DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
                    self.messageReceived?(messageArray, nil, .success)
                })
            }
        }
    }

Now here, I add the next set of data to the top of the array:
func handleResponse(query: Query) {
        query.getDocuments { (querySnapshot, error) in
            if let error = error {
                self.messageReceived?(nil, error.localizedDescription, .error)
            } else if querySnapshot!.isEmpty {
                self.messageReceived?(nil, nil, .end)
            } else if !querySnapshot!.isEmpty {
                let polledMessages = querySnapshot?.documents.compactMap { querySnapshot -> Message? in
                    return try? querySnapshot.data(as: Message.self)
                }
                guard let availableMessages = polledMessages else { return }
                var messageArray = [Message]()
                messageArray.append(contentsOf: availableMessages)
                self.lastDocument = querySnapshot!.documents.last
                DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
                    self.messageReceived?(messageArray, nil, .success)
                })
            }
        }
    }

The problem is that instead of seeing messages like this:
the first batch (newest first as the query is descending order of timestamp mentioned above):
20 Oct
25 Oct
28 Oct
31 Oct
second batch:
06 Oct
07 Oct
15 Oct
18 Oct
Once arranged in the array, I should get them all arranged nearly in descending order the further up I scroll just like Whatsapp, FB Messenger etc.
I am seeing this:
first batch (seems fine)
20 Oct
25 Oct
28 Oct
31 Oct
the second batch (in the reverse order)
18 Oct
15 Oct
07 Oct
06 Oct
Any idea why this is happening?
For reference, this is where I trigger the pagination:
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

    let off = scrollView.contentOffset.y
    let off1 = scrollView.contentSize.height

    if off < off1 + scrollView.frame.height * leadingScreensForBatching, let userId = userId {
        messageViewModel.getMessages(userId: userId, scrolled: true)
    }
}


text:
Q: Running Sample Tikz Code I am running Ubuntu version 11.04 with PGF package version 2.00-1.
I have trouble running this sample code posted to
 How to generate all possible Venn diagrams (with the case below) efficiently?
\documentclass{standalone}
%\url{https://tex.stackexchange.com/q/67395/86}
\usepackage{tikz}

\makeatletter

\def\venn@strip#1#2\venn@STOP{%
  \def\venn@next{#1}%
  \gdef\venn@rest{#2}%
}

\newcommand{\venn}[1]{%
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (2,0);
\coordinate (C) at (1,{sqrt(3)});
\coordinate (S-SE) at (5,-3);
\coordinate (S-NW) at (-3,{sqrt(3)+3});
  \edef\venn@rest{#100000000}%
  \foreach \i in {0,...,7} {
  \begin{scope}[even odd rule]
    \expandafter\venn@strip\venn@rest\venn@STOP
    \ifnum\venn@next=1\relax
    \pgfmathparse{Mod(\i,2) == 1 ? "(S-SE) rectangle (S-NW)" : ""}
    \path[clip] \pgfmathresult (A) circle[radius=2];
    \pgfmathparse{Mod(floor(\i/2),2) == 1 ? "(S-SE) rectangle (S-NW)" : ""}
    \path[clip] \pgfmathresult (B) circle[radius=2];
    \pgfmathparse{Mod(floor(\i/4),2) == 1 ? "(S-SE) rectangle (S-NW)" : ""}
    \path[clip] \pgfmathresult (C) circle[radius=2];
    \fill[rounded corners,red] (S-SE) rectangle (S-NW);
    \fi
  \end{scope}
  }
    \draw[ultra thick] (A) circle[radius=2];
    \draw[ultra thick] (B) circle[radius=2];
    \draw[ultra thick] (C) circle[radius=2];
    \draw[ultra thick,rounded corners] (S-SE) rectangle (S-NW);
\end{tikzpicture}
}

\makeatother

\newcommand{\allvendiagrams}{
% To generate the lot:
\foreach \j in {0,...,255} {
  \def\venncode{}
  \foreach \k in {0,...,7} {
    \pgfmathparse{Mod(floor(\j/2^\k),2) == 1 ? "\venncode1" : "\venncode0"}
    \global\let\venncode=\pgfmathresult
  }
  \venn{\venncode}

}
}

\begin{document}
\venn{10000000}
\venn{01000000}
\venn{11000000}
\end{document}

After I changed documentclass to article, I got this error
! Package PGF Math Error: Unknown function `Mod'

I thought may be my version of PGF is old and therefore missing the Mod
function. Did sudo apt-get update to get all missing updates, but the
error did not go away. Do I need to upgrade the level of Ubuntu to a higher
to get around this message?
After replacing all instances of Mod with mod in above code, I got this
error
   ! Illegal unit of measure (pt inserted).
   <to be read again>
                   ?
   l.57 \venn{10000000}

I need help in getting around this error and getting this sample run
successfully.
The \venn command accepts a 8 digit binary string, goes over each digit
and if a digit is 1, fills certain areas. For example, calling \venn{00000010}
will fill everything in circle A which does not overlap with circle B or C.
Code relevant to iteration of binary string:
\def\venn@strip#1#2\venn@STOP{%
  \def\venn@next{#1}%
  \gdef\venn@rest{#2}%
}

\edef\venn@rest{#100000000}%

\foreach \i in {0,...,7} {

  \begin{scope}[even odd rule]
    \expandafter\venn@strip\venn@rest\venn@STOP
    \ifnum\venn@next=1\relax
..............

I went through basic info about \def statement at http://en.wikibooks.org/wiki/TeX/def and confused about the \venn@STOP in \venn@strip after end of
second argument and start of macro contents. All examples, I have seen have
macro name followed by any optional arguments, immediately followed by
contents of macro.
In a call of \venn{00000010}, before start of the 'for' loop,
\venn@rest will be assigned 0000001000000000. In the 1st iteration
\venn@next will be assigned 0000001000000000(same as what was passed into
first argument) and \venn@rest will be assigned ""(nothing), same as what was passed into second argument to \venn@strip which was \venn@STOP(which has
not been defined at this point). The \ifnum statement expects in
\venn@next either a 0 or 1 for the position in the binary string
corresponding to current iteration. I don't see where in the code
such stripping of digits is happening.
The \relax directive asks TeX to do nothing. Not sure why we need
\relax as part of \ifnum statement.
On a call of \venn{00000010}, statements related to filling are
  \begin{scope}[even odd rule]
\path[clip] (S-SE) rectangle (S-NW) (A) circle[radius=2];
\path[clip] (B) circle[radius=2];
\path[clip] (C) circle[radius=2];
\fill[rounded corners,red] (S-SE) rectangle (S-NW);
  \end{scope}

In iteration 2 of the for loop, \i = 1 and this is the only iteration
which fills anything in the call.
Based on what is mentioned in the PGF manual, a clipping path restricts
painting to a certain area. Also, multiple clippings accumulate and clipping
is always done against the intersection of all clipping areas that have been
specified inside the current scope.
The first clip statement, gives the circle at A as the clipping area.
The second clip statement, gives the intersection of circle at A and B
as the clipping area. The third third clip statement gives the intersection
region of circles A, B and C as the clipping area. At the end when the
rectangle is being filled, I expect the clipped area to be filled.
Instead, what is filled is the area in circle A which is not overlapping
with circle B or C.
The even odd rule probably makes the fill to work the way it does.
This rule is explained in the manual in terms of shooting rays and count how
often we hit the path. I could not understand how to use it.

A: Let me start with \venn@strip.
\def\venn@strip#1#2\venn@STOP{%
  \def\venn@next{#1}%
  \gdef\venn@rest{#2}%
}

Here, we have a bit of slightly more complicated macro parameter specification.  The macro parameter specification is everything up to the opening brace of the definition.  In this case, it is #1#2\venn@STOP.  So when TeX encounters \venn@strip then it will do its best to match that pattern.  You can read more about exactly what it does in things like TeX by Topic, but let me try to explain what TeX does in this case.  The pattern #1#2\venn@STOP says: grab everything up to the next occurrence of the token \venn@STOP, putting it in the parameters #1 and #2 according to these rules: if there is nothing, don't put anything in; if there is only one thing, put it in #1; if there is more, put one thing in #1 and the rest in #2.  Moreover, the \venn@STOP is not examined and is thrown away, so its definition is immaterial.  So the idea is that we want to evaluate \venn@strip 01011011010100001010\venn@STOP.  It will then grab the first 0 as #1, the 1011011010100001010 as #2, and throw away the \venn@STOP.
The point is that we don't know how much stuff is in the rest of the string that we want to take the first character of, so we use a delimited macro to ensure that we get the rest.
Now, to its invocation:
\expandafter\venn@strip\venn@rest\venn@STOP

That \expandafter is key here.  This reaches over the \venn@strip and expands \venn@rest before \venn@strip is considered.  So when \venn@strip starts its stuff, the stream is actually \venn@strip010101101010100\venn@STOP and it can strip off the first character for testing.
(The extra zeros are pretty pointless.  They're to guard against the user not putting in an 8-digit code.)
Next bit:
\ifnum\venn@next=1\relax

\ifnum is greedy.  For each of its pieces (in this case, before and after the =) it will try to grab as much of a number as it can.  It might not stop at the 1 if the next thing coming could potentially be a number.  To guard against that (as I'm too lazy to figure out what the next thing is), the \relax is there.  Essentially, \relax is playing the role of a "No numbers here" sign.
Last bit:
\path[clip] (S-SE) rectangle (S-NW) (A) circle[radius=2];

This is where the even odd rule comes in.  This path is actually a rectangle with a circle inside it.  Under the even odd rule, the region viewed as "inside" this path is the bit between the rectangle and circle.  Inside the circle, we cross the path twice to "escape to infinity" - once being the circle and twice being the rectangle.  Thus the clip is for the outside of the circle centred at (A), which corresponds to the complement of that circle.  Neat, huh?
(That bit was inspired by the reverse clip question somewhere on this site.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: case statement to delete extra spaces only when there is some I replace all blanks with @ using this
SELECT *,  REPLACE(NAME,' ','@') AS NAME2

which results miss@test@blogs@@@@@@@@@@@@@@ (different number of @s dependent on length of name!
I then delete all @ signs after the name using this
select *, substring(Name2,0,charindex('@@',Name2)) as name3

which then gives my desired results of, for example MISS@test@blogs
However some wheren't giving this result, they are null. This is because annoyingly some rows in the sheet I have read in dont have the spaces after the name.
is there a case statement i can use so it only deletes @ signs after the name if they are there in the first place?
Thanks

A: The function rtrim can be used to remove trailing spaces.  For example:
select replace(rtrim('miss test blogs             '),' ','@')
-->
'miss@test@blogs'

Example at SQL Fiddle.

A: try this:
Declare @t table (name varchar(100),title varchar(100),forename varchar(100))
insert into @t
values('a  b   c','dasdh  dsalkdk  asdhl','asd dfg sd')

SELECT REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(name)),'  ',' '+CHAR(7)),CHAR(7)+' ','')  ,CHAR(7),'') AS Name,

REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(title)),'  ',' '+CHAR(7)),CHAR(7)+' ','')  ,CHAR(7),'') AS title,

REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(forename)),'  ',' '+CHAR(7)),CHAR(7)+' ','')  ,CHAR(7),'') AS forename

FROM @t WHERE
(CHARINDEX('  ',NAME) > 0 or CHARINDEX('  ',title) > 0 or CHARINDEX('  ',forename) > 0)

SQL Fiddle Demo

A: select name2, left(name2,len(name2)+1-patindex('%[^@]%',reverse(name2)+'.'))
from (
  SELECT *, REPLACE(NAME,' ','@') AS NAME2
  from t
) x;

Check this SQL Fiddle
For posterity, sample table:
create table t (name varchar(100));
insert t select 'name@name@ne@@@'
union all select '@name@name'
union all select 'name name hi   '
union all select 'joe public'
union all select ''
union all select 'joe'
union all select 'joe   '
union all select null
union all select '   leading spaces'
union all select '   leading trailing  ';

A: Don't quite understand the question, but if the problem is there is not spaces after some names, can't you do this first:
SELECT *,  REPLACE(NAME+' ',' ','@') AS NAME2

i.e., add a space to all names right off the bat?

A: I had this same problem some days ago.
Well actually, there's a quickly way to subtract the spaces from both the begin and end inside strings. In SQL Server, you can use the RTRIM and LTRIM for this. The first one supresses spaces from right side and the second supresses from left. But, if in your scenario also may exists more than one space in the middle of the string I sugest you take a look on this post on SQL Server Central: http://www.sqlservercentral.com/articles/T-SQL/68378/
There the script's author explain, in details, a good solution for this situation.


text:
Q: Where is the first good moment to take a screenshot in UIViewController I would like to make a screenshot of my view when view is loaded. I use this method:
- (UIImage *)screenshot {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0f);

    if( [self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)] ) {
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    } else {
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    }

    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return screenshot;
}

The screenshot method was tested and works well. I am using the method in my UIViewController in viewDidLoad. The problem is that the result is a grey image! It's mean that view is not loaded in viewDidLoad method. The same issue can be observe in viewDidAppear. So viewDidLoad and viewDidAppear are too early. I have made workaround in viewDidLoad method:
__weak MyUIViewController *weakSelf = self;

dispatch_async(dispatch_get_main_queue(), ^() {
    UIImage* image = [weakSelf.view screenshot]
    // do sth with image...
});

How to make a screenshot without dispatach_async ?

A: Try This:
- (UIImage *)screenshot {
    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, [UIScreen mainScreen].scale);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

UIView-JTViewToImage project also usefull.

A: You could also try the snapshotViewAfterScreenUpdates method of UIView:
[self.view snapshotViewAfterScreenUpdates:YES];

A: Try this
New API has been added since iOS 7, that should provide efficient way of getting snapshot
snapshotViewAfterScreenUpdates: renders the view into a UIView with unmodifiable content
resizableSnapshotViewFromRect:afterScreenUpdates:withCapInsets : same thing, but with resizable insets
drawViewHierarchyInRect:afterScreenUpdates:

same thing if you need all subviews to be drawn too (like labels, buttons...)
Hope it helps.


text:
Q: Python BeautifulSoup prettify I am trying to web scrap a webpage to download the data.
The code is as follow:
from bs4 import BeautifulSoup
import requests

link='https://www.abs.gov.au/statistics/economy/price-indexes-and-inflation/residential-property-price-indexes-eight-capital-cities/latest-release'
data=[]

url=requests.get(link).text
soup=BeautifulSoup(url,'lxml')
table=soup.find_all('div',class_='abs-content clearfix text-formatted field field--name-field-abs-text-paragraph-content field--type-text-long field--label-hidden')
for data in table:
    region=data.find_all('tr')
    for header in region:
        print(header.text)

And I finally get the below result:
Residential property pricesSep Qtr 21 to Dec Qtr 21Dec Qtr 20 to Dec Qtr 21
% change% change
Weighted average of eight capital cities4.723.7
Sydney4.126.7
Melbourne3.920.0
Brisbane9.627.8
Adelaide6.823.9
Perth2.915.7
Hobart6.529.8
Darwin1.513.0
Canberra6.428.8

Total value of the dwelling stock in AustraliaDec Qtr 21
Value of dwelling stock(a) ($b)9,901.6
Mean price of residential dwellings ($'000)920.1
Number of residential dwellings ('000)10,761.9
 RPPI (a)HPIADPI
Sep Qtr 21 to Dec Qtr 21Sep Qtr 21 to Dec Qtr 21Sep Qtr 21 to Dec Qtr 21
% change% change% change
Weighted average of eight capital cities4.75.33.2
Sydney4.14.53.3
Melbourne3.94.23.1
Brisbane9.610.83.9
Adelaide6.87.73.1
Perth2.92.92.3
Hobart6.56.74.9
Darwin1.51.32.1
Canberra6.47.04.3

How can I separate them into different columns and present the following data like this? Thank you.

A: Method 1
Using bs4 module first find table
import requests
from bs4 import BeautifulSoup
res=requests.get("https://www.abs.gov.au/statistics/economy/price-indexes-and-inflation/residential-property-price-indexes-eight-capital-cities/latest-release")
soup=BeautifulSoup(res.text,"html.parser")
table=soup.find("table")

Now find table headers and append to list of values
all_cols=table.find_all("th")
cols=[i.get_text(strip=True) for i in all_cols]
first_three=cols[:3]

Now find table row values and split it using , to append to list as list of list values which can be use in pandas  df and gives table structure data
lst=[]
for i in table.find("tbody").find_all("tr"):
    lst.append(i.get_text(strip=True,separator=",").split(","))

filtered=lst[:-1]
import pandas as pd
df=pd.DataFrame(filtered,columns=first_three)
df

Output:
Residential property prices Sep Qtr 21 to Dec Qtr 21    Dec Qtr 20 to Dec Qtr 21
0   Weighted average of eight capital cities    4.7 23.7
1   Sydney  4.1 26.7
....

Method 2
Simplest Method to get tables from URL is to use pandas module to get all table details
import pandas
lst=pd.read_html("https://www.abs.gov.au/statistics/economy/price-indexes-and-inflation/residential-property-price-indexes-eight-capital-cities/latest-release")
df=lst[0]

Output:
Residential property prices Sep Qtr 21 to Dec Qtr 21    Dec Qtr 20 to Dec Qtr 21
Residential property prices % change                    % change
0   Weighted average of eight capital cities    4.7     23.7
1   Sydney  4.1 26.7
2   Melbourne   3.9 20.0
.....


text:
Q: MySQL UPDATE multiple rows with results from API Say, I have a table with 4 columns. The first 2 columns are sourced from a feed. The columns value1 and value2 I need to update using results from API requests. The values from the API request should go into value1 and value2
+---------+------+-------+-------+
| prod_id | name | value1| value2|
+---------+------+-------+-------+
|   1105  | aat  |       |       |
|   1108  | bbv  |       |       |
|   1111  | ccq  |       |       |
|   1116  | dde  |       |       |
|   1123  | iir  |       |       |
|   1125  | jjm  |       |       |
+---------+------+-------+-------+

For example the API request gives me these values:
1108, banana, apple
1116, cucumber, pineapple
1123, orange, melon

So in this example I would like to update these 3 records, but in my case I would have update around 1000-2000 records at a time.
+---------+------+--------+----------+
| prod_id | name | value1 | value2   |
+---------+------+--------+----------+
|   1105  | aat  |        |          |
|   1108  | bbv  |banana  |apple     |
|   1111  | ccq  |        |          |
|   1116  | dde  |cucumber|pineapple |
|   1123  | iir  |orange  |melon     |
|   1125  | jjm  |        |          |
+---------+------+--------+----------+

How would I be able to update, say 2000 records using only one or a handful of queries? Would I need to use a temporary table or is there a way to do without?

A: You can implement a kind of batch update using CASE as described in How to bulk update mysql data with one query?.
Alternatively if you control the database schema you can insert the results of the API calls in batch INSERT statements and then JOIN when you need to lookup a particular value.
Table A
+---------+------+
| prod_id | name |
+---------+------+
|   1105  | aat  |
|   1108  | bbv  |
|   1111  | ccq  |
|   1116  | dde  |
|   1123  | iir  |
|   1125  | jjm  |
+---------+------+

Table B
+---------+----------+-----------+
| prod_id |  value1  |   value2  |
+---------+----------+-----------+
|   1108  | banana   | apple     |
|   1116  | cucumber | pineapple |
|   1123  | orange   | melon     |
+---------+----------+-----------+

When results are retrieved from API calls they can be inserted in batch.
INSERT INTO B (prod_id, value1, value2) VALUES
(1108, 'banana', 'apple'),
(1116, 'cucumber', 'pineapple'),
(1123, 'orange', 'melon')

Later if you need all values for prod_id 1108 for instance you can retrieve them whit a simple join of tables A and B.
SELECT A.prod_id, A.name, B.value1, B.value2
FROM A JOIN B ON A.prod_id = B.prod_id
WHERE A.prod_id = 1108


text:
Q: Is there a function that will quickly sort a file in C? Right, I'm writing some code using databases, and someone at my school was talking about some specific command that could automatically get a file and sort it.
I think I have a grasp on how to sort this file manually, but it requires a lot of work, so I was wondering if anyone knew this function.
edit: using DEV C++ , Library #stdio.h and # conio.h , (i can add the extra library if necessary) no idea what the specific complier is however.

A: assuming your input file is data.txt (Linux), you can use the system command sort:
sort data.txt > output.txt

A: As others have mentioned there is sort command in Unix:
sort myfile.txt

see man sort for more options.
And there is SORT command on Windows:
sort myfile.txt

or
SORT myfile.txt

for more help see: http://www.computerhope.com/sorthlp.htm
With that you could write simple C program that would use those commands.
// sort.system.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  if (argc != 2) { // expecting one argument, file which we will sort
    fprintf(stderr, "Usage: sort [FILE]\n");
    return EXIT_FAILURE;
  }

  int length = 5 + strlen(argv[1]) + 1; // length of "sort " is 5.
  char *command = (char *) calloc(length, sizeof(char));
  sprintf(command, "sort %s", argv[1]);

  int ret = system(command);

  return ret;
}

Here we just expect from user to enter file he wants to sort and then we are using this file and just give it to sort command. But first we need to make sure that user actually entered something. That is why we have if on beginning of main function.
Second approach would be to write sort command ourself. The fun starts here. :D
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LINE_LENGTH 1000000

// compare function for qsort function
int compare (const void *a, const void *b) {
  const char **s1 = (const char **) a;
  const char **s2 = (const char **) b;
  return strcmp(*s1, *s2);
}

int main(int argc, char **argv) {
  if (argc != 2) { // expecting one argument, file which we will sort
    fprintf(stderr, "Usage: sort [FILE]\n");
    return EXIT_FAILURE;
  }

  char *filename = argv[1]; // name of file to sort
  FILE *file = fopen(filename, "r"); // trying to open that file
  if (file == NULL) {
    fprintf(stderr, "Could not open file %s\n", filename);
    return EXIT_FAILURE;
  }

  int size = 16; // initial size of lines container
  char **lines = (char **) calloc(size, sizeof(char *)); // lines container
  if (lines == NULL) { // safety check
    fprintf(stderr, "Could not allocate the requested block of memory\n");
    return EXIT_FAILURE;
  }

  // buffer where we will store every line before putting it into line container
  char *buffer = (char *) calloc(MAX_LINE_LENGTH + 1, sizeof(char));
  if (buffer == NULL) { // safety check
    fprintf(stderr, "Could not allocate the requested block of memory\n");
    return EXIT_FAILURE;
  }

  int counter = 0; // line counter, counts how many lines we have readed

  // reading whole line into buffer
  while(fgets(buffer, MAX_LINE_LENGTH + 1, file) != NULL) {
    // measuring line length with strlen and adding 1 for '\0'
    int length = strlen(buffer);
    if (buffer[length - 1] == '\n') { // remove '\n' on end of line
      // replace '\n' with '\0', thus '\0' already included into length
      buffer[length - 1] = '\0';
    } else {
      length++; // include '\0'
    }

    // if our lines container is not large enough we will double its size
    if (counter + 1 == size) {
      size *= 2;
      lines = (char **) realloc(lines, size*sizeof(char *));
      if (lines == NULL) { // safety check
        fprintf(stderr, "Could not allocate the requested block of memory\n");
        return EXIT_FAILURE;
      }
    }

    // allocating space for line
    lines[counter] = (char *) malloc(length*sizeof(char));
    strcpy(lines[counter], buffer);

    counter++;
  }

  // using qsort function from stdlib.h
  qsort(lines, counter, sizeof(char *), compare);

  int i;
  for (i = 0; i < counter; i++) {
    puts(lines[i]);
  }

  return EXIT_SUCCESS;
}

Idea is to have some dynamic "lines container" whose initial size is 16. Every time we see that we need more space for storing our lines, we double the size of our "lines container".
Also, we have some buffer that we use to store every line and then we copy that line into next line container slot.
Here I limited size of one line to 10^6 characters. But you could dynamically allocate space for buffer too by using ftell and fseek functions. I suggest you to do that for practice. :)
For actual sorting of strings we are using qsort function from stdlib.h:
http://www.cplusplus.com/reference/cstdlib/qsort/


text:
Q: In IE 8 to show an Image, image/abc.gif and image\abc.gif both are working fine but in IE 11 it isn't. Can somebody help me out with this why I was working with some issue where image was not getting loaded on user computer by using IE11.
I had no issue seeing this because I was using IE8.
By some research I found out this issue. I am not getting any error o  my computer with IE8.
"image/img1.gif"
"image\img2.gif"
I was using above example for two image and both were working in IE8 but not in IE11.
Thanks

A: Hi I have found the answer of this issue. It was because of the new update of Microsoft,
https://support.microsoft.com/en-us/help/4491113/cumulative-update-for-internet-explorer-february-19-2019
After updating this I am able to use both / and \ in image src path in the HTML page.
Thanks Guys.


text:
Q: NPM postinstall Error on Dependency core-js Trying to Run on Docker I'm getting this error specifically on RUN npm install on Dockerfile:
> core-js@2.6.11 postinstall /app/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

The command '/bin/sh -c npm install' returned a non-zero code: 1

When I checked the package dependencies tree via npm ll, I saw that core-js is used by loopbackjs. I'm using version loopback 3.0.0.
I already tried the workaround here and here which is to put this before npm install:
RUN npm config set unsafe-perm true

but same result.
Here's the complete related error log:
Step 6/9 : RUN npm install
 ---> Running in 10ca507be4fa
npm WARN deprecated nsp@2.8.1: The Node Security Platform service is shutting down 9/30 - https://blog.npmjs.org/post/175511531085/the-node-security-platform-service-is-shutting
npm WARN deprecated joi@6.10.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated wreck@6.3.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated swagger-ui@2.2.10: No longer maintained, please upgrade to swagger-ui@3.
npm WARN deprecated topo@1.1.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@2.16.3: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated boom@2.10.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated jade@0.26.3: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm WARN deprecated to-iso-string@0.0.2: to-iso-string has been deprecated, use @segment/to-iso-string instead.
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue

> core-js@2.6.11 postinstall /app/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

The command '/bin/sh -c npm install' returned a non-zero code: 1

Here's my package.json:
{
...
"dependencies": {
    "axios": "^0.18.0",
    "body-parser": "^1.18.2",
    "calc-js": "^1.3.0",
    "compression": "^1.0.3",
    "connect-ensure-login": "^0.1.1",
    "cors": "^2.5.2",
    "crypto-js": "^3.1.9-1",
    "csv-parse": "^2.2.0",
    "csvjson": "^5.1.0",
    "email-validator": "^1.1.1",
    "express-flash": "0.0.2",
    "express-jwt": "^5.3.0",
    "file-system": "^2.2.2",
    "helmet": "^1.3.0",
    "js-big-decimal": "^1.2.1",
    "json2csv": "^4.5.4",
    "jsonwebtoken": "^8.1.1",
    "lodash": "^4.17.15",
    "loopback": "^3.0.0",
    "loopback-boot": "^2.6.5",
    "loopback-component-explorer": "^5.0.0",
    "loopback-component-passport": "^3.4.1",
    "loopback-component-storage": "^3.3.1",
    "loopback-connector-mysql": "^2.4.1",
    "loopback-context": "^3.3.0",
    "loopback-ds-timestamp-mixin": "^3.4.1",
    "moment-timezone": "^0.5.20",
    "passport": "^0.4.0",
    "passport-facebook": "^2.1.1",
    "passport-google-oauth": "^1.0.0",
    "passport-local": "^1.0.0",
    "pino": "^4.10.4",
    "pino-pretty": "^3.2.2",
    "safe-compare": "^1.1.2",
    "serve-favicon": "^2.0.1",
    "shortid": "^2.2.8",
    "sqlstring": "^2.3.1",
    "strong-error-handler": "^2.0.0",
    "underscore": "^1.8.3",
    "uuid": "^3.2.1"
  },
  "devDependencies": {
    "eslint": "^3.17.1",
    "eslint-config-loopback": "^8.0.0",
    "nsp": "^2.1.0"
  },
...
}

Here's the Dockerfile (some confidential parts replaced w/ ---):
FROM node:8.11.2-alpine

# Create app directory
RUN mkdir -p /app && ---
WORKDIR /app

# Install app dependencies
RUN apk update && apk upgrade && apk add libc6-compat && apk add curl && apk add bash && rm -rf /var/cache/apk/*
COPY package.json ./
RUN npm install

# Bundle app source
COPY . ./

EXPOSE 9003
CMD [ "npm", "start" ]

Thanks for all the help :)


text:
Q: Upload photos for past date I am trying to upload few old photos with a past creation date so that they appear properly in timeline.  Existing api allows only to pass message and source.
i.e
  POST https://graph.facebook.com/ALBUM_ID/photos?access_token=xyz
  ..multipart.form.data.with.message.and.source..

is the only way I can upload photos.
  POST https://graph.facebook.com/PHOTO_ID?access_token=xyz
  created_time=2010-01-20T09:04Z&updated_time=2010-01-20T09:04Z

doesn't move the photo date either.
I tried creating a post out of the photo upload using the /feed api, but it doesn't allow me to make an existing photo a post. It makes it a post of type link.
What I want to exactly create a photo object and publish following:
  {
    "id": "xx_yy",
    "from": {
       "name": "My Name",
       "id": "myfbid"
    },
    "story": "<My Name> added a new photo.",
    "picture": "<PhotoJPEG>",
    "link": "<FBPhoto_URL>",
    "name": "Photo Name",
    "icon": "https://s-static.ak.facebook.com/rsrc.php/v1/yz/r/StEh3RhPvjk.gif",
    "actions": [
       {
          "name": "Comment",
          "link": "https://www.facebook.com/xxx/posts/yy"
       },
       {
          "name": "Like",
          "link": "https://www.facebook.com/xx/posts/yy"
       }
    ],
    "privacy": {
       "description": "Group",
       "value": "CUSTOM",
       "friends": "SOME_FRIENDS",
       "allow": "<GROUPID>"
    },
    "place": {
       "id": "<placeid>",
       "name": "<PlaceName>"
    },
    "type": "photo",
    "object_id": "12345",
    "created_time": "2010-09-20T13:37:54+0000",
    "updated_time": "2010-09-20T13:37:54+0000",
    "comments": {
       "count": 0
    }
  }

A: I'm an Engineer at FB, but not on the Platform team so I'm not 100% up to date on this. There is an undocumented field 'backdated_time' available on the photo uploader in the Graph API. I assume it's supernew and will be being doc'd over the next few weeks, but feel free to try it in the interim (and report back here!).
It takes an ISO-8601 timestamp by the looks of it.
The docs team have been chased to figure out what's going on.
Also, DMCS isn't quite right. FB Engineers (particularly those in our Developer Support team) are encouraged to hang out here to help with questions, and each week on our developer blog we post how many questions were asked and how many were answered. So there is a commitment to getting questions on SO answered - see https://developers.facebook.com/blog/post/625/ as an example.
However, there's a difference between support of existing features and bugs/requests for new features. If you have a bug or feature request, add it to http://developers.facebook.com/bugs.
Thanks!

A: I would assume with how new the timeline is, that this is a Facebook bug or an enhancement that needs to be made to the API.  Have you submitted this to Facebook?

A: The following code works. (Combines this FB example code with mrtom's undocumented field.)
<?php

$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$post_login_url = "YOUR_POST_LOGIN_URL"; // should be the URL of this script

$code = $_REQUEST["code"];

//Obtain the access_token with publish_stream permission
if(empty($code)) {
  $dialog_url= "http://www.facebook.com/dialog/oauth?"
   . "client_id=" .  $app_id
   . "&redirect_uri=" . urlencode( $post_login_url)
   .  "&scope=publish_stream";
  echo("");
}
else {

  $token_url="https://graph.facebook.com/oauth/access_token?"
   . "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
   . "&client_secret=" . $app_secret
   . "&code=" . $code;
  $response = file_get_contents($token_url);
  $params = null;
  parse_str($response, $params);
  $access_token = $params['access_token'];

 // Show photo upload form to user and post to the Graph URL
 $graph_url= "https://graph.facebook.com/me/photos?"
 . "access_token=" .$access_token;

 echo '';
 echo '<form enctype="multipart/form-data" action="'
 .$graph_url .' "method="POST">';
 echo 'Please choose a photo: ';
 echo '<input name="source" type="file">

';
 echo 'Say something about this photo: ';
 echo '<input name="message"
     type="text" value="">

';
 echo 'ISO Date for this photo: ';
 echo '<input name="backdated_time"
     type="text" value="">

';

 echo '<input type="submit" value="Upload"/>
';
 echo '</form>';
 echo '';
}

?>


text:
Q: High Sierra forgets display layout on reboot Since I upgraded to High Sierra, my 2-display layout gets reset to side-by-side every time I reboot, when instead it should be vertical to match the physical layout of my monitors.
While potentially unrelated, High Sierra also lost my Login Items after the upgrade.
I'm using a MacBook Pro (15-inch, 2017), running 10.13.
How can I get High Sierra to remember my display layout?

A: Your MBP uses Non-Volatile Random-Access Memory (NVRAM) to store various settings. It may be worth resetting this.
To reset the NVRAM on all Late-2016 and 2017 MacBook Pro models (with and without Touch Bar) follow these steps:

*

*Shut down your MBP. Yes, a full shut down, not just logging out.

*Press the power button and then immediately press the commandoptionpr keys.

*Keep these keys pressed down for at least 20 seconds!

*Let go of the keys and let your MBP reboot normally.

Note 1: When you log back in you may need to readjust some of your system preferences (e.g. speaker volume, screen resolution, startup disk selection, time zone information, etc).
Note 2: If your Mac is using a firmware password, you will need to disable the firmware password before resetting NVRAM.


text:
Q: Access a nested object using a variable value in Javascript I am making a game.  The end-user will select a fighter among 12 available fighters.  Let's say they select 'Ryu'.  But they could have selected 'ChunLi'.  The player selection will be stored in the variable 'selectedPlayer'. Now I need to get/access the object (or its members) that matches the user's selection.  I have tried a number ways, including the one shown below, but I get in the console: "Uncaught TypeError: Cannot read property 'Ryu' of undefined."
var selectedPlayer = "Ryu";
var Slogan = players[selectedPlayer]['Slogan'];
console.log(Slogan);

var players = {
    Ryu:  {
        Name: "Ryu",
        Country: "Japan",
        Text: "The answer lies in the heart of battle.",
        smImg: "../images/small/ryu.png",
        lgImg: "../images/large/ryu.jpg",
        attack: [1,5,10,15,20,25]
    },
    ChunLi: {
        Name: "Chun Li",
        Country: "China",
        Slogan: "Want to see my Kung-Fu? I'll show you.",
        smImg: "../images/small/chunli.png",
        lgImg: "../images/large/chunli.jpg",
        attack: [1,4,11,15,21,25]
    }
}

I need to be able to get into the 'players' object and access the members of the selected fighers' object.  I could write a bunch of if statements, but that wouldn't be very clean.  Can I do something like this?
var playerOne = {
    Name: players.<some variable>.Name,
    Country: players.<some variable>.Country,
    Slogan: players.<some variable>.Slogan,
    smImage: players.<some variable>.smImg,
    lgImage: players.<some variable>.lgImg,
    Attack: players.<some variable>.attack
};

var playerTwo = {
    Name: players.<some variable>.Name,
    Country: players.<some variable>.Country,
    Slogan: players.<some variable>.Slogan,
    smImage: players.<some variable>.smImg,
    lgImage: players.<some variable>.lgImg,
    Attack: players.<some variable>.attack
};

Maybe there is a different.  I'm open to anything that works well.  Thank you.

A: You need to define the mapping before you access it. Plus, Ryu appears to have no Slogan.
var players = {
    Ryu:  {
        Name: "Ryu",
        Country: "Japan",
        // Shoudldn't this be "Slogan"?
        Text: "The answer lies in the heart of battle.",
        smImg: "../images/small/ryu.png",
        lgImg: "../images/large/ryu.jpg",
        attack: [1,5,10,15,20,25]
    },
    ChunLi: {
        Name: "Chun Li",
        Country: "China",
        Slogan: "Want to see my Kung-Fu? I'll show you.",
        smImg: "../images/small/chunli.png",
        lgImg: "../images/large/chunli.jpg",
        attack: [1,4,11,15,21,25]
    }
}

var selectedPlayer = "Ryu";
var Slogan = players[selectedPlayer]['Slogan'];
console.log(Slogan);

A: Your error is because you're referencing players before it's defined. Try this:
var players = {
    Ryu:  {
        Name: "Ryu",
        Country: "Japan",
        Text: "The answer lies in the heart of battle.",
        smImg: "../images/small/ryu.png",
        lgImg: "../images/large/ryu.jpg",
        attack: [1,5,10,15,20,25]
    },
    ChunLi: {
        Name: "Chun Li",
        Country: "China",
        Slogan: "Want to see my Kung-Fu? I'll show you.",
        smImg: "../images/small/chunli.png",
        lgImg: "../images/large/chunli.jpg",
        attack: [1,4,11,15,21,25]
    }
}

var selectedPlayer = "Ryu";
var Slogan = players[selectedPlayer]['Slogan'];
console.log(Slogan);


text:
Q: Prove that $ | a_0 | \leq \frac{2^n n^n}{n \cdot n! } $ Let $ P(x) = a_0 x^n + a_1x^{n-1}+\cdots+a_n $ be a polynomial with the following property :
$ |P(x)| \leq 1 $ for every $ x \in [0,1] $
Prove that
$$ | a_0 | \leq \frac{2^n n^n}{n \cdot n! } $$
I'm having some trouble proving this. I bet this one is solved using the divided difference of the polynomial, which is the coefficient of $ x^n$ $(a_0)$ :
$$ a_0 = [x_0,x_1,...,x_n;P] = \sum_{i=0}^{n} \frac{P(x_i)}{l'(x_i)} $$

A: The Chebyshev polynomials are defined by the recurrence:
$\begin{align*}
      T_0(x)
        &= 1 \\
      T_1(x)
        &= x \\
      T_{n + 1}(x)
        &= 2 x T_n(x) - T_{n - 1}(x)
          \quad n \ge 1
\end{align*}$
An explicit formula is:
$\begin{equation*}
  T_n(x)
    = \cos(n \arccos x)
\end{equation*}$
This can be proved by showing these polynomials satisfy the above recurrence. Note the recurrence implies $T_n(x) = 2^{n - 1} x^n + \dotsb$. By the explicit formula, $\lvert T_n(x) \rvert \le 1$ for $-1 \le x \le 1$.
Theorem: If $p(x)$ is a monic polynomial of degree $n \ge 1$, then:
$\begin{align*}
  \max_{-1 \le x \le 1} \lvert p(x) \rvert
        &\ge 2^{1 - n}
\end{align*}$
Proof: By contradiction. Assume that for the monic polynomial $p(x)$ of degree $n \ge 1$ for all $-1 \le x \le 1$ it is $\lvert p_n(x) \rvert < 2^{1 - n}$. Let $q(x) = 2^{1 - n} T_n(x)$, so $q$ is monic. Take the points $x_j = \cos (j \pi / n)$ for $0 \le j \le n$. By the explicit formula for Chebyshev polynomials, for those values $q(x_j) = (-1)^j \cdot 2^{1 - n}$. So $(-1)^j q(x_j) = 2^{1 - n}$. By our assumption on $p$, $(-1)^j p(x_j) \le \lvert p(x_j) \rvert < 2^{1 - n}  = (-1)^j q(x_j)$. So $(-1)^j (q(x_j) - p(x_j)) > 0$ for $x_0, \dotsc, x_n$ , i.e., the polynomial $q(x) - p(x)$ changes sign $n$ times in the interval. But as $p$ and $q$ are monic, $q(x) - p(x)$ is of degree $n - 1$, and can have at most $n - 1$ real zeros, contradiction.
Note this proves the bound $2^{1 - n}$ is best possible.


text:
Q: how to serve static content in springboot 2.2.6? I am newbie to Springboot and I am trying to display html page on its root(localhost:8080) path. To do so I googled and gone through -

*

*Spring Boot not serving static content

*https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

*Spring Boot app not serving static content

*Springboot does not serve static content
Tried almost everything but none of them worked for me.
Exact problem
With out index.html file inside any of resources/(static/ or public/ or meta-inf/resources) works fine and show the list of some spring data rest. If I create an index.html file then it gives an error of 404 not found with out @EnableWebMvc annotation, if use @EnableWebMvc then it shows the list of Spring data rest apis.
Other than index.html file it show the list of Spring data api in root path, and url(localhost:8080/test.html) to other than index.html has same problem.
This problem has no effects by implementing public class StaticResourceConfiguration implements WebMvcConfigurer with this configuration to.

A: Starting with a simple spring boot initializer
... we can place static (html) files into one of:

*

*(src/main/resources:)

*static

*resources

*public

*META-INF

*

*resources
which results in the default (class path) locations, configured via the spring.resources.static-locations property.
These will be exposed through the value of spring.mvc.static-path-pattern-property (ref), by default: /**.
So a static index.html file in one of the above mentioned folders, with default config, will be accessible at:

*

*http:localhost:8080/ (due to "welcome file mapping" -> static mapping)

*and http://localhost:8080/index.html (due to the static mapping)

Accordingly: no problem with http://localhost:8080/test.html ...

Checkout at github.
So this, at least answers the "question title" "how to serve static content in springboot 2.2.6?".

The order of spring.resources.static-locations appears (index.html preferred from META-INF/resources) also to be the "precedence" of static file locations (left-to-right, first match wins).

When we add @EnableWebMvc
..."evertyhing gets broken" (context loads, but) only:
WARN ... o.s.web.servlet.PageNotFound             : No mapping for GET /
WARN ... o.s.web.servlet.PageNotFound             : No mapping for GET /index.html
WARN ... o.s.web.servlet.PageNotFound             : No mapping for GET /test.html

..please aslo consider this: why spring-boot application doesn't require @EnableWebMvc
With "non-default config", You would have to provide more details, to find a specific solution.
But for "newbie in Springboot": starting with an intializer and "the defaults" sounds optimal! From here on, you can re-fine your configuration based on a working one.

And if you want/need the @EnableWebMvc annotation for some reason, this will result in the "previous" behavior again/restore the (2.2.6) default static content handling:
@EnableWebMvc
@SpringBootApplication
public class DemoApplication implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
          .addResourceHandler("/**")
          .addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/");

    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

(Assuming no conflicts with existing configuration/resource handlers)

A: It's working for me
registry.addResourceHandler("//**").addResourceLocations("classpath:/static/");


text:
Q: Slide gesture with custom back button freezes the root view controller I have custom back buttons all over my app and it looks like navigation controller does not like it.
So, I want the iOS7 swipe-to-go-back gesture to work along with my custom back buttons. Searched and tried different ways but none seems to be promising. The closest I could get is with http://keighl.com/post/ios7-interactive-pop-gesture-custom-back-button/.
However, Now when I keep pushing and popping the navigation stack, after sometime the rootViewController in the stack stops responding to any touch.
Any suggestions?

A: Subclassing UINavigationController, like keighl is suggesting, is the right approach imo. But he's missing a check for the root view controller to avoid freezing when the gesture is executed on the root view.
Here's a modified version with the additional check:
CBNavigationController.h:
#import <UIKit/UIKit.h>

@interface CBNavigationController : UINavigationController <UIGestureRecognizerDelegate, UINavigationControllerDelegate>
@end

CBNavigationController.m:
#import "CBNavigationController.h"

@interface CBNavigationController ()
@end

@implementation CBNavigationController
- (void)viewDidLoad
{
    NSLog(@"%s",__FUNCTION__);
    __weak CBNavigationController *weakSelf = self;

    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
    {
        self.interactivePopGestureRecognizer.delegate = weakSelf;
        self.delegate = weakSelf;
    }
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    NSLog(@"%s",__FUNCTION__);

    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
        self.interactivePopGestureRecognizer.enabled = NO;

    [super pushViewController:viewController animated:animated];
}

#pragma mark UINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController
       didShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animate
{
    NSLog(@"%s",__FUNCTION__);

    // Enable the gesture again once the new controller is shown AND is not the root view controller
    if (viewController == self.viewControllers.firstObject)
    {
        if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
            self.interactivePopGestureRecognizer.enabled = NO;
    }
    else
    {
        if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
            self.interactivePopGestureRecognizer.enabled = YES;
    }
}

@end

objective-c

A: I've got the same problem, here is my solution:
In your custom NavigationController, like MYNavigationController, cause you set the gesture delegate to the navigationController, you can add the delegate method there :

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if (self.viewControllers.count>1) {
        return YES;
    }
    return NO;
}

then it will stop the poping action when it's in the root viewController and avoiding the freezing behavior.

A: Even I had the same problem, I have fix it by modifying code provide in the link which you are referring . Now My screens freezes very rarely still finding for permanent fix.
@implementation PPNavigationController

-(void)viewDidLoad
{
    //[super viewDidLoad];
    // Do any additional setup after loading the view.

     __weak PPNavigationController *weakSelf = self;

    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
    {
        self.interactivePopGestureRecognizer.delegate = weakSelf;
        self.delegate = weakSelf;
    }

}

-(void)navigationController:(UINavigationController *)navigationController
       didShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animate
{
    // Enable the gesture again once the new controller is shown

    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
        self.interactivePopGestureRecognizer.delegate = viewController;
}

Don't use this method
//-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
//}

A: Here is my answer to a similar question asked here
You can use a little trick to get the native gesture working.
Create a subclass of UINavigationItem, then override leftBarButtonItems method:

- (NSArray*)leftBarButtonItems
{
    return nil;
}

Now use this class for the item that has custom left UIBarButtonItem. The gesture works! This is because UINavigationController thinks there are no left items and enables the gesture. You are still able to access your custom item through the leftBarButtonItem property.

A: Here's a simple Swift subclass of UINavigationController you can use that I adapted from @weak's answer. There shouldn't be a need to implement UIGestureRecognizerDelegate as the nav delegate's navigationController(_:didShow:animated:) handles the work of enabling and disabling the pop gesture.
Using this subclass in your storyboard or code is easier than doing a one-off disabling in your other controllers that are embedded in nav controllers.
import UIKit

@objc class LWNavigationController : UINavigationController,
                                     UINavigationControllerDelegate {
    override func viewDidLoad() {
        self.delegate = self
    }

    override func pushViewController(_ viewController: UIViewController,
                                     animated: Bool) {
        // Disable this gesture while animating a push.
        self.interactivePopGestureRecognizer?.isEnabled = false
        super.pushViewController(viewController, animated: animated)
        debugPrint("------\(#function) \(viewController)------")
    }

    // MARK: - UINavigationControllerDelegate

    func navigationController(_ navigationController: UINavigationController,
                              didShow viewController: UIViewController,
                              animated: Bool) {
        if (viewController == self.viewControllers.first) {
            // Keep the gesture disabled if we're at the root to avoid back swipes
            // from corrupting the navigation stack.
            self.interactivePopGestureRecognizer?.isEnabled = false
        } else {
            self.interactivePopGestureRecognizer?.isEnabled = true
        }
        debugPrint("------\(#function) \(viewController) " +
                   "enabled: \(self.interactivePopGestureRecognizer?.isEnabled)" +
                   "------")
    }
}


text:
Q: Running python script in colab very slow as compared to same code run on directly colab in notebook Recently I was trying to test my model which i already trained. Initially I was using Google colab notebook to write code because of it's interactive features, once I was done writing code and I was getting satisfactory results, it took around 2.5 hr to give final output. After that what I wanted was to transfer the notebook code to .py script, I did that with little bit of modification, saved it in gdrive, and then used command !python test.py. now it took me more than 4.5 hr to get the final output, can any one explain why does colab take so much time when trying to run the python script from gdrive while compared to the same code as used in notebook

A: I would add time calculation to every step I doubt that takes time and see which step in your whole program takes the time.
      a1 = time.time()
      //your code step
      print(time.time() - a1)

This will give you the time for each step and you can see which one is taking a long time.
Operations to check.
1. object creation in loops
2. read/write operation to Gdrive
Once you find the problem-causing piece of code, you may change it.

A: Well it can be because of the fact that colab is retrieving the data from gdrive and then might be again writing in gdrive which will of ofcourse take time i guess


text:
Q: Wordpress post slideToggle with each() issue I feel like I've been trying everything to get this to work, the problem is that I'm not that familiar with javascript nor jQuery.
My guess is that it's as simple as just adding one line, because I've almost got it to work.
I have a Wordpress blog which loops out numerous of posts, I've added unique ID's to everyone of them, which I'm able to grab the problem is that it doesn't work with slideToggle to show the content.

Then there's the container:
<div class="toggleContainer" data-container="<?php the_id(); ?>">
    <?php do_action( 'woocommerce_before_single_product_summary' ); ?>

And the toggle:
<a href="<?php the_permalink(); ?>" class="show_hide" data-id="<?php the_id(); ?>">

If I use an alert on each of them it shows the correct ID, but it doesn't work when I want to toggle the content.

A: try: $('[data-container*='+cid+']').slideToggle(1000);


text:
Q: Can't connect to Windows (SMB) I have a MacBook Pro (OS X 10.8.4) and a Windows 7 Ultimate machine. I can't connect to the latter because of incorrect password or login. I tried to create several users on Windows machine and even created quest user and it also does not work. On the Windows machine:

*

*network discovery turned on

*file and printer sharing turned on

*public sharing turned on

*firewall switched off

Also I can connect to Filezilla's FTP server and RDC Mac client works fine but SMB doesn't want to work at all.


text:
Q: How do I create a PDF that does NOT embed the used fonts? Using MS Word 2010, or a free program, how do I create a pdf that does not include the used font(s)? I need this to test a feature in GhostScript.

A: If you are using ghostscript anyway, you can generate the PDF with ghostscript using -dEmbedAllFonts=false.


text:
Q: Visual Studio: assign a key to maximize edit window How can I assign a hotkey to maximize the edit window?
Basically I want the equivalent of:

*

*switch to edit window + minimize all side panes

*or at least just minimize all side panes (and leaving the menu and toolbar as is)

NOTE: this is different than full screen, I do not want to change the size of the VS window itself.
I need this on Visual Studio 2017 / 2019.

A: Short of some sort of macro I thing the best way is probably like this:-

*

*Setup the windows in VS as you want them to look

*Save that as a layout.

*Assign a hotkey to the Switch to layout command.

A: Hot Windows extension provides shortcuts to hide and show all tool windows (e.g. Shift+Alt+Ins).


text:
Q: CSS not centering I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

Who's watching

First DIV

Second DIV

Third DIV

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996
I would like the squares next to eachtother.

A: Just use flex on outer
.divOuter {
  width: 50%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.divInner1,
.divInner2,
.divInner3 {
  flex: 1
}

A: Your .divOuter is correctly centered, but the problem is that you're apply a fixed width of 150px to your three inner elements. Swapping this to a percentage-based width of 100% correctly centers the elements:

.divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

Who's watching

First DIV

Second DIV

Third DIV

If you want to make use of a fixed width, you can do so by definining it on .divOuter:

.divOuter {
  width: 150px;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

Who's watching

First DIV

Second DIV

Third DIV

Also note that the  tag is self-closing; there is no  tag.
Hope this helps! :)

A: Using Chrome's Inspect, I got the results I think you are looking for with these updates to the .divInner1, 2 & 3 CSS classes.

*

*remove: "float: left;"

*add: "display: inline-block;

A:

    body{

  background: black;
}

#title h3{
  color: white;
  text-align: center;
}
.divOuter {
      margin: 0 auto;
      width: 100%;
      text-align: center;
      margin: 0 auto;
    }

    .divInner1,
    .divInner2,
    .divInner3 {
          border: 1px solid white;

          width: 150px;
          height: 150px;
          margin-left: 3px;
          margin-right: 3px;
          margin-top: 50px;
          text-align: center;
          display: inline-block;

Who's watching

First DIV

Second DIV

Third DIV

.divOuter {
  width: 150px;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

Who's watching

First DIV

Second DIV

Third DIV


text:
Q: Django annotate double nested key in JSONField My JSONField contains data like this:
class Car(models.Model):
   data = JSONField()

Car.objects.first().data

{
    u'colors': [
        {u'color_id': u'1', u'source': u'Manufacturer 3'},
        {u'color_id': u'2', u'source': u'Manufacturer 2'},
        {u'color_id': u'3', u'source': u'Manufacturer 1'},
    ]
}

I know that I can filter results with:
Car.objects.filter(data__colors__contains=[{'color_id':'3'}])

Is there any way I can annotate queryset so that 'color_id' are contained in a list? Something like:
Car.objects.all().annotate(color_ids=...)

That would enable me to do:
Car.objects.first().color_ids
['3', '2', '1']

Or something along those lines, just to filter with color_id value. Using Django 1.11 and Postgres 13.

A: I think you can use KeyTransform for getting the json value and ArrayAgg() for getting the list:
from django.contrib.postgres.fields.jsonb import KeyTransform

Car.objects.annotate(colors=KeyTransform("data", "colors")).annotate(color_id=KeyTransform("colors", "color_id")).annotate(colors_ids=ArrayAgg('color_id'))


text:
Q: How to exceed the limit of scan data for 1mb in dynamodb I am using dynamodb with nodejs, I am having 3000 records, and I am writing 60+ segments in the code, each segment scanning the data of 1mb and displaying the results to 60+ segments of 1 mb limit. So please provide the solution how to get the 3000 records scan in single step that means in one segment. Please provide the solution quickly because i am strucked in the middle of my project. Please help me. Below is my code.
var AWS = require("aws-sdk");
var async = require("async");

    AWS.config.update({
      region: "---",
      endpoint: "-----------",
      accessKeyId: "-----------------",
      secretAccessKey:"----------"
    });

var db = new AWS.DynamoDB.DocumentClient()

var table = "rets_property_all";
var pstart =new Date () .getTime ();

async.parallel({
            0 : function(callback){
        db.scan ({TableName: table,
          ProjectionExpression: "#cityname,ListingKey ",
          FilterExpression: "#cityname = :v_id",
          ExpressionAttributeNames: {
              "#cityname": "CityName",
          },
          ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            TotalSegments: 63,
            Segment:  0//by the worker who has been called
        },function (err , res) {
            callback (null , res.Items);
        });
            },
            1 : function(callback){
        db.scan ({TableName: table,
          ProjectionExpression: "#cityname,ListingKey ",
          FilterExpression: "#cityname = :v_id",
          ExpressionAttributeNames: {
              "#cityname": "CityName",
          },
          ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            TotalSegments: 63,
            Segment: 1//by the worker who has been called
        }, function (err , res) {
            callback (null , res.Items);
        });
            },
      2 : function(callback){
        db.scan ({TableName: table,
          ProjectionExpression: "#cityname,ListingKey ",
          FilterExpression: "#cityname = :v_id",
          ExpressionAttributeNames: {
              "#cityname": "CityName",
          },
          ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            TotalSegments: 63,
            Segment: 2//by the worker who has been called
        }, function (err , res) {
            callback (null , res.Items);
        });
            },
--------
---------
------

      62 : function(callback){
        db.scan ({TableName: table,
          ProjectionExpression: "#cityname,ListingKey ",
          FilterExpression: "#cityname = :v_id",
          ExpressionAttributeNames: {
              "#cityname": "CityName",
          },
          ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            TotalSegments: 63,
            Segment: 62//by the worker who has been called
        }, function (err , res) {
            callback (null , res.Items);
        });
      },

        },function(err,results){
      if (err) {throw err; }
      var pend = new Date () .getTime ();

      console.log (results);
        })

A: Actually, there is no way to override the 1 MB limit of scan. This is the DynamoDB design restriction and can't be overridden by any API. You may need to understand the limitation of the architecture or AWS service design.
You can use LastEvaluatedKey on the subsequent scans to start from where the previous scan ended.

The result set from a Scan is limited to 1 MB per call. You can use
  the LastEvaluatedKey from the scan response to retrieve more results.

The use case is unclear why you wanted to get all 3000 records in one scan. Even, if you have a specific use case, simply it can't be achieved on DynamoDB scan.
Even, in relation database, you get the cursor and go through the iterations to get all the records sequentially. Similarly, in DynamoDB you have to use Scan recursively until LastEvaluatedKey is null.
Sample code for single scan recursively until LastEvaluatedKey is null:-
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
    TableName: table,
    ProjectionExpression: "#cityname,ListingKey ",
    FilterExpression: "#cityname = :v_id",
    ExpressionAttributeNames: {
        "#cityname": "CityName",
    },
    ExpressionAttributeValues: { ":v_id": 'BALTIMORE' }
};

docClient.scan(params, onScan);

function onScan(err, data) {
    if (err) {
        console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        // print all the movies
        console.log("Scan succeeded.");
        data.Items.forEach(function (movie) {
            console.log("Item :", JSON.stringify(movie));
        });

        // continue scanning if we have more movies
        if (typeof data.LastEvaluatedKey != "undefined") {
            console.log("Scanning for more...");
            params.ExclusiveStartKey = data.LastEvaluatedKey;
            docClient.scan(params, onScan);
        }
    }
}


text:
Q: Tarskian and model-theoretic account of validity. ( On the importance of " logical form" in the account of deductive validity).
*

*In a paper published in A. Varzi's Nature of Logic, and entitled " Validity" , Graham Priest claims that the model-theoretic account of validity and the tarskian one are basically different ( though the tarskian one may be considered as a particular case of the MT one).

Source : in the 1999 section of the publication list ( http://grahampriest.net/publications/papers/) , section 1.4 of Priest's paper.

*

*As far as I understand , the tarskian one relies on the notion of valid form ( what you get when you replace all the non-logical vocabulary by variables while leaving logical constants in place).

Is this tentamount to claiming that the model theoretic notion of validity makes no official use of the notion of logical form?
Note : Model-theoretically , a reasoning " $\Gamma$ therefore $\phi$ " is valid just in case  any possible model  of $\Gamma$ ( i. e. structure in which all the members of $\Gamma$ are true) is also a model of $\phi$.

*

*Most introductory and elementary  textbooks say that a reasoning is valid iff its form is valid , that is iff every possible instance of its logical structure is valid.

Does this mean that they are committed to a tarskian account of validity rather to a model theoretic one?
More generally can one still say that, in the standard model theoretic account of validity, the logical consequence relation is formal ( in such a way that the conclusion holds " vi formae" ?


text:
Q: Angular, hot to show or hide elements depending on # bookmark in url I have a html page with several sections. In the main section I have links to the others, made like this:  and in every section a  to get back to the main section. I want Angular to detect chages on page bookmark and to show and hide the right section depending on it. How can I implement this?

A: See $location
// given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
var hash = $location.hash();
// => "hashValue"

Add this to your controller and based on that hash value you can show or hide your element.


text:
Q: How to set the maximum TCP receive window size in Linux? I want to limit the rate of every TCP connection. Can I set the maximum TCP receive window size in Linux?
With iptables + tc can only limit IP packets. The parameters net.core.rmem_max and net.core.wmem_max didn't not work well.

A: man tcp:

Linux supports RFC 1323 TCP high performance extensions. These include Protection Against Wrapped Sequence Numbers (PAWS), Window Scaling and Timestamps. Window scaling allows the use of large (> 64K) TCP windows in order to support links with high latency or bandwidth. To make use of them, the send and receive buffer sizes must be increased. They can be set globally with the /proc/sys/net/ipv4/tcp_wmem and /proc/sys/net/ipv4/tcp_rmem files, or on individual sockets by using the SO_SNDBUF and SO_RCVBUF socket options with the setsockopt(2) call.


text:
Q: How to dynamically import package in react and catch import errors without breaking app? I'm trying to dynamically import from my dependencies using a for loop like so
const packageNames = [
    '@packageA/address',
    '@packageB/app',
    '@packageC/auth',
]

    for await (const packageName of packageNames) {
        try {
            const importedPackage = await import(`${packageName}/custom-components`);
            console.log('importedPackage :', importedPackage);
            // Do something with the imported package
        } catch (error) {
            console.error(`Error importing ${packageName}: ${error}`);
        }
    }

I want to import custom-components from those packageNames and if it fails just to catch the error and log it.
But instead, it breaks the app if the custom-components file doesn't exist in the package I'm trying to import from.
One solution I was thinking of would be to use the fs package to check if custom-components file exists in the package but that's not possible to do in a React app.
Is there any other way to get around this, to just catch the error instead of breaking the app with an error like Can't resolve '@packageA/address/custom-components'


text:
Q: How to find If array of objects includes an element in javascript? and How to access it if includes? How can I find if an array of objects includes an element?
Suppose code is
var searchEngines = [{
    name: 'google',
    link: 'https://google.com'
  },
  {
    name: 'bing',
    link: 'https://bing.com'
  }];

//now I want to check if bing includes in array searchEngines or not (below code is wrong, please correct it)
console.log(searchEngines.name.includes('bing'));
//must return true. but it doesn't say true instead gives me an error and crashes the app.

so how can I check if searchEngines array includes bing or not?
Now if successfully checked that bing is included in searchEngines array, now how can I access bing?
like I wanna get the index number of bing array inside searchEngines array and then grab the link of it and console.log it, so I'll get https://bing.com

A: in this line console.log(searchEngines.name.includes('bing'));, you're trying to access the name property of the searchEngines variable which is an array.
I think a better way to find whether the array includes an object with the name variable set to 'bing' would be to use the find() function.
Here's an example:

var searchEngines = [{
    name: 'google',
    link: 'https://google.com'
  },
  {
    name: 'bing',
    link: 'https://bing.com'
  }];

const includesBing = searchEngines.find(se => se.name === 'bing') !== undefined;
const includesYahoo = searchEngines.find(se => se.name === 'yahoo') !== undefined;

console.log(includesBing)
console.log(includesYahoo)

A: Array.find will return undefined if no item which matches the condition is found.
You can use it to find the first item whose name property is 'bing'. To check whether an item was found, coerce it to a boolean and check whether it is true. If so, the item exists, and you can access it:

var searchEngines = [{
    name: 'google',
    link: 'https://google.com'
  },
  {
    name: 'bing',
    link: 'https://bing.com'
  }
];

const includesBing = searchEngines.find(e => e.name == 'bing')

if(includesBing){
  // bing exists
  console.log(includesBing.link)
}

A: searchEngines.name.includes('bing') throws an error because searchEngines is an array and therefore has no name property.
You had the right idea though, you just need to use the map method to get a list of just the names, rather than a list of objects, and then use includes to test that.

var searchEngines = [{
    name: 'google',
    link: 'https://google.com'
  },
  {
    name: 'bing',
    link: 'https://bing.com'
  }];

const searchEngineNames = searchEngines.map(engine => engine.name);

console.log(searchEngineNames.includes('bing'));

A:

var searchEngines = [{
    name: 'google',
    link: 'https://google.com'
  },
  {
    name: 'bing',
    link: 'https://bing.com'
  }];

const searchFn = (arr, prop, searchVal) => arr.findIndex(x => x[prop]==searchVal);

// search by name
const searchName = 'bing';
const index = searchFn(searchEngines, 'name', searchName);
if(index!=-1){
  console.log(searchEngines[index].link)
}

// search by link
const searchLink = 'https://google.com';
const index2 = searchFn(searchEngines, 'link', searchLink);
if(index2!=-1){
  console.log(searchEngines[index2].name)
}

A: I personally like simple solutions that also work for older versions.
var searchEngines = [{
    name: 'google',
    link: 'https://google.com'
  },
  {
    name: 'bing',
    link: 'https://bing.com'
  }];

function itemExists(propName, searchValue) {
    for (var i in searchEngines) {
        if (searchEngines[i][propName] === searchValue) {
            return true;
        }
    }
    return false;
}

console.log("containes 'bing': " + itemExists("name", "bing"));