text:
Q: The system is running in low-graphics mode I upgrade from 12.04 to 13.04. After I reboot i met "the system is running in low graphic".
my graphics driver is amd-driver-installer-catalyst-13-4-linux-x86.x86_64.
After I remove the driver I can get into the system, but only see wallpaper, but can use terminal but can't switch, and  can't move either, and system crash information always pop out.
My xorg.conf

Section "ServerLayout"

Identifier     "aticonfig Layout"
    Screen      0  "aticonfig-Screen[0]-0" 0 0
    EndSection

Section "Module"
  EndSection
Section "Monitor"

Identifier   "aticonfig-Monitor[0]-0"
     Option      "VendorName" "ATI Proprietary Driver"
     Option      "ModelName" "Generic Autodetecting Monitor"
     Option      "DPMS" "true"
    EndSection

Section "Device"

Identifier  "aticonfig-Device[0]-0"
     Driver      "fglrx"
     BusID       "PCI:1:0:0"
    EndSection

Section "Screen"

Identifier "aticonfig-Screen[0]-0"
     Device     "aticonfig-Device[0]-0"
     Monitor    "aticonfig-Monitor[0]-0"
     DefaultDepth     24
     SubSection "Display"
     Viewport   0 0
     Depth     24
     EndSubSection
    EndSection

$ glxinfo
name of display: :0.0
Error: couldn't find RGB GLX visual or fbconfig
I have tried many ways that i found, but i can't work out, all day. Anyone can help?
Thanks


text:
Q: Handling url parts in a api returned json format ***  I have updated code at the bottom.
I have a json object I'm working with and it's coming from Azure analytics for an application we build.  I'm trying to figure hot to parse the Url that comes back with just the limits and location keys data in separate columns.  The code I'm using is listed here:  (keys are take out as well as url because of api keys and tokens)
import request
import pandas as pd
from urllib.parse import urlparse
from furl import furl
import json

d1 = '<This is where I have the rule for the API>'

querystring = {"timespan":"P7D") #get's last 7 days
headers = { Stuff in here for headers }

response = requests.request("GET", d1, headers=headers, parms=querystring)

data = json.loads(response.text)

#then I clean up the stuff in the dataframe
for stuff in data(['value'])
    del stuff['count'].....(just a list of all the non needed fields in the json script)

