text:
Q: How do I select a row from a complex numpy array? I have read 10-20 different question/answers and cannot find an example like this.  I want to select rows out of a numpy array as follows:
test = [ [ [0], np.zeros((250,250)), np.array([0,0]) ],
         [ [0], np.zeros((250,250)), np.array([1,1]) ],
         [ [1], np.zeros((250,250)), np.array([2,2]) ],
         [ [2], np.zeros((250,250)), np.array([2,2]) ],
         [ [2], np.zeros((250,250)), np.array([2,2]) ]
       ]

Now convert the list to an numpy array and print the first column:
nptest = np.array(test)
print (nptest[:,0])
> output is: [[0] [0] [1] [2] [2]]

Now try to select just the row where the first element is = 1
just_1s = nptest[nptest[:,0] == 1]
print (just_1s)
> output is []

I don't understand this output.
In my actual problem set I have 100s of each with an arbitrary number of rows with values of 0-15 in the first column. Using the example data above, the desired result would be three numpy arrays as follows:
just_0s = [[ [0], np.zeros((250,250)), np.array([0,0]) ],
           [ [0], np.zeros((250,250)), np.array([1,1]) ]
          ]

just_1s = [[ [1], np.zeros((250,250)), np.array([2,2]) ]]

just_2s = [[ [2], np.zeros((250,250)), np.array([2,2]) ],
           [ [2], np.zeros((250,250)), np.array([2,2]) ]
          ]

A: Use list comprehension
just_1s = [el for el in nptest if el[0] == [1]]

But there is actually no need to work with nd.arrays, using the original list is ok
just_1s = [el for el in test if el[0] == [1]]

If your point is why does one get [] when doing nptest[nptest[:, 0] == [1]] (note that I test [1] instead of 1), I do not know. Because according to me (and Sam Marinelli) it should have worked. We are wrong.

But if one looks closer, it appears that

just_1s = nptest[ nptest[:,0].tolist().index([1]) ]

works fine but only if [1] is unique. Which is not the case of, e.g. [2].

A: This is list produces a (5,3) array of objects:
In [47]: nptest=np.array(test)
In [49]: nptest.shape
Out[49]: (5, 3)
In [50]: nptest.dtype
Out[50]: dtype('O')
In [51]: nptest[:,0]
Out[51]: array([list([0]), list([0]), list([1]), list([2]), list([2])], dtype=object)

The first column is an array (1d) of lists.  In my newer numpy version that's more explicit.
Doing an equality test on an array, or even list, of lists is not easy.  After trying several things I found this:
In [52]: arow = nptest[:,0]

In [56]: [x[0]==1 for x in arow]
Out[56]: [False, False, True, False, False]
In [57]: mask = [x[0]==1 for x in arow]
In [58]: nptest[mask,:]
Out[58]:
array([[list([1]),
        array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       ...,
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]]),
        array([2, 2])]], dtype=object)

Or we could turn the array of lists into an array of numbers:
In [60]: np.array(arow.tolist())
Out[60]:
array([[0],
       [0],
       [1],
       [2],
       [2]])
In [61]: np.array(arow.tolist())==1
Out[61]:
array([[False],
       [False],
       [ True],
       [False],
       [False]], dtype=bool)

Or test for [1] instead of 1.  Lists match lists, not their contents.
In [64]: [x==[1] for x in arow]
Out[64]: [False, False, True, False, False]

A: I believe the issue is with the expression nptest[:, 0] == 1.  You've already shown that nptest[:, 0] returns [[0], [0], [1], [2], [2]] as expected.  You can see that none of these values is equal to 1, so nptest[nptest[:, 0] == 1] will be empty.  Try nptest[nptest[:, 0] == [1]] instead.


text:
Q: How to access data from Method in Computed Methods:
methods: {
    fetchData () {
      axios.get(globalConfig.ORDERS_URL, {
        params: {
          limit: this.limit,
          offset: this.offset
        }
      })
        .then((resp) => {
          this.req = resp.data
          console.log(resp)
        })
        .catch((err) => {
          console.log(err)
        })
    }
}

Computed:
  computed: {
    filteredRequests () {
      return this.req.results.filter(item => {
        return item.created.toLowerCase().includes(this.name)
      })
    }
  }

Data:
  data () {
    return {
      req: {},
    }
  }

Parsing data from API endpoint, but i can't use req object in a computed method at all, it throws an error.
Contents of req object:

I also have used:
  created () {
    this.fetchData()
  },

  watch: {
    '$route': 'fetchData'
  }

So, when i use req object in a template directly - it works, but i cannot call it in a computed method to filter it.

