text:
Q: Discord.j - Function strangely empty this question is linked to another one. If you need to know why I'm asking this, check this question.
I'm developing a bot who should get a collection filled with members who have a specific role. But after testing and double checking role name and be sure I'm testing the bot in a server and not in DM the collection is always empty and unusable (the program couldn't run without it).
const eventMembers = message.guild.members.cache.filter(m =>
      m.roles.cache.some(r => r.name === "event")
   );

const connectedMembers = eventMembers.members.filter(m => {
      return voiceChannel.members.has(m.id)
   });
console.log(connectedMembers);

If anybody has a hint or a solution I take it

A: You forgot return :)
const eventMembers = message.guild.members.cache.filter(m => {
    return  m.roles.cache.some(r => r.name === "event")
      });

or
const eventMembers = message.guild.members.cache.filter(m => m.roles.cache.some(r => r.name === "event"));

You can check for the role with this name exist:
let role = message.guild.roles.cache.find(role => role.name === 'event')
if (role) {
    console.log('ok')
} else {
    console.log('No role found with this nickname')
}

V2
const eventMembers = message.guild.members.cache.filter(m => {
    return  m.roles.cache.some(r => r.name === "event") && m.voice && m.voice.channelID === message.member.voice.channelID
   });

or
const eventMembers = message.guild.members.cache.filter(m => m.roles.cache.some(r => r.name === "event") && m.voice && m.voice.channelID === message.member.voice.channelID)

V3 :D
bot.on('message', message => {
    if(message.content === '!test') {
        if(!message.member.voice.channel) return message.reply('You need joinVoiceChannel for use this command');
        let targetRole = message.guild.roles.cache.find(role => role.name === 'event')
        if (!targetRole) return message.reply('Can`t find a role');
        let eventMembersNotInVoice = targetRole.members.filter(member => member.voice.channelID !== message.member.voice.channelID)
        console.log(eventMembersNotInVoice.size)
    }
});