newstuff = json.dumps(data, indent=2, sort_keys=True
data2 = json.loads(newstuff)

ok now here is the part I am having problems with, I want to pull out 3 columns of data from each row. the ['request']['url'], ['timestamp'], ['user']['id']
I'm pretty sure I need to do a for loop so I'm doing the following to get the pieces out.
for x in data2['value']:
    time = x['timestamp']
    user = x['user']['id']
    url = furl(x['request']['url'])
    limit = url.args['limit']
    location = url.args['location']

What's happening is when I try this i'm getting limit does not exist for every url.  I think I have to do a if else statement but not sure how to formulate this.  I need to get everything into a dataframe so I can parse it out into a cursor.execute statement which I know how to do.
What's needed.
1.  Get the information in the for loop into a dataframe
2.  take the url and if the url does not have a Limit or a Location then make it none else put limit in a column and same for location in a column by itself.
Dataframe would look like this
    timestamp     user          limit    location
    2018-01-01    bob@home.com     null
    2018-01-01    bill@home.com  null
    2018-01-01    same@home.com  null    null
    2018-01-02    bob@home.com
here is the information on furl
here is some sample json to test with:
   {
    "value": [{
            "request": {
                "url": "https://website/testing"
            },
            "timestamp": "2018-09-23T18:32:58.153z",
            "user": {
                "id": ""
            }
        },
        {
            "request": {
                "url": "https://website/testing/limit?location=31737863-c431-e6611-9420-90b11c44c42f"
            },
            "timestamp": "2018-09-23T18:32:58.153z",
            "user": {
                "id": "steve@home.com"
            }
        },
        {
            "request": {
                "url": "https://website/testing/dealanalyzer?limit=57bd5872-3f45-42cf-bc32-72ec21c3b989&location=31737863-c431-e611-9420-90b11c44c42f"
            },
            "timestamp": "2018-09-23T18:32:58.153z",
            "user": {
                "id": "tom@home.com"
            }
        }
    ]
}

import requests
import pandas as pd
from urllib.parse import urlparse
import json
from pandas.io.json import json_normalize

d1 = "https://nowebsite/v1/apps/11111111-2222-2222-2222-33333333333333/events/requests"

querystring = {"timespan":"P7D"}

headers = {
    'x-api-key': "xxxxxxxxxxxxxxxxxxxxxxxx",
    'Cache-Control': "no-cache",
    'Postman-Token': "xxxxxxxxxxxxxxxxxxxx"
    }

response = requests.request("GET", d1, headers=headers, params=querystring)

data = json.loads(response.text)

# delete crap out of API GET Request
for stuff in data['value']:
    del stuff['count']
    del stuff['customDimensions']
    del stuff['operation']
    del stuff['session']
    del stuff['cloud']
    del stuff['ai']
    del stuff['application']
    del stuff['client']
    del stuff['id']
    del stuff['type']
    del stuff['customMeasurements']
    del stuff['user']['authenticatedId']
    del stuff['user']['accountId']
    del stuff['request']['name']
    del stuff['request']['success']
    del stuff['request']['duration']
    del stuff['request']['performanceBucket']
    del stuff['request']['resultCode']
    del stuff['request']['source']
    del stuff['request']['id']

newstuff = json.dumps(data, indent=2, sort_keys=True)
#print(newstuff)
# Now it's in a cleaner format to work with
data2 = json.loads(newstuff)
json_normalize(data2['value'])

From here the data is in a pandas dataframe and looks like I want it to.
I just need to know how to use the furl to pull the limit and location out of the url on a per row basis and create a new column called load and limits as mentions above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: tail -f produces no output in Ubuntu live CD For some test I start Ubuntu Live from USB.
I'm trying to use tail command to show debug log, but it doesn't work.
I also test opening two terminals (t1, t2) with this code:
t1:
touch a

t2:
tail -f a

t1:
for i in `seq 1 10`; do echo $i >> a; sleep 1; done

Nothing in t2! What can be the cause?

A: If it's a case of tail not working at all, then it could be because your liveCD is using the overlayfs filesystem, which has a bug regarding notifications of modified files.  You could try to move the log to another filesystem, such as /tmp if the application creating the log has an option to do so.
You could also carry out your test in /tmp instead of your homedir.


text:
Q: Replacement for .Filtered in NEST 5.5.0 I'm trying to convert this block of code but can't find the correct definition to replace .Filtered accepting Action < FilteredQueryDescriptor< T >> selector.
I have upgraded to NEST version 5.5.0 and here's the block of code that I'm trying to convert to work using higher version of NEST:
        UserView defaultUserView = new UserView();

        SearchDescriptor<MyOrder> _searchDesc = new SearchDescriptor<MyOrder>();

        _searchDesc = _searchDesc
                .Index(MyIndex)
                .Type(MyType)
                .Query(mq => mq.Filtered(QueryDescriptor(defaultView)))
                .SearchType(SearchType.Count)

Here's the QueryDescriptor:
    private Func<SearchDescriptor<MyOrder>, SearchDescriptor<MyOrder>> QueryDescriptor(UserView userView)
    {
        Func<SearchDescriptor<MyOrder>, SearchDescriptor<MyOrder>> result;

        result = delegate(SearchDescriptor<MyOrder> descriptor)
        {
            descriptor.Query
            (
                query => query.MatchAll()
            )
            .Query(f => f.Bool(CommonHelper.GetFilters(userView)));
            return descriptor;
        };

        return result;
    }

EDITED:Here's the CommonHelper.GetFilters(userView):
 public static class CommonHelper
 {
    public static Func<BoolQueryDescriptor<MyOrder>, BoolQueryDescriptor<MyOrder>> GetFilters(UserView userView)
    {
       Func<BoolQueryDescriptor<MyOrder>, BoolQueryDescriptor<MyOrder>>
       result= delegate (BoolQueryDescriptor<MyOrder> descriptor)
         {
             switch (userView.UserView)
             {
                  case UserView.1:
                       descriptor.Must(OldDefaultFilter());
                       break;
                  case UserView.2:
                       descriptor.Must(OldDefaultFilter())
                              .MustNot(MustNotDefaultFilter());
                       break;
             }
             return descriptor;
          };
        return result;

}
   }

A: FilteredQueryDescriptor<T> was deprecated in NEST 2.x and removed in NEST 5.x, in line with the change in Elasticsearch in the respective major versions.
Moving forward, use a bool query instead with a must clause for the query and a filter clause for the filter.


text:
Q: sort data in ascending order by the sum of the columns I have a dataframe that looks similar to this:
v1 v2 v3 v4 v5 v6
.. .. .. .. .. ..
.. .. .. .. .. ..

With 100 rows. I want to sort my data into ascending order by the sum of individuals in col v5 and v6.
I have tried using this code but to no avail:
datatestt <- rowSums(df(V5, V6))

The code above gives me an error, how-else can I sort my data?

A: If we want to order based on the rowSums of subset of columns, subset the columns df[c("v5", "v6")], apply rowSums and order the vector to create an index ('i1') which can used in i for ordering the rows
i1 <- order(rowSums(df[c("v5", "v6")]))
dfnew <- df[i1, ]

Or using tidyverse
library(dplyr)
library(purrr)
df %>%
    arrange(select(., v5, v6) %>%
                 reduce(`+`))

data
set.seed(24)
df <- as.data.frame(matrix(sample(1:20, 6 * 10, replace = TRUE),
      ncol = 6, dimnames = list(NULL, paste0("v", 1:6))))


text:
Q: cordova notification.alert listen to button click I need to run a function when the user clicks on the button on the alert window. Problem I'm having is that using navigator.notification.alert actually runs the call back function as soon as the alert box opens. I also tried.
 navigator.notification.confirm(

but this has the same behavior. The closest I have gotten to running a function just when the user clicks on the button on the pop up window is using notification.prompt.
However this forces an input box on the alert window. Very annoying. So is there any way of doing what I need to do? All I want to do is run a function only after the user has click one of the buttons on the alert box.
There has got to be a work around for this. Can someone give me a tip.
Thanks!

A: warning and perhaps  quite noticeable to other people.
 in the call back function you cannot pass parameters otherwise you will call the callback function immediately i feel like a big idiot.
look below if you do stopfunction(); as supposed to stopfunction you will end up calling the callback function immediately and chase your own tale. Hopefully this helps someone else who might run into this problem. The key hear is that "()"makes an anonymous function in Java script and immediately runs the function.
navigator.notification.confirm(
     'you are aproaching your desired location', // message
      stopFunction,  // callback to invoke with index of button pressed
      'Alarm',      // title
      ['Dismissed']    // buttonLabels
       );


text:
Q: Trying to store an equation into a variable I am trying to figure out how to store the calculated gross pay into the grossPay variable to use it for calculating net pay. Throws me off when using a struct.
#include<string>
#include <iostream>
using namespace std;

struct Workers {
    string name;
    double hourlyWage;
    int hoursWorkedPerDay;
    int hoursWorkedPerWeek;

};
int healthTax = 130;
double otherTaxes = 0.17;
double grossPay;

int main() {
    Workers JohnDoe;
    JohnDoe.name = "John Doe";
    JohnDoe.hourlyWage = 8.50;
    JohnDoe.hoursWorkedPerDay = 6;
    cout<<"- John Doe's weekly earnings - "<< endl;
    cout<<"Hourly rate: $8.50" << endl;
    cout<<"Hours worked per day: 6" << endl;
    cout<<"Gross pay: $" << 7 * (JohnDoe.hourlyWage * JohnDoe.hoursWorkedPerDay)<<endl; // gross pay
    grossPay; // how to store gross pay into this variable?
    cout<<"Net pay: $" << otherTaxes * (grossPay - healthTax) / 100; // net pay
}

A: I think you may not be understanding how variables work. You don't store the formula, you store the result of calculating the formula:
     double grossPay =  7 * (JohnDoe.hourlyWage * JohnDoe.hoursWorkedPerDay);

A: Other answers are right, but a slightly better solution would be a function wich takes a Worker reference as parameter and returns the result:
double getGrossPay(const Workers& worker) {
        return 7 * (worker.hourlyWage * worker.hoursWorkedPerDay);
}

Then simply:
cout<<"Gross pay: $" << getGrossPay(JohnDoe) <<endl; // gross pay

A: This is what you hae to do :
double grossPay =  7 * ( JohnDoe.hourlyWage * JohnDoe.hoursWorkedPerDay );

Then you can use it, in this case, print it :
cout<<"Gross pay: $" << grossPay <<endl;


text:
Q: Approximation of ln(x) in the vicinity of x=0 I would like to find approximative (polynomial) expression for $x^2 ln(x)$ in the vicinity of x=0, but any expansion (e.g. the last row of the first table on http://math2.org/math/expansion/log.htm) seems to diverge. On the other hand, the x->0 limit of the above expression, by using the L'Hopital's Rule, is 0. Does anyone has any idea how to get the approximative expression?
The reason why I am looking for an approximation is because I want to find the simplest possible expression, i.e., dependence on x. The full expression reads $\frac{1 -x^2 ln(2/x)}{1+x^2}$, and by plotting it in the range (0.1,0.7), I found (fit, or Mean Value Theorem, but not analytically) that sufficiently good approximation (within few percent) is $1-x$. But, I also need the same expression to be valid for my entire $x$ range, from 0.02 up to 0.7.

A: Since $$\lim_{x\to 0} \, x\log(x)=\lim_{x\to 0} \, (x^x-1)$$ you could use,as an approximation,
$$x^2 \log(x) \sim x(x^x-1)$$
To give an idea, consider the norm
$$\Phi=\int_{0}^{\frac 1{10}}\Big[x^2 \log(x) -x(x^x-1)\Big]^2\,dx=1.14\times 10^{-7}$$
Edit
Graphically, for $0 \leq x \leq 1$
$$x^2 \log(x) \sim (x-1) x \sqrt x$$ So, consider the norm
$$\Phi(a)=\int_0^a \Big[x^2 \log(x) -k_a (x-1) x \sqrt x\Big]^2\,dx$$ which is explicit. Now, solve, for $k$,  $\Phi'(a)=0$. This gives
$$k_a=\frac{40 \sqrt{a} (-162 a+891 a \log (a)-1089 \log (a)+242)}{3267 \left(10 a^2-24a+15\right)}$$
If you want the best approximation for $a=\frac 1{100}$,
$$k_{\frac 1{100}}=\frac{40 (24038+216018 \log (10))}{48224187}\sim \frac{298}{689}$$ and
$$\Phi \left(\frac{1}{100}\right)=2.38 \times 10^{-12}$$
Update
We can do a bit better using the previous similarity
$$x^2 \log(x) \sim (x-1) x \sqrt x$$ and use as an approximation
$$x^2 \log(x) \sim \sum_{k=0}^p A_k^{(p)} x^{\frac{k+3}2}$$
This would give
$$ A_0^{(1)}=\frac{8}{81} \sqrt{a} \,(9 \log (a)-2)\implies \Phi \left(\frac{1}{100}\right)=2.27 \times 10^{-12}$$
$$ A_0^{(2)}=-\frac{8 \sqrt{a}}{5} \qquad  A_1^{(2)}=\log (a)+\frac{71}{45}\implies \Phi \left(\frac{1}{100}\right)=9.88 \times 10^{-15}$$

A: For some identities, it is fruitful to look at
log(x)x x
This is a simple example to apply the Taylor expansion. It is an example of the by far more general formulare:
$f(0)ln(x)+ln(x)f'(0)x+ln(x)/2f''(0)x^2+O(x^3)$
with
$f(x)=x^2$
In this example this is the identity to the third-order Taylor expansion is the same as the product function given up to the third-order correction term.
This result can be verified on the name computational knowledge engine from Wolfram. It is close to the Taylor expansion of function with the exponential function giving a similar polynomial for $f(x_0)$. Simply substitute $t=exp(x)$ to get the logarithm out of the expansion function product. It is then rather difficult to deal with the transformation of $0\rightarrow -\infty$. There is a complex function theory needed to prove a deal further with that. Put the expansion as given, known and valid maths is much easier to cope with.
This knowledge is astonishingly rare among Mathematicians. It is fairly common among Electronic Engineers in some of their disciplines. Despite it belong to complex function theory Taylor expansion methodology.
Hope the helped and kept the answer short enough. In short prove theory of informal extend the graphical match shall be prove enough, too enough since it is identic and therefore special.


text:
Q: Surjectivity of expanding map Suppose that $(X, d)$ is a compact metric space and that $f: X \rightarrow X$ is a continuous function satisfying $d(x,y) \leq d(f(x), f(y))$ for all $x, y \in X$. Show that $f(X) = X$.
Here is a cheap argument (for which I am not entirely confidence with): Since $X$ is a compact metric space and $f$ is continuous, $X \backslash f(X)$ is an open subset of $X$, which is either empty or non-empty. If empty then we are done. Otherwise it has a point $x_{0}$. Then there exists a $\delta >0$ such that a ball centered at $x_{0}$ of radius $\delta$ is contained in $X \backslash f(X)$. Pick a point $t$ in this ball.
Then by uniform continuity of $f$, we have for any $\epsilon >0$, $\epsilon > d(f(x_{0}), f(t)) \geq d(x_{0}, t)$ with the last inequality from the hypothesis. But then since $\epsilon$ is arbitrary, we have $x_{0} = t$ a contradiction since a ball must be open.

A: Let's continue your proof. Let $x_0$ as in your proof. Define the sequence  $x_n=f(x_{n-1})$. The following holds:
$$   d(x_{n+m},x_n) \ge d(x_{n+m-1},x_{n-1}) \ge .... \ge  d(x_m,x_0) > \delta $$
In particular, the sequence $x_n$ has no convergent subsequence. Contradiction because $X$ is compact.


text:
Q: Silverlight 4.0 in Visual Studio 2008? I've been trying to find official requirements for Silverlight 4.0, but can't seem to find anything.
What I want to know is if VS2008 supports Silverlight 4.0, or if I need to upgrade to VS2010.
The only mention I could find was on this Silverlight forum:
http://forums.silverlight.net/forums/p/156538/350841.aspx
Does anyone know of an official link?

A: I pretty sure you require Visual Studio 2010 to use Silverlight 4.  I was using 3 and had to install VS2010 to use Silverlight 4.  There are no SL4 tools in VS2008.
Notice no mention of VS2008: http://www.silverlight.net/getstarted/
Link to tools also with no mention or links to alternate downloads:
http://www.microsoft.com/downloads/details.aspx?familyid=68A158AF-9BB8-4855-A724-D09D196EAAF3&displaylang=en
On the Silverlight forums asking to build SL4 in VS2008:
http://forums.silverlight.net/forums/t/150762.aspx
Also, Microsoft I am sure wants to provide as many reasons as possible to get developers to upgrade to VS2010.  Silverlight 4 is one of them.

A: You can't use Silverlight 4 with Visual Studio 2008.
Silverlight.net only mentions Visual Studio 2010
As does the Silverlight page on microsoft.com.

A: Due to the fact that there was no support for SL4 in VS2008 whilst it was in beta, I don't think it will ever be available.


text:
Q: Pass a variable from class in another class in python How can I pass a variable from class in another class in python?
I'm a beginner, I just started learning python and tkinter.
Example:
File main.py:
if __name__ == "__main__":
    root = Tk()
    window = Articles(root)
    root.mainloop()

when run this code, articles.py work; Window it's open.
File articles.py
class Articles:
    def __init__(self, master)
    self.master = master
    #...
    #Here is many widgets. No matter, it's works. :)
    #....
    #When I want to double-click on one of the rows in the treeview, it should send me the <item>
    #variable in the ArticleInfo class and display it in a label when the popup window opens.

    mytree.bind('Double-1', self.get_article_id)

    def get_article_id(self):
        item = self.myTree.identify("item", event.x, event.y)

File article_info.py
class ArticleInfo:
    def __init__(self):
        t = Toplevel()
        myvar_from_articlesclass = ???
        Label(t, text=myvar_from_articlesclass).pack()

I tried many options from what I found on the net, but I was getting different errors.

A: In your case, you can pass the item variable from the Articles class to the ArticleInfo class by either of the following methods:
Method 1: Passing the variable as an argument to the constructor
In the get_article_id method of the Articles class, you can create an instance of the ArticleInfo class and pass the item variable as an argument to its constructor:
def get_article_id(self, event):
    item = self.myTree.identify("item", event.x, event.y)
    article_info = ArticleInfo(self.master, item)

In the ArticleInfo class, you can receive the item variable as an argument in the constructor and store it as an instance attribute:
class ArticleInfo:
    def __init__(self, master, item):
        t = Toplevel(master)
        self.item = item
        Label(t, text=self.item).pack()


text:
Q: Get title name of the column by RecRef RecRef is datatype of RecRef, and by this i access to table and can select the field of the table;
RecRef.OPEN(IDTABLE); RecRef.field(2); -> RETURN THE FIELD DATA OF THE IDTABLE.
but now i want to take; Title name of the column and number of columns, of the table
Thanks in advance,
EDIT
Is possible whit RecRef.FIELD(IndexVal).CAPTION

A: You need to use FieldRef to this
https://msdn.microsoft.com/en-us/library/dd301382.aspx


text:
Q: Manage aar dependencies in my aar We ship an aar to our customer(say A). Now our code uses a 3rd party AAR (say B). Now when we use this 3rd party AAR we add a compile dependency in our AAR's gradle.
compile 'B@aar'

The problem is that our customer wont have B.aar in their repo and we cant explicitly provide them a 3rd party AAR. How can I bundle B as a dependency in my aar?


text:
Q: How to write log data from a file to Splunk An application writes its logs into files which are saved e.g in /home/my-user/myapp/ directory.
I want to send the data (logs) from those files to Splunk.
I was thinking to use [inputs.file] or [inputs.tail] plugins in Telegraf.
In order to verify that it will work out,  I want to output data from a log file /home/myuser/myapp/connect.log1 to another file testoutput_log first.
The example log data is as follows:
[2022-09-02 20:06:30,199] INFO [sftp_source_bht_extract|task-0] No files matching [^\s]+(\.(?i)(csv))$ were found in /dci/BHT (io.confluent.connect.sftp.source.SftpFileDequeue:86)
[2022-09-02 20:06:30,446] INFO [mongo_sftp_source_billing_statement_history|task-0] File queue out of files, searching for new file(s) in /dci/genius/out (io.confluent.connect.sftp.source.SftpFileDequeue:66)
[2022-09-02 20:06:30,449] INFO [sftp_source_bht_extract|task-0] File queue out of files, searching for new file(s) in /dci/BHT (io.confluent.connect.sftp.source.SftpFileDequeue:66)

Here is the part of Telegraf config covering the use case described above:
[[inputs.file]]
  files = ["/home/my-user/myapp/connect.log.1"]
  data_format = "grok"
  grok_patterns = ["%{GREEDYDATA}"]

[[outputs.file]]
    files = ["stdout","/tmp/testoutput_log"]
    data_format = "influx"

But the output file remains empty. Also tried with various output data formats - no success.
What am I doing wrong?

A: Per the docs, you need to define at least one field when using the grok parser.
When using the influx data format a metric requires a field to be valid, hence this requirement.


text:
Q: GAE: port_sqlite fails on local dev server On my OS X local dev server, when I try to port an existing datastore to sqllite using port_sqlite (in combination wit use_sqlite), I get this error:

google.appengine.runtime.apiproxy_errors.ApplicationError:
  ApplicationError: 3 Data in
  /Users//Documents/workspace-data/datastore/.datastore is corrupt or a
  different version. Try running with the --clear_datastore flag.
DatabaseError('file is encrypted or is not a database',)

The datastore works fine in the regular non-sqlite way.
What do I do? Thanks.

A: The clear datastore works in some cases.
I found that removing the --logs_path argument or replacing it with a new file also may help
--logs_path=/pathtologs/newfile.log
The devserver writes to the log file with logging.info(). The log entries are stored in a sqllite3 database. It is getting corrupted.

A: The issue I had was on the old dev server. It works properly now on the new dev server.


text:
Q: connect to siebel client with local ip address I have installed siebel client and tools on my Virtual Machine.
I can access the siebel web client using http://localhost/start.swe?
My goal is to connect to Siebel web client on Virtual Machine from my local machine.
why cant i acces the client using my VM local ip address like http://10.0.x.x./start.swe?
Please let me know what i am missing.?
I havent install Siebel Enterprise server and Siebel Web Server Extension.
Do i need that ??

A: There are a few things you would need to check such as firewall, NAT and port forwarding settings.
This link walks you thru an example.
Hope this helps


text:
Q: The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, ListViewFragment) I have error in listfragment "The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, ListFragment)" what should i do? cause i can't appear my fragment.
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

private FadingActionBarHelper mFadingActionBarHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mFadingActionBarHelper = new FadingActionBarHelper(getActionBar(),
            getResources().getDrawable(R.drawable.actionbar_bg));

    if (savedInstanceState == null) {
         getFragmentManager().beginTransaction()
                .add(R.id.container, new ListViewFragment())
                .commit();

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    }
    return super.onOptionsItemSelected(item);
}

public FadingActionBarHelper getFadingActionBarHelper() {
    return mFadingActionBarHelper;
}

}