A: You call this.req.results in computed while the initial data is req: {} and asynchronous fetchData() method does not resolve instantly, that's why it causes an error. Do something like:
computed: {
  filteredRequests () {
    if (this.req.results) {
      return this.req.results.filter(item => {
        return item.created.toLowerCase().includes(this.name)
      })
    } else {
      return 'No results'
    }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sitecore Partial Language Fallback not falling back We are attempting to implement Alex Shyba's Partial Language Fallback module.
I believe we have everything configured correctly based on the video. We've set the fallback language for ES to EN in Sitecore. We've verified there is a ES version of the both the template and the item.
We've enabled fallback on all the fields of the Home template.
After creating the Spanish version in Sitecore, I switch to version and it appears to be properly falling back to EN. Here is how both the Master db and Web db appear in the client:

This is screen shot is the ES version on WEB db. You can see there is content in the image and link fields.
However, when I hit the site, the content returns null and fails to display.

The module is a bit of a pain because of the lack of documentation (that I can find) and good examples on the web.
Could someone provide a link to a good working example or share how they've configured multi-site, multi-language sitecore?

A: I think you are misinterpreting how the module works. According to the documentation in the link you provided, the module detects the absense of a version in the current context language. If no version is detected, it falls back to the next available language version.

When an item is retrieved from a Sitecore database, the provider
checks whether the item has versions in the requested language. If
yes, then the item is returned to the caller. If there are not
versions in the requested language in the database, then the provider
performs fallback operation:
[Latest available item version in the fallback language is retrieved from the database]

You stated that you've set the fallback for ES to be EN, and that you have verified that an ES version of the item exists. From the modules perspective, everything is hunky dory... there is indeed a Spanish version, and so it will use it and not attempt to fallback.
That said, this doesn't explain why your field would be null while debugging. I suspect you simply need to re-publish the site in both languages.

A: I understand very well how Alex's Partial Language Fallback tool works.  I have recently posted a 10 blog series on the topic in sitecore's technical blog area.  If you'd like to see the details about how to configure it and what all the configurations mean, please see this post:
http://www.sitecore.net/Community/Technical-Blogs/Elizabeth-Spranzani/Posts/2014/03/Fallback-Series-Post-2.aspx
You are indeed correct, it is based on field fallback, not on the language version.  You need to make sure you have the following:

*

*fallback enabled in the site node of BOTH the site you are using on the front end and the shell site.

*Both the web and master database referenced in the standardValues SupportedDatabases setting

*Enforce version presence setting in side node set to 'false' or set to 'true' and have the version created in your language

*The language you want to have fallback set to fallback to the main language in the system/languages section

*The field in the 'english' version of the template is has the 'enable fallback' checkbox checked.

*Publish the item in both language versions

You DON'T need to have different language versions of the templates, unless you have the Fallback.VaryFallbackSettingsPerLanguage in the config set to true.  And I wouldn't recommend doing that, unless you want the field to fallback in some languages but not others.  I haven't run into a scenario where that is necessary.  But if you do decide to do this, you will need to make sure the checkbox is checked for every field in each language version.
I have a full working demo of the partial language fallback module here:
https://github.com/Verndale-Corp/Sitecore-Fallback-FullDemo
Make sure to uncheck the Standard fields checkbox when in content editor, to see the 'fallback value' text show to indicate whether a field is falling back.  Otherwise, it will just show 'standard values'.
Liz


text:
Q: Prolog: Maplist appending results to main list instead of sublists So I have the simple predicate defined as
pred(Info, List, Result) :-
  maplist(pred_calculate(Info), List, Result).

pred_calculate returns a list of X elements after an operation on a element of list, so for example pred_calculate(Info, List, Result) would return something like [2,3,5]
I want to add all the results of applying the pred_calculate predicate to all the elements of List, the problem I'm running into is that at the moment it's adding all the results from pred_calculate as sublists instead of adding to the single main list only.
So at the moment Result returns
[[2,3,5],[5,7,8],[8,9,11]] when it should return only [2,3,5,5,7,8,8,9,11]
How would I go about changing it to fix this behaviour?

A: When using foldl/4 with append/3, you have to pass the arguments in the correct order to append, if the order of the items is important1:
pred(Info, List, Result) :-
    maplist(pred_calculate(Info), List, List1),
    foldl([A, B, C] >> append(B, A, C), List1, [], Result).

Also, flatten/2 would achieve the same result, i.e.:
pred(Info, List, Result) :-
    maplist(pred_calculate(Info), List, List1),
    flatten(List1, Result).

1: foldl(append, List1, [], Result) would give you [8,9,11,5,7,8,2,3,5] as result.

A: maplist calls pred_calculate(Info) on every corresponding element of List and Result. Perhaps maplist is not what you really want to use here if pred_calculate results in a list on each call since it's not a 1-1 correspondence. You have a 1-to-many and you want the many in one big, flat list. You could use flatten or fold as !joel76 suggests. Or, you could "manually" write your own maplist-like predicate which is very simple - just a basic list recursion and probably using append to achieve each step:
pred(Info, List, Result) :-
    pred(Info, List, [], Result).

pred(Info, [], Result, Result).
pred(Info, [H|T], Acc, Result) :-
    pred_calculate(Info, H, R),
    append(Acc, R, Acc1),
    pred(Info, T, Acc1, Result).


text:
Q: Parsing a multidimensional JsonArray dynamically I'm trying to parse json data from the api. The json data I'm trying to parse can be seen here at

i want to show the output in listbox for as below

here is what im trying to do
dynamic json = JsonConvert.DeserializeObject(jsons);

foreach (var abc in json.sfkpi)
{
    Resultclass objs = new Resultclass();

    string months = abc.month;
    if (months == "Jan")
    {

        objs.p1 = (string)json["sfkpi"][0]["optima"][0]["productValue"];
        objs.p2 = (string)json["sfkpi"][0]["optima"][0]["productValue"];
        objs.p3 = (string)json["sfkpi"][0]["optima"][0]["productValue"];

        lstAnnouncement.Items.Add(objs);
    }
}

but here it adds the same value for for every month that is first productValue
 so what i am doing wrong how to achieve it.

A: You have 3 elements in sfkpi, and you are accessing only one element
//look at the index 0
(string)json["sfkpi"][0]
(string)json["sfkpi"][0]
(string)json["sfkpi"][0]

You just have to change the index
(string)json["sfkpi"][0]
(string)json["sfkpi"][1]
(string)json["sfkpi"][2]


text:
Q: Using Python, export SQLite schema In the SQLite command line, the command .schema can be used to export a database schema in SQL syntax, and that export can be used to rebuild a database of the same structure:
.output folderpath/schema.sql
.schema

Saves the following to a file named "schema.sql":
CREATE TABLE mytable (id INTEGER NOT NULL, name TEXT NOT NULL, date DATETIME, PRIMARY KEY (id), FOREIGN KEY (name) REFERENCES mytable2 (na ...

Can the same output .sql file be achieved using Python's sqlite3 library without a custom function?
There are several questions on Stack Overflow with similar titles, but I didn't find any that are actually trying to get the full schema (they are actually looking for PRAGMA table_info which does not have the CREATE TABLE, etc. statements in the output).

A: Well. Rewritten the answer above. It that exactly what you need?
import sqlite3

dbname = 'chinook.db'

with sqlite3.connect(dbname) as con:
    cursor = con.cursor()
    cursor.execute('select sql from sqlite_master')
    for r in cursor.fetchall():
        print(r[0])
    cursor.close()

With the test sqlite3 database I received the following:
CREATE TABLE "albums"
(
    [AlbumId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Title] NVARCHAR(160)  NOT NULL,
    [ArtistId] INTEGER  NOT NULL,
    FOREIGN KEY ([ArtistId]) REFERENCES "artists" ([ArtistId])
                ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE sqlite_sequence(name,seq)
CREATE TABLE "artists"
(
    [ArtistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Name] NVARCHAR(120)
)
CREATE TABLE "customers"
(
    [CustomerId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [FirstName] NVARCHAR(40)  NOT NULL,
    [LastName] NVARCHAR(20)  NOT NULL,
    [Company] NVARCHAR(80),
    [Address] NVARCHAR(70),
    [City] NVARCHAR(40),
    [State] NVARCHAR(40),
    [Country] NVARCHAR(40),
    [PostalCode] NVARCHAR(10),
    [Phone] NVARCHAR(24),
    [Fax] NVARCHAR(24),
    [Email] NVARCHAR(60)  NOT NULL,
    [SupportRepId] INTEGER,
    FOREIGN KEY ([SupportRepId]) REFERENCES "employees" ([EmployeeId])
                ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "employees"
(
    [EmployeeId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [LastName] NVARCHAR(20)  NOT NULL,
    [FirstName] NVARCHAR(20)  NOT NULL,
    [Title] NVARCHAR(30),
    [ReportsTo] INTEGER,
    [BirthDate] DATETIME,
    [HireDate] DATETIME,
    [Address] NVARCHAR(70),
    [City] NVARCHAR(40),
    [State] NVARCHAR(40),
    [Country] NVARCHAR(40),
    [PostalCode] NVARCHAR(10),
    [Phone] NVARCHAR(24),
    [Fax] NVARCHAR(24),
    [Email] NVARCHAR(60),
    FOREIGN KEY ([ReportsTo]) REFERENCES "employees" ([EmployeeId])
                ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "genres"
(
    [GenreId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Name] NVARCHAR(120)
)
CREATE TABLE "invoices"
(
    [InvoiceId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [CustomerId] INTEGER  NOT NULL,
    [InvoiceDate] DATETIME  NOT NULL,
    [BillingAddress] NVARCHAR(70),
    [BillingCity] NVARCHAR(40),
    [BillingState] NVARCHAR(40),
    [BillingCountry] NVARCHAR(40),
    [BillingPostalCode] NVARCHAR(10),
    [Total] NUMERIC(10,2)  NOT NULL,
    FOREIGN KEY ([CustomerId]) REFERENCES "customers" ([CustomerId])
                ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "invoice_items"
(
    [InvoiceLineId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [InvoiceId] INTEGER  NOT NULL,
    [TrackId] INTEGER  NOT NULL,
    [UnitPrice] NUMERIC(10,2)  NOT NULL,
    [Quantity] INTEGER  NOT NULL,
    FOREIGN KEY ([InvoiceId]) REFERENCES "invoices" ([InvoiceId])
                ON DELETE NO ACTION ON UPDATE NO ACTION,
    FOREIGN KEY ([TrackId]) REFERENCES "tracks" ([TrackId])
                ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "media_types"
(
    [MediaTypeId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Name] NVARCHAR(120)
)
CREATE TABLE "playlists"
(
    [PlaylistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Name] NVARCHAR(120)
)
CREATE TABLE "playlist_track"
(
    [PlaylistId] INTEGER  NOT NULL,
    [TrackId] INTEGER  NOT NULL,
    CONSTRAINT [PK_PlaylistTrack] PRIMARY KEY  ([PlaylistId], [TrackId]),
    FOREIGN KEY ([PlaylistId]) REFERENCES "playlists" ([PlaylistId])
                ON DELETE NO ACTION ON UPDATE NO ACTION,
    FOREIGN KEY ([TrackId]) REFERENCES "tracks" ([TrackId])
                ON DELETE NO ACTION ON UPDATE NO ACTION
)
None
CREATE TABLE "tracks"
(
    [TrackId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Name] NVARCHAR(200)  NOT NULL,
    [AlbumId] INTEGER,
    [MediaTypeId] INTEGER  NOT NULL,
    [GenreId] INTEGER,
    [Composer] NVARCHAR(220),
    [Milliseconds] INTEGER  NOT NULL,
    [Bytes] INTEGER,
    [UnitPrice] NUMERIC(10,2)  NOT NULL,
    FOREIGN KEY ([AlbumId]) REFERENCES "albums" ([AlbumId])
                ON DELETE NO ACTION ON UPDATE NO ACTION,
    FOREIGN KEY ([GenreId]) REFERENCES "genres" ([GenreId])
                ON DELETE NO ACTION ON UPDATE NO ACTION,
    FOREIGN KEY ([MediaTypeId]) REFERENCES "media_types" ([MediaTypeId])
                ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE INDEX [IFK_AlbumArtistId] ON "albums" ([ArtistId])
CREATE INDEX [IFK_CustomerSupportRepId] ON "customers" ([SupportRepId])
CREATE INDEX [IFK_EmployeeReportsTo] ON "employees" ([ReportsTo])
CREATE INDEX [IFK_InvoiceCustomerId] ON "invoices" ([CustomerId])
CREATE INDEX [IFK_InvoiceLineInvoiceId] ON "invoice_items" ([InvoiceId])
CREATE INDEX [IFK_InvoiceLineTrackId] ON "invoice_items" ([TrackId])
CREATE INDEX [IFK_PlaylistTrackTrackId] ON "playlist_track" ([TrackId])
CREATE INDEX [IFK_TrackAlbumId] ON "tracks" ([AlbumId])
CREATE INDEX [IFK_TrackGenreId] ON "tracks" ([GenreId])
CREATE INDEX [IFK_TrackMediaTypeId] ON "tracks" ([MediaTypeId])
CREATE TABLE sqlite_stat1(tbl,idx,stat)


text:
Q: Safety of calling C++ functions with enum created using static_cast I have been using enumerations for function input parameters, but I have noticed that this may be very dangerous.
For example:
enum class MYENUM {
    X1 = 0, X2
};

std::map<MYENUM, int> mymap;
//init mymap here with known enum values of X1 and X2

int MyFunc(const MYENUM& input) {
    return mymap.at(input);
}

int main() {
    MyFunc(static_cast<MYENUM>(10000));
}

So 10000 is not a valid enum value. How would you personally find a solution to this? Would you encase the map access in a try block and catch the exception? What if I have many functions which access container information with user input enum values - would you then put try catch in all of them too?

A:
How would you personally find a solution to this?

Easy. One of the reasons for class enums introduction was type-safety - they would not accept any value automatically. So, the code you have here
MyFunc(static_cast<MYENUM>(10000));

Just circumvents the safety which was offered by the language. The solution is simple - do not circumvent the safety by casting, and the compiler will not allow you to use incorrect values.
And if someone else uses the cast - this is not of your problem. There are endless ways someone can bypass built-in type safety and provide completely bogus values to the functions. There is nothing library writer can do about it.

A:
So 10000 is not a valid enum value

That may be true, but not because it's not equal to X1 or X2. An enum doesn't have to hold one of the named enumerators. It can hold any value in its integer range.
Now, the actual range of MYENUM is up to the compiler, as long as the integral underlying type it picks can represent both X1 and X2. So, it could be a int8_t, for example, which cannot hold 10000.
(In practice, it's probably an int here.)

How would you personally find a solution to this? Would you encase the map access in a try block and catch the exception?

Yes, if you like.
There are many approaches to error handling for functions like this, whether they involve enums or not. You can throw an exception (the .at() call will already do this for you, but you could catch it and throw an exception of your own type if you liked).
You could populate an error code, return a placeholder value, return a std::optional… or just ignore it, and document that the user of your function must pass a named member of the enum, or fall foul of a sort of "undefined behaviour" (possibly choosing to have the function act as if X1 were passed in that case, so that it has something to do at least).
All the usual options.

What if I have many functions which access container information with user input enum values - would you then put try catch in all of them too?

That is indeed a possible consideration to bear in mind when choosing your input argument error handling methodology.

A: There is nothing inherently dangerous about enum and function signatures with enum parameters are not bad practice. In your particular example, 10000 is still a valid enum, just not one that has a name.
This only becomes a problem when looking up in a std::map<MyEnum, Something> or using a switch (myEnum). To mitigate these problems, you could perform a sanity-check for your enum values:
// specify a type for MyEnum explicitly so that we know we can fit values
// such as 100000
enum class MyEnum : unsigned {
    X1 = 0, X2
};

// On a side note, enums are so small in size that it makes no sense to
// pass them by reference, simply pass them by value everywhere.
constexpr bool sanityCheck(MyEnum e) {
    return e == MyEnum::X1 || e == MyEnum::X2;
}

int MyFunc(const MyEnum& input) {
    assert(sanityCheck(input));
    return mymap[input];
}

You could even create an assert function that only compiles on release builds to have zero runtime cost. This will be much more effective than putting a try-catch everywhere.
But the best solution is to simply be careful when you create MyEnum using a static_cast. Don't pass the result into functions accepting MyEnum if you're not 100% sure that the value has a name.


text:
Q: How does Stack Exchange parse out URLs so well from answers and comments? There are a number of questions already on SO about parsing out a URL from text (here and here are 2 OK examples I've found).  Even Jeff Atwood posted a blog entry about this.  These are a bit unsatisfying though and I didn't want to post a duplicate question so I wanted to turn to Meta as SO actually does this very well in their questions and answers.
What is the mechanism used by Stack Exchange to parse URLs in text in questions, answers, and comments like (google.com),  http://google.com  or www.google.com?


text:
Q: how to find unique items in a total data set I have a data set with around 60,000 rows. It is a purchase order where you do not have a unique ID. Sample data below.
36 40 41 42 43 45 46
38 39 48 50 51 57
41 59 62
63 66 67 68
74 75 76 77

In the above list each number is an item purchased. I need the following:

*

*Total unique items in the data set.

*Top 5 items which were most purchased.

A: This should do it:
from collections import Counter

items = Counter()
with open('data_file.txt', 'r') as f:
    for line in f:
        items.update(line.split())

print("Total Unique Items: {0}".format(len(items)))

for item, count in items.most_common(5):
    print("Item {0} was purchased {1} times".format(item, count))

Yes, it's that short :).

A: Assuming that you dataset is a csv file or a text file.
from collections import Counter

with open(path, "r") as fp:
    raw = fp.readlines()

purchases = [item for line in raw for item in line.split()]
print "Unique ids: %s" %(len(set(purchases))
print "Most purchased ids:" %(",".join([ item[1] for item in Counter(purchases).most_common(5)]))

The above code should give your results.
Hope it helps.

A: To get the total length of the list, iterate through the rows using a loop and add each integer to a Python list using list.append(x) with the condition that if x not in list to get rid of the duplicates. Then, sort the list using list.sort(). Finally, do len(list).
To get the top 5 most purchased items, again iterate through the rows using a loop, but this time add all of the integers to a list, regardless of duplicates. Then do collections.Counter(list).most_common(5)[0][0].
See the Python list docs here and the collections docs here.


text:
Q: Close connection instead of setting 'keep-alive' I'm trying to disable the keep-alive setting in a very simple express app. I tried the answer from someone doing the same in an older version:
var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.set('Connection', 'close'); // attempting to override default (keep-alive)
    res.set('Proof', 'close');      // just to show that this should modify the header value
    res.send('hello');
});

var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});

However, Connection is still set to keep-alive:
$ curl -D - http://my-test-site.com
HTTP/1.1 200 OK
Server: nginx/1.4.7
Date: Sun, 11 May 2014 08:07:51 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 5
Connection: keep-alive
X-Powered-By: Express
Proof: close
ETag: "907060870"

hello%

How can I change keep-alive to close?
Versions
node 0.10.8
express 4.1.1

A: It works fine for me. I test it localhost the same version.
$ curl -D - 127.0.0.1:3000
HTTP/1.1 200 OK
X-Powered-By: Express
Connection: close
Proof: close
Content-Type: text/html; charset=utf-8
Content-Length: 5
ETag: "907060870"
Date: Sun, 11 May 2014 08:52:32 GMT

hello%

I see that you may use nginx to proxy. Like below:
client--nginx proxy--real server
I guess that you should disable keep-alive in nginx config file.


text:
Q: React Native Android restart app when crashes I'm working on an that needs to run in Kiosk Mode. I think I have covered every possible way so the user cannot leave the app, but I want some sort of safety net: in case the app crashes I need it to restart automatically.
I've been looking at guide on how to do it, but I haven't found one that I could translate to React Native.
I found this article particularly useful. However, I cannot replicate it entirely due to the fact that in React Native there isn't a .java Application file (or at least I haven't found one), so I can override the UncaughtExceptionHandler.
I can restart the app programmatically by calling this method:
public void restartApp(){
    Intent i = getBaseContext().getPackageManager()
        .getLaunchIntentForPackage( getBaseContext().getPackageName());
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
    | Intent.FLAG_ACTIVITY_CLEAR_TASK
    | Intent.FLAG_ACTIVITY_NEW_TASK);

    startActivity(i);
}

But I simple cannot call it when the app crashes.


text:
Q: Circuitikz short label interferes with arrow Why does the short label l= interfere with the arrow marker and how do I fix it?
MWE:
\documentclass{minimal}
\usepackage[european,RPvoltages]{circuitikz}
\begin{document}
\begin{circuitikz}
    \draw (0,2) to [short,l=$i(t)$, i=~] (1,2) to [short] (4,2);
    \draw (0,0) to [short,f=$i(t)$     ] (1,0) to [L, i_=$i(t)$, l_=$L$, v^<=$u(t)$](4,0);
\end{circuitikz}
\end{document}

A: Don't use the label element l if you want to add currents to your circuit. To add currents CircuiTikz provides the current option i or the flow option f.
If the distance of the current element is still to small you can customize the style of the current element by changing bipole current style.

\documentclass{minimal}
\usepackage[european,RPvoltages]{circuitikz}

\ctikzset{
    bipole current style/.style = {
        draw=red,
        text=black,
        thick,
        fill=orange,
        yshift=0.2cm,
        inner ysep=6pt},
}
\begin{document}

\begin{circuitikz}
    \draw (0,2) to [short,i>=$I_1(t)$] (1,2) to [short] (5,2);
    \draw (0,0)
        to [short,f=$I_2(t)$] ++(1,0)
        to [L, l_=$L$, v^>=$u(t)$] ++(2,0)
        to [short, i>=$I_2(t)$] ++(2,0);
\end{circuitikz}

\end{document}


text:
Q: Passing default global object to an external javascript module as 'this' I want to know how to pass 'this' to an external module (script.js).
Currently 'this' passed to 'script.js' is undefined, but I want to find a way to pass the default global object instead. By the way, script.js is auto-generated by another library, so I can't change it in any ways. Please help.
index.html
<script src='./script.js' defer></script>
<script>
    var interval = setInterval(function () {
        if (document.readyState === 'complete') {
            clearInterval(interval);

            (function (scope) {
                console.log('this inside of function')
                console.log(scope) //this prints 'global {frames: global, ..}
            })(this)  // <<<<< THIS works
        }
    }, 100);
</script>

script.js
(function (scope) {
    console.log('this inside of script.js')
    console.log(scope)    /// this prints 'undefined'
})(this)   // << THIS is undefined.


text:
Q: Post only checked values  to viewmodel I have some trouble getting the checked values in my form model to be posted correctly.
I have this Product class
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte[] Photo { get; set; }
    public int InStock { get; set; }
    public decimal Price { get; set; }
    public decimal Discount { get; set; }
    public decimal TotalPrice => Price - Discount;
    public int SupplierId { get; set; }
    public string SupplierName { get; set; }
    public IEnumerable<Category> Categories { get; set; }//Contains only the categories the product is bound to
}

And this Category class
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

And this EditVM class
public class EditVM
{
    public Product Product { get; set; }
    public IEnumerable<Category> Categories {get; set;}//Contains all the categories in the db
}

In my ProductController I have the Edit action method.
public async Task<IActionResult> Edit(int id)
{
    var product = await _productRepo.Get(id);
    if (product == null) return RedirectToAction(nameof(Index));
    var categories = await _categoryRepo.Get();
    var editVM = new EditVM()
    {
        Product = product,
        Categories = categories
    };
    return View(editVM);
}

This is the HTML in my view where I loop through the categories
@{var categoryIdList = @Model.Product.Categories.Select(x => x.Id); //Again, contains only the categories the Product is bound to (And gets the id's)
int counter = 0;}
@foreach (Category category in Model.Categories)//Loop through all the categories in the db
{
    if (categoryIdList.Contains(category.Id))
    {
        <input type="checkbox" name="Product.Categories[@counter].Id" value="@category.Id" checked />
    }
    else
    {
        <input type="checkbox" name="Product.Categories[@counter].Id" value="@category.Id" />
    }
    @category.Name
    { counter++;}
}

So far, so good, everything works till here. If I have 5 categories in the db and the product is bound to 2 of them, 5 checkboxes are shown and 2 are checked. So this is perfect.
However, the problem is when I select or deselect checkboxes. Now every Categories.Id in the db (Checked or unchecked) is posted to the HttpPost Edit action method and I want only the Ids posted whom are selected.
[HttpPost]
//Note the Product class contains an IEnumerable<Category> Categories prop for the categories the propduct is bound to. This is where the chechbox values must come in play...
public async Task<IActionResult> Edit(Product Product)
{
    var EditedProduct = await _productRepo.Update(Product);
    return RedirectToAction(nameof(Index));
}

I could chose to make an EditPostVM but this has nót my preference. (But it is not forbidden if that's a solution to my problem!). Also changing the incoming viewmodel is ok.
Some extra debug info: So I have 5 categories, so 5 checkboxes. If I select the last three and use the emmidiate window and run the following commands I get these results:
this.Request.Form.ElementAt(5)
{[Product.InStock, {120}]}
    Key: "Product.InStock"
    Value: {120}
this.Request.Form.ElementAt(6)
{[Product.SupplierName, {Kipleverancier}]}
    Key: "Product.SupplierName"
    Value: {Kipleverancier}
//Values above are from other form elements. And this works just fine. The problem is below...
this.Request.Form.ElementAt(7)
{[Product.Categories[2].Id, {3}]}
    Key: "Product.Categories[2].Id"
    Value: {3}
this.Request.Form.ElementAt(8)
{[Product.Categories[3].Id, {4}]}
    Key: "Product.Categories[3].Id"
    Value: {4}
this.Request.Form.ElementAt(9)
{[Product.Categories[4].Id, {5}]}
    Key: "Product.Categories[4].Id"
    Value: {5}

How can I bind these last three items to my Product.Categories prop?
If I check the first 2 items and also the last(out of 5 checkboxes) the first 2 checked items values are bound to Product.Categories. The last checked item value is posted, but not bound...
Basically I have 5 categories, so 5 checkboxes. If I select checkbox 2 and 4 I want an array of 2 items to be posted with the id's of the values of checkbox 2 and 4. How can this be achieved?

A: You have a hidden input in your foreach loop, it will send all the categories to the post edit. Just remove it:
<input type="hidden" name="Product.Categories[@counter].Id" value="@category.Id" />

Update:
You can use jquery to change the selected checkboxes name when submit the form:
@model EditVM
@{
    var categoryIdList = @Model.Product.Categories.Select(x => x.Id); //Again, contains only the categories the Product is bound to (And gets the id's)
    int counter = 0;
}
<form asp-action="Edit" method="post">

    @foreach (Category category in Model.Categories)//Loop through all the categories in the db
    {
        if (categoryIdList.Contains(category.Id))
        {
            <input type="checkbox" name="Product.Categories[@counter].Id" value="@category.Id" checked />
        }
        else
        {
            <input type="checkbox" name="Product.Categories[@counter].Id" value="@category.Id" />
        }
        @category.Name
        { counter++; }
    }
    <input id="btn" type="submit" value="submit" />
</form>

@section scripts{

}


text:
Q: How to export only gridview content but not the whole page in pdf? `

`I'm displaying the PDF on clicking the Export button, but after exporting what I get is the whole page. There is no other content in the aspx page but it is a web page using master page. So the contents from the master page are also being downloaded which is unwanted.

Aspx code
     <asp:GridView ID="GVAppRec" runat="server" AllowPaging="false" CssClass="center" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" AutoGenerateColumns="False">
                        <Columns>
                            <asp:TemplateField HeaderText="ReceivalID">
                                <ItemTemplate >
                                    <asp:Label ID="LblRecId" runat="server" Text='<% # Eval("ReceivalId") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="ApplicantID">
                                <ItemTemplate >
                                    <asp:Label ID="LblApId" runat="server" Text='<% # Eval("ApplicantId") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="FirstName">
                                <ItemTemplate >
                                    <asp:Label ID="LblFname" runat="server" Text='<% # Eval("Fname") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="LastName">
                                <ItemTemplate >
                                    <asp:Label ID="LblLname" runat="server" Text='<% # Eval("Lname") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="PostID">
                                <ItemTemplate >
                                    <asp:Label ID="LblPsId" runat="server" Text='<% # Eval("PostId") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Status">
                                <ItemTemplate >
                                    <asp:CheckBox ID="CkSts" OnCheckedChanged="CheckBox1_CheckedChanged" runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

code behind
    PdfPTable pdfTable = new PdfPTable(GVAppRec.HeaderRow.Cells.Count);
    foreach (TableCell headerCell in GVAppRec.HeaderRow.Cells)
    {
        Font f = new Font();
        f.Color = new BaseColor(GVAppRec.HeaderStyle.ForeColor);

        PdfPCell pdfdCell = new PdfPCell(new Phrase(headerCell.Text, f));
        pdfdCell.BackgroundColor = new BaseColor(GVAppRec.HeaderStyle.BackColor);
        pdfTable.AddCell(pdfdCell);
    }

    foreach (GridViewRow gvr in GVAppRec.Rows)
    {
       foreach (TableCell tc in gvr.Cells)
       {
           Font f = new Font();
           f.Color = new BaseColor(GVAppRec.RowStyle.ForeColor);
           PdfPCell pdfdCell = new PdfPCell(new Phrase(tc.Text));
           pdfdCell.BackgroundColor = new BaseColor(GVAppRec.RowStyle.BackColor);
           pdfTable.AddCell(pdfdCell);
       }
    }

    Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
    PdfWriter.GetInstance(doc, Response.OutputStream);
    doc.Open();
    doc.Add(pdfTable);
    doc.Close();

    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment;filename=VacancyReceived.pdf");
    Response.Write(doc);
    Response.Flush();
    Response.End();

I expect to export only the content of gridview but not the master page associated.

A: EDITED
Code Behind :
private void ExportGridToPDF()
{

    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
    GridView1.AllowPaging = true;
    GridView1.DataBind();
}


text:
Q: How do I fully relocate my user's home directory to another disk? I installed Lion on a new disk today and let the migration assistant move users, applications and stuff from my internal disk to the SSD connected via FW800. So far everything works great.
Because I have a pretty large photos and audio library, I want to leave my user's home directory on the old Volume and have OS and Applications on the other disk.
To achieve this I opened up Terminal.app, sudo'd and entered the following command:

cd /Users
mv mwidmann mwidmann_
ln -s /Volumes/Macintosh\ HD/Users/mwidmann .
chown -R mwidmann:mwidmann mwidmann

So far so good.
In finder the home folder was replaced with mwidmann_, but I removed that item from the sidebar and added the new one instead. Same goes for documents, downloads, pictures, videos, music. Other items I added there, worked like before.
Why I feel that I'm missing something is because the nice sidebar and dock icons for these "special" folders aren't showing up.
There must be an additional thing that tells Lion that THIS is my home folder and it is in /Volumes/Macintosh\ HD/Users/mwidmann and nowhere else.
Any Ideas?

A: You could also go System Preferences > Users & Group, right click on your username, click Advanced Options, and set the path of your Home directory. I also feel it's a more "robust" solution, because it's "endorsed" by Apple.

A: Nevermind, I found the solution!
I had to restart the computer and re-set the shortcuts and now it's working like I want it to. All the icons are showing up like I wanted.
So it really seems to be enough to just move the folder, set a link, set the correct permissions and that's it.


text:
Q: why does pyspark filter a string column work with integers? And why does pandas behave the other way around? When I have a pyspark dataframe with a column of numbers as strings and filter it using an integer the filter applies to the strings:
df = spark.createDataFrame([
  ("a", "1"),
  ("a", "2"),
  ("b", "1"),
  ("b", "2"),
], ["id", "number"])

df.filter(col('number')==1)

results in
id  number
a   1
b   1
c   1

wheareas, when I convert it to a pandas data frame and apply the same filter, the result is an empty df
pandas_df = df.toPandas()
pandas_df[pandas_df['number']==1]
# result
id  number

that leads to two questions:

*

*why does the pyspark filter function matches the strings, when I filter using integers?

*is there a way to filter type specific in pyspark? So creating the same results as in pandas? I cool have avoided quite some time of searching for an error with that functionality

A: This is the physical plan of your query:

== Physical Plan ==
*(1) Filter (isnotnull(number#18) AND (cast(number#18 as int) = 1))
+- *(1) Scan ExistingRDD[id#17,number#18]

As you can see, spark is casting the column to integer cast(number#18 as int) = 1
You can access logical and physical plans with .explain().
If you change your query by df.filter(col('number')=="1"), there will be no casting.


text:
Q: The structure of "he works as an architect" I am aware that the basic grammar pattern of a sentence is subject + predicate + object, where object is optional.
In this sentence,

I want a cup of tea

"I" is a personal pronoun, which functions as a subject; "want" is a verb, which functions as a  predicate; "a cup of tea" is a noun phrase, which functions as an object.
So far so good.
Consider another sentence,

He works as an architect.

"He" is a personal pronoun, which functions as a subject; "want" is a verb, which functions as a  predicate.
How about the last part? Could someone please give a hint? Thanks in advance.
Note: I understand the sentence conveys someone's occupation, what does he do for a living, and that is NOT what I am asking. I am asking about its grammatical function and analysis.
Similar to "subject", "predicate", what is the term (or canonical name) to describe the component of a sentence that "as an architect" functions as? Obviously, it is not an "object".

A: In this context, as is a preposition and an architect is the object of the preposition.

He is a subject pronoun
works is an intransitive verb
as an architect is a prepositional phrase which modifies the verb works.

Note that prepositional phrase describes how it was constructed - it starts with a preposition. We can also describe it in terms of its grammatical function within the sentence. A prepositional phrase can function as an adverbial phrase when it modifies a verb, or as an adjectival phrase when it modifies a noun, for example

The man at the centre of the controversy is ..."

In your example, it modifies a verb, so it is functioning as an adverbial phrase.


text:
Q: Set each system as data node and get the data from each I'm very beginner if the hadoop and HDFS

*

*There is 5 servers connected in lan

*Each server has log files with different data

Problems is this

*

*I need to process all the log files with Spark.

*I need to load all the log files to spark and process.

*I had a idea to have hdfs cluster, like each servers as slave (Each
one as slave)  and request to each slave and get the log files and
load to spark.

Am I correct or is there any better way or better technology.

A: Lets say there are 100 log files and each node has 20 of them in local file system. And your question is should I load all 100 to spark?
Before running spark you need to load the files from local file system into HDFS (If the files are in different nodes you can load them using SSH or something). Then, execute your spark program specifying the HDFS location of the 100 log files.
Typical scenario as steps:
Assuming there are 100 log files in 5 servers (20 each) and 5 servers are a hadoop cluster:
Step 1 : Load the files into HDFS. Propagate hdfs load command from all 5 servers. At this point, you should have all 100 files when you try hdfs dfs -ls /path/to/logfiles
Step 2 : Execute Spark program point to this /path/to/logfiles location.
Hope it helps.


text:
Q: Unresolved reference: lifecycleOwner , why I get this error? in my project I use a viewModel and live data,
in the fragment I want to observe that live data from the viewmodel, I just want to set the lifecycleOwner but it doesn't exist at all in the generated binding class.
although the same settings in my both gradle files will work fine in other projects and I can access binding.lifecycleOwner without any problems, is there somthing I am missing?
class HomeFragment : Fragment() {

    private val sharedViewModel: HomeViewModel by activityViewModels()
    private lateinit var binding: FragmentHomeBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.tvHome.text = sharedViewModel.randomMealLiveData.value!!.idMeal
        binding.lifecycleOwner = viewLifecycleOwner

    }
}

dependencies {
    def nav_version = "2.5.3"
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    //navigation component
    implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
    implementation("androidx.navigation:navigation-ui-ktx:$nav_version")

    //intuit
    implementation 'com.intuit.sdp:sdp-android:1.0.6'
    implementation 'com.intuit.ssp:ssp-android:1.0.6'

    //gif
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.17'
    //Retrofit and Json Converter
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    //glide for image loading from the internet
    implementation 'com.github.bumptech.glide:glide:4.12.0'

    //videoModel mvvm
    def lifecycle_version = "2.4.0-rc01"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    implementation "android.arch.lifecycle:extensions:1.1.0"
}


text:
Q: SQLite exception : no such column found ( id primary key) I have two tables in my database and I use inner join to print out data to LogCat which satisfying conditions.
I sure, it is just a foolish mistake.
Caused by:
Caused by: android.database.sqlite.SQLiteException: no such column: position.id (code 1 SQLITE_ERROR): , while compiling: select people.name as Name, position.name as Position, salary as Salary from people inner join position on people.posid = position.id where salary > ?

How I create two tables:
public static final String TABLE_POSITION = "position";
public static final String TABLE_PEOPLE = "people";

public static final String KEY_ID = "id";
public static final String KEY_NAME = "name";

public static final String KEY_SALARY = "salary";
public static final String KEY_POSID = "posid";

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_POSITION + "(" + KEY_ID + " integer primary key," + KEY_NAME + " text," + KEY_SALARY + " integer" + ");");
    db.execSQL("create table " + TABLE_PEOPLE + "(" + KEY_ID + " integer primary key autoincrement," + KEY_NAME + " text," + KEY_POSID + " integer" + ");");
}

How I fill out position table:
cursor = sqLiteDatabase.query(databaseHelper.TABLE_POSITION,null,null,null,null,null,null);
    if(cursor.getCount() == 0){
        for(int i = 0; i < position_id.length; i++){
            contentValues.put(databaseHelper.KEY_ID,position_id[i]);
            contentValues.put(databaseHelper.KEY_NAME,position_name[i]);
            contentValues.put(databaseHelper.KEY_SALARY,position_salary[i]);
            sqLiteDatabase.insert(databaseHelper.TABLE_POSITION,null,contentValues);
        }
    }
    cursor.close();

Data for position table:
    int[] position_id = { 1, 2, 3, 4 };
    String[] position_name = { "CEO", "Programmer", "Teacher", "Policeman" };
    int[] position_salary = { 15000, 13000, 10000, 8000 };

Data for people table:
String[] people_name = { "Ivan", "Maria", "Petr", "Anton", "Daria", "Boris", "John", "Suzy" };
int[] people_posid = { 2, 3, 2, 2, 3, 1, 2, 4 };

Error on this line:
String sqlQuery = "select people.name as Name, position.name as Position, salary as Salary from people inner join position on people.posid = position.id where salary > ?";
        cursor = sqLiteDatabase.rawQuery(sqlQuery,new String[]{"12000"});
        logCursor(cursor); //priting out cursor to LOG.d
        cursor.close();

I know that id without autoincrement is autoincrementing also, but I have to know id in position table for inner join as I suggess. So, how to solve this error? I know it is only primary key/autoincrement error

A: Solved people.posid = position._id ..But no data in tables.. (after two hours of thoughts)


text:
Q: Is it possible to use Qt threading without inheriting any Qt object? The only way to enable threading demonstrated in qt documentation is through inheriting QThread and then override its run() method.
class MyThread : public QThread
 {
 public:
     void run();
 };

 void MyThread::run()
 {
     QTcpSocket socket;
     // connect QTcpSocket's signals somewhere meaningful
     ...
     socket.connectToHost(hostName, portNumber);
     exec();
 }

I wonder if there is any way to use qt thread without ever inheriting from any qt objects?

A: QThread itself is derived from QObject. You need to override its run method to use it, therefore you have to inherit from QObject in order to use QThread.
Why do you want not to inherit from QObject?

A: If you do not wish to inherit QThread you could make a wrapper that inherits QThread and takes your objects as an argument, e.g. through a IRunnable interface (which you make and let your thread-classes inherit).

A: You can use multithreading without inheriting from QObject with QtConcurrent::run():

QFuture QtConcurrent::run ( Function function, ... )
  Runs function in a separate thread. The thread is taken from the global QThreadPool. Note that the function may not run immediately; the function will only be run when a thread is available.


text:
Q: How to use DataFrame Window expressions and withColumn and not to change partition? For some reason I have to convert RDD to DataFrame, then do something with DataFrame.
My interface is RDD,so I have to convert DataFrame to RDD, and when I use df.withcolumn, the partition change to 1, so I have to repartition and sortBy RDD.
Is there any cleaner solution ?
This is my code :
val rdd = sc.parallelize(List(1,3,2,4,5,6,7,8),4)
val partition = rdd.getNumPartitions
println(partition + "rdd")

val df=rdd.toDF()
val rdd2=df.rdd

val result = rdd.toDF("col1")
  .withColumn("csum", sum($"col1").over(Window.orderBy($"col1")))
  .withColumn("rownum", row_number().over(Window.orderBy($"col1")))
  .withColumn("avg", $"csum"/$"rownum").rdd

println(result.getNumPartitions + "rdd2")

A: Let's make this as simple as possible, we will generate the same data into 4 partitions
scala> val df = spark.range(1,9,1,4).toDF
df: org.apache.spark.sql.DataFrame = [id: bigint]

scala> df.show
+---+
| id|
+---+
|  1|
|  2|
|  3|
|  4|
|  5|
|  6|
|  7|
|  8|
+---+

scala> df.rdd.getNumPartitions
res13: Int = 4

We don't need 3 window functions to prove this, so let's do it with one :
scala> import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.expressions.Window

scala> val df2 = df.withColumn("csum", sum($"id").over(Window.orderBy($"id")))
df2: org.apache.spark.sql.DataFrame = [id: bigint, csum: bigint]

So what's happening here is that we didn't just add a column but we computed a window of cumulative sum over the data and since you haven't provided an partition column, the window function will move all the data to a single partition and you even get a warning from spark :
scala> df2.rdd.getNumPartitions
17/06/06 10:05:53 WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
res14: Int = 1

scala> df2.show
17/06/06 10:05:56 WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
+---+----+
| id|csum|
+---+----+
|  1|   1|
|  2|   3|
|  3|   6|
|  4|  10|
|  5|  15|
|  6|  21|
|  7|  28|
|  8|  36|
+---+----+

So let's add now a column to partition on. We will create a new DataFrame just for the sake of demonstration :
scala> val df3 = df.withColumn("x", when($"id"<5,lit("a")).otherwise("b"))
df3: org.apache.spark.sql.DataFrame = [id: bigint, x: string]

It has indeed the same number of partitions that we defined explicitly on df :
scala> df3.rdd.getNumPartitions
res18: Int = 4

Let's perform our window operation using the column x to partition :
scala> val df4 = df3.withColumn("csum", sum($"id").over(Window.orderBy($"id").partitionBy($"x")))
df4: org.apache.spark.sql.DataFrame = [id: bigint, x: string ... 1 more field]

scala> df4.show
+---+---+----+
| id|  x|csum|
+---+---+----+
|  5|  b|   5|
|  6|  b|  11|
|  7|  b|  18|
|  8|  b|  26|
|  1|  a|   1|
|  2|  a|   3|
|  3|  a|   6|
|  4|  a|  10|
+---+---+----+

The window function will repartition our data using the default number of partitions set in spark configuration.
scala> df4.rdd.getNumPartitions
res20: Int = 200

A: I was just reading about controlling the number of partitions when using groupBy aggregation, from https://jaceklaskowski.gitbooks.io/mastering-spark-sql/spark-sql-performance-tuning-groupBy-aggregation.html, it seems the same trick works with Window, in my code I'm defining a window like
windowSpec = Window \
    .partitionBy('colA', 'colB') \
    .orderBy('timeCol') \
    .rowsBetween(1, 1)

and then doing
next_event = F.lead('timeCol', 1).over(windowSpec)

and creating a dataframe via
df2 = df.withColumn('next_event', next_event)

and indeed, it has 200 partitions. But, if I do
df2 = df.repartition(10, 'colA', 'colB').withColumn('next_event', next_event)

it has 10!


text:
Q: Spring cloud gateway multiple filters I need to configure multiple filters in SCG, some in Java code and some via configuration. Is this possible to have a request to get filters by multiple filters? I ask this because every filters takes an argument url that must to pointing to a service URL or any upsteam URL. And if any 1st filters predicates_true by any request that it'll route that request to ustream URL and hence 2nd filter(be it in Java code or conf) wont get triggered.
Problem:
1st filter:
.route("decrypt_request_encrypt_response", r -> r
                        .asyncPredicate(serverWebExchange -> {
                            return Mono.just(Arrays.stream(RouterProperties.getProperty("enc.dec.paths").split(",")).filter(path -> serverWebExchange.getRequest().getURI().getPath().contains(path)).findFirst().isPresent());
                        })
                        .filters(f -> f.prefixPath("/")
                                .modifyRequestBody(String.class, String.class, MediaType.APPLICATION_JSON_VALUE,
                                        (exchange, s) -> Mono.just(aesEncryption.decrypt(s)))
                        )
                        .uri("lb://misc-service1"))

2nd filer:
gateway:
            routes:
                - id: test1
                  uri: http://localhost:9900/
                  predicates:
                      - Path=/
                      - Weight=group1,9
                - id: test2
                  uri: http://localhost:9901/
                  predicates:
                      - Path=/
                      - Weight=group1,1

Is it possible to route a request to from 1st filter to 2nd filter?


text:
Q: I am getting the error 'expected a quoted string', when I use certain rss feed. XMLParser I am getting the above error message when I use the second feed in the array, the other feeds work fine; it is just that particular feed which is throwing the error.
Could someone please point me in the right direction.
Thanks!
(The feed array is in the rssRun() method, and it is the second feed which is causing me error)
UPDATE:
It seems that the problem was, is that sometimes 'doc' proved to be null, therefore throwing an error. So I just put a try catch method around the code, and this seems to have done the trick....any item which throws an error will just be skipped.
MainCode:
package com.androidhive.xmlparsing;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidXMLParsingActivity extends ListActivity {

    // All static variables
    //static final String URL = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
    String[] URL = new String[3];
    int count = 0;
    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";
    static final String KEY_LINK = "link";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        rssRun();

    }

    public void rssRun()
    {
        URL[0] = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/a/arsenal/rss.xml";
        URL[1] = "http://www.skysports.com/rss/0,20514,11661,00.xml";
        URL[2] = "http://www.football365.com/premier-league/rss";

        //URL[3] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
        for (int f= 0;f < 3;f++)
        {
            count+=1;

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL[f]); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element
        //Log.e("XML", xml);

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        //Log.e("NODELIST", nl.toString());
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            //map.put(KEY_DESC, parser.getCharacterDataFromElement(e, KEY_DESC));
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
            map.put(KEY_COST, parser.getValue(e, KEY_COST));
            map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
            map.put(KEY_LINK, parser.getValue(e, KEY_LINK));

            // adding HashList to ArrayList
            menuItems.add(map);
        }

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item,
                new String[] { KEY_NAME, KEY_DESC, KEY_COST, KEY_LINK }, new int[] {
                        R.id.name, R.id.desciption, R.id.cost, R.id.link});
        //if (count==3)
        //{
            setListAdapter(adapter);
        //}

        // selecting single ListView item
        ListView lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(KEY_NAME, name);
                in.putExtra(KEY_COST, cost);
                in.putExtra(KEY_DESC, description);
                startActivity(in);

            }
        });
    }
    }

    public String getCharacterDataFromElement(Element e, String str) {
        NodeList n = e.getElementsByTagName(str);
        Element e1=(Element) n.item(0);

        Node child = e1.getFirstChild();
        if (child instanceof CharacterData) {
          CharacterData cd = (CharacterData) child;
          return cd.getData();
        }
        return "";
        }

}

XMlParser:
package com.androidhive.xmlparsing;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

    // constructor
    public XMLParser() {

    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();
            dbf.setCoalescing(true);
            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
    public final String getElementValue2( Node elem ) {
        Node child;
        if( elem != null){
            if (elem.hasChildNodes()){
                for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                    //if( child.getNodeType() == Node.TEXT_NODE  ){
                     if( child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE  ){
                        return child.getNodeValue();
                    }
                }
            }
        }
        return "";
        //return elem.getTextContent();
    }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue2(n.item(0));
        }

}

Error Log:
08-27 11:32:42.327: E/Error:(5730): Expected a quoted string (position:DOCDECL @1:50 in java.io.StringReader@42c223e8)
08-27 11:32:42.337: D/AndroidRuntime(5730): Shutting down VM
08-27 11:32:42.337: W/dalvikvm(5730): threadid=1: thread exiting with uncaught exception (group=0x41966da0)
08-27 11:32:42.347: E/AndroidRuntime(5730): FATAL EXCEPTION: main
08-27 11:32:42.347: E/AndroidRuntime(5730): Process: com.androidhive.xmlparsing, PID: 5730
08-27 11:32:42.347: E/AndroidRuntime(5730): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.xmlparsing/com.androidhive.xmlparsing.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.app.ActivityThread.access$900(ActivityThread.java:161)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.os.Looper.loop(Looper.java:157)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.app.ActivityThread.main(ActivityThread.java:5356)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at java.lang.reflect.Method.invokeNative(Native Method)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at java.lang.reflect.Method.invoke(Method.java:515)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at dalvik.system.NativeStart.main(Native Method)
08-27 11:32:42.347: E/AndroidRuntime(5730): Caused by: java.lang.NullPointerException
08-27 11:32:42.347: E/AndroidRuntime(5730):     at com.androidhive.xmlparsing.AndroidXMLParsingActivity.rssRun(AndroidXMLParsingActivity.java:71)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at com.androidhive.xmlparsing.AndroidXMLParsingActivity.onCreate(AndroidXMLParsingActivity.java:48)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.app.Activity.performCreate(Activity.java:5426)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-27 11:32:42.347: E/AndroidRuntime(5730):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)


text:
Q: How to solve and why: WordPress hosted on Azure keeps asking me for FTP login details when browsing and editing (not when adding plugins and updating) I currently hosting a WordPress Website on Azure, but it keeps popping up pages asking for FTP access while I am browsing and editing the website. I Googled a lot on this but people keep having the same issue when they updating and install new plugins, but I am having this issue when I am just doing normal browsing and editing. Anyone have the same issue? Anyone knows why this is happening and how to solve this please?

A: Maybe you installed any plugin which need FTP info of your website. Also you can get these info on Azure manage portal.
You can login Azure portal=>find your website in the App services resources=>click Get publish profile to download the profile file.

You can find the FTP url, userName and userPWD in the publishProfile section.
Meanwhile, you can set up FTP Access on Azure portal. On this manage page of your website, click All settings=>Deployment credentials=>then you can set up your FTP username and password.

A: Are you sure it is asking for FTP credentials. It sounds like it is asking you for your wordpress admin credentials while you are navigating around the admin dashboard. I had this problewm as well and it ended up being an Azure specific problem that I was able to solve to adding the following to my web.config:
<configuration>
  <system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Arr-Disable-Session-Affinity" value="true" />
        </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

Azure adds an extra cookie that you do not need and can cause this very issue.


text:
Q: Iterating over json objects in array I have an array called mainarray which has multiple json objects.
mainarray:Object
  >key1: Array[30]
  >key2: Array[20]

I want to do sorting on Array[30] and Array[20].
I am trying to do it like this:
mainarray.forEach((arrayinner)
{
  //sort
});

But I am getting error : as Cannot read property of undefined.
How can I iterate ? and also key names are dynamic ,I cant hardcode it and start iterating/

A: You need the function keyword for a valid callback declaration.
mainarray.forEach(function (arrayinner)
//                ^^^^^^^^
{
  //sort
});

But the problem is deeper:
You need to get the keys and to iterate over them and take the propery value to apply a sort
Object.keys(mainarray).forEach(function (key) {
    mainarray[key].sort();
});

A: You can do it by using $.each
$.each(mainarray, function(key,val){
  val.sort((a,b) => {return a > b ? 1 : a < b ? -1 : 0});
});

since the val is an array aka an object. Its reference will be shared inside of the callBack function. So affecting that array inside callBack will affect the original array.
DEMO

A: You can get the array of keys to iterate over
Object.keys ( mainarray ).forEach( function( arrayinner ){
  arrayinner.sort();
});

if the all the keys inside mainarray may not have Array value, then you can check before sorting
Object.keys ( mainarray ).forEach( function( arrayinner ){
  Array.isArray( arrayinner ) || arrayinner.sort();
});

A: You could achieve this by looping over the properties of the object itself and sorting the arrays they contain, something like this:
for (var key in mainarray) {
    if (mainarray[key] === Array)
        mainarray[key].sort();
}

Working example
Note that by default sort() only uses basic alphanumeric sorting logic. If you need anything more complex you would need to implement that yourself.


text:
Q: SAP Replication Server (from ASE to ASE to Oracle) I have 2 Sybase DB and 1 Oracle DB, I would like to replicate my Sybase DB X to my Sybase DB Y, and from Sybase DB Y to Oracle. The replication linking is like this:-
Sybase DB X --> Sybase DB Y --> Oracle
The replication from Sybase DB X to Sybase DB Y is working fine, but replication failed from Sybase DB Y to Oracle. When I tried to insert/delete/update some records on Sybase DB Y, it has been replicated to Oracle, but...when I tried to insert/delete/update some records on Sybase DB X, these transactions are able to replicate to Sybase DB Y, but it couldn't replicate to Oracle. WHY??
Appreciate if anyone could solve my doubts. Thanks a lot.

A: By default the repagent (in Sybase DB Y) will not replicate maintenance user transactions (ie, transactions replicated from Sybase DB X to Sybase DB Y).
To get the repagent (Sybase DB Y) to also replicate maintenance transactions (ie, transactions from Sybase DB X, once applied in Sybase DB Y, are then re-replicated to Oracle), you'll need to configure the Sybase DB Y repagent:
use <Sybase_DB_Y>
go
sp_config_rep_agent <Sybase_DB_Y>,'send maint xacts to replicate',true
go
sp_stop_rep_agent <Sybase_DB_Y>
go
-- wait for repagent to go down and then ...
sp_start_rep_agent <Sybase_DB_Y>
go


text:
Q: How can I pattern match a tuple containing a &mut enum and use the enum in one match arm and a recursive call in another? How can the code below be made to compile? It seems perfectly safe, but I can't convince the compiler that it is.
The version matching *self gives the error:
error[E0507]: cannot move out of borrowed content
 --> src/main.rs:8:16
  |
8 |         match (*self, y) {
  |                ^^^^^ cannot move out of borrowed content

The version matching self gives:
error[E0382]: use of moved value: `*self`
  --> src/main.rs:17:26
   |
8  |         match (self, y) {
   |                ---- value moved here
...
17 |                 (*a * b, self)
   |                          ^^^^ value used here after move
   |
   = note: move occurs because `self` has type `&'a mut Foo<'a>`, which does not implement the `Copy` trait

enum Foo<'a> {
    Foo1(Option<&'a mut Foo<'a>>),
    Foo2(i16),
}

impl<'a> Foo<'a> {
    fn bar(&'a mut self, y: i16) -> (i16, &'a mut Foo<'a>) {
        match (self, y) {
            (&mut Foo::Foo1(Some(ref mut a)), b) if (b == 5) => {
                return a.bar(y)
            },

            (&mut Foo::Foo2(ref mut a), b) if (b == 5) => {
                print!("is five");
                *a = (b + 42) as i16;

                (*a * b, self)
            },

            ref mut x => {
                print!("is not five!");
                (y, self)
            }
        }
    }
}

I feel like I would need a match arm such as the following, but it doesn't seem to be valid syntax:
(ref mut f @ Foo::Foo1, b) if (b == 5) => {
    print!("is five");
    f.0 = b + 42;
    (b, f)
}

error[E0532]: expected unit struct/variant or constant, found tuple variant `Foo::Foo1`
  --> src/main.rs:24:30
   |
24 |                 (ref mut f @ Foo::Foo1, b) if (b == 5) => {
   |                              ^^^^^^^^^ not a unit struct/variant or constant

This is a dumbed down version of a deep_fetch_mut of a toml::Value that I am trying to write. The goal would be to be able to call .deep_fetch_mut(vec!["aaa","bbb","ccc"]), that will return a mutable reference to that value inside the toml::Value.
This question is an extension of How can I pattern match a tuple containing a &mut enum and use the enum in the match arm?

A: This seems to compile, but it's very ugly. Is there a way to simplify this?
enum Foo<'a> {
    Foo1(Option<&'a mut Foo<'a>>),
    Foo2(i16),
}

impl<'a> Foo<'a> {
    fn bar(&'a mut self, y: i16) -> (i16, &'a mut Foo<'a>) {
        match (&mut *self, y) {
            (Foo::Foo1(Some(ref mut a)), b) if (b == 5) => {
                return a.bar(y)
            },

            (self2, c) => {
                let n = match (&mut *self2 , c) {
                    (Foo::Foo2(ref mut a), b) if (b == 5) => {
                        print!("is five");
                        *a = (b + 42) as i16;

                        *a * b
                    },

                    ref mut x => {
                        print!("is not five!");
                        y
                    }
                };

                return (n, self2)
            }
        }
    }
}


text:
Q: Getting all the Carriers in dropdown menu How do we get all the carriers available in Magento drop down menu? I want the carriers drop-down menu in user dashboard (not is Superadmin) so user can select and add the tracking no. I have gone through many post but unable to get the particular method.
Thanks in advance :)

A: Try this.
public function getAllShippingMethods()
{
    $methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
            $options = array();

            foreach($methods as $_code => $_method)
            {
                if(!$_title = Mage::getStoreConfig("carriers/$_code/title"))
                    $_title = $_code;
                $options[] = array('value' => $_code, 'label' => $_title . " ($_code)");
            }

    return $options; // This array will have all the active shipping methods
}


text:
Q: python - generalizing y-axis limits for mean line in density plots I have this simple dataframe:
df = pd.DataFrame({"X": np.random.randint(50,53,size=100),
             "Y": np.random.randint(200,300,size=100),
             "Z": np.random.randint(400,800,size=100)})

And as I have many columns (all of them numeric), I did this loop in order to do a specific plot:
for i in df.columns:
    data = df[i]
    data.plot(kind="kde")
    plt.vlines(x=data.mean(),ymin=0, ymax=0.01, linestyles="dotted")
    plt.show()

However, I'm having trouble trying to generalize the ymax argument of plt.vlines(), as I need to get the maximum y-axis value of each density plot in order to plot the mean vline of each plot accordingly. I have tried with np.argmax(), but it doesn't seem to work.
Any suggestions?

A: pandas.DataFrame.plot() returns matplotlib.axes.Axes object. You can use get_ylim() function to get ymin and ymax.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"X": np.random.randint(50,53,size=100),
             "Y": np.random.randint(200,300,size=100),
             "Z": np.random.randint(400,800,size=100)})