text:
Q: AngularJS - Controller Function Order - Some References wont work I have the following code:titledbApp.controller('TitleListController', ['$cookieStore', function($scope, $http, $cookieStore) {
It won't work - It basically cants detect $CookieStore and says it's undefined so all .get and .put requests fail.
When I move $cookieStore in function() to the start (Before $scope) it works fine but then $scope and $http fail to work.
Full code:
titledbApp.controller('TitleListController', ['$cookieStore', function($cookieStore, $scope, $http) {
    $cookieStore.put('ETag', 'test');
    var etag = 't';
    $http.get('https://api.github.com/users/ImReallyShiny/repos', {headers: {'If-None-Match': 't'}}).then(function successCallback(response, headers) {
        $cookieStore.put('ETag', headers('ETag'));
        $scope.titles = response.data;
        $scope.titles.splice(1, 1);
        $scope.titles.sort(function(a, b){
            if(a.name.toUpperCase() < b.name.toUpperCase()) return -1;
            if(a.name.toUpperCase() > b.name.toUpperCase()) return 1;
            return 0;
        });
        }), function errorCallback() {
        return "Error";
        };
}]);

A: titledbApp.controller('TitleListController', ['$cookieStore', function($cookieStore, $scope, $http)

Should be
titledbApp.controller('TitleListController', ['$cookieStore', '$scope', '$http', function($cookieStore, $scope, $http)

You have to inject them all before you can access them in your code.

A: According to angular js official documentation, the order and the no: of parameters of the dependencies should be same.
titledbApp.controller('TitleListController', ['$cookieStore','$scope', '$http', function($cookieStore, $scope, $http) {
    $cookieStore.put('ETag', 'test');
    var etag = 't';
    $http.get('https://api.github.com/users/ImReallyShiny/repos', {headers: {'If-None-Match': 't'}}).then(function successCallback(response, headers) {
            $cookieStore.put('ETag', headers('ETag'));
        $scope.titles = response.data;
        $scope.titles.splice(1, 1);
        $scope.titles.sort(function(a, b){
            if(a.name.toUpperCase() < b.name.toUpperCase()) return -1;
            if(a.name.toUpperCase() > b.name.toUpperCase()) return 1;
            return 0;
        });
        }), function errorCallback() {
        return "Error";
        };
}]);

You can also use the function syntax,
titledbApp.controller('TitleListController', TitleListController);

function TitleListController($cookieStore,$scope, $http){
    $cookieStore.put('ETag', 'test');
    var etag = 't';
    $http.get('https://api.github.com/users/ImReallyShiny/repos', {headers: {'If-None-Match': 't'}}).then(function successCallback(response, headers) {
            $cookieStore.put('ETag', headers('ETag'));
        $scope.titles = response.data;
        $scope.titles.splice(1, 1);
        $scope.titles.sort(function(a, b){
            if(a.name.toUpperCase() < b.name.toUpperCase()) return -1;
            if(a.name.toUpperCase() > b.name.toUpperCase()) return 1;
            return 0;
        });
        }), function errorCallback() {
        return "Error";
        };

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable To Disconnect Docker Container From Network I am trying to disconnect a Docker container (ContainerA1) connected to a network (NetworkA), but am unable to do so, even with the --force flag.
$ docker network disconnect NetworkA ContainerA1

I get an error response: container c5d345a09c6d is not connected to the network. (container IDs trimmed for brevity).
Oddly enough, I am able to disconnect other containers from NetworkA.
I inspected the network using docker network inspect NetworkA. I see :
[
    {
        "Name": "NetworkA",
        "Id": "9e4895ee72a1648ad10f297357447529b277beb92fe21069a244a8265b8f7306",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1/16"
                }
            ]
        },
        "Internal": false,
        "Containers": {
            "aded6369aef63b5237a7f543333f0b7fafbe2f01496efb2012bb7f5d67f14268": {
                "Name": "ContainerA2",
                "EndpointID": "c93b9dde46884181ca5acb63c03b2fb5fb3141e98416dda3e6cbc98b166b88ee",
                "MacAddress": "02:42:ac:12:00:03",
                "IPv4Address": "172.18.0.3/16",
                "IPv6Address": ""
            },
            "ep-0f7d832a8d0cd86d8655ea9e0c1f7bbf33f1102b7bbe6454aca1ab8a48a6e4cd": {
                "Name": "ContainerA1",
                "EndpointID": "0f7d832a8d0cd86d8655ea9e0c1f7bbf33f1102b7bbe6454aca1ab8a48a6e4cd",
                "MacAddress": "02:42:ac:12:00:07",
                "IPv4Address": "172.18.0.7/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

Notice the ep- prefix for ContainerA1.
I tried removing the container, but still see it in the list of containers when I do docker network inspect NetworkA. The "EndpointID" is different from the container ID, but having same name.
How can I remove stale entries from network, NetworkA?


text:
Q: postgres array of arrays to columns Sample of my table
Table_A
id integer
arr varchar(20) []

Sample data
id.         arr
1.    {{'a', 'b', 'c'}, {'d', 'test1', 'sample1'}}
2.    {{'sample2', sample3, sample4'}}
3.     null
4.    {{'sample6', 'sample7', 'test done'}}

I want to select to have the data as:
id.     col1.       col2          col3
1       'a'         'b'.          'c'
1.      'd'.       'test1'.      'sample1'
2.      'sample2'  'sample3'.    'sample4'
3.      null        null          null
4.     'sample6'.  'sample7'.    'test done'

the data is guaranteed to have 5 elements in array if not null. Sample data above is with  3 elements for convenience.
It's a fairly large table which will grow over time.
Right now I am doing it using unnest and then row_number() over () and then joining them with id.
Is there any better way of doing it.

A: unnest() for a regular multidimensional array has the problem, that it expands all elements of all dimensions, not only the first one. So, there is no way for these types to get this done.
A possible workaround is casting the array into a JSON array. For JSON arrays this is not a problem:
demo:db<>fiddle
SELECT
    id,
    elems ->> 0 AS col1,
    elems ->> 1 AS col2,
    elems ->> 2 AS col3
FROM
    table_a,
    json_array_elements(array_to_json(arr)) elems

json_array_elements() expands the first dimension of the array, so the subarrays are moved into their one row. Afterwards simple get their elemens by their indexes.

The query above eliminates the NULL rows because of its comma notation (which, in fact, is the shortcut for INNER JOIN LATERAL in this case). This can be avoided using an LEFT OUTER JOIN LATERAL instead:
demo:db<>fiddle
SELECT
    id,
    elems ->> 0 AS col1,
    elems ->> 1 AS col2,
    elems ->> 2 AS col3
FROM
    table_a
LEFT JOIN LATERAL
    json_array_elements(array_to_json(arr)) elems ON TRUE

A: There is only one alternative - write procedural code in some PL language like Perl, Python or PLpgSQL. The code in Perl or Python will be more dynamic (you don't need special type), the code in PLpgSQL is easy to write. Probably procedural code should be faster for large arrays.
CREATE OR REPLACE FUNCTION unnest_to_columns3(a text[])
RETURNS TABLE(col1 text, col2 text, col3 text)
AS $$
DECLARE r text[];
BEGIN
  FOREACH r SLICE 1 IN ARRAY a
  LOOP
    col1 := r[1]; col2 := r[2]; col3 := r[3];
    RETURN NEXT;
  END LOOP;
END
$$ LANGUAGE plpgsql;

postgres=# SELECT * FROM unnest_to_columns3('{{a,b,c},{Ahoj,Nazdar,Servus}}');
+------+--------+--------+
| col1 |  col2  |  col3  |
+------+--------+--------+
| a    | b      | c      |
| Ahoj | Nazdar | Servus |
+------+--------+--------+
(2 rows)

Note: PostgreSQL has not a array of arrays - it has only multidimensional arrays.
It is much more practical work with arrays of records than multidimensional arrays. There is simple conversion between relations and arrays of this type.
create table foo(v1 text, v2 text, v3 text);
insert into foo values('ahoj','nazdar','servus');
insert into foo values('hi','greating',null);

postgres=# select array_agg(foo) from foo;
+-------------------------------------------+
|                 array_agg                 |
+-------------------------------------------+
| {"(ahoj,nazdar,servus)","(hi,greating,)"} |
+-------------------------------------------+
(1 row)

postgres=# select * from unnest('{"(ahoj,nazdar,servus)","(hi,greating,)"}'::foo[]);
+------+----------+--------+
|  v1  |    v2    |   v3   |
+------+----------+--------+
| ahoj | nazdar   | servus |
| hi   | greating | ∅      |
+------+----------+--------+
(2 rows)

Important note - relation (table) is not a array, and a arrays is not a relation (table).


text:
Q: Temp table drop in Sybase I have a jsp page which calls an SQL. This SQL creates a temp table and drops it at the end.
I see that the first time this code works properly but the second time it gives an error stating the temp table already exists.
This means the temp table is not getting dropped. Could you tell me what could be the reasons for it.

A: If you are creating the same table structure try this:
IF OBJECT_ID('tempdb..##tablename') IS NOT NULL
  TRUNCATE TABLE ##tablename
ELSE
  CREATE TABLE ##tablename(fields datatypes)

A: Why are you creating a table if you drop it at the end of the run?
Maybe you need a view that can be permanent instead of a temporary table.
Otherwise your drop query is wrong I think. Probably the table name is typed.


text:
Q: Can't get cookies with php curl from www.dramexchange.com I can get cookie from the others but not from this site www.dramexchange.com? Anybody know why? Maybe someone can do it with php and curl? :>
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.dramexchange.com");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output
curl_close ($ch);
unset($ch);

A: For whatever reason, http://www.dramexchange.com/index.html isn't sending back a Set-Cookie header.
When I open the page up in a browser, the site sets several cookies (mostly from ad.dramexchange.com), but since curl doesn't fetch every HTTP resource that appears in the page -- it only fetches the one you tell it to -- your request won't retrieve those cookies. You might try retrieving some resources from ad.dramexchange.com, or having wireshark open while you open the site in your browser. Any resource that sends back a cookie will have a Set-Cookie header in its HTTP response headers.

A: It seems to me that all the cookies sent from the public sections of this specific websites come from inline content (banners, web beacons, etc), and most likely are used only for tracking purposes.
If what you want to do is scrape content protected under the log-in, the server might send you a cookie once you issue a POST request to:
 login.aspx?ReturnUrl=www.dramexchange.com%2fDefault.aspx

Things you might need to do:

*

*Add the curl option CURLOPT_FOLLOWLOCATION in order follow redirects,

*there are three hidden fields in the login form, you may want to send them as well  with your userid and password

(firebug is your friend!)

A: From what I can tell, the URL you give doesn't actually return any cookies:
Cache-Control: private
Date: Sun, 09 Aug 2009 10:44:37 GMT
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Content-Encoding: gzip
Vary: Accept-Encoding
Transfer-Encoding: chunked

A: if you try to get cookie from a ordre website on you own website you can't doe it.
pls tell os what you own domain name is, its easyer to help you.


text:
Q: How I setup a background limit in CSS? I have a page with a searchable table, when someone use the text box to search for data the jQuery code will give live results "like google search suggestion" but inside the table itself.
When there is no text inside the search text box, the table show all data inside it. and the background work great on that, no matter how long the page is.
My problem is when someone search on specific thing and the table only show a few data like "1 or two" the background crop and a blank white background appear in the footer.
What am I doing wrong?
Here is my CSS:
body {
    margin: 30px 0 0 0;
    background: url(https://example.com/how/900.jpg) no-repeat center center fixed;
    background-size: cover;
    color: #000000;
    height: auto;
}

A: Add this as the first rule in your stylesheet
{
    html, body{ height:100%; }
}

Remove height: auto; from you body selector.

Since you did not "reset" your styles, the browser is using the default one, and sadly the default style for the body does not render it as at least the full height as the viewport allows

A: Change height: auto to height: 100vh will resolve your issue. Thanks


text:
Q: Responsive and Sticky Nav Bar I have a nav bar that is fixed to the top of the page when the width is under 768px.
When it is over 768px it starts at the bottom and when the user scroll past it it become stuck to the top.
Both of these instance work fine on their own, but when the browser is resized there are some issues when going from under 768px to above. (Going from 768 to below works fine.)
When I load the page in a browser size under 768px and then resize the window above that is where I run in to problems.
I would like for the nav bar to smoothly transition between states. (It works beautifuly when loading above 768px then reszing to under and reszing above - Ideally this is how I would like it to work when loaded below 768px.) Or as an alternative just have the nav bar be fixed to the top when moving from under 768px to above.
This is the link to the site.
This is my CSS
.header{
width: 100%;
min-width: 300px;
height: 100px;
padding: 0px;
background: black;
position: absolute;
bottom: 0px;
z-index: 99999;
-webkit-font-smoothing: subpixel-antialiased;
}

.header.fixed{
width: 100%;
position: fixed;
top: 0px;
height: 100px;
-webkit-font-smoothing: subpixel-antialiased;
}

@media only screen and (max-width: 768px){
.header{
width: 100%;
background: black;
position: fixed;
top: 0px;
height: 100px;
-webkit-font-smoothing: subpixel-antialiased;
}
}

and this is the Javascript
<script>

jQuery(document).ready(function() {
    var s = jQuery(".header");
    var pos = s.position();
    jQuery(window).scroll(function() {
        var windowpos = jQuery(window).scrollTop();
        if (windowpos >= pos.top) {
            s.addClass("fixed");
        } else {
            s.removeClass("fixed");
        }
    });
});
</script>

I have also tried below to no luck.
<script>
if ( jQuery(window).width() > 768) {
jQuery(document).ready(function() {
    var s = jQuery(".header");
    var pos = s.position();
    jQuery(window).scroll(function() {
        var windowpos = jQuery(window).scrollTop();
        if (windowpos >= pos.top) {
            s.addClass("fixed");
        } else {
            s.removeClass("fixed");
        }
    });
});
}</script>

<script>
jQuery(window).resize(function(){
if ( jQuery(window).width() > 768) {
jQuery(document).ready(function() {
    var s = jQuery(".header");
    var pos = s.position();
    jQuery(window).scroll(function() {
        var windowpos = jQuery(window).scrollTop();
        if (windowpos >= pos.top) {
            s.addClass("fixed");
        } else {
            s.removeClass("fixed");
        }
    });
});
}})</script>

A: try this:
function sticky_navigation() {
    var browserWidth = $(window).width();
    var scroll_top = $(window).scrollTop(); // our current vertical position from the top

    // if we've scrolled more than the page, change its position to fixed to stick to top,
    // otherwise change it back to relative
    if ((scroll_top > $('.header').height()) && (browserWidth > 720)) {
        $('.header').css({ 'position': 'fixed', 'top':0, 'z-index':999999, 'opacity': 0.9, 'box-shadow': '0px 3px 5px #393939' });
    } else {
        $('.header').css({ 'position': 'relative', 'opacity': 1, 'box-shadow': 'none' });
    }
};

// and run it again every time you scroll
$(window).scroll(function() {
     sticky_navigation();
});

// and run every time you resize to boot
$(window).resize(function() {
     sticky_navigation();
});


text:
Q: How do I count the number of Values inserted in a table in SQL Server? I have a table like below:
DirectoryName    FileName
    A               Ab.pdf
    B               bc.mp3
    C               cd.doc
    A               de.pdf
    F               fg.pdf
    A               kl.pdf

The output should be like this:
Directory
 A - 3
 B - 1
 C - 1
 F - 1

And same with FileName.
Thanks

A: Simple Solution is :
select distinct DirectoryName, count(FileName)
from tableName group by DirectoryName

Or you can use partition by over DirectoryName
select distinct DirectoryName, COUNT(FileName)
over(Partition by DirectoryName)
Count from tableName

Hope this will work for you.


text:
Q: Conditional ISNUMBER Statement in Excel I'm looking for a way to use an ISNUMBER statement but to change the value depending if it was ever true in another row
Take this example:
   A.       B.       C
Device   Status   Results
 dev1.   Trusted   True
 dev1.     -       False
 dev2.     -       False
 dev1.   Trusted   True
 dev3.     -       False
 dev3.   Trusted   True

dev1 appears trusted in the first row so the result of the ISNUMBER function appears as True
In the second row, the information is missing so the result appears as False
I would like to be able to find a function stating that as long as a device has been trusted in any row, the result will always be True even if the information is missing
Basically, the previous example would show as:
   A.       B.       C
Device   Status   Results
 dev1.   Trusted   True
 dev1.     -       True
 dev2.     -       False
 dev1.   Trusted   True
 dev3.     -       True
 dev3.   Trusted   True

C2=ISNUMBER(SEARCH("Trusted", B2))
C3=ISNUMBER(SEARCH("Trusted", B3))
...

I use an ISNUMBER function because I have a string of characters with the word trusted in it, this string can change but if the device is trusted, the word "trusted" will always appear somewhere in the cell.

A: Well, sure this can be reduced, but it works...
You can take each apart to see what is happening.

Columns F2 and G2 just produce a list of "valid" devices...


text:
Q: create matrix based on another matrix contain index of element I have a matrix that contains indices of column ides to the element of matrix I want create it
>  index
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    1    2    5
    [3,]    1    3    4
    [4,]    1    3    5
    [5,]    1    4    5
    [6,]    2    3    5
    [7,]    3    4    5

example first row have the column id 1 ,2 , 3  that set to it value 1
second row have the column id 1 , 2 , 5 that set to it value 1
now I want to create the following matrix:

     a1 a2 a3  a4 a5
[1,]  1  1  1  0  0
[2,]  1  1  0  0  1
[3,]  1  0  1  1  0
[4,]  1  0  1  0  1
[5,]  1  0  0  1  1
[6,]  0  1  1  0  1
[7,]  0  0  1  1  1

Data
index <- rbind(c(1,2,3), c(1,2,5), c(1,3,4), c(1,3,5), c(1,4,5), c(2,3,5), c(3,4,5))

A: Here is an extremely fast and efficient base R method mentioned in the comments using matrix indexing.
# construct 0 matrix with correct dimensions
newMat <- matrix(0L, nrow(myMat), max(myMat))

# fill in matrix using matrix indexing
newMat[cbind(c(row(myMat)), c(myMat))] <- 1L

This returns
newMat
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    0    0
[2,]    1    1    0    0    1
[3,]    1    0    1    1    0
[4,]    1    0    1    0    1
[5,]    1    0    0    1    1
[6,]    0    1    1    0    1
[7,]    0    0    1    1    1

data
myMat <-
structure(c(1L, 1L, 1L, 1L, 1L, 2L, 3L, 2L, 2L, 3L, 3L, 4L, 3L,
4L, 3L, 5L, 4L, 5L, 5L, 5L, 5L), .Dim = c(7L, 3L))

A: Here is a solution in base R:
# Your sample matrix
m.idx <- matrix(c(1,1,1,1,1,2,3,2,2,3,3,4,3,4,3,5,4,5,5,5,5), ncol = 3);

# Construct empty matrix of the right dims
m.val <- matrix(0, nrow = nrow(m.idx), ncol = max(m.idx));

for (i in 1:nrow(m.idx)) m.val[i, m.idx[i, ]] <- 1;
m.val;
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    1    1    0    0
#[2,]    1    1    0    0    1
#[3,]    1    0    1    1    0
#[4,]    1    0    1    0    1
#[5,]    1    0    0    1    1
#[6,]    0    1    1    0    1
#[7,]    0    0    1    1    1

Update
Please see below for benchmarking results of all methods presented here. I've wrapped all methods inside functions
# The original matrix with indices
m.idx <- matrix(c(1,1,1,1,1,2,3,2,2,3,3,4,3,4,3,5,4,5,5,5,5), ncol = 3);

# For loop method
method.for_loop <- function(m) {
    m.val <- matrix(0, nrow = nrow(m), ncol = max(m));
    for (i in 1:nrow(m.idx)) m.val[i, m.idx[i, ]] <- 1;
    return(m.val);
}

# lapply method (@Headpoint)
method.lapply <- function(m) {
    m.val <- as.data.frame(matrix(0, nrow = nrow(m), ncol = max(m)));
    invisible(lapply(1:nrow(m),
                   function(x) m.val[x,][m[x,]] <<- 1));
    return(m.val);
}

# Direct indexing method (@lmo)
method.indexing <- function(m) {
    m.val <- matrix(0L, nrow(m.idx), max(m.idx));
    m.val[cbind(c(row(m.idx)), c(m.idx))] <- 1L;
    return(m.val);
}

# tidyr/dplyr method (@CPak)
method.dplyr_tidyr <- function(m) {
    as.data.frame(m) %>%
      gather() %>%                   # wide-to-long format
      group_by(key) %>%
      mutate(rn = row_number()) %>%  # add unique row_id per `key` group
      mutate(newval = 1) %>%         # fill in `existing` with this value
      ungroup() %>%                  # ungroup and unselect `key` group
      select(-key) %>%
      spread(value, newval, fill=0) %>%  # long-to-wide format
                                         # fill in `non-existing` with `0`
      select(-rn) %>%                    # unselect row_id column
      rename_all(funs(paste0("a", .)))   # rename columns
}

The results from microbenchmark are given below.
library(microbenchmark);
library(tidyr);
library(dplyr);
library(magrittr);

res <- microbenchmark(
    for_loop = method.for_loop(m.idx),
    lapply = method.lapply(m.idx),
    indexing = method.indexing(m.idx),
    dplyr_tidyr = method.dplyr_tidyr(m.idx),
    times = 1000L
)
print(res);
#    Unit: microseconds
#        expr       min         lq        mean    median        uq       max
#    for_loop     6.796     9.5405    16.89643    13.497    20.445    96.537
#      lapply  1315.765  1441.5990  1696.74392  1518.256  1675.027 66181.880
#    indexing     5.695     8.1450    20.49116    14.918    20.094  3139.946
# dplyr_tidyr 18777.669 20525.8095 22225.51936 21647.120 23215.714 84791.858

Conclusion: The methods using a for loop or direct indexing are tied and the fastest. lapply is second, the tidyr/dplyr method the slowest (but note the large increases in runtime).

A: No for loop, but didn't really check if it is faster.
index <- matrix(c(1,1,1,1,1,2,3,2,2,3,3,4,3,4,3,5,4,5,5,5,5),
                                   ncol = 3)
df <- as.data.frame(matrix(0, nrow = 7, ncol = 5))

invisible(lapply(1:nrow(index),
                   function(x) df[x,][index[x,]] <<- 1))
df
# V1 V2 V3 V4 V5
# 1  1  1  1  0  0
# 2  1  1  0  0  1
# 3  1  0  1  1  0
# 4  1  0  1  0  1
# 5  1  0  0  1  1
# 6  0  1  1  0  1
# 7  0  0  1  1  1

A: You can do this with a combination of dplyr and tidyr
Your data
df <- read.table(text="1    2    3
1    2    5
1    3    4
1    3    5
1    4    5
2    3    5
3    4    5", header=FALSE)

Solution: some of these steps are to clean up the output
df %>%
  gather() %>%                   # wide-to-long format
  group_by(key) %>%
  mutate(rn = row_number()) %>%  # add unique row_id per `key` group
  mutate(newval = 1) %>%         # fill in `existing` with this value
  ungroup() %>%                  # ungroup and unselect `key` group
  select(-key) %>%
  spread(value, newval, fill=0) %>%  # long-to-wide format
                                     # fill in `non-existing` with `0`
  select(-rn) %>%                    # unselect row_id column
  rename_all(funs(paste0("a", .)))   # rename columns

Output
# A tibble: 7 x 5
     a1    a2    a3    a4    a5
* <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     1     1     0     0
2     1     1     0     0     1
3     1     0     1     1     0
4     1     0     1     0     1
5     1     0     0     1     1
6     0     1     1     0     1
7     0     0     1     1     1


text:
Q: How to handle SIGTERM when received from subprocess.Popen on workers in multiprocessing.Processs without terminating process tree I have a python script which creates multiprocessing processes and each process worker uses subprocess.Popen to run some database operations using a linux database utility. Sometimes the Data Base utility sends a SIGTERM. How do I handle the SIGTERM coming from a linux command, without terminating the whole process tree and also the current process worker?
My code so far:
import multiprocessing as mp
import subprocess
import shlex
import signal

class SigTermError(Exception):
    pass

def sig_handler(sig, frame):
    raise SigTermError( ("Received Signal:{} "
                     "on line:{} in file:{}")
                    .format(str(sig)
                            , str(frame.f_lineno)
                            , frame.f_code.co_filename))

def do_something_to_hanlde_sigterm():
    print('Handled SIGTERM')

def move_on():
    print('Moving on')

def run_shell_command(cmd_string):
    """ Run a shell command"""
    original_sigterm_handler = signal.getsignal(signal.SIGTERM)
    signal.signal(signal.SIGTERM, sig_handler)
    args = shlex.split(cmd_string)

    # I want to handle the SIGTERM and if the cmd_string sends a SIGTERM then return a ret_code of -99
    try:
        p = subprocess.Popen(args, shell=False
                             , stdout=subprocess.PIPE
                             , stderr=subprocess.PIPE
                             )

        out, err = p.communicate() # This fails if the cmd_string sends a SIGTERM

        ret_code = p.returncode
    except SigTermError:
        ret_code = -99
    finally:
        signal.signal(signal.SIGTERM, original_sigterm_handler)
        return ret_code

def worker(arg1, arg2):
    """ Run db_command with 2 arguments. """
    cmd_string = 'db_command -parameter1 {arg1} -parameter2 {arg2}'.format(arg1=arg1,arg2=arg2)
    func_return = run_shell_command(cmd_string)  # The whole process tree terminates if subprocess sends sigterm
    if func_return == -99:
        do_something_to_hanlde_sigterm()
    else:
        move_on()

if __name__ == '__main__':

    processes = [mp.Process(target=worker, args=(x, x*x)) for x in list(range(4))]

    for p in processes:
        p.start()

    for p in processes:
        p.join()

    print('All Done')


text:
Q: How To check Windows device is rooted/jailbrake or not programatically? Since I am new to Windows Phone Technology, I want to programatically find in my application that windows device is rooted/jailbrake or not. I found many links but it seems like no way for finding rooted windows device programatically. So is there any way to find rooted/jailbreak windows device programatically any API available for this ? Can anyone help me ?
Thanks

A: Rooting and/or jailbreaking is not officially supported by Microsoft and therefore there is no official way for you to check if your application is running on such device.
In principle, you could check that, but that check would involve adding stuff to your application that would not pass the certification which means that you can run that application only on jailbroken device.
Which then means that you don't need to check at all since you already know that you are running on such hardware.


text:
Q: MYSQL Query error WHERE id = $id I'm creating and then editing a row in a table, however my edit mysql query in php is giving me an error that I can't figure out. Any help?
The creation query:
$query = "INSERT INTO timelines (
id, event_name, event_date, date_created, attendee_count, attendee_names, maximum_attendees, creator_id, creator_name, price, thumbnail
) VALUES (
'{$timelineID}', '{$event_name}', '{$event_date}', '{$date_created}', '{$attendee_count}', '{$attendee_names}', '{$maximum_attendees}', '{$creator_id}', '{$creator_name}', '{$price}', '{$thumbnail}'
)";

The edit query:
$query = "UPDATE timelines SET
event_name = '{$event_name}',
event_date = '{$event_date}',
maximum_attendees = '{$maximum_attendees}',
price = '{$price}',
thumbnail = '{$thumbnail}',
WHERE id = {$timelineID}";

Error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'WHERE id =' at line 8

A: you have an extra comma before the WHERE clause. just remove it and it will work fine.
thumbnail = '{$thumbnail}',
                          ^ here
WHERE ...

final query,
$query = "UPDATE timelines SET
event_name = '{$event_name}',
event_date = '{$event_date}',
maximum_attendees = '{$maximum_attendees}',
price = '{$price}',
thumbnail = '{$thumbnail}'
WHERE id = {$timelineID}";

Your query is vulnerable with SQL INJECTION, please read the article below to learn how to protect from it.

*

*How can I prevent SQL injection in PHP?


text:
Q: Coverting DateTime property to string format from List ASP.NET In my ASP.NET MVC web application Im assigning some data from the database to a list.
There in the database example like start_date is stored as DateTime property.
So when it comes to the view, I just want to show the dd mmm yyyy format.
What I currently did was, I got all the data I wanted from the database and again used foreach condition and converted the DateTime to string to another property I created on the model.
It worked when there was one record to show. But when It comes to the list, it applied to the first record only. Others becomes null.
Can anyone suggest a better solution for this.
This is my current code
IEnumerable < MyTasks > myTasks = (from t in db.TaskMain
                                    join c in db.Customer on t.Customer_Id equals c.Id
                                    join s in db.Services on t.Service_Id equals s.Id
                                    join step in db.ServiceSteps on t.Task_Step_Id equals step.Id
                                    join state in db.ServiceState on t.Task_State_Id equals state.Id
                                    where t.CreateBy == UserId && t.Status == true && t.Task_Step_Id != 12
                                    select new MyTasks
                                    {
                                        Id = t.Id,
                                        Customer_Name = c.Name,
                                        Service = s.Service_NameEng,
                                        Current_Step = step.Service_Step_Primary_Language,
                                        End_Date = t.Service_End_Date,
                                        Start_Date = t.CreatedDate,
                                        Task_Number = t.TaskNumber,
                                        Task_State = state.Service_State_Name
                                    }).ToList();

foreach(var item in myTasks)
    {
        myTasks.First().Start_Date_Formated = item.Start_Date.ToString("dd MMM yyyy");
        myTasks.First().End_Date_Formated = item.End_Date.ToString("dd MMM yyyy");
    }

This is the result

A: you just need to select the format you wanted like this
  IEnumerable<MyTasks> myTasks = (from t in db.TaskMain
                                        join c in db.Customer on t.Customer_Id equals c.Id
                                        join s in db.Services on t.Service_Id equals s.Id
                                        join step in db.ServiceSteps on t.Task_Step_Id equals step.Id
                                        join state in db.ServiceState on t.Task_State_Id equals state.Id
                                        where t.CreateBy == UserId && t.Status == true && t.Task_Step_Id != 12
                                        select new MyTasks
                                        {
                                            Id = t.Id,
                                            Customer_Name = c.Name,
                                            Service = s.Service_NameEng,
                                    End_Date = t.Service_End_Date,
                                    Start_Date = t.CreatedDate,
                                            Current_Step = step.Service_Step_Primary_Language,
                                            End_Date_Formated = t.Service_End_Date.ToString("dd MMM yyyy"),
                                            Start_Date_Formated = t.CreatedDate.ToString("dd MMM yyyy"),
                                            Task_Number = t.TaskNumber,
                                            Task_State = state.Service_State_Name
                                        }).ToList();

but if the dates is nullable value then you need to check so the code become like this
   IEnumerable<MyTasks> myTasks = (from t in db.TaskMain
                                    join c in db.Customer on t.Customer_Id equals c.Id
                                    join s in db.Services on t.Service_Id equals s.Id
                                    join step in db.ServiceSteps on t.Task_Step_Id equals step.Id
                                    join state in db.ServiceState on t.Task_State_Id equals state.Id
                                    where t.CreateBy == UserId && t.Status == true && t.Task_Step_Id != 12
                                    select new MyTasks
                                    {
                                        Id = t.Id,
                                        Customer_Name = c.Name,
                                        Service = s.Service_NameEng,
                                    End_Date = t.Service_End_Date,
                                    Start_Date = t.CreatedDate,
                                        Current_Step = step.Service_Step_Primary_Language,
                                        End_Date_Formated = t.Service_End_Date==null? null: t.Service_End_Date.ToString("dd MMM yyyy"),
                                        Start_Date_Formated = t.CreatedDate==null?null: t.CreatedDate.ToString("dd MMM yyyy"),
                                        Task_Number = t.TaskNumber,
                                        Task_State = state.Service_State_Name
                                    }).ToList();

and you can set a default value for the date if it is null like "N/A"
 End_Date_Formated = t.Service_End_Date == null ? "N/A" : t.Service_End_Date.ToString("dd MMM yyyy"),
 Start_Date_Formated = t.CreatedDate == null ? "N/A" : t.CreatedDate.ToString("dd MMM yyyy"),

But you should comment this code as it only changes the first object and after the loop ends you will find that it takes its value from last item on the "myTasks"
 //foreach (var item in myTasks)
        //{
        //    myTasks.First().Start_Date_Formated = item.Start_Date.ToString("dd MMM yyyy");
        //    myTasks.First().End_Date_Formated = item.End_Date.ToString("dd MMM yyyy");
        //}


text:
Q: What is the correct method of finding the leading order behavior of a function in a given limit? I am kind of confused about finding the correct leading order behavior of a function. Example: If I want to understand the behavior of the following function
$$f(x)=\coth(x)-\frac{1}{x}$$
I can write it as (after some algebraic manipulations)
$$f(x)= 1+ \frac{2}{e^{2x}-1} - \frac{1}{x}$$
I can series expand some of the terms to have
$$f(x)= 1+ \frac{2}{2x+2x^2+\frac{4}{3}x^3+...} -\frac{1}{x}$$
Now, I want the leading order behavior of this function in the limit $x \rightarrow 0$. The correct answer is that it goes as $\frac{x}{3}$ in this limit. And, $f(0) = 0$. But I do not know how ?.
My confusion is general and I want to know, in general, how should I approach a problem like this. What is the best way to expand a function like this. I am a physics student so please excuse my ignorance.
Thanks

A: HINT:
Write the hyperbolic cotangent as
$$\coth(x)=\frac{1+\frac12x^2+O(x^4)}{x(1+\frac16x^2+O(x^4))}=\frac1x\left(\frac{1+\frac12x^2+O(x^4)}{1+\frac16x^2+O(x^4)}\right)\tag 1$$

SPOILER ALERT Scroll over the highlighted area to reveal solution

Starting with the right-hand side of $(1)$, we have $$\frac1x\left(\frac{1+\frac12x^2+O(x^4)}{1+\frac16x^2+O(x^4)}\right)=\frac1x\left(1+\frac13x^2+O(x^4)\right)$$Finally, we have $$\coth(x)-\frac1x=\frac13x+O(x^3)$$And we are done!

A: Differentiating (and, optionally, taking advantage of the fact that $\tanh x$ is odd) gives that
$$\tanh x = x - \frac{x^3}{3} + O(x^5) = x\left(1 - \frac{x^2}{3} + O(x^4)\right),$$
and so
$$\coth x = \frac{1}{\tanh x} = \frac{1}{x} \left(1 + \frac{x^2}{3} + O(x^4)\right) = \frac{1}{x} + \frac{x}{3} + O(x^3) .$$
Rearranging gives
$$\color{#bf0000}{\boxed{\coth x - \frac{1}{x} = \frac{x}{3} + O(x^3)}}.$$


text:
Q: Can somebody help me with tenses? I have a problem.
I don't understand what does this "result" should look like in present perfect, because when I see in movie that a character says: I forgot it. The result is that he doesn't remember it or maybe he didn't do something. So how should I interpret it?
Three examples:
1a) "Aaaaaah! I forgot to buy something for my friend"
Interpretation: normal conversation between two characters (my interpretation is that she use "PAST" simple because she wanted to give an information, even if the result is that she doesn't have this thing)
OR
1b) "Aaaaah! I've forgotten to buy something for my friend"
The result is that he doesn't have this thing he had to buy for his friend

2a) "Hey Tom. There was an apple in the fridge, what happened to it?"
Tom: "Yea I ate it."
Interpretation: Even if the apple wasn't in fridge "result" we are informing him, or I guess it is supposed to be some kind of informal thing. Or maybe this is some kind of emphasis?
vs.
2b) "Hey, Tom. There was an apple in the fridge, what has happened to it?
I've eaten it"
Well, he ate this apple and the result is that there is no apple in the fridge.

3a) "I haven't delivered the package."
The result is that he is holding that package, or maybe some kind of info.
vs
3b) "I didn't deliver the package."
He just inform that he didn't deliver the package, maybe he hold this package but we don't care about result, we care about if he did it in past or not.

A: The simple past means something which occurred in the past. The present perfect means something which occurred in the past, with emphasis on "all the way up to the present moment, including now." However, this topic is complicated, and written about at length in other posts.

*

*"Aaaaaah I forgot, to buy something for my friend" OR "Aaaaah I've forgotten, to buy something for my friend"

In just this example #1, the past tense is preferable because it's simpler, and yet conveys the same meaning. Refer to further explanations below for #2 and #3, they may also apply here...

*"Hey Tom.There was an apple in the fridge, what happened to it? Yea I ate it." OR "Hey Tom. There was an apple in the fridge., what has happened to him ? I've eaten it"

Both are acceptable, however in most cases the past tense is preferable. Why complicate things with the present perfect?
A reason would be if you wanted to strongly connect the past event with the present moment. "I've eaten it, and now I feel sick." That's a valid usage.
If there isn't more to tell, and it's only "I ate the apple", then use the past tense.
The "result" on both tenses is that the apple is gone.

*"I haven't delivered the package ...." OR "I didn't deliver the package ..."

The present perfect "haven't" would make sense if there is more to the story in the present tense, such as "I haven't delivered the package yet, but I am going to this afternoon."
The simple past would be better for "I didn't deliver the package. Period. And I'm not going to." The story was already completed, in the past.
Therefore, each choice has a different meaning and both are valid options.
For all of these, you asked about the "result". And I think basically the "result" is the same, regardless of tense. The apple is gone. The package was not delivered.


text:
Q: Modify OctoberCMS Laravel Plugin to Disable Form Username Change I'm using OctoberCMS based on Laravel with the official Users plugin.
How can I modify this plugin to Disable or Deny Username Change?
The form can easily be hacked to allow change.
Plugin
Here is the file on GitHub I need to edit: Account.php
In the onUpdate() function, where it says $user->fill, it is saving all input fields.
I need to deny the username field in the function or with the validator.
public function onUpdate()
{
    if (!$user = $this->user()) {
        return;
    }

    $user->fill(post());
    $user->save();

OctoberCMS
I set Login attribute to Username.

User Update Details
The User Update Page displays the form inputs a user can change:
Full Name is a column in the Database called surname that I don't use.
Username is the column username, the one I use, but it's not included on the default form.

Though someone can add the username field in the browser just by inspect element, edit the HTML:

    Username
    <input name="username" type="text" id="accountUsername" value="Desired Username">

Submit and it will change the name and update the username column in the database.

A: You could extend the User model with something like this:
\RainLab\User\Models\User::extend(function($model) {

    $model->bindEvent('model.beforeUpdate', function() use ($model) {

        if ($model->isDirty('username')) {

            throw new \ValidationException(['username' => 'Sorry!...']);

        }

    });

});

The above code will have a global impact, if defined in a registration method, preventing the username from ever being changed. To restrict it only to the front-end, consider using an expression like if (!App::runningInBackend()) { /* ... */ }. Otherwise you could simply listen to the event on that page only, inside the onInit page code function.


text:
Q: ScrollViewer поверх дочернего ScrollViewer Глобальный скролл прокручивается пока мышкой не попадаешь на область UserContol'a, у которого свой горизонтальный скролл. В итоге чтобы увидеть содержимое всего UserControl нужно докрутить наведя мышкой.
Вопрос: как прокручивать глобальный скролл вне зависимости от того в какой части указатель мыши?
(Еще было бы замечательно, если ваш ответ был применим для MVVM)

<catel:DataWindow x:Class="VFL_catel.Views.MainWindow"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:catel="http://catel.codeplex.com"
                  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                  xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
    <Grid Height="auto"
          Background="#F6F8F8">
        <ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="ScrollViewerVerticalGlobal">
            <WrapPanel Orientation="Horizontal">
                <GroupBox Header="Турнирная таблица"
                          FontWeight="Bold">
                   <!--  Содержимое -->
                </GroupBox>
                <GroupBox Header="Серии"
                          FontWeight="Bold"
                          Visibility="{Binding ElementName=series, Path=IsChecked, Converter={catel:BooleanToCollapsingVisibilityConverter}}"
                          Background="#F6F8F8">
                        <!--  Содержимое -->

                </GroupBox>
                <GroupBox Header="Подробная информация"
                          MinWidth="400"
                          FontWeight="Bold"
                          Background="#F6F8F8">
                    <ScrollViewer HorizontalScrollBarVisibility="Auto">
                        <Grid>
                           <!--  Содержимое -->
                        </Grid>
                    </ScrollViewer>
                </GroupBox>
            </WrapPanel>
        </ScrollViewer>
    </Grid>
</catel:DataWindow>

Пробовал через Interaction, но тщетно.
<i:Interaction.Triggers>
     <i:EventTrigger EventName="PreviewMouseWheel"
                                            SourceName="ScrollViewerVerticalGlobal"
                                            SourceObject="{Binding ElementName=ScrollViewerVerticalGlobal}">
                                <catel:EventToCommand Command="{Binding ScrollHorizontalMouseWheel}"
                                                      DisableAssociatedObjectOnCannotExecute="False"
                                                      PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>

A: Хорошо. Воспользуемся системой маршрутизируемых событий WPF.
Добавьте обработчик у верхнего ScrollViewer:
<ScrollViewer VerticalScrollBarVisibility="Auto"
              x:Name="ScrollViewerVerticalGlobal"
              PreviewMouseWheel="OnPreviewMouseWheel">

В обработчике напишите:
private void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    ScrollViewerVerticalGlobal.ScrollToVerticalOffset(
        ScrollViewerVerticalGlobal.VerticalOffset - e.Delta);
    e.Handled = true;
}

A: Как вариант через рефлексию, команду и триггер.
Оговорка, использую фреймворк catel, у которого есть встроенный менеджер, но т.к. все примерно похоже переложить на свой фреймворк должно быть не трудно.
Разметка XAML
<ScrollViewer VerticalScrollBarVisibility="Auto"
                                      x:Name="ScrollViewerVerticalGlobal">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseWheel"
            <catel:EventToCommand Command="{Binding ScrollVerticalMouseWheel}"
                                  PassEventArgsToCommand="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <!-- content -->
</ScrollViewer>

Команда обработчик
public Command<MouseWheelEventArgs> ScrollVerticalMouseWheel { get; private set; }
private void OnScrollVerticalMouseWheelExecute(MouseWheelEventArgs eventArgs)
{
    var scrollField = _view.GetType().GetFieldEx("ScrollViewerVerticalGlobal");
    var scrollbar = scrollField.GetValue(_view) as ScrollViewer;
    if (scrollbar == null) return;
    scrollbar.ScrollToVerticalOffset(scrollbar.VerticalOffset - eventArgs.Delta);
    eventArgs.Handled = true;
}

Где _view мой  View полученный через сервисы фреймворка.
Пример для catel.
Создаем объект команды в конструкторе ViewModel
ScrollVerticalMouseWheel = new Command<MouseWheelEventArgs>(OnScrollVerticalMouseWheelExecute);


text:
Q: Userform not triggering Initialize or Activate event I kept a userform control button in my worksheet to fire up a macro, which in turn shows a user form, In the form I wish to display the opened files in checkboxes(using the Workbooks collection).I wish to run a macro that performs action for the user selected files only.
So for the button in my worksheet,  I have assigned the following macro
Private Sub Button2_Click()

    Load MyForm

    MyForm.Show

End Sub

At first I kept the below code in the module where my macro sub is there.Since it's not working, I right clicked on user form and selected view code and kept the below code there.But still it's showing the same static designed user form, not the dynamic.I kept breakpoint at both load Myform and MYform.Show() and I stepped through code.It never went into intialize or activate method at all.
Private Sub MyForm_Activate()
  'for checking the whether this method is called or not I am trying to change caption
  MyForm.LabelSelectFile.Caption = "dhfdfldkfldzjf;zdfkz;d"

  Dim mymyWorkBook As Workbook
  For Each mymyWorkBook In Workbooks
     'code for creating checkbox based on the file name displayed by the workbook collection
  Next mymyWorkBook
End Sub

I can't understand why that event is not getting triggered.Please help me to overcome this.Thanks in advance

A: Even though the name of the form is MyForm, you still need to use userform.
'~~> in your worksheet
Private Sub Button2_Click()
    MyForm.Show
End Sub

'~~> In the userform code area
Private Sub UserForm_Initialize()
    '~~> Your code here
End Sub

or
Private Sub UserForm_Activate()

End Sub

The best is to always select the event from the drop down, rather than typing it


text:
Q: Need to clear data after update or app will not work After I download my app from the play store and go to Settings -> Apps -> myApp -> Storage, it will have 4.59 mb of data for some reason. Even if i haven't opened the app at all. I have to hit clear data or my app will not run. Once I do clear the data it runs fine, until the next update, then I have to do it again.
Logcat says
audit: type=1701 audit(1560151257.983:14744): auid=4294967295 uid=10521 gid=10521 ses=4294967295 subj=u:r:untrusted_app:s0:c9,c258,c512,c768 pid=31263 comm="UnityMain" exe="/system/bin/app_process64" sig=11

one time logcat said this instead
/AndroidRuntime: FATAL EXCEPTION: UnityMain
    Process: com.myord.myapp, PID: 28413
    java.lang.Error: signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 000000000000012f
    Build fingerprint: 'samsung/crownqltesq/crownqltesq:9/PPR1.180610.011/N960USQS1CSD1:user/release-keys'
    Revision: '11'
    pid: 28413, tid: 28431, name: UnityMain  >>> com.myorg.myapp <<<
        x0   0000000000000000  x1   0000000000000000  x2   0000007b48d66be8  x3   0000000000000000
        x4   0000007b48d66b28  x5   0000000000000004  x6   0000007b59722d80  x7   00000000013e61f7
        x8   0000000000000001  x9   7a0a23fc6ec12b11  x10  0000007b44beb000  x11  0000007b4552407c
        x12  00000000000005e7  x13  0000000000000001  x14  0000000000000008  x15  aaaaaaaaaaaaaaab
        x16  0000007b464635e0  x17  0000007be651da20  x18  0000000000000001  x19  0000007b46510000
        x20  0000000000000000  x21  0000000000000000  x22  0000007b4675dab8  x23  0000007b46514000
        x24  0000007b45fc35d8  x25  0000007b467402d8  x26  0000007b46020104  x27  0000007b45fbeef7
        x28  0000007b48d67430  x29  0000007b48d66c50  x30  0000007b45841454
        sp   0000007b48d66c20  pc   0000007b45841468  pstate 0000000060000000

        at [vdso].(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.(:0)
        at libil2cpp.il2cpp_init(il2cpp_init:44)
        at libunity.(:0)
        at libunity.(:0)
        at libunity.(:0)
        at libunity.(:0)
        at base.(:0)

i also see this alot at the end
Channel is unrecoverably broken and will be disposed!

A: Add this in manifest.
android:fullBackupContent="false"

This worked for me!!!


text:
Q: Call CollectionViewCell item from IBAction I would like to add actions to a button in a toolbar I added to a collectionView.
The toolbar has 4 share buttons but some reason, I'm not able to call the collectionView items properly.
- (IBAction)share:(id)sender
{
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    [_collectionView insertItemsAtIndexPaths:@[newIndexPath]];
    NSArray *selectedIndexPaths = [_collectionView indexPathsForSelectedItems];
    NSMutableArray *selectedTexts = [NSMutableArray array];
    for (NSIndexPath *indexPath in selectedIndexPaths) {
        NSArray *section = videoArray[indexPath.section];
        NSString *text = section[indexPath.row];
        [selectedTexts addObject:text];
        SLComposeViewController *tweetSheet = [SLComposeViewController
            composeViewControllerForServiceType:SLServiceTypeTwitter];
        [tweetSheet setInitialText:text];
        [self presentViewController:tweetSheet animated:YES completion:nil];
        NSLog(@"%@", text);
    }
    // NSLog(@"The share works fine");
}

This returns an error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 0.  The number of items contained in an existing section after the update (3) must be equal to the number of items contained in that section before the update (3), plus or minus the number of items inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'

A: When you call -insertItemsAtIndexPaths: you should take care about dataSource methods as well because UICollectionView asks them again about updated items. In your case you don't return proper numbers of updated items count in section 0 and that leads to the error you get.
Usually you have some source of your UICollectionView and you should update it as well

A: You have to update your property which contains your items. Check numberOfRowsInSection: method
EDIT:
To share the text of the appropriate collection view cells you no need to insert any cells into existing collection view. try this code
- (IBAction)share:(id)sender
{
    NSArray *selectedIndexPaths = [_collectionView indexPathsForSelectedItems];
    NSMutableArray *selectedTexts = [NSMutableArray array];
    for (NSIndexPath *indexPath in selectedIndexPaths) {
        NSArray *section = videoArray[indexPath.section];
        NSString *text = section[indexPath.row];
        [selectedTexts addObject:text];
    }

    SLComposeViewController *tweetSheet = [SLComposeViewController
                                           composeViewControllerForServiceType:SLServiceTypeTwitter];
    NSString *textToShare = [selectedTexts componentsJoinedByString:@" "];
    [tweetSheet setInitialText:textToShare];
    [self presentViewController:tweetSheet animated:YES completion:nil];
    NSLog(@"%@", textToShare);
}


text:
Q: Converting ordered dictionary into new columns in Python Pandas In my dataframe, some of the columns are in OrderedDictionary format. How could I convert them into new columns (without knowing which columns contain OrderedDictionary and the elements in OrderedDictionary)
Example column:
inventors
[OrderedDict([('@sequence', '001'), ('@app-type', 'applicant'), ('@designation', 'us-only'), ('addressbook', OrderedDict([('last-name', 'Nahm'), ('first-name', 'Seung Hoon'), ('address', OrderedDict([('city', 'Daejeon'), ('country', 'KR')]))])), ('residence', OrderedDict([('country', 'KR')]))]), OrderedDict([('@sequence', '002'), ('@app-type', 'applicant'), ('@designation', 'us-only'), ('addressbook', OrderedDict([('last-name', 'Jang'), ('first-name', 'Hoon Sik'), ('address', OrderedDict([('city', 'Daegu'), ('country', 'KR')]))])), ('residence', OrderedDict([('country', 'KR')]))])]

I want to convert it to the following dataframe (did not write all of the columns):
@sequence1  @app_type1   @designation1 @last_name1 @first_name1 ....
001         applicant    us_only        Nahm       Seung Hoon

In this example, last_name and first_name is coming from another nested dictionary. And in the data, I don't know which columns contain OrderedDictonary, for the sake of the simplicty, I just included one column from the dataset which is inventors

A: Have you considered the pandas from_dict() function?
# Create example dict
import collections
inventors = collections.OrderedDict()
inventors['@sequence'] =  "001"
inventors['@app-type'] =  "applicant"
inventors['@designation'] =  "us-only"
inventors['last-name'] =  "Nahm"
inventors['first-name'] =  "Seung Hoon"

# Import pandas to use from_dict function
import pandas as pd

# Use from_dict() function; include orient='index' for now to avoid index error
df = pd.DataFrame.from_dict(inventors, orient='index')

# Transpose for final output
df.T


text:
Q: How to retrieve an image from a database using a link? I have made a page which saves the image in database as a tiny blob.
Now I want to retrieve it from there in a webpage by mouse over a text "picture".
When I bring my mouse over text "picture" it should show me the picture.
//here is my first page which save the image
<< ? php require_once('../../Connections/pictureinsertion.php'); ? >
<< ? php
if (!function_exists("GetSQLValueString")) {
  function GetSQLValueString($theValue, $theType, $theDefinedValue = "",
    $theNotDefinedValue = "") {
    if (PHP_VERSION < 6) {
      $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
    }

    $theValue = function_exists("mysql_real_escape_string") ?
      mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

    switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'".$theValue.
      "'": "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'".$theValue.
      "'": "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
    }
    return $theValue;
  }
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction. = "?".htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "picturfname")) {
  $insertSQL = sprintf("INSERT INTO pictures (photo) VALUES (%s)",
    GetSQLValueString($_POST['image'], "double"));

  mysql_select_db($database_pictureinsertion, $pictureinsertion);
  $Result1 = mysql_query($insertSQL, $pictureinsertion) or die(mysql_error());
}

mysql_select_db($database_pictureinsertion, $pictureinsertion);
$query_pictureinsertion = "SELECT * FROM pictures";
$pictureinsertion = mysql_query($query_pictureinsertion, $pictureinsertion) or die(
  mysql_error());
$row_pictureinsertion = mysql_fetch_assoc($pictureinsertion);
$totalRows_pictureinsertion = mysql_num_rows($pictureinsertion); ?
>
<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="pictureform" name="picturfname" method="POST" action="<?php echo $editFormAction; ?>">

<input type="file" name="image"/>
<br/>
<input type="submit" />
<input type="hidden" name="MM_insert" value="picturfname" />
</form>

<body>
</body>
</html>
<?php
mysql_free_result($pictureinsertion);
?>


text:
Q: variables passes null value I have tried setting my session values, but every time I want to display the text a user has entered in the previous page it returns null
I have three pages Subscriber details, Package Selection and Bank Details, all three pages follow each other and the user has filled all pages with his/her desired info and clicks next, they are directed to a page where all the info they entered are displayed.
I cant seem too see what I'm doing wrong?
SubscriberDetails.aspx
protected void Button1_Click(object sender, EventArgs e)
{
    string FullName = txtFullName.Text;
    string CompanyName = txtCompanyName.Text;
    string Vat = txtVAT.Text;
    string ContactNumber = txtContactNumber.Text;
    string Fax = txtFax.Text;
    string District = txtDistrict.Text;
    string Street = txtStreet.Text;
    string City = txtCity.Text;
    string Code = txtPostal.Text;
    string Trading = txtTrading.Text;
    string Id = txtID.Text;
    string ContactPerson = txtContactPerson.Text;
    string Email = txtEmail.Text;

        Session["FullName"] = FullName;
        Session["CompanyName"] = CompanyName;
        Session["VAT"] = Vat;
        Session["ContactNumber"] = ContactNumber;
        Session["Fax"] = Fax;
        Session["District"] = District;
        Session["City"] = City;
        Session["Street"] = Street;
        Session["Code"] = Code;
        Session["Trading"] = Trading;
        Session["ID"] = txtID.Text;
        Session["ContactPerson"] = ContactPerson;
        Session["Email"] = Email;

}

Final.aspx
protected void Page_Load(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty((string)Session["Fullname"]))
    {
        lblFullName.Text = "N/A";
    }
    else
    {
        lblFullName.Text = Session["FullName"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["CompanyName"]))
    {
        lblCompanyName.Text = "N/A";
    }
    else
    {
        lblCompanyName.Text = Session["CompanyName"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["VAT"]))
    {
        lblVat.Text = "N/A";
    }
    else
    {
        lblVat.Text = Session["VAT"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["ContactNumber"]))
    {
        lblContactNumber.Text = "N/A";
    }
    else
    {
        lblContactNumber.Text = Session["ContactNumber"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["Fax"]))
    {
        lblFax.Text = "N/A";
    }
    else
    {
        lblFax.Text = Session["Fax"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["District"]))
    {
        lblDistrict.Text = "N/A";
    }
    else
    {
        lblDistrict.Text = Session["District"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["Street"]))
    {
        lblStreet.Text = "N/A";
    }
    else
    {
    lblStreet.Text = Session["Street"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["City"]))
    {
        lblCity.Text = "N/A";
    }
    else
    {
        lblCity.Text = Session["City"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["Code"]))
    {
        lblCode.Text = "N/A";
    }
    else
    {
    lblCode.Text = Session["Code"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["Trading"]))
    {
        lblTrading.Text = "N/A";
    }
    else
    {
    lblTrading.Text = Session["Trading"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["ID"]))
    {
        lblID.Text = "N/A";
    }
    else
    {
    lblID.Text = Session["ID"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["ContactPerson"]))
    {
        lblContactPerson.Text = "N/A";
    }
    else
    {
    lblContactPerson.Text = Session["ContactPerson"].ToString();
    }
    if (string.IsNullOrEmpty((string)Session["Email"]))
    {
        lblMail.Text = "N/A";
    }
    else
    {
    lblMail.Text = Session["Email"].ToString();
    }
}

A: Well you don't have many options there, if that is happening you have an issue with your session. Perhaps every other request is initiating a new session, check that to make sure it is not happening.
Check with:
Session.SessionID;

A: I see one piece of code using TextBox controls and the lower using Label controls.
You aren't, maybe, reading the wrong ones, are you?
This as just an FYI: We get customer complaints on our websites if we fill in values like "N/A". Most people seem to prefer to see the blank spaces, which would also simplify your code:
lblVariable.Text = string.Format("{0}", Session["Variable"]);

Variable, obviously, needs to change with your Session and Control variable names.


text:
Q: JCodeModel method writing, issues with "new" Need help in converting the following piece of code to jcodemodel understandable format
@Override
    public final void blah() {
XStream xstream = new XStream(new DomDriver());
        String xml = xstream.toXML(this);
}

Any help appreciated.

A: Never mind... solved it... :)
JBlock block = jtoStringMethod.body();
        JVar line1 = block.decl(xstream, "xstream", JExpr._new(xstream).arg(JExpr._new(domDriver)));
        JVar line2 = block.decl(jmod._ref(String.class), "xml", JExpr.ref("xstream").invoke("toXML").arg(JExpr._this()));
        block._return(JExpr.ref("xml"));


text:
Q: Uniformly most powerful size $\alpha = .05$ test Suppose $X$ is a single observation from a $\text{Poisson}(\lambda)$ distribution. Determine the uniformly most powerful size $\alpha = .05$ test for the hypothesis test $H_0: \lambda = 5$ and $H_1: \lambda = 10$.
My thoughts: The Neyman-Pearson Lemma tells us the UMP level $\alpha$ test is the likelihood ratio test. The likelihood ratio function is
$\Lambda = \frac{5^x e^{-5}}{x!}/ \frac{10^x e^{-10}}{x!} = 2^{-x}e^5$. We reject the null hypothesis if $\Lambda < k$ which is equivalent to rejecting if $x > k^*$.
Our hypothesis test will be of the form
$$\phi(x) =
\begin{cases}
1 \hfill &\text{if $x > k^*$} \\
\gamma \hfill &\text{if $x = k^*$} \\
0 \hfill &\text{otherwise}
\end{cases}
$$
To make a size $\alpha$ test we want to solve for $\gamma$ in the following:
$$\alpha = .05 = \text{E}_{\lambda=5}(\phi(x)) = P_{\lambda=5}(X>k^*) + \gamma P_{\lambda=5}(X=k^*).$$
Can someone offer some confirmation/guidance on this? I am not confident in my method.

A: In case you are still interested, your work upto this point was correct as far as I can tell.
Suppose $\lambda\in\Theta$ where $\Theta=\mathbb R^{+}$ is the parameter space.
By Neyman-Pearson lemma, a most powerful test of size $\alpha$ for testing $H_0:\lambda=\lambda_0$ against $H_1:\lambda=\lambda_1(\ne\lambda_0)$ is usually defined as
\begin{align}
\phi(x)=\begin{cases}1&,\text{ if }\Lambda(x)>c\\\gamma&,\text{ if }\Lambda(x)=c\\0&,\text{ if }\Lambda(x)<c\end{cases}
\end{align}
, where
$$\Lambda(x)=\frac{f_{\lambda_1}(x)}{f_{\lambda_0}(x)}$$
and $c\,(>0)$ and $\gamma\in(0,1)$ are so chosen that $$E_{\lambda=\lambda_0}\,\phi(X)=\alpha$$
Therefore in this case,
$$\Lambda(x)=e^{-5}2^x\quad,\,\text{ an increasing function of }x$$
That is, for some positive $k$, $$\Lambda(x)>c\implies x>k$$
So the test $\phi$ is of the form
\begin{align}
\phi(x)=\begin{cases}1&,\text{ if }x>k\\\gamma&,\text{ if }x=k\\0&,\text{ if }x<k\end{cases}
\end{align}
, where $k$ and $\gamma\in(0,1)$ are so chosen that
\begin{align}
E_{\lambda=5}\,\phi(X)=0.05
\end{align}
That is, $$P(Y>k)+\gamma P(Y=k)=0.05\quad,\, Y\sim \text{Poisson}(5)$$
I used WolframAlpha to get
$$P(Y>8)\approx 0.068094\qquad\text{ and }\qquad P(Y>9)\approx 0.031838$$
So looks like $k=9$ is the appropriate value subject to the size restriction and corresponding to that, we get $$\gamma\approx 0.501075$$
Finally, the test function is
\begin{align}
\phi(x)=\begin{cases}1&,\text{ if }x>9\\0.501075&,\text{ if }x=9\\0&,\text{ if }x<9\end{cases}
\end{align}
Since the above test is independent of $\lambda_1=10$, $\phi$ is most powerful against all alternatives $\lambda_1\in \Theta_1$ where $\Theta_1\subset \Theta-\{\lambda_0\}$. Hence $\phi$ is uniformly most powerful of size $\alpha$ for testing $H_0$ versus $H_1$.


text:
Q: Convergence of a sequence in a k- dimensional Euclidean metric space Consider a sequence in $\mathbb{R}^{k}$, call it $(x^{(n)})$. I understand with the most familiar metric $d(x,y) = \left[\sum_{j=1}^{k}(x_j-y_j)^2\right]^{1/2}$ that this sequence will converge if and only if the $i$th term in this sequence converges $(x_{i}^{(n)})$ in $\mathbb{R}$ for every $i = 1, 2, \ldots, k$. Is this statement necessarily true for any metric $d$? I know how to prove this statement with the metric stated above but I have no idea how to prove this with any other metric $d$, if this is even possible.

A: No. Any non-empty set $X$ has the "trivial metric" which is defined as
\begin{align}
d(x,y)=
\begin{cases}
1&\text{if $x\neq y$}\\
0&\text{if $x= y$}
\end{cases}
\end{align}
A sequence $\{x_n\}_{n=1}^{\infty}$ converges to a point $x$ relative to this metric if and only if there exists an $N\in\Bbb{N}$ such that for all $n\geq N$, we have $x_n=x$. In other words, convergence relative to this metric requires the sequence eventually be constant.
So, a sequence in $\Bbb{R}^2$ (same idea works for any $k$) such as $x_n=\left(\frac{1}{n},\frac{1}{n}\right)$ does not converge relative to this metric, even though each "component" $x_{n,1}=\frac{1}{n}$  and $x_{n,2}=\frac{1}{n}$ converges to $0$ relative to the standard metric on $\Bbb{R}$.

Edit in Response to Comment
Yes, we can also construct counterexamples for the converse; here's the general idea. Let $X$ be a set, $\delta$ a metric on $X$ and $f:X\to X$ a bijection. We can consider the pull-back metric $d=f^*\delta$ on $X$ defined as $d(x,y):=\delta(f(x),f(y))$. We now ask whether it is possible to find a sequence $\{x_n\}_{n=1}^{\infty}$ such that

*

*$\{x_n\}_{n=1}^{\infty}$ converges relative to $d=f^*\delta$ (or equivalently $\{f(x_n)\}_{n=1}^{\infty}$ converges relative to $\delta$);

*$\{x_n\}_{n=1}^{\infty}$ does not converge relative to $\delta$.

Such examples are easy to construct in $\Bbb{R}$ (perhaps there are even simpler solutions, but this is the first which came to mind). So, we consider $X=\Bbb{R}$, $\delta$ to be the standard metric and $x_n=(-1)^nn$. This sequence alternates in sign and approaches $\infty$ in magnitude,so it is clear that $\{x_n\}_{n=1}^{\infty}$ does not converge relative to $\delta$ (the standard metric on $\Bbb{R}$).
Now, define $f:\Bbb{R}\to\Bbb{R}$ by setting $f(x)=\frac{1}{x}$ if $x\neq 0$ and $f(0)=0$. Then, $f$ is a bijection, and $f(x_n)=\frac{(-1)^n}{n}$ converges to $0$ relative to $\delta$, the standard metric. Thus, $x_n$ converges relative to $d=f^*\delta$, which is precisely what we want.


text:
Q: Java String internal representation I understand that the internal representation of Java for String is UTF-16. What is java string representation?
Also, I know that in a UTF-16 String, each 'character' is encoded with one or two 16-bit code units.
However, when I debug the following java code
String hello = "Hello";

the variable hello is an array of 5 bytes 0x48, 0x101, 0x108, 0x108, 0x111
which is ASCII for "Hello".
How can this be?

A: I took a gcore dump of a mini java process with this code:
 class Hi {
    public static void main(String args[]) {
        String hello = "Hello";
        try {
            Thread.sleep(60_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

And did a gcore memory dump on Ubuntu. (usign jps to get the pid and passed that to gcore)
If found this: 48 65 6C 6C 6F in the dump using a Hexeditor, so it is somewhere in the memory as ASCII.
But also 48 00 65 00 6C 00 6C which is part of the UTF-16 representation of the String

A: String internal representation is not specified, it's the implementation detail, so you cannot rely on it. It's very likely that in JDK-9 it will be changed to use double encoding (Latin-1 for strings which can be encoded in Latin-1, UTF-16 for other strings). See JEP-254 for details. This feature is already integrated in OpenJDK master codebase, so if you are using Java-9 early access builds, you will have actually 5 bytes.


text:
Q: Streaming Pattern Matching using Regex I'd want to parse a large text file formatted in Warc version 0.9. A sample of such text is here. If you take a look at it, you'll find the whole document consists of a list of following entries.
[Warc Headers]

[HTTP Headers]

[HTML Content]

I need to extract URL and HTML content from each entry (please note that the sample file consists of multiple page entries each of which is formatted like the content above.)
I used the following regular expression in Java:
Pattern.compile("warc/0\\.9\\s\\d+\\sresponse\\s(\\S+)\\s.*\n\n.*\n\n(.*)\n\n", Pattern.DOTALL)

Where group 1 and 2 represents the URL and the HTML content respectively. There's two problem with this code:

*

*It's very slow to find a match.

*Only matches with the first page.

Java Codes:
if(mStreamScanner.findWithinHorizon(PAGE_ENTRY, 0) == null){
    return null;
} else {
    MatchResult result = mStreamScanner.match();
    return new WarcPageEntry(result.group(1), result.group(2));
}

Questions:

*

*Why is my code only parsing the first page entry?

*Is there a faster way to parse a large text in a streaming manner?

A: I wouldn't tackle these huge HTML strings with a regex. How about relying on the structure of the document, instead?
E.g. like so:
HashMap<String, String> output = new HashMap<>();
Pattern pattern = Pattern.compile("^warc\\/0\\.9\\s\\d+\\sresponse\\s(\\S+)\\s.*");

try (InputStreamReader is = new InputStreamReader(new FileInputStream("excerpt.txt"), "UTF-8")) {
    try (BufferedReader br = new BufferedReader(is)) {
        String line;
        while ((line = br.readLine()) != null) {
            Matcher matcher = pattern.matcher(line);

            if (matcher.matches()) {
                entityLoop: while (true) {
                    String url = matcher.group(1);

                    // skip header
                    int countEmptyLines = 0;
                    while ((line = br.readLine()) != null) {
                        if ("".equals(line)) {
                            countEmptyLines++;
                            if (countEmptyLines == 2) break;
                        }
                    }

                    // extract HTML
                    StringBuilder sb = new StringBuilder();
                    while ((line = br.readLine()) != null) {
                        matcher = pattern.matcher(line);
                        if (matcher.matches()) {
                            // got all HTML; store our findings
                            output.put(url, sb.toString());
                            continue entityLoop;
                        }
                        sb.append(line);
                    }
                    break; // no more url/html-entities available
                }
            }
        }
    }
} catch (IOException e) {
    // do something smart
}

// now all your extracted data is stored in "output"

There is still room for improvement in the above code. But it should give you an idea on how to get started.


text:
Q: Load file local or from cdn I have a pretty simple question that I had in my mind today. I'm linking to jquery locally, from my pc in case I don't have internet connection but I was wondering if there is a way to check if there is internet connection and if so, load jquery from CDN. Any suggestions?

A: You can do this CDN fallback:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/libs/jquery-1.11.1.min.js"><\/script>')</script>

HTML5 boilerplate is using this technique: https://github.com/h5bp/html5-boilerplate/blob/master/dist/index.html
Please check this article: http://www.hanselman.com/blog/CDNsFailButYourScriptsDontHaveToFallbackFromCDNToLocalJQuery.aspx

A: Pure html solution:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"        "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
  <title>Test CDN fallback</title>
</head>

<body>
  <object data="https://cdn.invented.com/something" type="text/javascript">
    <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
  </object>
  <!-- in your case -->
    <!-- <object data="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript">
      <script src="/local/jquery-3.0.0.min.js"></script>
    </object> -->
</body>
</html>


text:
Q: Repeatedly send email with python on time interval I want to make a python script that sends an email with an attachment (txt) every 30 minutes. Here is my code to send the email with the attachment. It's working without any problems. However, I need help to figure out how to send this on a time schedule.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path

email = 'myaddress@gmail.com'
password = 'password'
send_to_email = 'sentoaddreess@gmail.com'
subject = 'This is the subject'
message = 'This is my message'
file_location = 'C:\\Users\\You\\Desktop\\attach.txt'

msg = MIMEMultipart()
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject

msg.attach(MIMEText(message, 'plain'))

filename = os.path.basename(file_location)
attachment = open(file_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()

A: Two options for you

*

*You can look into scheduling your python script to run at a certain time interval. This means, each script run would send one email, and you would stop the automated task rather than stopping the script when you want the emails to stop. If you're running Windows OS, they have a built in application called Task Scheduler to manage this for you.

*Option two is to use the time.sleep() function. This method would mean the script would continue to run and shoot off an email every 30 minutes. The script would have to be stopped when you want the emails to stop.
import time
while True:
    {insert your email send code here}
    time.sleep(60*30) # this is in seconds, so 60 seconds x 30 mins


text:
Q: Computing difficult indefinite integral \begin{array}{l}{\text { Compute the following integral in the case that } n \text { is a positive integer. }} \\ \\ {\\\quad A(n, x)=\int \frac{x^{n} d x}{1+x+\frac{x^{2}}{2 !}+\ldots+\frac{x^{n}}{n !}}, \quad \\  \text{Seems like the denominator has something to do with Taylor Series?} }\end{array}

A: Hint:
$$
\frac{x^n}{1+x+\cdots + \frac{x^n}{n!}}
= n! - n!\cdot\frac{1+x+\cdots + \frac{x^{n-1}}{(n-1)!}}{1+x+\cdots + \frac{x^n}{n!}}
$$
Now split up the integral and use a substitution on the second one.


text:
Q: Compiler behaviour when constructing virtual base class Consider this piece of code:
#include <iostream>

class A {
  public:
    A(int s) { std::cout << "A(" << s << ")\n"; }
};

class B1 : virtual public A {
  public:
    B1(int s1, int s2)
        : A{s1} { std::cout << "B1(" << s1 << "," << s2 << ")\n"; }
};

class B2 : virtual public A {
  public:
    B2(int s1, int s2)
        : A{s1} { std::cout << "B2(" << s1 << "," << s2 << ")\n"; }
};

class C1 : public B1, public B2 {
  public:
    C1() : B1{1,2}, B2{3,4}, A{5} {}
};

class C2 : public B1, public B2 {
  public:
    C2() : B1(1,2), B2(3,4), A{5} {}
};

int main()
{
    std::cout << "Create c1:\n";
    C1 c1;

    std::cout << "\n";
    std::cout << "Create c2:\n";
    C2 c2;

}

Class A is a virtual base class of B1 and B2. Classes C1 and C2 are identical, except that C1 uses {...} and C2 uses (...) to construct B1 and B2.
Because of the virtual inheritance used here, class A should be constructed as part of the construction of C1 or C2.
If I compile this code with Microsoft VS2015, it produces this output when running:
Create c1:
A(5)
B1(1,2)
B2(3,4)

Create c2:
A(5)
B1(1,2)
B2(3,4)

which is exactly what I would expect.
But if I compile it with GCC (6.1.0) it produces this output:
Create c1:
A(5)
A(1)
B1(1,2)
A(3)
B2(3,4)

Create c2:
A(5)
B1(1,2)
B2(3,4)

Here, A's constructor is called three times when constructing c1, but only once when constructing c2.
Is this a bug in GCC or have I misunderstood something?

A: Answering my own question:
Apparently, GCC does have a bug in this case. Compiling the code with GCC version 7.0.0 produces the correct behaviour with this output:
Create c1:
A(5)
B1(1,2)
B2(3,4)

Create c2:
A(5)
B1(1,2)
B2(3,4)

A: Not quite sure why is it so, but shouldn't A class be polymorphic (have at least one virtual function) to properly virtually inherit from it?!

A: The bug is much worse:
    #include <iostream>

    class A {
       public:
          A(int s) { std::cout << "A(" << s << ")\n"; ms = s; };
          int ms;
          virtual void dummy() {std::cout << "Aaaaaa!" << std::endl;};
          virtual ~A() {std::cout << "~A(" << ms << ")\n";};
    };

    class B1 : virtual public A {
        public:
           B1(int s1, int s2)
              : A{s1} { std::cout << "B1(" << s1 << "," << s2 << ")\n"; };
    };

    class B2 : virtual public A {
        public:
           B2(int s1, int s2)
              : A{s1} { std::cout << "B2(" << s1 << "," << s2 << ")\n"; };
    };

       class C1 : public B1, public B2 {
           public:
              C1() : B1{1,2}, B2{3,4}, A{5}  {};
       };

       class C2 : public B1, public B2 {
           public:
              C2() : B1(1,2), B2(3,4), A{5} {};
       };

      int main()
      {
         {
             std::cout << "Create c1:\n";
             C1 c1;
             std::cout << "Calling A's dummy on c1: " << std::endl;
             c1.dummy();
             std::cout << "Size of c1: " << sizeof(c1) << std::endl;
         }

         {
             std::cout << "\n";
             std::cout << "Create c2:\n";
             C2 c2;
             std::cout << "Calling A's dummy on c2: " << std::endl;
             c2.dummy();
             std::cout << "Size of c2: " <<sizeof(c2) << std::endl;
         }

     }

Compiled on GCC 5.4.0
Running this code produced the following output:

*

*Create c1:

*A(5)

*A(1)

*B1(1,2)

*A(3)

*B2(3,4)

*Calling A's dummy on c1:

*Aaaaaa!

*Size of c1: 32

*~A(3)

*

*Create c2:

*A(5)

*B1(1,2)

*B2(3,4)

*Calling A's dummy on c2:

*Aaaaaa!

*Size of c2: 32

*~A(5)


text:
Q: electromagnet over heating I am building a PEMF style device using a number of electromagnet coils. They are  ZYE1-P20/15 12v 0.25A units from china capable of lifting 2.5kg. I took a chance on the strengh but that is not the issue. I am controlling 1 at the moment using an 8 channel relay board and raspberry pi. The boards relays can take 30v 10A dc so I assumed there would be no problem. I am using the relay as a switch with a 12v 200mA transformer to switch the coils on and off. It is just the supply, coil and relay in series. I set a program to switch it on for 5 seconds and off for 1 second, I couldn't find a duty cycle so don't know if this is inappropriate but the coils were sold as being able to be used in machines for packing and they are switch on and off frequently. The problem I have is after about 5 minutes the coil was very hot and the raspberry pi was being affected. Is this feedback and will a 1N5349B diode in the circuit stop it getting hot?

A: First, you haven't actually told us what your problem is. You say that the Raspberry is being affected. Why? Do you have both in closed box and the Raspberry is getting hot? Well, there's an old joke about a guy who goes to a doctor and says, "Doctor, it hurts when I do this". The doctor responds, "Well, don't do it." If the coil heating the Raspberry isn't your problem, what is? What, exactly, does "being affected" mean? If the coil is heating the Raspberry, move the coil or move the Raspberry.
That said, you actually know the answer, but you're not willing to face it.
"I couldn't find a duty cycle so don't know if this is inappropriate but the coils were sold as being able to be used in machines for packing and they are switch on and off frequently."
So you got a unit off the internet and you don't know if it will do the job. So instead of figuring out whether or not the duty cycle is giving you problems, you have fixed on a flyback diode as your savior. This simply isn't going to work.
So what you need to do is this:
1) Get yourself a tin can. Place it on a flat, fireproof surface - a cinderblock will do nicely.
2) Take one of your coils and put it in the can.
3) Hook up 12 volts to the solenoid.
4) Let it run overnight.
5) If it hasn't caught fire, find the coil temperature. You can touch it with a thermometer, or pour enough water in the can to cover the coil and let it run for another hour, then measure water temperature. As a very rough indicator, 60 C is the "Ouch!" point, where most folk can't hold a hot object.
6) Check to see that the coil is still working.
If the coil has not caught fire and is still working properly, you know how hot it gets and that it can survive this temperature and still work, so you don't need to do anything.
A flyback diode is always a good idea to limit switching transients and extend the lifetime of your relay contacts, but it will do nothing to solve your temperature problem.

A: (1) You have "12v 0.25A" adapter. You are using "12v 200mA" transformer.
Your transformer is not rated even for a single relay. Most likely it overheats as well.
(2) Is this feedback and will a 1N5349B diode in the circuit stop it getting hot.
You have a relay board, right? Then it is not feedback. Diode is needed to protect raspberry pi side of things, and looks like your problem is on relay side.
(2) the raspberry pi was being affected.
This is strange -- relays should be good at isolating parts from each other. Is raspberry pi close to your coil? Could it be pi overheating?


text:
Q: Embed forms and then persist in the tables days ago I have been struggling with this problem and do not know how to fix it !!!
Controller
public function crearUsuarioDatosAction()
    {
        $usuario = new User();
        $datos = new Datos();
        $datos->setPersonales($usuario);
        $request = $this->getRequest();
        $form = $this->createForm(new UserType(), $usuario);
        $form->add('datos', new DatosType());

        if($request->getMethod() == 'POST')
            {
                        $form->bind($request);

                if($form->isValid())
                    {
                        $em = $this->getDoctrine()->getEntityManager();
                        $em->persist($form);
                        $em->flush();

                    }

                return $this->redirect($this->generateUrl('home'));

            }

            return $this->render('AtajoBundle:IngresarValores:crearUsuarioDatos.html.twig', array('form' => $form->createView()));

    }

my entity User
    <?php

namespace Proyecto\LavocBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * User
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Proyecto\LavocBundle\Entity\UserRepository")
 */
class User {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="usuario", type="string", length=30)
     */
    private $usuario;

    /**
     * @var string
     *
     * @ORM\Column(name="pass", type="string", length=20)
     */
    private $pass;

/**
     *  @ORM\OneToOne(targetEntity="Datos", mappedBy="personales")
     */

    private $datos;

/**
     * Get datos
     *
     * @return string
     */

    public function getDatos()
    {
        return $this->datos;
    }

    /**
     * Set datos
     *
     * @param string $datos
     * @return User
     */

    public function setDatos($datos)
    {
        $this->datos = $datos;
        $datos->setPersonales($this);
        return $this;
    }

now, my entity DATA:
    <?php

namespace Proyecto\LavocBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Datos
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Proyecto\LavocBundle\Entity\DatosRepository")
 */
class Datos
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="empresa", type="string", length=50)
     */
    private $empresa;

    /**
     * @var integer
     *
     * @ORM\Column(name="cuit", type="integer")
     */
    private $cuit;

    /**
     * @var string
     *
     * @ORM\Column(name="localidad", type="string", length=50)
     */

    private $localidad;

    /**
     * @var string
     *
     * @ORM\Column(name="calle", type="string", length=40)
     */
    private $calle;

    /**
     * @var integer
     *
     * @ORM\Column(name="altura", type="integer")
     */
    private $altura;

    /**
     * @var integer
     *
     * @ORM\Column(name="areaTel", type="integer")
     */
    private $areaTel;

    /**
     * @var integer
     *
     * @ORM\Column(name="telefono", type="integer")
     */
    private $telefono;

    /**
     * @var integer
     *
     * @ORM\Column(name="areaCel", type="integer")
     */
    private $areaCel;

    /**
     * @var integer
     *
     * @ORM\Column(name="celular", type="integer")
     */
    private $celular;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string")
     */

    private $email;

    /**
    * @ORM\OneToOne(targetEntity="User", inversedBy="datos")
    * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
    */

    private $personales;

    /**
     * Get id
     *
     * @return integer
     */

/**
     * Set personales
     *
     * @param string $personales
     * @return Datos
     */

    public function setPersonales($personales)
    {
        $this->personales = $personales;
        return $this;

    }

    /**
     * Get personales
     *
     * @return string
     */

    public function getPersonales()
    {
        return $this->personales;
    }

UserType
<?php

namespace Proyecto\LavocBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('usuario');
        $builder->add('pass');
    }

    public function getName()
    {
        return 'user_form';
    }
}

DatosType:
    <?php

namespace Proyecto\LavocBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class DatosType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('empresa');
        $builder->add('cuit');
        $builder->add('localidad');
        $builder->add('calle');
        $builder->add('altura');
        $builder->add('areaTel');
        $builder->add('telefono');
        $builder->add('areaCel');
        $builder->add('celular');
        $builder->add('email');
    }

    public function getName()
    {
    return 'datos_form';
    }

}