The problem is that the FragmentTransaction 's .add(int, Fragment) method accept arguments with the second one of type Fragment, however, I have ListFragment which is not acceptable by this method.
So, how to add ListFragment with FragmentTransaction ?
Here ListView Fragement class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.TabPageIndicator;

public class ListViewFragment extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Recent", "Artists",
        "Albums", "Songs", "Playlists", "Genres", "Hello", "Hii" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_listview);

    FragmentPagerAdapter adapter = new GoogleMusicAdapter(
            getSupportFragmentManager());

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
    indicator.setViewPager(pager);
}

class GoogleMusicAdapter extends FragmentPagerAdapter {
    public GoogleMusicAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return CONTENT[position % CONTENT.length].toUpperCase();
    }

    @Override
    public int getCount() {
        return CONTENT.length;

    }
}

A: Maybe I am wrong but without your ListViewFragment code I will assume that some of these are the problem you are finding.

*

*(Not very likely) Your ListViewFragment is not a subclass of Fragment (or ListFragment).

*Your ListViewFragment is a subclass of android.support.v4.app.Fragment (check your imports)  instead of being a subclass of android.app.Fragment. If this is the case you have 2 possibilities.
2.1 Change your import to android.app.Fragment
2.2 Make your Activity a subclass of FragmentActivity and use getSupportFragmentManager() instead of getFragmentManager().
If neither of these are your problem, please post your ListViewFragment class.
Hope it helps :)


text:
Q: convert pair(1L,2L) to pair(1,2) my problem is i'm trying to get pairs by this code:
    for (i in 1:4)
    {
    for (j in 1:4)
    {
    print(pair(i,j))
    }
    }
my expected result to be (1,1),(1,2).... not (1L,1L),(1L,2L)

A: -- answer to question before edit --
I'm assuming you mean pairlist and not pair.
If so you can do the following:
v <- list(pairlist(1,2),pairlist(3,4))

if (any(sapply(v,identical,pairlist(1,2))))
  print(1)
# [1] 1

if (any(sapply(v,identical,pairlist(2,2))))
  print(1)
# *nothing happens*


text:
Q: What is the meaning of this line? "Memory-mapped, cached view of external QSPI flash. The cache is specified as 32 KB with 4-way associativity."
Memory-mapped, cached view of external QSPI flash. The cache is specified as 32 KB with
  4-way associativity.

Does it mean that my external QSPI Flash is only 32Kb or it has been memory mapped onto 32Kb?
Does cached view mean that repeated read will get the data cached within the processor and not actually access the memory?

A: The sentence is pretty clear:

The cache is specified as 32 KB with 4-way associativity.

So,

Does it mean that my external QSPI Flash is only 32Kb or it has been memory mapped onto 32Kb?

Neither. The cache is 32 kB (not Kb, which is Kelvinbit! Watch your capitalization!).

Does cached view mean that repeated read will get the data cached within the processor and not actually access the memory?

Well, see wikipedia on caches. Yes, a repeated read within the cached regions will fetch the information from the cache. That's what a cache does.
No, that cache is not necessarily part of the processor, but of the flash controller peripheral.

A: The confusion probably comes from the formulation: "memory-mapped, cached view" The fact it is memory-mapped has nothing to do with the fact it is cached. The size of the memory mapping is independant of the size of the cache.
So, I'll break it down for you:

Memory-mapped

Means you can access the contents of the external memory directly by reading/writing the main memory address space (at some specified address). Also typically imply that, if the external memory contains executable code, you can execute this code simply by branching: you don't need to copy the code in internal memory before branching. This is achieved by the MCU which, internally, translates any access to this part of the memory into the required QSPI commands to read the external flash on the fly. At this point, it does not imply that there is a cache.

Cached

Means that data read from this part of the memory will be placed in a smaller-sized, intermediate memory area (not accessible directly), which the MCU will lookup first when the the external memory will have to be accessed again. This way, when the same data is accessed twice, the external memory does not need to be accessed again. The data from the cache will be retrieved, which is much faster.
Indeed, this is very useful for memory-mapped QSPI. The QSPI interface is much slower than the CPU: any read/write operation has to be translated into commands sent serially on a few signal lines, which adds a lot of overhead. To reduce this overhead, you'll typically try to read multiple bytes for each QSPI access, and store them in a cache so that, if the next read addresses the neighboring byte (which is likely), you have it ready.

32kB

Here, this is the size of the cache, not the size of the memory map. The size of the memory-map will typically be big enough for the whole size of the external memory (check the detailed specs).

4-way associativity

This is the way the cache is internally organized. The cache is much smaller than the external memory. The naive way to implement a cache would be to store all the recently accessed bytes along with their corresponding addresses, and, when subsequent accesses are made, check in the whole cache if an existing byte has its address corresponding to the accessed address. This is extremely inefficient. For each byte, you would have to store the address, which multiplies by five the required size for the cache (assuming 32-bit addresses: for each byte, you need the data byte value plus four bytes for the corresponding address), and, for each access, you need to compare the address against 32768 possible values to check if it is already in the cache or not.
So, here is how it is done:

*

*First, the cache is organized in lines of N bytes (e.g. 16 or 32 bytes - Note that the cache line size is not specified in your case). You store the addresses for the whole cache lines, not for each byte, which saves a lot of space.

*Then, not all possible addresses can be stored anywhere in the cache. When accessing the cache, you take a part of the address, and this will give you the index of a "cache set". Each cache set can contain 4 cache lines (in your case). When checking if the data is in the cache, this means that you only have these 4 cache lines addresses to check because you know that, if it is there, it will necessarily be in this set. This will reduce the complexity of the cache structure a great deal, at the expense of less flexibility in storing the data (meaning a possibly lower cache hit rate, depending on the memory access patterns).

This is what the cache associativity is: The number of cache lines per set. This gives an indication of the likeliness you can retrieve data in the cache if it has been read before. The bigger the associativity, the better, but it makes the cache more complex and more expensive to manufacture. And at some point, the benefits are not even worth it. 4 is not bad (which is why they are proud to advertise it).


text:
Q: Bootstrap centering item in navbar when other items are right-aligned I'm currently making a webpage and am using a navbar using Bootstrap. I have three icons aligned on the right, and I want to align another item in the center. However, using mx-auto doesn't center it in the middle of the webpage and shifts it left a little bit because of the icons on the right. The code is below:

        colordle

        <button class="icons settings-icon"></button>
        <button class="icons leaderboard-icon"></button>
        <button class="icons question-icon"></button>