for i in df.columns:
    data = df[i]
    ax = data.plot(kind="kde")
    ymin, ymax = ax.get_ylim()
    plt.vlines(x=data.mean(),ymin=ymin, ymax=ymax, linestyles="dotted")
    plt.show()

A: To get the value of the kde corresponding to the mean, you could extract the curve from the plot and interpolate it at the position of the mean:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({"X": 20 + np.random.randint(-1, 2, size=100).cumsum(),
                   "Y": 30 + np.random.randint(-1, 2, size=100).cumsum(),
                   "Z": 40 + np.random.randint(-1, 2, size=100).cumsum()})
fig, ax = plt.subplots()
for col in df.columns:
    data = df[col]
    data.plot(kind="kde", ax=ax)
    x = data.mean()
    kdeline = ax.lines[-1]
    ymax = np.interp(x, kdeline.get_xdata(), kdeline.get_ydata())
    ax.vlines(x=data.mean(), ymin=0, ymax=ymax, linestyles="dotted")
ax.set_ylim(ymin=0) # ax.vlines() moves the bottom ylim; set it back to 0
plt.show()

A: Use plt.axvline. You specify the limits as numbers in the range [0,1], 0 being the bottom of the plot, 1 being the top.
for i in df.columns:
    data = df[i]
    data.plot(kind="kde")
    plt.axvline(data.mean(), 0, 1, linestyle='dotted', color='black')
    plt.show()