Days ago I try to embed forms, before he had made a type file with embedded forms but as I worked , the nest directly on the controller. If anyone can help me , I would appreciate , some days I 'm dealing with this.
My role is to show the form and when the user is sent , data persist in their respective entities. THANKS

A: try to persist the entity instead of the form
$em->persist($form->getData());

instead of
$em->persist($form);

be sure to have a look at the docs


text:
Q: Returning correct value from array in Form Select Just having trouble trying to retrieve the correct value from form::select upon form submit.
I am passing in an array (which contains full_name and ID). The form is displaying the correct information, however, when I return the value from form submit (e.g. if the coach changes the current value/player to new Name), I am getting back the form array ID, not the username ID I am trying to get. Code below
In controller:
    $ids = array($p1, $p2, $p3, $p4, $p5, $p6, $p7, $p8, $p9, $p10, $p11, $p12, $p13, $p14, $p15, $p16);
    $ids_ordered = implode(',', $ids);

    $player= DB::table('players')
        ->whereIn('id', $ids)
        ->selectRaw('id, CONCAT(fname," ",lname) as full_name')
        ->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))
        //->pluck('id' ,'full_name') //Only returning  ONE value - not both?
        ->get()
        ->mapWithKeys(function($i) {
          return [$i->id => $i->full_name.' ('.$i->id.')'];
        });

    $player=collect([$player])->flatten();