How can I center one element even with elements aligned on the right?

A: Here you go... I've added more icons to show you that the snippet is working. Remove them in your actual project.

.rainbow {
  color: blue !important;
  text-decoration: underline !important;
}
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />

        colordle
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".dual-collapse2">

          </button>

          <button class="icons settings-icon">

            </button>
          <button class="icons leaderboard-icon">

            </button>
          <button class="icons question-icon">

            </button>
          <button class="icons settings-icon">

            </button>
          <button class="icons leaderboard-icon">

            </button>
          <button class="icons question-icon">

            </button>
          <button class="icons settings-icon">

            </button>
          <button class="icons leaderboard-icon">

            </button>
          <button class="icons question-icon">

            </button>


text:
Q: How to implement thread in succession I would like to implement a transfer with socket for transfering pictures and check on the server if the picture is ever loaded and if it is true not transfering the picture simply change the imageView.
I have a client and a server which work for simply transfer picture between 2 devices. But i want to send a hash of each pictures once at each time before send them. My dificulty is primarily on the thread manager, i have implement a listener for the 1st thread (send / receive picture's hash on client / server) to know when it's finished and then start the second thread (send / receive pictures on client / server). But i don't know if my methodology is ok because it doesn't work well (the server receive the hash on the start but not the other).
I hope that i am clear, here is my parts of code concerned, thanks to someone who can give me a solution.
Server
private class ReceiverHash extends Thread {
    private List<TaskListener> listeners = new ArrayList<TaskListener>();

    public void addListener(TaskListener listener) {
        listeners.add(listener);
    }

    void getTaskState(Boolean state) {
        for (TaskListener listener : listeners) {
            listener.getTaskState(state);
        }
    }

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(socketServerPORT);

            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

            while (true) {
                String str = br.readLine();          // lecture du message
                if (str.equals("END")) {
                    serverSocket.close();
                    getTaskState(true);
                    break;
                }
                hashList.add(str);
                Log.d("HASH_RECEIVER_LOG", str);   // Log debug hash
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private class Receiver extends Thread {

    int pos = 0;
    int cmpt = 0;

    @Override
    public void run() {
        // create ServerSocket using specified port
        try {
            ServerSocket serverSocket = new ServerSocket(socketServerPORT);
            while (true) {

                //checkFileExist();
                File f = new File(getFilesDir(), "img" + Integer.toString(pos) + ".png");
                fileList.add(f);
                Log.d("HASH_RECEIVER_LOG", "Attente d'une réponse du client");
                Socket socket = serverSocket.accept();
                Log.d("HASH_RECEIVER_LOG", "Reception d'une réponse");
                f.createNewFile();

                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = new FileOutputStream(f);

                byte[] bytes = new byte[2 * 1024];
                int count;

                while ((count = inputStream.read(bytes)) > 0) {
                        Log.d("RECEIVER_CMPT", Integer.toString(cmpt));
                        outputStream.write(bytes, 0, count);
                        cmpt = cmpt + count;
                }
                myBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imgDiapo.setImageBitmap(myBitmap);
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How i use listener on the activity :
ReceiverHash receiverHash = new ReceiverHash();
    receiverHash.start();
    receiverHash.addListener(this);

Client
public class Sender extends AsyncTask<Void, Void, Void> {
private String dstAddress;
private int dstPort;
private String fPath;

public Sender(String address, int port, String path) {
    dstAddress = address;
    dstPort = port;
    fPath = path;

}

@Override
protected Void doInBackground(Void... arg0) {

    Socket socket = null;
    try {
        socket = new Socket(dstAddress, dstPort);

        FileInputStream inputStreamSend = new FileInputStream(fPath);
        OutputStream outputStreamSend = socket.getOutputStream();
        byte[] buffer = new byte[2 * 1024];
        int count;
        while ((count = inputStreamSend.read(buffer)) > 0) {
            outputStreamSend.write(buffer, 0, count);
        }
        outputStreamSend.close();
        inputStreamSend.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

public class HashSender extends AsyncTask<Void, Void, Void>  {
private String dstAddress;
private int dstPort;
String hash;
//private ArrayList <String> listHash;
private List<TaskListener> listeners = new ArrayList<TaskListener>();

public HashSender(String address, int port, String path) throws IOException, NoSuchAlgorithmException {
    dstAddress = address;
    dstPort = port;
    hash = sha1(new File(path)); //methode encryption in sha1
}

public void addListener(TaskListener listener) {
    listeners.add(listener);
}
void getTaskState(Boolean state) {
    for (TaskListener listener : listeners) {
        listener.getTaskState(state);
    }
}

@Override
protected void onPostExecute(Void v) {
    getTaskState(true);
}

@Override
protected Void doInBackground(Void... arg0) {

    Socket socket = null;

    try {
        socket = new Socket(dstAddress, dstPort);

        OutputStream outputStreamSend = socket.getOutputStream();
        BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(outputStreamSend));
        buf.write(hash);
        buf.newLine();
        buf.flush();
        Log.d("toto", hash);
        buf.write("END");
        buf.newLine();
        buf.flush();
        outputStreamSend.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

How i use listener on the activity :
HashSender hashSender = new HashSender(dstAddress.get(i), dstPort, selectedItemPath.get(pos));
                    hashSender.addListener(ControlsActivity.this);
                    hashSender.execute();


text:
Q: Node express session variables different browsers the same result - why? I am writing chat program and don't know how to store names of the users. When I store it in to session.name it has the same value in every browser I run. Is it possible to do that without using database ?
This is how I do it:
 var MemoryStore = express.session.MemoryStore,
 sessionStore = new MemoryStore();

and then I just store value:
 sessionStore.nickname=nickname

now I run browser fill nickname and send it to server. Then open another browser and it already has that value - - I need different values for each of them.

A: I'm uncertain from the question (even the edited version) if you're modifying the sessionStore or the session. The above code indicates you're modifying the sessionStore, which should be the same for all requests. To add values to an individual session, assuming you are also using Express, you need to modify the HTTP request's session variable. In Express 2.x this is done with request.session.nickname = nickname;.


text:
Q: Quantifying change in a graph I need to a way to express a change in the structure of a given graph G, such that the original graph is G and the changed graph is G'. A change in the graph can be the addition or removal of any number of vertices and/or edges.
Currently, my thought is to express the change as two percentages: the number of vertices in G' as a percentage of the number of vertices in G, and the same for edges. However, it occurs to me that removing a vertex also means removing all edges connected to it.
Are there any standard ways of quantifying the change in a graphs structure?

A: If you only allow addition or deletion of edges, then there is a way of measuring how "far apart" two graphs are.  If $G$ and $G'$ are two graphs on the same vertex set, the edit distance between $G$ and $G'$ is the smallest number of edges of $G$ that must be deleted and non-edges of $G$ that must be added in order to transform $G$ into $G'$.  In symbols,
$$d(G, G') = \lvert E(G) \triangle E(G') \rvert,$$
where $A \triangle B$ denotes the symmetric difference of $A$ and $B$.
Edit distance was introduced by Axenovich, Kezdy, and Martin in this paper.

A: This paper describes a metric based on maximal common subgraphs, which the authors claim is superior to the edit distance in some applications.


text:
Q: React native react-native-google-places-autocomplete VirtualizedLists warning I created a form in which I have a field called address. Where I implemented 'react-native-google-places-autocomplete' plugin. It's working fine if I don't add scrollView. But I need to add scrollView just because I have so many input fields inside that form. but then I got a warning "VirtualizedLists should never be nested inside plain ScrollViews with the same orientation".
Here is my code:
Add.js
<SafeAreaView style={{ flex: 1, paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0, backgroundColor: 'white' }}>
    <View style={{ flex: 1 }}>
        <ScrollView scrollEventThrottle={16}>
            <View style={{ flex: 1 }}>
                <Text style={{ fontSize: 20, marginTop: 5, marginBottom: 10, paddingHorizontal: 15, fontFamily: 'Mulish-SemiBold' }}>Add Ground</Text>

                <TouchableWithoutFeedback style={styles.button} onPress={(e) => this.chooseFile()}>
                    <Image source={this.state.avatarSource ? this.state.avatarSource : require('./../../assets/images/default-cover.jpg')} style={{ width: '100%', height: 150 }} />
                </TouchableWithoutFeedback>

                <View style={styles.inputWrapper}>
                    <Text style={styles.inputLabel}>Name</Text>
                    <TextInput
                        style={styles.input}
                        placeholder="e.g Drealit Stadium"
                        onChangeText={name => this.setState({ name })}
                        value={this.state.name}
                        autoCorrect={false}
                    />
                </View>

                <View style={styles.inputWrapper}>
                    <Text style={styles.inputLabel}>Address</Text>
                    {/*
                        onChangeText={address => this.setState({ address })}
                        value={this.state.address}
                    */}
                    <ScrollView>
                        <GooglePlacesInput />
                    </ScrollView>
                </View>

                <View style={styles.inputWrapper}>
                    <Text style={styles.inputLabel}>Contact Person Name</Text>
                    <TextInput
                        style={styles.input}
                        placeholder="e.g David Johnson"
                        onChangeText={organizer_name => this.setState({ organizer_name })}
                        value={this.state.organizer_name}
                        autoCorrect={false}
                    />
                </View>

                <View style={styles.inputWrapper}>
                    <Text style={styles.inputLabel}>Contact Person Number</Text>
                    <TextInputMask
                        type={'cel-phone'}
                        options={{
                            maskType: 'INTERNATIONAL',
                        }}
                        placeholder="e.g 509-962-9014"
                        style={styles.input}
                        value={this.state.organizer_number}
                        onChangeText={organizer_number => this.setState({ organizer_number })}
                    />
                </View>

                <View style={styles.inputWrapper}>
                    <Text style={styles.inputLabel}>Description</Text>
                    <TextInput
                        placeholder="e.g A Ground suitable for small side cricket tournament. Ideal for some fast paced cricket and lot of fun."
                        onChangeText={description => this.setState({ description })}
                        value={this.state.description}
                        autoCorrect={false}
                        multiline={true}
                        numberOfLines={4}
                        style={[styles.input, { height: 'auto', textAlignVertical: 'top' }]}
                    />
                </View>

                <View style={styles.inputWrapper}>
                    <Text style={styles.inputLabel}>Rate per hour / day</Text>
                    <TextInput
                        style={styles.input}
                        placeholder="e.g 3500"
                        keyboardType="numeric"
                        onChangeText={ratePerHourDay => this.setState({ ratePerHourDay })}
                        value={this.state.ratePerHourDay}
                        autoCorrect={false}
                    />
                </View>

                <View style={styles.inputWrapper}>
                    <Text style={styles.inputLabel}>Rate per hour / night</Text>
                    <TextInput
                        style={styles.input}
                        placeholder="e.g 4500"
                        keyboardType="numeric"
                        onChangeText={ratePerHourNight => this.setState({ ratePerHourNight })}
                        value={this.state.ratePerHourNight}
                        autoCorrect={false}
                    />
                </View>

                <View style={{ marginHorizontal: 15, marginVertical: 10 }}>
                    <TouchableWithoutFeedback style={styles.button} onPress={(e) => this.manageAddGround(e)}>
                        <LinearGradient
                            colors={["#4678f6", "#4475ee", "#5053eb"]}
                            start={{ x: 0, y: 0 }}
                            end={{ x: 0, y: 0 }}
                            locations={[0, 0.5, 0.6]}
                            style={styles.appButtonContainer}
                        >
                            <Text style={styles.buttonText}>Save</Text>
                        </LinearGradient>
                    </TouchableWithoutFeedback>
                </View>
            </View>
        </ScrollView>
    </View>
</SafeAreaView>

GooglePlacesInput.js
<View style={{ flex: 1 }}>
    <GooglePlacesAutocomplete
        placeholder='e.g 640 Cross Creek Dr, Ellensburg, WA, 98926'
        query={{
            key: GOOGLE_PLACES_API_KEY,
            language: 'en',
        }}
        enablePoweredByContainer={false}
        onPress={(data, details = null) => {
            console.log("GooglePlacesInput -> data", data)
        }}
        debounce={200}
        styles={{
            textInputContainer: {
                backgroundColor: '#fff',
                borderTopWidth: 0,
                borderBottomWidth: 0,
            },
            textInput: {
                marginLeft: 0,
                marginRight: 0,
                height: 40,
                borderBottomWidth: 1,
                color: '#000',
                borderBottomColor: '#dedede'
            },
            predefinedPlacesDescription: {
                color: '#1faadb',
            },
            listView: {
                backgroundColor: '#fff',
                borderWidth: 0.5,
                borderColor: '#dedede',
                shadowColor: '#000',
                shadowOffset: {
                    width: 0,
                    height: 6,
                },
                shadowOpacity: 0.05,
                shadowRadius: 10,
                elevation: 4
            }
        }}
    />
</View>

A: You are receiving this warning because react-native-google-places-autocomplete renders a  component to show results, and you have  wrapped in a .
It's a warning, not an error. If it works for you can leave it as is.


text:
Q: subscribe to websocket subject create multiple connections Sharing a websocket connection among multiple components duplicates the connection.
export class NotificationService {
  notification;
  destroy$ = new Subject();
  constructor(private appService: AppService) {}
  createWs() {
      this.notification = this.appService
        .getTicket()
        .pipe(
          mergeMap(data =>
            webSocket(`wss://echo.websocket.org/`).pipe(
              takeUntil(this.destroy$)
            )
          )
        )
        .pipe(
          catchError(e => {
            return throwError(e);
          }),
          retryWhen(errors =>
            errors.pipe(
              concatMap((_, iteration) => timer(Math.pow(2, iteration) * 1000)),
              take(10)
            )
          )
        );
  }

  filterNotification() {
    if (!this.notification) {
      this.createWs();
    }
    return this.notification;
  }
}

Calling this.notificationService.filterNotification() in various components create multiples websocket connections. Per documentation here,

When WebSocketSubject is subscribed, it attempts to make a socket connection, unless there is one made already. This means that many subscribers will always listen on the same socket, thus saving resources. If however, two instances are made of WebSocketSubject, even if these two were provided with the same url, they will attempt to make separate connections

A new instance is not created, but the subscription duplicates the connection.
stackblitz

A: The mergeMap was triggering a new websocket instance for each subscription leading to the duplication. By keeping a reference to the inner observable, the later is returned instead of opening a new websocket
this.notification = this.appService
        .getTicket()
        .pipe(
          mergeMap(data =>
            this.ws ? this.ws : this.ws = webSocket(`wss://echo.websocket.org/`).pipe(
              takeUntil(this.destroy$)
            )
          )
        )


text:
Q: Exclude category from main RSS feed, but not all feeds I've got a blog that supplies content to multiple MailChimp newsletters via RSS. The first newsletter works fine, but the second I'm having issues with. The issue I have is that the second newsletter has "hidden" content. This content isn't meant for wide consumption, so it doesn't appear on the frontpage, but is accessible elsewhere on the site. The snafu with this is that not all of this content is hidden, just some of it, while other pieces of content for this newsletter could overlap with the first newsletter. This obviously makes excluding everything problematic, as they could be assigned multiple categories, some of which I wouldn't want hidden.
The issue I'm running into is that I have a way to exclude this content from the frontpage, but not from the main RSS feed. I'm using WP Hide Post for this, which allows me to exclude from feed, which in turn removes it from all feeds, including the ones that feed the newsletter. I'm currently using /feed?cat=XXX to reference these feeds. Is there a way to make it so category feeds still work, just the main /feed RSS would exclude it?

A: Thank you! This worked perfectly to exclude a category from the main rss feed but still include it in the category rss feed.
However, there was a small syntax error in the code that crashed my site when I inserted it into the functions.php. It was missing the opening '{' bracket for the if statement. Here is the corrected code:
add_action('pre_get_posts', 'exclude_category' );
function exclude_category( &$wp_query )
    // Exclude from loop, archive and feed but not from category page/feed
   { if( is_home() || ( is_feed() && !is_category() ) || ( is_archive() && !is_category() )) { // Exclude from home, feed, but not from category page/feed
        set_query_var('category__not_in', array(120)); // Exclude category with ID 120
    }
}

And of course, remember to change the '120' to your category id.
Thank you again. This was so helpful!

A: I'm not sure if you want this. I guessed you want to exclude one or more categories from your rss feed and to do it you can add this code snippet in your functions.php
function myFeedExcluder($query) {
    if ($query->is_feed) {
       $query->set('cat','-10'); // excludes category with id 10
    }                            // for multiple you can use '-10,-20,-30′
    return $query;
}
add_filter('pre_get_posts','myFeedExcluder');

Also you can use in the link directly like
<a href="<?php bloginfo('url'); ?>/feed?cat=-10&cat=-20">Entries (RSS)
<a href="<?php bloginfo('url'); ?>/feed=rss2&cat=-10,-20">Entries (RSS)

You can also check this plugin to exclude some posts from feed but I didn't test it and here is another article about excluding categories from RSS Feed And More.

A: I ended up having to rethink this problem from another angle. Instead of being able to exclude posts from the main feed, I had to create unique feeds for each of my categories. This made it so these feeds were independent of the main feed and wouldn't be affected by the WP Hide Posts plugin.
What I did was drop this file into my theme folder, then create blank pages with this template assigned to it. At the top I have it handling each page I created and assigning it to the corresponding category.
<?php
/*
Template Name: Custom feeds
*/
$numposts = 10; // number of posts in feed

if ( is_page( 'custom-feed-1' )) {
    $posts = query_posts('showposts='.$numposts.'&cat=1');
} elseif ( is_page( 'custom-feed-2' )) {
    $posts = query_posts('showposts='.$numposts.'&cat=2');
} elseif ( is_page( 'custom-feed-3' )) {
    $posts = query_posts('showposts='.$numposts.'&cat=3');
}

$more = 1;

header('Content-Type: '.feed_content_type('rss-http').'; charset='.get_option('blog_charset'), true);
echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>';
?>

<rss version="2.0"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:wfw="http://wellformedweb.org/CommentAPI/"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
  xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  xmlns:media="http://search.yahoo.com/mrss/">

<channel>
  <title><?php bloginfo_rss('name'); wp_title_rss(); ?> - Article Feed</title>
  <atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" />
  <link><?php bloginfo_rss('url') ?></link>
  <description><?php bloginfo_rss("description") ?></description>
  <lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate>
  <?php the_generator( 'rss2' ); ?>
  <language>en-US</language>
  <sy:updatePeriod><?php echo apply_filters( 'rss_update_period', 'hourly' ); ?></sy:updatePeriod>
  <sy:updateFrequency><?php echo apply_filters( 'rss_update_frequency', '1' ); ?></sy:updateFrequency>
  <?php do_action('rss2_head'); ?>
  <?php while( have_posts()) : the_post(); ?>

  <item>
    <title><?php the_title_rss(); ?></title>
    <link><?php the_permalink_rss(); ?></link>
    <comments><?php comments_link(); ?></comments>
    <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate>
    <dc:creator><?php the_author(); ?></dc:creator>
<?php the_category_rss(); ?>
    <guid isPermaLink="false"><?php the_guid(); ?></guid>
<?php if (get_option('rss_use_excerpt')) : ?>
    <description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
<?php else : ?>
    <description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
  <?php if ( strlen( $post->post_content ) > 0 ) : ?>
    <content:encoded><![CDATA[<?php the_content() ?>]]></content:encoded>
  <?php else : ?>
    <content:encoded><![CDATA[<?php the_excerpt_rss() ?>]]></content:encoded>
  <?php endif; ?>
<?php endif; ?>

<?php do_action('rss2_item'); ?>

  </item>
  <?php endwhile; ?>

</channel>
</rss>

Also I don't wish to lay claim to this template, I found it online awhile back and modified it a bit, I just can't remember where I came across it.

A: add_action('pre_get_posts', 'exclude_category' );
function exclude_category( &$wp_query )
    // Exclude from loop, archive and feed but not from category page/feed
   if( is_home() || ( is_feed() && !is_category() ) || ( is_archive() && !is_category() )) { // Exclude from home, feed, but not from category page/feed
        set_query_var('category__not_in', array(120)); // Exclude category with ID 120
    }
}


text:
Q: How to drag and pan on a large image after input range zoom? So I have a large map file (just a big image) that displays at 100% on page load, then I have range slider to zoom in and out which I have working correctly. However, I'm not sure how to add panning (click and drag with mouse) after the image is zoomed in on. How do I add panning to the image after the user zooms in? If possible, would also be nice to be able to use the left mouse button OR click and hold the scroll wheel to drag.
I did some searching but I didn't find an example that used it with a range slider or it had jQuery. I'd like to just use vanilla JS.
css
        #map {
            cursor: grab;
            width: 100%;
            min-width: 100%;
            max-width: 8500px;
        }

        #map-slider-div {
            position: fixed;
            bottom: 15px;
            width: 100%;
            text-align: center;
        }

        #map-div {
            text-align: center;
        }

html

        <input id="map-slider" type="range" min="300" max="8500" value="300">

JS
    const init = () => {
        let mapSlider = document.querySelector('#map-slider');
        mapSlider.addEventListener('change', zoomMap);
    }

    const zoomMap = () => {
        let map = document.querySelector('#map');
        let mapSliderVal = document.querySelector('#map-slider').value;
        map.style.width = mapSliderVal + 'px';
    }

    window.onload = init;

Thanks!

A: Ok kind of got it working to how I want, New init method:
    const init = () => {

        let mapSlider = document.querySelector('#map-slider');
        mapSlider.addEventListener('change', zoomMap);

        let map = document.querySelector('#map');
        let mapDiv = document.querySelector('#map-div');
        map.addEventListener('mousedown', start_drag);
        mapDiv.addEventListener('mousemove', while_drag);
        mapDiv.addEventListener('mouseup', stop_drag);

        var img_ele = null,
            x_cursor = 0,
            y_cursor = 0,
            x_img_ele = 0,
            y_img_ele = 0;

        function start_drag() {
            img_ele = this;
            x_img_ele = window.event.clientX - map.offsetLeft;
            y_img_ele = window.event.clientY - map.offsetTop;
        }

        function stop_drag() {
            img_ele = null;
        }

        function while_drag() {
            var x_cursor = window.event.clientX;
            var y_cursor = window.event.clientY;
            if (img_ele !== null) {
                img_ele.style.left = (x_cursor - x_img_ele) + 'px';
                img_ele.style.top = (window.event.clientY - y_img_ele) + 'px';

                console.log(img_ele.style.left + ' - ' + img_ele.style.top);

            }
        }

    }

But is there someway I can make it so the image can't be moved off the edge of the screen? if you're at the bottom of the image and try to zoom out the map can disappear sometimes. Or maybe someway to reset coordinates of the image on zoom?
EDIT: Also answered this... close enough anyways. Reset the top and left of the image on each zoom so it won't ever go completely out of view:
const zoomMap = () => {
        let map = document.querySelector('#map');
        map.style.top = 0;
        map.style.left = 0;
        let mapSliderVal = document.querySelector('#map-slider').value;
        map.style.width = mapSliderVal + 'px';
    }

Would love for it to zoom in and out on current/last position though.. For some reason it always zooms to the top left?


text:
Q: Laravel - TokenMismatchException in VerifyCsrfToken because of upload filesize I have found that i need to change these settings in order to upload bigger files
I have changed these settings in my php.ini file
upload_max_filesize = 32M
max_file_uploads = 20

and this in my nginx.conf file
client_max_body_size 40m;

but i still get this error:
PHP Warning:  POST Content-Length of 27772457 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

This is 8MB limit....but where...i have restarted my machine and it still doesn't work
Where else can i adjust the file upload limit?

A: in your php.ini you should also change your
post_max_size

and make it larger than your upload_max_filesize
for exemple i use :
post_max_size = 125M
upload_max_filesize = 100M

then restart php-fpm


text:
Q: Moongoose Model.find() returns empty array when i have uppercase letter in the table name When the table name includes a capital letter (e.g. fooBar), Moongoose Model.find() returns an empty array.  If I change both the table name and the search string to be lowercase without changing anything else - it works fine.
Is this expected?

A: I think I have read somewhere about collection names being treated by default as lowercase inside of mongoose.  I always circumvent it by using models:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const FoobarSchema = new Schema({
    name: { type: String }
}, { collection: 'fooBar' });

module.exports = mongoose.model('fooBar', FoobarSchema);

The important part is what you name the collection in the Schema definition.  In the export that 'fooBar' can be named whatever you want and is a means to reference the model in your code.


text:
Q: get specific value from parameter I have a multi-valued parameter TimeMonthOfYear(from cube) that contains January Februrary...December.
I want to set a default value showing current month using MonthName(Month(Today)) (I tried it and it didn't work) when running report...
If I do this [Time].[Month Of Year].&[October] it works! October is selected in dropdown after previous dropdown (Year) was selected.
I don't want to do it the "hard coded" way...I have tried
[Time].[Month Of Year].&[MonthName(Month(Today))] and
="[Time].[Month Of Year].&["&MonthName(Month(Today))&"]" without luck
Any help is very much appreciated!

A: Yup :) Well it's now working with may be a not so nice solution but will work for now with the help of vb code. in standard value I have ="[Time].[Month Of Year].&[" + Code.SetMonth() + "]" and custom code Function SetMonth() As String Dim x as STRING x =CStr(MonthName(Month(Today))) 'CStr not needed I think If x = "januari" Then x = "January" ElseIf x = "februari" Then x = "February" ... End If Return(x) End Function That is giving me the current month after selecting value in year drop-down :)


text:
Q: create a macro in sas I have a report that is generated once a year. each report has the form of the year inside the name - report-2011.xls, report-2012.xls etc. each report contains the following vars: ID, SAL=average monthly salary of that year, Gender (0=male, 1=female), Married (0=not married, 1=married), I need to create a macro that calculates the mean.std,min and max of the salary, per year in accordance to gender type and married type. in the macro I need to include a parameter for the relevant year.
how do I refer to each type separately in calculating these parameters?
and how do I create a separate parameter for the year var?

A: %macro reporting(year, gender, marital_status);
    proc means data=data&year min max std;  * <== you should have separate datasets for different years
    class gender married ;

%mend reporting

%reporting( 2015, 1, 1)

Is that something you are looking for?

A: I macro is just a way to generate code.  So first design the code you want it to generate.  Then you can figure out what parts of it vary and replace those with macro variable references.  The macro variables then become the parameters for your macro.
proc import datafile="report-2011.xls" out=report_2011 ; run;
proc means data=report_2011 ;
   class gender married;
run;

A: proc summary allows you to control exactly which ways you want to cross the data.
%macro report(year);

proc import datafile="/path/to/report-&year..xls"
    out= salary_data
    dbms=csv replace ;

proc summary data = salary_data;
    class married gender;
    types married gender married*gender;
    var sal;
    output out = salary_results mean(sal) = mean_salary std(sal) = std_salary;

* Print the summary;
proc print;

* Delete the data and summary after using them;
proc delete data= salary_data salary_results; run;

%mend report;

Note that proc summary produces other useful information which you can read about here. You can drop them if you don't need them.


text:
Q: How to generate multiple jar files with gradle's java plugin I have a multi-project gradle build using the java plugin setup as follows:
myProj/
  settings.gradle
  build.gradle
  util/
    build.gradle

In my util project, I would like to generate 2 jars... one for packageA and one for packageB. I'm a noob with gradle so any help here would be much appreciated. Here are my settings and gradle files:
myProj/settings.gradle
include 'util'

myProj/build.gradle
subprojects {
    apply plugin: 'java'

    repositories {
        maven {
            url "http://mymavenurl"
        }
    }

    sourceSets {
        main {
            java {
                srcDir 'src/java'
            }
        }
    }
}

myProj/util/build.gradle
dependencies {
    .
    .
    .
}
jar {
    baseName = 'packageA'
    includes = ['com/mycomp/packageA']
}
task packageBJar(type: Jar) {
    dependsOn classes
    includes = ['com/mycomp/packageB']
    baseName = 'packageB'
}

When I try to build my project here is the output:
:util:compileJava
:util:processResources UP-TO-DATE
:util:classes
:util:jar
:util:assemble
:util:compileTestJava UP-TO-DATE
:util:processTestResources UP-TO-DATE
:util:testClasses UP-TO-DATE
:util:test
:util:check
:util:build

I would hope to see :util:packageBJar after classes, but I'm not having any luck.

A: One way is to declare packageBJar as an artifact of, say, the archives configuration:
artifacts {
    archives packageBJar
}

Now gradle assemble, and therefore also gradle build, will produce packageBJar.


text:
Q: How to get mood stocks scan to result in a textview? I am working with the Moodstocks sdk in an iOS application.  I would like for the following to occur:

*

*When a user scans the item, it will then open up a specific textview with information about the item.

How would I go about doing this?  Thank you very much for your help!

A: I assume that you have indexed your image and implemented MSScanner + MSAutoScannerSession, in brief, got started with the Moodstocks SDK. Otherwise, let me know and I'll explain to you or you could follow this tutorial: Getting started with Moodstocks SDK in few steps.
I'll fix your issue by displaying an ActionSheet, which makes more sense in case that you only want to display the recognized image identifier.
On a result, didFindResult: delegate method is called and you have access to the MSResult object which contains the recognized image informations:
// set UIActionSheetDelegate protocol

@interface ViewController () <MSAutoScannerSessionDelegate, UIActionSheetDelegate>

//...

- (void)session:(id)scannerSession didFindResult:(MSResult *)result
{
    // check if result exist
    if (result) {

        // result.string contains your image identifier
        // (e.g "steve jobs" if you have named your image "steve jobs.png")
        NSString *citation;

        if ([[result string] isEqualToString:@"Steve Jobs"]) {
            citation = @"Your time is limited, so don't waste it living someone else's life."
                        "Don't be trapped by dogma - which is living with the results of other people's thinking."
                        "Don't let the noise of others' opinions drown out your own inner voice."
                        "And most important, have the courage to follow your heart and intuition.";
        }
        else {
            // other checks .....
        }

        // display an action sheet with the result string
        dispatch_async(dispatch_get_main_queue(), ^{

            UIActionSheet *asView = [[UIActionSheet alloc] initWithTitle:citation
                                                                delegate:self
                                                       cancelButtonTitle:@"OK"
                                                  destructiveButtonTitle:nil
                                                       otherButtonTitles:nil];
            [asView showInView:self.view];
        });
    }
}

Implement UIAlertViewDelegate method:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    // handle actions if needed and
    // do not forget to resume the scanner session

    [_scannerSession resumeProcessing];
}

Of course, MSResult does not only contain the string identifier, you can retrieve a few more properties. see the doc.


text:
Q: Search Solr: Match exact result Koh S* I have a schema as below
 <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
       <tokenizer class="solr.KeywordTokenizerFactory"/>
       <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
 <analyzer type="query">
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
 </fieldType>

And my document will be:

*

*Koh Samui

*Koh Chang

*Koh Lanta

When i do the search Koh* It returns 3 results. it accepted. But when i search koh S*. it return zero result. I want the result would be only Koh Samui

A: I assume you want to use a wildcard query. This depends on the Query Parser you are using. If you are using the Standard Query Parser, Dismax, or eDismax, all of these don't support wild card queries.
And to be honest if you are using Solr to search for wildcard queries, you might be using the wrong tool as the solution, you can use any SQL Database and use text like 'Koh S%' in the where clause, and this will give you what you want.
But anyway, to use a wild card Query in Solr you need to use the Lucene query parser directly. To do this, use the following query:
http://localhost:8983/solr/core/select?q={!lucene df=text}Koh S*


text:
Q: Group orderring I am looking to group a list of projects by a nested field, in this case custom_field.value when a certain id is passed in.
[{
  id: 1,
  name: "project one ",
  custom_fields: [
       {
           id: 4,
           name: "Year",
           value: "2010"
       },
       {
           id: 5,
           name: "Priority",
           value: "low"
       },
 ]},
 {
  id: 2,
  name: "project two ",
  custom_fields: [
       {
           id: 4,
           name: "Year",
           value: "2011"
       },
       {
           id: 5,
           name: "Priority",
           value: "medium"
       },
 ]},
 {
  id: 3,
  name: "project three ",
  custom_fields: [
       {
           id: 4,
           name: "Year",
           value: "2012"
       },
       {
           id: 5,
           name: "Priority",
           value: "high"
       },
 ]}]

So if the params[:id] == 4 I want the list to be ordered by the custom_field id's corresponding value in decending order.
So in this case they would be ordered.
2012
2011
2010

Any ideas?

A: Assume projects is the data you pasted.
def order_values_by_id(pjs, id)
  pjs.map{|p| p[:custom_fields].find{|f| f[:id] == id}[:value] }.sort.reverse
end

order_values_by_id(projects)
#=> ["2012", "2011", "2010"]

A: Is this what you are looking for? Your question is a bit unclear but I think this should suffice:
Your Original Hash:
    test = [{
      id: 1,
      name: "project one ",
      custom_fields: [
           {
               id: 4,
               name: "Year",
               value: "2010"
           },
           {
               id: 5,
               name: "Priority",
               value: "low"
           },
     ]},
     {
      id: 2,
      name: "project two ",
      custom_fields: [
           {
               id: 4,
               name: "Year",
               value: "2011"
           },
           {
               id: 5,
               name: "Priority",
               value: "medium"
           },
     ]},
     {
      id: 3,
      name: "project three ",
      custom_fields: [
           {
               id: 4,
               name: "Year",
               value: "2012"
           },
           {
               id: 5,
               name: "Priority",
               value: "high"
           },
     ]}]

Use group_by and sort(with handling for elements where there is no id found):
    def group_and_sort(test_hash,id)
      test_hash.group_by do |g|
        elem = g[:custom_fields].detect {|h| h[:id] == id}
        elem ? elem[:value] : "0"
      end.sort.reverse.to_h
    end

Then call like:
    group_and_sort(test,4)
    #=>{"2012"=>
      [{:id=>3,
        :name=>"project three ",
        :custom_fields=>
         [{:id=>4, :name=>"Year", :value=>"2012"},
          {:id=>5, :name=>"Priority", :value=>"high"}]}],
     "2011"=>
      [{:id=>2,
        :name=>"project two ",
        :custom_fields=>
         [{:id=>4, :name=>"Year", :value=>"2011"},
          {:id=>5, :name=>"Priority", :value=>"medium"}]}],
     "2010"=>
      [{:id=>1,
        :name=>"project one ",
        :custom_fields=>
         [{:id=>4, :name=>"Year", :value=>"2010"},
          {:id=>5, :name=>"Priority", :value=>"low"}]}]}


text:
Q: Trace Error in ASP.NET MVC Application I am creating my first MVC application with VS 2012 on WIN 10. I added this line in System.Web section of Web.config file:
<trace enabled="true" pageOutput="True" />

My machine.config file has this line:

and this line:

When I run my application and enter this URL:http://localhost/MvcDemo/Trace.axd, I get the following error:

How can I solve it?

A: Acccording to this blog post: http://knucklebones.blogspot.com/2010/11/enable-tracing-in-aspnet-mvc.html
You need to add a little extra web.config plumbing for MVC:
<system.diagnostics>
  <trace>
      <listeners>
          <add name="WebPageTraceListener"
               type="System.Web.WebPageTraceListener, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
      </listeners>
  </trace>
</system.diagnostics>


text:
Q: Mdx Iif statment I'm trying to get calculated measure while evaluating Pentaho Analyser.
Point: Need a measure with condition. My code:
IIf ([Product].CurrentMember Is [Product].[Food], [Unit Sales], 0)

So I get:
Drinks  0
Food    14
Else    0
End it works only until [Product] dimension is present on rows or columns.
But when I insert another slicer, and remove [Product] ( [Partner] for example) I get:
IBM   0
MS    0
Apple 0
Instead of:
IBM   7
MS    2
Apple 5
I know, the main problem is CurrentMember property, and it's always zero because there is on CurrentMember on given dimension. Please, do not answer with: 'Filter it on "Food"'
because I'm trying to build something more complex and this is a first step.
Is there any trick to get this Measure work?
EDIT:
I have 3 dimensions: Product, Partner, Country
I need to get via mdx formula calculated measure:
[Unit Sales] when it is [Product].[Food] and [Product].[Drink] and it NOT is [Country].[US] and [Country].[DE] but everything else.
Thanks,
Best Regards

A: I am not a specialist for Pentaho/Mondrian, but I would assume the issue is that in your second scenario, the [Product].CurrentMember is the all member of the products, not the Food member, and thus the system behaves as you told it, and returns 0.
From how I understand your question, something like
IIf(
    Count(
        Intersect(
            { [Product].CurrentMember },
            { [Product].[Food], [Product].[Drink], [Product].[All] }
        )
    ) = 1
    AND
    Count(
        Intersect(
            { [Country].CurrentMember },
            { [Country].[US], [Country].[DE], [Country].[All] }
        )
    ) = 0
    [Unit Sales],
    0
   )

should deliver what you want. The trick here is that the intersection between the one-element set containing the CurrentMember and another set can either have one element - in case the CurrentMember is contained in the set -, or zero elements - in case the element is not contained in the set.


text:
Q: Losing Data on Reload When Fetching Data from a Service in Angular 8 I am using a service to send two lists of objects between two Angular pages, which works correctly. The problem is, if I happen to reload the page that recieves the data, the lists will get deleted from memory.
Is there a way to avoid this problem?
The way I am sending the data is simply by having two lists in the service defined as global variables, and I assign them the values of the two lists in page 1 before navigating to page 2. Once I'm in page two, I simply fetch the service on the OnInit method and assign the lists to the ones on page 2. Is there a way to persist this data after a reload?

A: Put this to the place where you get the data:
localStorage.setItem('theKeyYouWant', JSON.stringify(this.list));

Put this to the ngOnInit:
const item = localStorage.getItem('theKeyYouWant');
if (item) {
    this.list = JSON.parse(item);
} else {
    this.list = [];
}

See: MDN localStorage
localStorage exists in the browser, there is no need to import something.
I often use this code in my projects:
import { BehaviorSubject } from 'rxjs';

export class TypedDataService<T> {
  private readonly bhs: BehaviorSubject<T> = new BehaviorSubject<T>(null);
  valueChanges$ = this.bhs.asObservable();
  private value: T;

  constructor(
    private readonly key: string,
    private readonly defaultValue: T = null,
    private readonly equals: (x: T, y: T) => boolean = (x: T, y: T) =>
      JSON.stringify(x) === JSON.stringify(y),
    private readonly clone: (x: T) => T = (x: T) => JSON.parse(JSON.stringify(x)),
    private readonly parse: (s: string) => T = (s: string) => JSON.parse(s) as T,
    private readonly stringify: (x: T) => string = (x: T) => JSON.stringify(x)
  ) {
    this.init();
  }

  init() {
    const item = localStorage.getItem(this.key);
    if (item) {
      this.value = this.parse(item);
    } else {
      this.value = this.defaultValue;
    }
    if (this.value) {
      this.next();
    }
  }

  update(nvObj: T) {
    if (!this.equals(nvObj, this.value)) {
      if (nvObj === null) {
        localStorage.removeItem(this.key);

      } else {
        this.value = this.parse(this.stringify(nvObj));
        const nv = this.stringify(nvObj);
        localStorage.setItem(this.key, nv);
      }
      this.next();
    }
  }

  getValue(): T {
    return this.value;
  }

  private next() {
    this.bhs.next(this.clone(this.value));
  }
}

Example usage:
import { Injectable } from '@angular/core';
import { SettingsData } from '../data/settings.data';
import { TypedDataService } from '../../common/typed-data-service';

@Injectable({
  providedIn: 'root'
})
export class SettingsService {
  private static readonly innerService = new TypedDataService<SettingsData>(
    'settings',
    new SettingsData()
  );

  get settings$() {
    return SettingsService.innerService.valueChanges$;
  }

  getSettingsFromStorage(): SettingsData {
    return SettingsService.innerService.getValue();
  }

  settings2storage(data: SettingsData): void {
    SettingsService.innerService.update(data);
  }

  private deleteSettingsFromStorage(): void {
    SettingsService.innerService.update(null);
  }
}


text:
Q: poco class custom name Is there a way to a coded class called "Pessoa" decorate some atttribute to be referenced with a conceptual class named as "Person" that is in a conceptual model ? I'm mean:
[Table("Person")] // or something like that
public class Pessoa

I tried
[EdmEntityTypeAttribute(Name = "Person")]

but no success....

A: Here is MS answer:

Currently, Entity Framework doesn't
  support custom mapping between Object
  and Conceptual types (names should
  match). However, we will be
  considering this feature for future
  releases.
Thanks,
Kavitha Jonnakuti
Entity Framework test team


text:
Q: remove specified elements from an array in mongodb a doc:
{"_id":1,"m":[{"id":1,"m":11},{"id":2,"m":22},{"id":3,"m":33}]}

I want remove "m.id" == 1 AND "m.id" == 2 in single update. I can use $in, like:
update({"_id":1},{$pull:{"m":{$in:[{"id":1,"m":11},{"id":2,"m":22}]}}})

But it requires the whole doc rather than "m.id" $in [1,2]

A: If you want to only specify the id property from the m array objects, you can run the following query:
db.test.update({_id: 1}, {
    $pull: {
        m: {
            id: {
                $in: [1,2]
            }
        }
    }
});


text:
Q: dividing long xticks in 2 lines matplotlib I have the following matplotlib
I would like to divide x-ticks into 2 lines instead of 1 because sometimes they are so long that is why they come over another and then it is impossible to read x-ticks.
KEEP IN MIND X-ticks are not hard coded and they are changing. So not always same x-ticks.
So for following example it would be good if I have instead of to Schleswig-Holstein I could have:
to Schleswig-
  Holstein

How would I put the string after - in newline for the x ticks? or simply after lets say 10 letters I wanna go to a new line
Btw it would be also good if I could center all the text like the example above
So following is also okay but not the best.
to Schleswig-
Holstein

PS: Here is the code I use:
# create figure
fig = plt.figure()

# x-Axis (sites)
i = np.array(i)
i_pos = np.arange(len(i))

# y-Axis (values)
u = urbs_values
o = oemof_values

plt.bar(i_pos-0.15, list(u.values()), label='urbs', align='center', alpha=0.75, width=0.2)
plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
plt.bar(i_pos+0.15, list(o.values()), label='oemof', align='center', alpha=0.75, width=0.2)
plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))

# tick names
plt.xticks(i_pos, list(map((' to ').__add__, list(u.keys()))))

# plot specs
plt.xlabel('Lines')
plt.ylabel('Capacity [MW]')
plt.title(site+' '+name)
plt.grid(True)
plt.legend()
plt.ticklabel_format(style='sci', axis='y')
# plt.show()

# save plot
fig.savefig(os.path.join(result_dir, 'comp_'+name+'_'+site+'.png'), dpi=300)
plt.close(fig)

A: You can use re as suggested on this answer and create a list of new labels with a new line character after every 10th character.
import re
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

xlabels = ["to Schleswig-Holstein", "to Mecklenburg-Vorpommern", r"to Lower Saxony"]

xlabels_new = [re.sub("(.{10})", "\\1\n", label, 0, re.DOTALL) for label in xlabels]

plt.plot(range(3))
plt.xticks(range(3), xlabels_new)
plt.show()

Alternative
xlabels_new = [label.replace('-', '-\n') for label in xlabels]


text:
Q: Sequential HTTP request in IONIC2/Angular I am building a mobile app for my ecom store.
Most of the app is done but now when we are integrating we are facing some issues, its mostly related to multiple http requests. (correct me if i am wrong) I think they happen sequentially or one wait for the other to send the response.
Here is the issue, on the landing page of the app we have couple of section which requests server to send the data. First time when we get the data we cache the data in the localstorage for faster load later on.
Now the problem occurs when you navigate to a different section and that section also has to do some http request. Then that page takes a lot of time to show the data.
There are 4 http requests from the landing page.
Lets say they are A,B,C and D
And there is a page called as new arrivals and it makes one request to get the latest updates from the server, this request is E
So if a user opens the app then the http requests would be executed in following order
A -> B -> C -> D

And then if user decides to navigate to new arrivals page then there is one more http request added in the queue
A -> B -> C -> D -> E

So now user has to wait for each http request to complete to get the response. It takes a lot of time for the new arrivals page content to load. But if i disable the landing page http requests and then i do the whole thing again the new arrivals page loads a lot faster. I am guess since it was first in the queue.
Why is this happening?? Am i doing something wrong? or there is a way to change this behavior?
Added code sample:
@Component({
  selector: 'page-landing',
  templateUrl: 'landing.html',
  providers: [HomePageProducts,General,Auth,Crop,Products],
})
export class Landing {
 public products1 :any;
 public products2 :any;
 public products3 :any;
 public products4 :any;

 constructor(private productService:Products){
  loadProducts();
 }

 loadProducts(){
  this.productService.getPOTW().then((data) => {
   this.products1 = data;
  })
  this.productService.getBestSeller().then((data) => {
   this.products2 = data;
  })
  this.productService.getFeatured().then((data) => {
   this.products3 = data;
  })
  this.productService.getOnSale().then((data) => {
   this.products4 = data;
  })
 }
}

UPDATE 11-01-2017
Here is a test result after i did the above test in browser as suggested by few members:
Result 1
https://gyazo.com/1efc3fec9ea339bc46be46758552e31c
Here if you see the highlighted request was fired before the requests below it but it waited until the others finished and then we got the response for it
Result 2:
https://gyazo.com/3c14a4e4aad57256f843b57a2288f4cf
Here i disabled the other requests and tested again. And if you see the same requests returns a response faster than earlier.
The whole thing that i want to know is, does angular2 in any ways process the http requests and response in any sequence? or they are processed in sequence.
Can we do anything to disable this behavior? I mean that's why we fire ajax request to get async response and update the content without waiting for other response.


text:
Q: How to give a constant input to keras My network has two time-series inputs. One of the input has a fixed vector repeating for every time step. Is there an elegant way to load this fixed vector into the model just once and use it for computation?

A: You can create a static input using the tensor argument as described by jdehesa, however the tensor should be a Keras (not tensorflow) variable. You can create this as follows:
from keras.layers import Input
from keras import backend as K

constants = [1,2,3]
k_constants = K.variable(constants)
fixed_input = Input(tensor=k_constants)

A: EDIT: Apparently the answer below does not work (nowadays anyway). See Creating constant value in Keras for a related answer.

Looking at the source (I haven't been able to find a reference in the docs), it looks like you can just use Input and pass it a constant Theano/TensorFlow tensor.
from keras.layers import Input
import tensorflow as tf

fixed_input = Input(tensor=tf.constant([1, 2, 3, 4]))

This will "wrap" the tensor (actually more like "extend" it with metadata) so you can use it with any Keras layer.

A: Something to add:
When you come to compile the model you need to give the constant input as an input otherwise the graph disconnects
#your input
inputs = Input(shape = (input_shape,))

# an array of ones
constants = [1] * input_shape

# make the array a variable
k_constants = K.variable(constants, name = "ones_variable")

# make the variable a tensor
ones_tensor = Input(tensor=k_constants, name = "ones_tensor")

# do some layers
inputs = (Some_Layers())(inputs)

# get the complementary of the outputs
output = Subtract()([ones_tensor,inputs])

model = Model([inputs, ones_tensor],output)
model.complie(some_params)

when you train you can just feed in the data you have, you don't need the constant layer anymore.
I have found that no matter what you try it's usually easier to just use a custom layer and take advantage of the power of numpy:
class Complementry(Layer):

    def __init__(self, **kwargs):
        super(Complementry, self).__init__(**kwargs)

    def build(self, input_shape):
        super(Complementry, self).build(input_shape)  # Be sure to call this at the end

    def call(self, x):
        return 1-x  # here use MyArray + x


text:
Q: Finding integer solutions to a system of equations I am solving a problem and I reached the following system: $$\begin{cases}2y=x+z\\z^2=yt\\x+t=37\\y+z=36\end{cases}.$$
I have to find only the integer solutions, if that helps. I would be very grateful if you could give me some tips on solving it.

A: I started as so:
We have $$\begin{cases}2y=x+z\\z^2=yt\\x+t=37\\y+z=36\end{cases}.$$ and I labeled equation the equations from 1-4. By equation 1, we have that $z=2y-x$ and by equation 4 we have that $z=36-y$. We can now equate the both z equations and we have that $36-y=2y-x$. Solving this for $y$ we have that $y=12+\frac{x}{3}$. By equation 3 we have that $t=37-x$. As stated earlier we know what Fromm equation 1 that $z=2y-x$, so by equation 2 we have that $z^2 = (2y-x)^2 = (4y^2-4yx+x^2)$. Where $z^2=yt$, where $t=37-x$. Thus we have that $(4y^2-4yx+x^2)=(37-x)(y)$ where $y=12 +\frac{x}{3}$. By plugging this into the equation we have now, we have $\frac{x^2-144x}{9} +576 = \frac{-x^2}{3} + \frac{x}{3} +444$. To get rid of all of the fractions we can multiply both sides by 9 and get $x^2-144x +5184 = -3x^2+3x+3996$, and by simplifying this we have $4x^2-147x+1188=0$ which we can solve with the quadratic formula. We then get that $x=99/4, x=12$ since we only want integer solutions we take the $x=12$ solution and plug it into our $y=12+\frac{x}{3}$ and get that $y=16$. From earlier we had that $t=37-x$ so $t=25$. Lastly since $z=2y-x$ we have that $z=20$. So your integer solutions are $x=12,y=16,t=25,z=20$. I hope this process makes sense!


text:
Q: C++11 std::threads not exiting Could you please check the following code which is not exiting even after condition becomes false?
I'm trying to print numbers from 1 to 10 by first thread, 2 to 20 by second thread likewise & I have 10 threads, whenever count reaches to 100, my program should terminate safely by terminating all threads. But that is not happening, after printing, it stuck up and I don't understand why?
Is there any data race? Please guide.
#include<iostream>
#include<vector>
#include<thread>
#include<mutex>
#include<condition_variable>

std::mutex mu;
int count=1;
bool isDone = true;
std::condition_variable cv;

void Print10(int tid)
{
        std::unique_lock<std::mutex> lock(mu);
        while(isDone){
                cv.wait(lock,[tid](){ return ((count/10)==tid);});
                for(int i=0;i<10;i++)
                        std::cout<<"tid="<<tid<<" count="<<count++<<"\n";
                isDone = count<100;//!(count == (((tid+1)*10)+1));
                std::cout<<"tid="<<tid<<" isDone="<<isDone<<"\n";
                cv.notify_all();
        }
}
int main()
{
        std::vector<std::thread> vec;

        for(int i=0;i<10;i++)
        {
                vec.push_back(std::thread(Print10,i));
        }

        for(auto &th : vec)
        {
                if(th.joinable())
                        th.join();
        }

}

A: I believe the following code should work for you
    #include<iostream>
    #include<vector>
    #include<thread>
    #include<mutex>
    #include<condition_variable>

    using namespace std;
    mutex mu;
    int count=1;
    bool isDone = true;
    condition_variable cv;

    void Print10(int tid)
    {
        unique_lock<std::mutex> lock(mu);

        // Wait until condition --> Wait till count/10 = tid
        while(count/10 != tid)
            cv.wait(lock);

        // Core logic
        for(int i=0;i<10;i++)
            cout<<"tid="<<tid<<" count="<<count++<<"\n";

        // Release the current thread thus ensuring serailization
        cv.notify_one();
    }
    int main()
    {
        std::vector<std::thread> vec;

        for(int i=0;i<10;i++)
        {
            vec.push_back(std::thread(Print10,i));
        }

        for(auto &th : vec)
        {
            if(th.joinable())
                th.join();
        }

        return 0;
    }


text:
Q: Live monitoring on web server logs by tailing the webserver access log I am looking for a way to find who causes high load on my nginx web server but I do have too many requests per minutes to figure it out which one is the real cause.
I want a solution that would work like top but that would give me starts like
ip |  requests | average response time | total response time
---|-----------|-----------------------|--------------------

Every line looks like:
 10.80.3.169 - - [02/Nov/2012:12:15:37 +0000] "POST /pages/docreatepage.action HTTP/1.1" 302 0 "http://example.com/pages/docreate" "Mozilla..." "-" 1.074 1.074

So all I need form each line is the first part (IP) and last part (duration) and to count them and display starts every few seconds.
Is there a tool that is able do to this, or should I have to code it myself?

A: Likely you're looking for ngxtop.

Real-time metrics for nginx server
ngxtop parses your nginx access log and outputs useful, top-like,
  metrics of your nginx server. So you can tell what is happening with
  your server in real-time.

A: Are you looking for something like ntop?
http://www.ntop.org/