text:
Q: What does "pyenv virtualenvwrapper" do? I am using pyenv with virtualenvwrapper.
For using virtualenvwrapper (without pyenv) I have in my .bash_profile source /usr/local/bin/virtualenvwrapper.sh
When using pyenv with virtualenvwrapper plugin what exactly does pyenv virtualenvwrapper do ?
What I see online is this is required to setup a virtualenvwrapper into your shell. Is it still required if I have sourced virtualenvwrapper.sh ?
To add some more details: as per
https://alysivji.github.io/setting-up-pyenv-virtualenvwrapper.html
Anytime we install a new version of Python, we will need to install
virtualenvwrapper. This is done with either the pyenv
virtualenvwrapper or pyenv virtualenvwrapper_lazy

Is it required only once when a new version of python is installed in pyenv ?

A: In short, from the pyenv-virtualenvwrapper readme:

pyenv-virtualenvwrapper is a pyenv plugin which provides a pyenv virtualenvwrapper command to manage your virtualenvs with virtualenvwrapper.

There are three tools involved here:

*

*virtualenv or venv - Used for isolating python environments (collections of packages) by using 'virtual environments'. virtualenv has been more or less superseded by venv, but for the purpose of this answer, they are interchangeable.

*virtualenvwrapper - A set of tools for automating some of the steps involved in using virtualenv or venv.