Note: I need to get the 16 x IDs in the correct order as it is a sports team selection form. This part is working. I also tried using Pluck, but for some reaon could only return ONE value (e.g. full_name OR ID) - not both. So I changed to mapWithKeys.
In form/view:
    <div class="form-group">
        {!! Form::label('capt','Team Captain for Matchcard') !!}
        {!! Form::select('capt', $played, null, ['placeholder' => $played[0] ,'class' => 'form-control']) !!}

    </div>

There are 16 fields in the form as per above. the placeholder is the current value (currently selected team player). The coach can CHANGE from the drop-down ($played array).
The form displays perfectly. So whats happening, lets say the coach changes the capt field above (current player id is 17 but $played array value is 0). If we change/select a new player from the drop down (e.g. id 25 which may be 4th name in the drop list - hence array value [3] ) - my return on submit (back in controller) is displaying 3 and I want 25 (the actual player ID of the desired name/player from the Players table).
Appreciate if someone can help me get the new ID in this scenario... much appreciated and thanks in advance.
PS: I am using Laravel 5.4
Array display:

Using example above, if I change the capt field in form select to Corry Allsop (id 12), the form is returning 2 (3rd name in array)

A: correct way to get $played from database using pluck
$player= DB::table('players')
        ->whereIn('id', $ids)
        ->selectRaw('id, CONCAT(fname," ",lname) as full_name')
        ->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))
        ->pluck('full_name' ,'id')

pluck second parameter will be array key and the first is value
//view
{{ Form::select('capt', $played, null) }}

Edit:
remove this line $player=collect([$player])->flatten();.
The flatten method flattens a multi-dimensional collection into a single dimension. that's why the id as key replaced by array key (start from 0)
Edit 2:
display current player
//controller
return view('grades.matchcard.edit', ['ids' => $ids, played' => $player, 'matchcards' => $data, 'rounds' => $data1, 'mid' => $mcid, 'gstat' => $gstat, 'Rplayers' => $Rplayers]);

//view
{{ Form::select('capt', $played, $ids[0], ['class' => 'form-control']) }}

{{ Form::select('capt', $played, $ids[1], ['class' => 'form-control']) }}