*pyenv-virtualenvwrapper is a plugin that allows virtualenvwrapper to work with pyenv

*pyenv - a tool for managing multiple versions of python on the same computer system.

Another way to manage virtual environments when using pyenv is pyenv-virtualenv


text:
Q: calculus question about finding a limit of a sequence of functions. Let $$f_n = n \chi_{[0,\frac{1}{n} ]}$$
I want to find $ \lim f_n$. I think it is $0$ since if we fix $x$ then can find $x > \frac{1}{N} $ By archimedes. So $f_n(x) $ must be $0$ for all $n > N$ is this correct?

A: It seems like $f_n(x)$ approaches $0$ for each positive $x$, is $0$ for any negative $x$, and approaches $\infty$ for $x=0$.  Since $f_n(0) = n \chi_{[0,n^{-1}]}(0) = n\cdot 1 = n$ we have the sequence $\{1,2,3,4,\ldots\}$.


text:
Q: Select A Value Given Multiple Rows This is a very basic query (related to this one) I can't figure out …
Let's say I have a two column table like this:
A  -  B
1  -  1
1  -  2
1  -  3
2  -  1
3  -  1
3  -  4

I want to get all distinct As that do not have a B of 2 or 3. Using the above example, the only results I want returned is As 2 and 3. How do I do this?

A: SELECT DISTINCT `A` FROM `t` AS `t1`
    WHERE NOT EXISTS (
        SELECT 1 FROM `t`
            WHERE `t`.`A` = `t1`.`A`
            AND `B` in (2,3)
    );

SQL Fiddle demo

A: try to use the following code:
select distinct a
from tbl
where B not IN(2,3)


text:
Q: Enable Service Topology on k8s I'm using k8s with kubeadm version 1.17. I'm trying to enable Service Topology feature gates but I can't. Documentation say to use "--feature-gates="ServiceTopology=true,EndpointSlice=true". I tried to use that in "kubeadm init"... But kubeadm say that is not available to the cluster. Can you help me? That is the documentation that I'm following: https://kubernetes.io/docs/tasks/administer-cluster/enabling-service-topology/

A: It's not a flag of kubeadm. You need to enable it for each kubernetes control plane component such as controller manager, API Server, Scheduler, Kube proxy. The yamls for each of these components located at /etc/kubernetes/manifests location on all the master nodes need to be modified to add the feature flag - --feature-gates=ServiceTopology=true
API Server yaml for example
root@kind-control-plane:/# cat /etc/kubernetes/manifests/kube-apiserver.yaml
apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubeadm.kubernetes.io/kube-apiserver.advertise-address.endpoint: 172.18.0.2:6443
  creationTimestamp: null
  labels:
    component: kube-apiserver
    tier: control-plane
  name: kube-apiserver
  namespace: kube-system
spec:
  containers:
  - command:
    - kube-apiserver
    - --advertise-address=172.18.0.2
    - --allow-privileged=true
    - --authorization-mode=Node,RBAC
    - --client-ca-file=/etc/kubernetes/pki/ca.crt
    - --enable-admission-plugins=NodeRestriction
    - --enable-bootstrap-token-auth=true
    - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt
    - --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt
    - --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key
    - --etcd-servers=https://127.0.0.1:2379
    - --insecure-port=0
    - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt
    - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key
    - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
    - --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt
    - --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key
    - --requestheader-allowed-names=front-proxy-client
    - --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt
    - --requestheader-extra-headers-prefix=X-Remote-Extra-
    - --requestheader-group-headers=X-Remote-Group
    - --requestheader-username-headers=X-Remote-User
    - --secure-port=6443
    - --service-account-key-file=/etc/kubernetes/pki/sa.pub
    - --service-cluster-ip-range=10.96.0.0/12
    - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt
    - --tls-private-key-file=/etc/kubernetes/pki/apiserver.key
    - --feature-gates=ServiceTopology=true

Edit:
For kube proxy a custom kubeadm config file need to be created to add the feature flag
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
...
---
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
FeatureGates:
  ServiceTopology: true

Reference here

A: In my case (kubeadm version 1.18.2), it works with the following kubeadm configuration .yaml file (podSubnet is there because I am using Flannel CNI).
The key of kube-proxy is "featureGates" as mentioned in https://godoc.org/k8s.io/kube-proxy/config/v1alpha1#KubeProxyConfiguration
---
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
apiServer:
  extraArgs:
    feature-gates: "ServiceTopology=true,EndpointSlice=true"
controllerManager:
  extraArgs:
    feature-gates: "ServiceTopology=true,EndpointSlice=true"
scheduler:
  extraArgs:
    feature-gates: "ServiceTopology=true,EndpointSlice=true"
networking:
   podSubnet: "10.244.0.0/16"

---
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
featureGates:
  ServiceTopology: true
  EndpointSliceProxying: true


text:
Q: "onclick" event is not triggering on image to change it

In this code while clicking on the image then 'prompt' box must be displayed. But it is doing nothing. please help!

A: click is a native javascript function already. It simulates a mouse click. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
Use a different name for your function.
PS - your tag has a bunch of syntax errors. Remove the ;'s and height and width doesn't need units, just numbers, and align is obsolete on an img in html5.

A: Using a different function name and an image that is actually accessible, it works here:

function my_function()
    {
        var username = prompt("Enter ur name:");
        if(username)
        {
            alert("Hi,"+username);
            document.getElementById("rockPic").src = "http://placehold.it/200x200/d95";
        }
    }

A: Per documentation, the string values of "onClick" handler attributes are interpreted as the bodies of handler functions. Now since, there is already a function called 'click' for calling the event handler, declaring another function with the same name will basically override the native click.

 function clickAction()
  {
        var username = prompt("Enter ur name:");
        if(username)
        {
            alert("Hi,"+username);
            document.getElementById("rockPic").src = "rocksmile.jpg";
        }
    }


text:
Q: number of items to replace is not a multiple of replacement length warning is my function First, I have thee vectors,
(x <- c(7.2, 8.6, 9.1, 9.5, 10.9, 10.9, 11.1, 11.5, 11.7,
        11.9, 11.9, 12.7, 12.9, 13.9, 14.1, 14.5, 14.7))
#>  [1]  7.2  8.6  9.1  9.5 10.9 10.9 11.1 11.5 11.7 11.9 11.9 12.7 12.9 13.9 14.1 14.5
#> [17] 14.7
(qjx <- c(6.12, 7.90, 8.85, 9.30, 10.20, 10.90, 11.00, 11.30, 11.60,
          11.80, 11.90, 12.30, 12.80, 13.40, 14.00, 14.30, 14.60, 17.42))
#>  [1]  6.12  7.90  8.85  9.30 10.20 10.90 11.00 11.30 11.60 11.80 11.90 12.30 12.80
#> [14] 13.40 14.00 14.30 14.60 17.42

(rjx <- c(1.78, 0.95, 0.45, 0.9, 0.7, 0.1, 0.3, 0.3,
          0.2, 0.1, 0.4, 0.5, 0.6, 0.6, 0.3, 0.3, 2.82))
#>  [1] 1.78 0.95 0.45 0.90 0.70 0.10 0.30 0.30 0.20 0.10 0.40 0.50 0.60 0.60 0.30 0.30
#> [17] 2.82

For the x.seq is the smoothed vector of the x and Fm is a function to determine c.d.f value of vector x
x.seq <- seq(qjx[1],qjx[m+1],by=0.01)

Fm <- function(data,x){ #data = smooth data, x = intial data
x.smooth <- NULL;
xsmooth <- matrix(,nrow=(length(x)),ncol=length(data))
xsmooth. <- matrix(,nrow=(length(x)),ncol=length(data))
for(i in 1:m){
 for(j in 1:length(data)){
  xsmooth[i,j] <- (data[j] - qjx[i])/rjx[i]
    if(xsmooth[i,j] < 0){
     xsmooth.[i,j] <-  0
    } else
    if(xsmooth[i,j] >= 0 && xsmooth[i,j] <= 1){
     xsmooth.[i,j] = xsmooth[i,j]
    } else
    if(xsmooth[i,j] > 1){
     xsmooth.[i,j] <- 1
    }
 }
}
xsmoothing <- NULL
for(k in 1:ncol(xsmooth.)){
    xsmoothing[k] <- mean(xsmooth.[,k])
}
    print(as.numeric(xsmoothing))
}

next I want to compute the inverse value of t from function Fm with my function below here
m <- length(x)
Finv <- function(t){
    if(t > 0){
    f.inv <- matrix(,ncol=2,nrow=m)
    k <- 1;f.invers <- NULL
    while(k <= m){
        f.inv[k,1] <- (k-1)/m
        f.inv[k,2] <- k/m
        if(t >= f.inv[k,1] && t <= f.inv[k,2]){
         f.invers[k] <- (((m*t)-(k-1))*rjx[k])+qjx[k]
        } else
         f.invers[k] <- NA
      k <- k+1
      }
     hasil <- as.numeric(f.invers[!is.na(f.invers)])
     print(hasil)
    } else
     hasil <- L # L = the initial value,for example L is 2.06
     print(as.numeric(hasil))
    }

The reason is why I made this function because, there are many sequence of t. So, I compile for every single q from 1 until the last order the vector of t
t <- Fm(x.seq,x)
invers <- NULL
for(q in 1:length(t)){
    print(invers[q] <- Finv(1-t[q]))
}
invers

It works properly , but while processing the value of invers, there are warnings
Warning messages:
1: In invers[q] <- Finv(1 - t[q]) :
  number of items to replace is not a multiple of replacement length
2: In invers[q] <- Finv(1 - t[q]) :
  number of items to replace is not a multiple of replacement length
3: In invers[q] <- Finv(1 - t[q]) :
  number of items to replace is not a multiple of replacement length
4: In invers[q] <- Finv(1 - t[q]) :
  number of items to replace is not a multiple of replacement length
5: In invers[q] <- Finv(1 - t[q]) :
  number of items to replace is not a multiple of replacement length
6: In invers[q] <- Finv(1 - t[q]) :
  number of items to replace is not a multiple of replacement length

I just want to know where's the fault from my inverse function. Thanks

A: try this after t,
invers<-vector()
invers <- NULL
for(q in 1:(length(t)-1)){
  invers<-c(invers,Finv(1-t[q]))
}
invers

This will I tested with:
 invers <- NULL
 for(q in 1:(length(t))){
   invers<-c(invers,Finv(1-t[q]))
 }
 invers
 invers1<-vector()
 invers1 <- NULL
 for(q in 1:(length(t)-1)){
   invers1<-c(invers,Finv(1-t[q]))
 }
 invers1
 which(invers[1:1134]!=invers1[1:1134])

this is the result from the console.
 > which(invers[1:1134]!=invers1[1:1134])
 integer(0)


text:
Q: R gsub partial replacement wildcards I hope this is sufficiently different related, prior posts to justify its own thread; unfortunately, they were unhelpful to me. I think my interest in partial replacement, plus use of a wildcard is thus far unique, but apologies if I simply haven't searched or read carefully enough!
Suppose I have the following string:
str <- c("FOO_1", "FOO_2", "BAR_1", "BAR_2")

I'd like to replace the 1 at the end of FOO_1 with something else, say A. I attempted to do so with both
gsub("[^F.*](1)$", "\\_A", str)

and
gsub("^F.*(1)$", "\\_BLAH", str)

but clearly neither of them worked to replace only 1, leaving the rest of FOO_ intact, while also not altering BAR_1. I have a dumb solution to the problem that simply involves a line of grep() and a line of gsub(), but I will hate myself if that's what I settle on.

A:
I only want to replace variables starting with FOO and ending with 1

Capture FOO and everything after it into Group 1 and just match _1 at the end of the string. Then, in the replacement pattern, use a replacement backreference to the Group1  value:
str <- c("FOO_1", "FOO_2", "BAR_1", "BAR_2")
sub("^(FOO.*)_1$", "\\1_A", str)
## => [1] "FOO_A" "FOO_2" "BAR_1" "BAR_2"

See this R demo
If any digit amount at the end of the string must be matched, replace 1 with \\d+.
Details

*

*^ - string start

*(FOO.*) - FOO substring and then any 0+ chars, as many as possible

*_1 - a _1 substring  (if you replace 1 with \\d+, it will match 1 or more digits)

*$ - end of string.


text:
Q: DataGridView editing cells on WinForms I have a Windows Form VS2010 .NET 4 project with a standard DataGridView bound to a datasource on a form.
The grid has a text column that I want to be a point and edit at the character clicked to.
Like normal textbox/editors when you click on the character you want to adjust.  If possible I would also like to use the UP/DOWN keys to move between rows but would like the cursor to move to the same character position obviously in the same column without selecting the entire text.
I have tried a few things:
DataGridView1.ClearSelection()
DataGridView1.BeginEdit(False)
The BeginEdit just puts the cursor at the end of the text, which means another click to point to the character position for editing.
I know a Commercial grid like DevExpress defaults to editing in which you can click to the correct character position with one click but obviously costs money.
I have tried in the DataGridView1_EditingControlShowing event
If TypeOf e.Control Is System.Windows.Forms.DataGridViewTextBoxEditingControl Then
        Dim tb As TextBox = e.Control
        tb.SelectionStart = 5
        tb.SelectionLength = 5
End If

But this does nothing.
I am just trying to remove the two or three clicks to get to the character position that needs adjustment.
I haven't looked at a Custom DataColumn as yet.
Any suggestions would be greatly appreciated.

A: There is no good out of the box way of doing this. The closest there is is to set the EditMode of the grid to EditOnEnter but that means you only need two clicks, not three.
You will need to write your own column type.
Someone has done just that here.
I haven't checked if that example handles up and down - if it doesn't then you were on the right track with the SelectionStart and SelectionLength properties, just grab the caret position of the cell you are leaving and apply it to the new cell.

It turns out that setting these properties is a little bit more involved that I remembered (possibly because I was already using a MaskedTextBox custom column type last time I did this).
The code below (in c# but the principle holds for vb.Net and I can give the vb code if you can't convert it yourself) works happily - could be tidied up by putting it into a custom control but I'll leave that as an exercise :)
First I add a handler for the EditingControlShowing event:
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    DataGridViewTextBoxEditingControl t = e.Control as DataGridViewTextBoxEditingControl;
    current_control = t;
    t.Leave += new EventHandler(t_Leave);
}

In the method above current_control is a form level private variable. The event handler for t looks like this:
void t_Leave(object sender, EventArgs e)
{
    cell_caret_pos = current_control.SelectionStart;
}

There again we have a class level private field - cell_caret_pos.
Then what I found was that to set SelectionStart and SelectionLength you need to work within the CellEnter event handler:
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.BeginEdit(false);
    DataGridViewTextBoxEditingControl editControl =
        (DataGridViewTextBoxEditingControl)dataGridView1.EditingControl;

    if (cell_caret_pos != 0)
    {
        editControl.SelectionStart = cell_caret_pos;
        editControl.SelectionLength = 0;
    }
}


text:
Q: Custom views for cgridview based on role I want to filter my CgridView to only display has "student" role from Authassignment Model, I read some tutorials but none of them show this.
Please help me, this is related to my thesis.
<?php

$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'users-grid',
    'dataProvider'=>$model->search(),
    // 'filter'=>$model,
    'columns'=>array(

        'userID',
        'lastname',

        array(
            'class'=>'bootstrap.widgets.TbButtonColumn',
        ),
    ),
));

?>

StudentView

A: Hi Please refer this as suggestion
I don't  know whats your table structure is but the best way of doing this may be. Create a field in user table named user_role and at the time of user creation insert value in this like 1 for admin 2 for student and then you can easily get only student role by below method like
public function actionIndex()
    {
        $model=new User('search');

        $model->unsetAttributes();  // clear any default values
      $model->user_role = 2;// for student role
        if(isset($_GET['User']))
            $model->attributes=$_GET['User'];

        $this->render('index',array(
            'model'=>$model,
        ));
    }


text:
Q: tail -f to several files piped to "while read" gives unexpected results I wrote a quick bash script to monitor several log files and send their contents to a Mattermost chat. This is the script:
#!/bin/bash

# HOOKS
hook1=...#Mattermost hook
hook2=...#Mattermost hook
hook3=...#Mattermost hook

date=$1
year=$2

unbuffer tail -f -n0 /var/log/$year/hook1_*$date.log \
  /var/log/$year/hook2_*$date.log \
  /var/log/$year/hook3_*$date.log | grep "ERROR" | while read -r msg
  do
    if [[ $msg = *"hook1"* ]]
    then
      hook=$hook1
    elif [[ $msg = *"hook2"* ]]
    then
      hook=$hook2
    else
      hook=$hook3
    fi
    msg=$(echo "$msg" | sed -r "s/\"/\\\\\"/g")
    curl -i -X POST --data-urlencode "payload={\"text\": \"$msg\"}" $hook

  done

The sed part escapes quotes so I can replace the message into curl.
However, several problems arise during execution:

*

*There seems to be 2 processes in htop after I run the script once.

*Sometimes messages are not sent to Mattermost as they appear, but instead they come out in batches.

*Messages sometimes appear cut and some content is lost.