text:
Q: How do I handle CORS with html2Canvas and AWS S3 images? I know similar questions have been asked before but I still can't make it work. I have a div with images inside of it loaded from a bucket in AWS s3, they load perfectly no problem.
Now I want to be able to save as a jpeg whatever is in that specific div (like taking a screenshot), the plugin html2canvas helps with that. The problem is that when I try to actually save it (or simply show immediately the result of such screenshot) I run into these issues:

*

*Canvas is tainted => I set allowTaint: true in the plugin but it would throw this error, so I disabled it and the error went away. I keep useCORS set to true though to allow images from another source.

*Access to image has been blocked by CORS policy
In order to solve this I set up CORS on my AWS S3 bucket, but that didn't seem to work (or it worked partially). I noticed that the response header of those images don't have CORS metadata when the plugin uses them to generate the jpeg. I then tried to set crossOrigin="anonymous" in those images inside the div but it would throw a CORS error right away, which shouldn't happen since the AWS bucket has been set up for that as follows:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

I am running out of options on how to make this work. Any idea on how to proceed from here would be very appreciated.
EDIT: More details, I am using React and the images urls are retrieved from a server. This means that as soon as I get this array of urls I generate:

  { urls.map(url => ) }

If I add the crossOrigin="anonymous" I get the CORS error. If I leave that out, the images display but then the html2canvas plugin throws a CORS error as well when trying to generate the "screenshot".
More details about the HTTP requests. So the first time I load an image inside the div, this is the Response Header:
Accept-Ranges:bytes
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
Cache-Control:max-age=2592000
Content-Length:508208
Content-Type:image/png
Date:Thu, 16 Feb 2017 18:25:05 GMT
Last-Modified:Wed, 15 Feb 2017 19:09:44 GMT
Server:AmazonS3
Vary:Origin, Access-Control-Request-Headers, Access-Control-Request-Method

Now this works if crossOrigin='anonymous' and the picture is not from the cache. If the crossOrigin attribute is not set I get:
Accept-Ranges:bytes
Cache-Control:max-age=2592000
Content-Length:508208
Content-Type:image/png
Date:Thu, 16 Feb 2017 19:03:53 GMT
Last-Modified:Wed, 15 Feb 2017 19:09:44 GMT
Server:AmazonS3

or it throws a CORS error on the console without showing any meta data on the response header. I tried adding a random string at the end of the url (?somethingsomething) so that they would never be grabbed from the cache, and that fixed the issue completely. But this is just a hack and it works for now but it is not definitely the solution I am looking for. I think Chrome is doing something with the cache and I have a hard time tracking the source of the issue, other than the fact that it's hard to reproduce this problem on my machine since it always retrieved the screenshot from cache even if I am using completely new images and disable/clear cache. It's very confusing.

A: I solved this problem by adding proxy:( image src ) option in html2canvas. Now your image is also included in pdf
Typescript Code:
download() {
        var data = document.getElementById('view-eob');
        html2canvas(data, { proxy: this.eobDetail.member.parentCompany.logo })
        .then(canvas => {
            var imgWidth = 208;
            var imgHeight = canvas.height * imgWidth / canvas.width;
            const contentDataURL = canvas.toDataURL('image/png')
            let pdf = new jsPDF('p', 'mm', 'a4');
            var position = 0;
            pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
            pdf.save(`${this.eobDetail.episode.name}-EOB.pdf`);
        });
    }

HTML Code:

<button type="button" (click)="download()"> Download</button>

A: I solved this error with adding crossOrigin attribute at IMG tag. So, your code will look like (tag at React js):
<Image crossOrigin="true" />

And my configuration at S3 bucket with CORS:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>http://localhost:8000</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
<CORSRule>
    <AllowedOrigin>https://testing.d1wr8lk28mi6l0.amplifyapp.com</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

HTML2CANVAS:
 html2canvas(getWrapper, { allowTaint: true, useCORS: true, logging: true })
  .then((canvas) => {
    const imgData = canvas.toDataURL('image/png');
    console.log(imgData);
  });

A:
See the edit, I did try setting the crossOrigin attribute with no
  luck, and I use useCORS set to true (forgot to mention that sorry).
  Still no luck.

I fixed some cors issues I was having with the combination of Google Chrome, AWS S3, and multiple origins.
I found this stackoverflow thread:
Chrome + CORS + cache - requesting same file from two different origins
Which links to this bug report:
https://bugs.chromium.org/p/chromium/issues/detail?id=260239
Anyhow as workaround solution you can try this modified version of html2canvas:
https://gist.github.com/CrandellWS/6bc2078aced496004d7a045e6360f19b
use the options:
allowTaint : false,
useCORS: true

Hope that helps.
FYI, this will add the current time stamp to cors image urls to sidestep a cache issue I was having on Chrome...
https://gist.github.com/CrandellWS/6bc2078aced496004d7a045e6360f19b#file-html2canvas-js-L6838
Which means it will effect performance by re-downloading those images...
original post:
https://github.com/niklasvh/html2canvas/issues/1544#issuecomment-435640901


text:
Q: "justify-content: space-between;" não está funcionando - Flexbox Olá. Tudo bem?
Estou criando uma caixa com três itens. Um precisa estar colado na parte superior, outro no meio e outro colado na parte inferior, para a base do layout que estou precisando fazer.
Então utilizei flexbox com space-between, mas por algum motivo não está funcionando como esperado.
O que pode estar acontecendo para gerar este resultado, diferente do esperado?

Código:

div#apresentation-box {
    width: 900px;
    height: 900px;
    background-color: rgb(5, 5, 5);
    display: flex;
    flex-flow: column wrap;
    justify-content: space-between;
    align-items: center;
}

div#border-background {
    width: 500px;
    height: 250px;
    border-style: solid;
    border-width: 15px;
    border-color: rgba(255, 255, 255, 0.329);
}

div#apresentation-text {
    width: 800px;
    height: 350px;
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
}

span#foundation-date {
    font-family: Helvetica, Arial, sans-serif;
    font-size: 20px;
    font-weight: bold;
    color: white;
    margin-bottom: 25px;
}

span#foundation-date::before,
span#foundation-date::after {
    content: "";
    background-color: white;
    width: 50px;
    height: 2px;
    display: inline-block;
    position: relative;
    vertical-align: middle;
    margin-left: 20px;
    margin-right: 20px;
}

div#apresentation-text p {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 55px;
    font-weight: 900;
    color: white;
    text-align: center;
}

div#apresentation-text p span{
    color: orange;
}

div#apresentation-buttons {
    width: 490px;
    height: 250px;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;
    align-items: center;
}

div#apresentation-buttons a {
    width: 230px;
    height: 58px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 18px;
    font-weight: bold;
    text-decoration: none;
    display: flex;
    justify-content: center;
    align-items: center;
}

                                Desde 2012

                                FICAREMOS FELIZES EM DESENVOLVER DE SUA ARTE

                                Contate-nos
                                arrow_forward

                                Peça um orçamento
                                arrow_forward

A: Boa tarde!
Analisei meu código, novamente, e descobri que o erro estava no  height da div#apresentation-buttons. Eu coloquei espaço mais do que necessário.
Desta forma, space-between está funcionando perfeitamente. Foi apenas um erro no controle de tamanhos, que cometi.
Obrigado!

redpajama_set_name: RedPajamaStackExchange


text:
Q: reading delimiter with fortran I need to read this kind of file. I have problem reading the delimiters within the file.
xxxx
dd/mm/yyyy
text
text
angle
Number of points
-13.82|654781.695|292510.337|4.889|SD
0.00|654795.515|292510.337|4.373|P1
1.25|654796.765|292510.337|4.324|SD
1.29|654796.805|292510.337|4.657|SD
1.68|654797.195|292510.337|4.622|SD
......

A: (1) Read lines from the file into a string using the "(a)" format.
(2) Replace unwanted delimiters in the string with delimiters recognized by Fortran (spaces or commas).
(3) Get data from the string using an "internal read".
The program below illustrates steps (2) and (3).
program main
implicit none
character (len=20) :: str
integer            :: i
real               :: x,y
str = "321.1|5678.9"
do i=1,len_trim(str)
   if (str(i:i) == "|") str(i:i) = " "
end do
print*,"str = '" // trim(str) // "'"  ! output: '321.1 5678.9'
read (str,*) x,y
print*,"x, y =",x,y ! output: x, y = 321.1 5678.9
end program main


text:
Q: Record from a from a background-service using MediaProjection API: is this kind of approach the only one possible?
  Intent dialogIntent = new Intent(BackgroundService.this, ScreenShotActivity.class);
  dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(dialogIntent);

I want to ask you if starting the activity ScreenShotActivity.class, which is the class for the MediaProjection implementation, from a background-service is the only way to record everything happening on screen.
Source: How to take a Screenshot from a background-service class using MediaProjection API?
Or is it possible to implement everything of the MediaProjection API inside the service itself, without needing an "util" activity?

A:
is it possible to implement everything of the MediaProjection API inside the service itself, without needing an "util" activity?

No. The user needs to agree to allow your app to record the screen, and the system-supplied dialog for that is displayed via startActivityForResult(). That, in turn, requires an activity.


text:
Q: Manage list using data tables plugin I am using DataTables plugin to have sorting and paging on the tables.
But plugin is not working as expected (at least for me) when I try to submit the form while using paging.
For ex: If total records is 14 and page size is 10, and when I navigate to page 2 and submit the page, only 4 records are posted to server instead of 14.
I assumed plugin is dynamically performing the operations without disturbing the content but its not the case, html table is regenerated when I navigate to other page, thus losing page 1 markup/content.
Any insights appreciated.

A: My mistake, I missed the documentation and also a thread which might help others as well.
Pagination with selected check boxes. Checkboxes will only work on current pagination page. jQuery datatables


text:
Q: Error 'e' was not declared in this scope Я, конечно не самый опытный программист но почему после компиляции этого кода:
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char** argv) {
string s;
cin >> s;
int N = 0;
for ( int i = 0 ; i < s.size() ; i++ ){
    if (s[i] != '_')
    N++;
    }
string mas[N];
int i = 0;
int j = 0;
int d = 1;
while ( i < N ){
    while (s[j] != '_' && j < s.size()){
        if ( s[j] != s[d] )
        int e = d;
        mas[i] = mas[i] + s[j];
        d++;
        if ( d == '_' ){
            d = e + 1;
        }
    }
    i++;
    j++;
}
cout << mas[i];
return 0;
}

Dev выдает вот такую ошибку:[Error] 'e' was not declared in this scope

A: while (s[j] != '_' && j < s.size()){
    if ( s[j] != s[d] )
    int e = d;

Если s[j] = s[d],
то e не будет объявлена. Объявите е вне цикла и в этом месте делайте присваивание.

A: Вот это
        if ( s[j] != s[d] )
        int e = d;
        mas[i] = mas[i] + s[j];

фактически равно
        if ( s[j] != s[d] ){
          int e = d;
        }
        mas[i] = mas[i] + s[j];

Что здесь проверяется ?

A: #include <iostream>
#include <string>

using namespace std;

int main(int argc, char** argv) {
string s;
cin >> s;
int N = 0;
for ( int i = 0 ; i < s.size() ; i++ ){
    if (s[i] != '_')
    N++;
    }
string mas[N];
int i = 0;
int j = 0;
int d = 1;
int e = 0; //объявим как все остальные переменные
while ( i < N ){
    while (s[j] != '_' && j < s.size()){
        if ( s[j] != s[d] )
        mas[i] = mas[i] + s[j];
        d++;
        if ( d == '_' ){
            d = e + 1;
        }
    }
    i++;
    j++;
}
cout << mas[i];
return 0;
}

программа уйдет в бесконечный цикл при работе, конечно же


text:
Q: Best build process solution to manage build versions I run a rather complex project with several independent applications. These use however a couple of shared components. So I have a source tree looking something like the below.

*

*My Project

*

*Application A

*Shared1

*Shared2

*Application B

*Application C

All applications have their own MSBuild script that builds the project and all the shared resources it needs. I also run these builds on a CruiseControl controlled continuous integration build server.
When the applications are deployed they are deployed on several servers to distribute load. This means that it's extremely important to keep track of what build/revision is deployed on each of the different servers (we need to have the current version in the DLL version, for example "1.0.0.68").
It's equally important to be able to recreate a revision/build that been built to be able to roll back if something didn't work out as intended (o yes, that happends ...). Today we're using SourceSafe for source control but that possible to change if we could present good reasons for that (SS it's actually working ok for us so far).
Another principle that we try to follow is that it's only code that been build and tested by the integration server that we deploy further.
"CrusieControl Build Labels" solution
We had several ideas on solving the above. The first was to have the continuous integration server build and locally deploy the project and test it (it does that now). As you probably know a successful build in CruiseControl generates a build label and I guess we somehow could use that to set the DLL version of our executables (so build label 35 would create a DLL like "1.0.0.35" )? The idea was also to use this build label to label the complete source tree. Then we probably could check out by that label and recreate the build later on.
The reason for labeling the complete tree is to include not only the actual application code (that's in one place in the source tree) but also all the shared items (that's in different places in the tree). So a successful build of "Application A" would label to whole tree with label "ApplicationA35" for example.
There might however be an issue when trying to recreate this build and setting the DLL version before deploying as we then don't have access to the CruiseControl generated build label anymore. If all CrusieControl build labels were unique for all the projects we could use only the number for labeling but that's not the case (both application A and B could at the same time be on build 35) so we have to include the application name in the label. Hence SourceSafe label "Application35". How can I then recreate build 34 and set 1.0.0.34 to the DLL version numbers once we built build 35?
"Revision number" solution
Someone told me that Subversion for example creates a revision number for the entire source tree on every check in – is this the case? Has SourceSafe something similar? If this is correct the idea is then to grab that revision number when getting latest and build on the CruiseControl server. The revision number could then be used to set the DLL version number (to for example "1.0.0.5678"). I guess we could then get this specific revision for the Subversion if needed and that then would include that application and all the shared items to be able to recreate a specific version from the past. Would that work and could this also be achived using SourceSafe?
Summarize
So the two main requirements are:

*

*Be able to track build/revision number of the build and deployed DLL.

*Be able to rebuild a past revision/build, set the old build/revision number on the executables of that build (to comply with requirement 1).

So how would you solve this? What would be your preferred approach and how would you solve it (or do you have a totally different idea?)? **Pleased give detailed answers. **
Bonus question What are the difference between a revision number and a build number and when would one really need both?

A: Your scheme is sound and achievable in VSS (although I would suggest you consider an alternative, VSS is really an outdated product).
For your "CI" Build - you would do the Versioning take a look at MSBuild Community Tasks Project which has a "Version" tasks.  Typically you will have a "Version.txt" in your source tree and the MSBuild task will increment the "Release" number while the developers control the Major.Minor.Release.Revision numbers (that's how a client of mine wanted it).  You can use revision if you prefer.
You then would have a "FileUpdate" tasks to edit the AssemblyInfo.cs file with that version, and your EXE's and "DLL's" will have the desired version.
Finally the VSSLabel task will label all your files appropriately.
For your "Rebuild" Build - you would modify your "Get" to get files from that Label, obviously not execute the "Version" task (as you are SELECTING a version to build) and then the FileUpdate tasks would use that version number.
Bonus question:
These are all "how you want to use them" - I would use build number for, well the build number, that is what I'd increment.  If you are using CI you'll have very many builds - the vast majority with no intention of ever deploying anywhere.
The major and minor are self evident - but revision I've always used for a "Hotfix" indicator.  I intend to have a "1.3" release - which would in reality be a product with say 1.3.1234.0 version.  While working on 1.4 - I find a bug - and need a hot fix as 1.3.2400.1. Then when 1.4 is ready - it would be say 1.4.3500.0

A: I need more space than responding as comments directly allows...

Thanks! Good answer! What would be the
  difference, what would be better
  solving this using SubVersion for
  example?Richard Hallgren (15 hours
  ago)

The problems with VSS have nothing to do with this example (although the "Labeling" feature I believe is implemented inefficiently...)
Here are a few of the issues with VSS
1) Branching is basically impossible
2) Shared checkout is generally not used (I know of a few people who have had success with it)
3) performance is very poor - it is exteremly "chatty"
4) unless you have a very small repository - it is completely unreliable, to the point for most shops it's a ticking timebomb.
For 4 - the problem is that VSS is implemented by the entire repository being represented as "flat files" in the file system.  When the repository gets over a certain size (I believe 4GB but I'm not confident in that figure) you get a chance for "corruption".  As the size increases the chances of corruption grow until it becomes an almost certainty.
So take a look at your repository size - and if you are getting into the Gigabytes - I'd strongly recommend you begin planning on replacing VSS.
Regardless - a google of "VSS Sucks" gives 30K hits...  I think if you did start using an alterantive - you will realize it's well worth the effort.

A: *

*Have CC.net label the successful builds

*have each project in the solution link to a common solutioninfo.cs file which contains assembly and file version attributes (remove from each projects assemblyinfo.cs)

*Before the build have cruise control run an msbuild regex replace (from msbuild community tasks) to update the version information using the cc.net build label (passed in as a parameter to the msbuild task)

*build the solution, run tests, fx cop etc

*Optionally revert the solution info file

The result is that all assemblies in the cc.net published build have the same version numbers which conform to a label in the source code repository

A: UppercuT can do all of this with a custom packaging task to split the applications up.  And to get the version number of the source, you might think about Subversion.
It's also insanely easy to get started.
http://code.google.com/p/uppercut/
Some good explanations here: UppercuT


text:
Q: Drawing grid pattern in matplotlib I would like to draw a sketch like the one below, using python with matplotlib. I guess making a grid is not so hard, but what about coloring certain squares in a specific way?

A: N = 15
# make an empty data set
data = np.ones((N, N)) * np.nan
# fill in some fake data
for j in range(3)[::-1]:
    data[N//2 - j : N//2 + j +1, N//2 - j : N//2 + j +1] = j
# make a figure + axes
fig, ax = plt.subplots(1, 1, tight_layout=True)
# make color map
my_cmap = matplotlib.colors.ListedColormap(['r', 'g', 'b'])
# set the 'bad' values (nan) to be white and transparent
my_cmap.set_bad(color='w', alpha=0)
# draw the grid
for x in range(N + 1):
    ax.axhline(x, lw=2, color='k', zorder=5)
    ax.axvline(x, lw=2, color='k', zorder=5)
# draw the boxes
ax.imshow(data, interpolation='none', cmap=my_cmap, extent=[0, N, 0, N], zorder=0)
# turn off the axis labels
ax.axis('off')


text:
Q: Create a KeyValuePair with Linq I'm developing a C# library with .NET Framework 4.6.2, Entity Framework 6.1.3 and Repository pattern.
I want to create a KeyValuePair<byte, string[]> in a select as follows:
Dictionary<string, byte> dict =
    GetAggregationLevelsNameId(arvatoConnectionString, productionOrderId);

KeyValuePair<byte, string[]>[] codes = null;

List<Data.Code> aCodes =
    repo.SearchFor(c => c.ProductionOrderId == productionOrderId).ToList();

if ((aCodes != null) && (aCodes.Count > 0))
{
    codes =
        aCodes
            .Select(ac => new { ac.Level, ac.Serial })
            .AsEnumerable()
            .Select(ac => new KeyValuePair<byte, string[]>(dict[ac.Level], ac.Serial))
            .ToArray();
}

But here .Select(ac => new KeyValuePair<byte, string[]>(dict[ac.Level], ac.Serial)) I get the following error:

Cannot convert string to string[].

How can I create a KeyValuePair<byte, string[]> in that select?
I want to group all the ac.Serial with the same ac.Level into a KeyValuePair.
ac is a struct that I haven't declare it anywhere. I create it here Select(ac => new { ac.Level, ac.Serial }).
ac.Level is a string.
ac.Serial is a string.
UPDATE:
I have this code that works converting the select into a Dictionary (note that the following dictionary has its key as a string, not as a byte that the one I want to create now):
GenericRepository<Data.Code> repo =
    new GenericRepository<Data.Code>(context);

codes =
    repo
        .SearchFor(c => c.ProductionOrderId == productionOrderId)
        .GroupBy(c => c.Level)
        .ToDictionary(dic => dic.Key, dic => dic.Select(c => c.Serial).ToList());

UPDATE 2:
The Data.Code is a POCO object that represents a Database table where there are a lot of Serial with the same Level.

A: Try this
codes =
    aCodes
        .AsEnumerable()
        .GroupBy(ac => dict[ac.Level])
        .Select(ac => new KeyValuePair<byte, string[]>(ac.Key, ac.Select(a => a.Serial).ToArray()))
        .ToArray();

Or to a dictionary:
codes =
    aCodes
        .AsEnumerable()
        .GroupBy(ac => dict[ac.Level])
        .ToDictionary(ac => ac.Key, ac.ToArray());


text:
Q: Regex PHP - Validation of email address function validateemail($email) {
$v = "/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/";

return (bool)preg_match($v, $email);
}
// check e-mail address, to see if it's a valid phone number
if ($validateemail($email)) {
$error = true;
echo 'Invalid phone number!';
}

I'm trying to check if an e-mail address is valid by the function validateemail, if it's an invalid phone number a message is displayed and $error is set to true. However I can't seem to get this code to work, there are no syntax errors as far as I know. Any advice would be appreciated.
BTW - I know there are other ways to validate e-mail addresses, this is for a college project and for that purpose we have to use regex.
Thanks in advance!

A: You have - not in the final position inside the first [a-zA-Z0-9_-.+] group.
Try
[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z]+
Have a look at this example.

A: You need to escape the dash as it can also be used to indicate a character range.
function validateemail($email) {
  $v = "/[a-zA-Z0-9_\-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/";
  return (bool)preg_match($v, $email);
}

A: If you only want to check if it is a valide e-mail or not, I'd suggest  filter_var($email, FILTER_VALIDATE_EMAIL, e.g.:
<?php
$email = "john.doe@example.com";

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}
?>

Source: www.w3schools.com/php/filter_validate_email.asp


text:
Q: Get the list of all possible numpy array column deletions Given the following numpy array:
>>> a = np.arange(9).reshape((3, 3))
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

How can get the list of all possible column deletions? So in this case:
array([[[1, 2],
        [4, 5],
        [7, 8]],

       [[0, 2],
        [3, 5],
        [6, 8]],

       [[0, 1],
        [3, 4],
        [6, 7]]])

A: You can use itertools.combinations:
>>> from itertools import combinations
>>> np.array([a[:, list(comb)] for comb in combinations(range(a.shape[1]), r=2)])

array([[[0, 1],
        [3, 4],
        [6, 7]],

       [[0, 2],
        [3, 5],
        [6, 8]],

       [[1, 2],
        [4, 5],
        [7, 8]]])

A: Alternatively you can create a list of needed column indices first and then use integer array indexing to pick up the required columns from the original array:
r = range(a.shape[1])
cols = [[j for j in r if i != j] for i in r]

cols
# [[1, 2], [0, 2], [0, 1]]

a[:, cols].swapaxes(0, 1)

#[[[1 2]
#  [4 5]
#  [7 8]]
#
# [[0 2]
#  [3 5]
#  [6 8]]
#
# [[0 1]
#  [3 4]
#  [6 7]]]


text:
Q: ST_BestSRID function in PostGIS This talk by Paul Ramsey mentions that there is a _ST_BestSRID function in PostGIS. I assume it exists to find the best projection when casting unprojected data for other uses.
I cannot find docs on this. Is it actually exposed, and if so, what are the parameters?

A: Yes that is correct.  The functions that start with _ are not documented because they are what we consider  "private" functions, not for general consumption.
If you look at the functions with smiley faces on this page:  http://postgis.net/docs/PostGIS_Special_Functions_Index.html#PostGIS_TypeFunctionMatrix
You will see they all use this _ST_BestSRID functions (and there are two forms of that function).  The smiley is meant to say these are functions using a hack, and not using pure geodetic calculate.
Study the code behind the smiley face functions and it should be clear how to use _STBestSRID in all its forms.


text:
Q: Properties of a linear operator given an inequality Let $X$ be a Banach** space and let $X'$ be its dual. Let $x_0 \in X$ and assume that there is $L \in X'$ such that for every $x \in X$ $$\frac{1}{2}\|x_0\|_X^2 - L(x_0) \le \frac{1}{2}\|x\|_X^2 - L(x).$$
I want to prove that $L(x_0) = \|x_0\|_X^2$ and furthermore that $\|L\|_{X'} = \|x_0\|_X$.
**I am not sure that we really need the space to be Banach (normed should be enough), but it is also true that performing only algebraic operations on the above inequality I could not prove anything.. So even if it is irrelevant for the formulation of the problem it is not impossible that we really need the space to be Banach.

A: For $\lVert\xi\rVert_X = 1$, on the line through $0$ and $\xi$, the minimal value of
$$h_\xi(t) = \frac{\lVert t\xi\rVert_X^2}{2} - L(t\xi) = \frac{1}{2}t^2 - t\cdot L(\xi)$$
is $-\frac{1}{2}L(\xi)^2$, attained at $t = L(\xi)$. Thus if
$$\frac{\lVert x_0\rVert_X^2}{2} - L(x_0) \leqslant \frac{\lVert x\rVert_X^2}{2} - L(x)\tag{1}$$
for all $x\in X$, then if $x_0 = 0$, we must have $L = 0$, and otherwise
$$\frac{\lVert x_0\rVert_X^2}{2} - L(x_0) \leqslant -\frac{1}{2} L\left(\frac{x_0}{\lVert x_0\rVert_X}\right)^2 \iff \left(L(x_0) - \lVert x_0\rVert_X^2\right)^2\leqslant 0,$$
so $L(x_0) = \lVert x_0\rVert_X^2$, whence $\lVert L\rVert_{X'} \geqslant \lVert x_0\rVert_X$. Furthermore we must then have
$$\lVert L\rVert_{X'}^2 = \sup_{\lVert\xi\rVert_X = 1} L(\xi)^2 \leqslant 2L(x_0) - \lVert x_0\rVert_X^2 = \lVert x_0\rVert^2,$$
and that means $\lVert L\rVert_{X'} \leqslant \lVert x_0\rVert_X$.
A completeness assumption for $X$ is not needed at any step. Furthermore, the above shows that $(1)$ holds for all $x\in X$ if and only if $\lVert L\rVert_{X'} = \lVert x_0\rVert_X$ and $L(x_0) = \lVert x_0\rVert_X^2$, and by the Hahn-Banach theorem(s), there is such an $L\in X'$ for every $x_0 \in X$.


text:
Q: Dudas con Funcion Sum Mysql Mi duda es simple, tengo una tabla de ventas y otra con los tipos de ventas (crédito, contado, instituciones_asociadas) que están relacionadas entre si, y necesito realizar un informe en donde obtener el total vendido por estas categorías, ejemplo: hoy vendí 100 mil contado, 300 mil en crédito.
esto lo logro con un:
SELECT TIP_VTA,SUM(TOT_VTA)
FROM VENTAS,TIPVTA
WHERE VENTAS.TIP_VTA=TIPVTA.COD_VTA
AND FEC_VTA = '2020-02-05'
GROUP BY TIP_VTA;

En el informe deben aparecer todas las categorías y esta consulta solo me las muestra todas si en la fecha que indique efectivamente se ocuparon estos tipos de venta.
Como podría realizar una consulta donde aparezcan todas las categorías independiente si se utilizaron o no en una fecha especifica. Lo que necesito es que si en la fecha indicada en la consulta no existen ventas crédito, por decir algo, esta aparezca pero con la sumatoria en 0.
De antemano muchas gracias.

A: Entiendo que puedes lograr esto utilizando un Join en tu consulta:
SELECT TIP_VTA,SUM(TOT_VTA)
FROM VENTAS
RIGHT JOIN TIPVTA
ON VENTAS.TIP_VTA=TIPVTA.COD_VTA AND FEC_VTA = '2020-02-05'
GROUP BY TIP_VTA;

De esta forma te aseguras de tener las filas de la tabla TIPVTA.
También puedes usar un LEFT JOIN que haría una lectura mas limpia de la consulta:
SELECT TIP_VTA,SUM(TOT_VTA)
FROM TIPVTA
LEFT JOIN VENTAS
ON VENTAS.TIP_VTA=TIPVTA.COD_VTA AND FEC_VTA = '2020-02-05'
GROUP BY TIP_VTA;

El LEFT JOIN te permite mostrar todos los registros de la tabla a la izquierda, en este caso TIPVTA y juntarlos con la otra tabla, quedando los valores que no tienen registros vinculados en null o en 0. Con el RIGHT JOIN ocurre lo mismo de forma análoga.

A: Puedes utilizar el OR en la condición de la fecha para que obtengas el resultado que esperas.
SELECT TIP_VTA,SUM(TOT_VTA) FROM VENTAS,TIPVTA WHERE VENTAS.TIP_VTA=TIPVTA.COD_VTA AND (FEC_VTA = '2020-02-05' OR FEC_VTA IS NULL OR FEC_VTA <> '2020-02-05') GROUP BY TIP_VTA;


text:
Q: Spring deferred result & request scoped bean(Oauth2ClientContext) in the web filter From my controller I'm returning deferred result which is filled by another thread:
FooController.java
@RequestMapping("/deferred")
public DeferredResult<String> deferred() throws InterruptedException, ExecutionException{
    DeferredResult<String> deferred = new DeferredResult<>();
    pagePreparer.setResult(deferred);
    return deferred;
}

PagePreparer.java
@Async
public void setResult(DeferredResult<String> result){
    try {
        logger.debug("Execute method asynchronously - " + Thread.currentThread().getName());
        Thread.sleep(2000l);
        result.setResult("deferred");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Apparently DeferredResult calls all the filters again to "finalize" the request. One of my filter, needs to access oauth2ClientContext bean, which is request scoped. That call is throwing an exception
2015-04-23 15:47:28.501 DEBUG 20530 --- [nio-8084-exec-3] com.fm.nd.common.web.Oauth2TokenFilter   : filtering
2015-04-23 15:47:28.525 DEBUG 20530 --- [nio-8084-exec-3] com.fm.nd.common.web.Oauth2TokenFilter   : clearing context
2015-04-23 15:47:28.529 DEBUG 20530 --- [cTaskExecutor-2] com.fm.nd.doc.service.PagePreparer       : Execute method asynchronously - SimpleAsyncTaskExecutor-2
2015-04-23 15:47:30.550 DEBUG 20530 --- [nio-8084-exec-4] com.fm.nd.common.web.Oauth2TokenFilter   : filtering
2015-04-23 15:47:30.551 DEBUG 20530 --- [nio-8084-exec-4] com.fm.nd.common.web.Oauth2TokenFilter   : clearing context
2015-04-23 15:47:30.557 ERROR 20530 --- [nio-8084-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet dispatcherServlet threw exception

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.oauth2ClientContext': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:352)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:187)
    at com.sun.proxy.$Proxy106.getAccessToken(Unknown Source)
    at com.fm.nd.common.web.Oauth2TokenFilter$$EPAf9Cq0.doFilter(Oauth2TokenFilter.java:59)
    at com.fm.nd.common.web.Oauth2TokenFilter$$DPAf9Cq0.doFilter(Unknown Source)
    at com.fm.nd.common.web.Oauth2TokenFilter.doFilter(Oauth2TokenFilter.java)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.fm.nd.common.web.TenantFilter.doFilter(TenantFilter.java:31)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:108)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:64)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:160)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter(OAuth2ClientContextFilter.java:57)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
    at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:639)
    at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:605)
    at org.apache.catalina.core.AsyncContextImpl$1.run(AsyncContextImpl.java:208)
    at org.apache.catalina.core.AsyncContextImpl.doInternalDispatch(AsyncContextImpl.java:367)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.asyncDispatch(CoyoteAdapter.java:388)
    at org.apache.coyote.http11.AbstractHttp11Processor.asyncDispatch(AbstractHttp11Processor.java:1705)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:650)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
    at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:41)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337)
    ... 73 common frames omitted

Looking at the exception I've configured:
@Bean
public RequestContextListener requestContextListener(){
    return new RequestContextListener();
}

But there's no difference. How can I solve this?

A: Actually it turns out, you have to do the following:
@Bean
public FilterRegistrationBean requestContextFilterRegistration(){
    FilterRegistrationBean filter = new FilterRegistrationBean();
    filter.setFilter(requestContextFilter());
    filter.setOrder(0);
    return filter;
}

@Bean
public RequestContextFilter requestContextFilter(){
    return new RequestContextFilter();
}


text:
Q: The geometry of functions $\mathbb{R}^2\rightarrow \mathbb{R}$ that satisfy the norm axioms What are constraints on the "looks" of a function $f:\mathbb{R}^2\rightarrow \mathbb{R}$, if $f$ satisfies $$f(x_1+x_2)\leq f(x_1) + f(x_2), \ \quad x_1,x_2\in \mathbb{R}^2 \quad \quad (1)$$i.e. the triangle inequality  ?
An answer should be something analoguous to: if $f$ satisfies  $f(\lambda x_1)=|\lambda| f(x_1),   x_1\in \mathbb{R}^2, \lambda \in \mathbb{R} $, then $f$ is a  function symmetric with respect to the planes defined be $y=0$ and $x=0$ (if $x$ and $y$ denote the first and second component of some vector $x_1$), such that on every line through the origin, $f$ is a linear function.
If we add continuity, then $f$ can be thought of to be glued together by planes and sections of   this function (which illstrates one extreme: Total roundness - vs. the function $(x,y)\mapsto y $ or $x$  which, if refrain from considering trivial functions, illustrates the other extreme of being totally not-round).
So I guess I'm  actually looking for properties describing the solution set of the "functional inequality" of $(1)$.
By the way, this question arose when I was trying to visualize how real functions in the plane look, if they satisfy the norm axioms. So even if you can't answer the above (more abstract) questions, maybe you can contribute to this.
EDIT (In response to M. Sleziaks comment) I would also welcome:
a) every answer that summarizes only the geometric aspects of subadditive functions in the book Martin Sleziaks named (since I'm rather short of time to dig through the whole chaprter that also covers algebraic and topologic/differenitiability results), if someone maybe already has read it.
b) geometric properties of real functions that satisfy all norm axioms (this may make the treatment easier since already the geometric results I described, that follow only from the positive homogeneity  axiom, seem to me to be rather restricting)


text:
Q: java and C# libraries for wi-fi here is a tough question :D
can anyone tell me the names of libraries concerning Wi-Fi as i want to build a mobile application that can connect to a local server through wi-fi and exchange information with it.
also i want to know which library is better and which language too ??
thanks in advance

A: for Java, I googled:
http://java.sun.com/products/sjwtoolkit/FAQ.html
see also:
http://msdn.microsoft.com/en-us/library/ms706783.aspx
http://msdn.microsoft.com/en-us/library/ms706274%28v=VS.85%29.aspx
http://managedwifi.codeplex.com/
got that from: http://bytes.com/topic/c-sharp/answers/811865-c-newbie-wifi-programming


text:
Q: Display data within date range in swift I have this method works, but how can I add to it a date range so only data within that date range will appear?
Note: I saved the date in all the receipt
code:
    func getGasTotal(completion:@escaping (Double) -> Void){
    let uid = (Auth.auth().currentUser?.uid)!

    var gasTotal = 0.0

    db.collection("User").document(uid).collection("Receipts").whereField("category", isEqualTo: "Gas")
        .getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                guard let snap = querySnapshot else {return}
                for document in snap.documents{
                    let data = document.data()
                    let total = (data["total"]) as! Double
                    gasTotal += total
                }
            }
            completion(gasTotal)
    }
    }


text:
Q: Android: Inserting data into SQLite database difficulties I have List of objects I want insert into database. I've created insert insert inside foreach loop, but it still ends with exception constraint failed. In my table I have created column '_id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL. My insert method looks like
    public void insertData(List<Item> list) {
        dbAdapter = DBAdapter.getDBAdapterInstance(getActivity());
        dbAdapter.openDataBase();
        for (Itemm item : list) {
            ContentValues values = new ContentValues();
            values.put("item_id", item.getItemId());
            values.put("item_category", item.getItemCategory());
            values.put("order_number", item.getOrderNumber());
            dbAdapter.insertRecordsInDB("order_list", null, values);
          }
          dbAdapter.close();
}

Here's DBAdapter class:
public class DBAdapter extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/<my_package>/databases/";
    private static String DB_NAME = "mydatabase.db";
    private static final int DB_VERSION = 1;

    private SQLiteDatabase myDataBase;
    private final Context myContext;

    private static DBAdapter myDBAdapter;

    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     *
     * @param context
     */
    private DBAdapter(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.myContext = context;
    }

    /**
     * getting Instance
     *
     * @param context
     * @return DBAdapter
     */
    public static synchronized DBAdapter getDBAdapterInstance(Context context) {
        if (myDBAdapter == null) {
            myDBAdapter = new DBAdapter(context);
        }
        return myDBAdapter;
    }

    /**
     * Creates an empty database on the system and rewrites it with your own
     * database.
     **/
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // do nothing - database already exist
        } else {
            // By calling following method
            // 1) an empty database will be created into
            // the default system path of your application
            // 2) than we overwrite that database with our database.
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        //SQLiteDatabase checkdb = null;
        boolean checkdb = false;
        try{
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            //checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
            checkdb = dbfile.exists();
        }
        catch(SQLiteException e){
            System.out.println("Database doesn't exist");
        }

        return checkdb;
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException {
        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);
        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;
        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);
        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    /**
     * Open the database
     *
     * @throws SQLException
     */
    public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
        if (!myDataBase.isReadOnly()) {
            myDataBase.execSQL("PRAGMA foreign_keys=ON;");
        }
    }

    /**
     * Close the database if exist
     */
    @Override
    public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();
        super.close();
    }

    /**
     * Call on creating data base for example for creating tables at run time
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    /**
     * can used for drop tables then call onCreate(db) function to create tables
     * again - upgrade
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // ----------------------- CRUD Functions ------------------------------

    /**
     * This function used to select the records from DB.
     *
     * @param tableName
     * @param tableColumns
     * @param whereClase
     * @param whereArgs
     * @param groupBy
     * @param having
     * @param orderBy
     * @return A Cursor object, which is positioned before the first entry.
     */
    public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
            String whereClase, String whereArgs[], String groupBy,
            String having, String orderBy) {
        return myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
                groupBy, having, orderBy);
    }

    /**
     * select records from db and return in list
     *
     * @param tableName
     * @param tableColumns
     * @param whereClase
     * @param whereArgs
     * @param groupBy
     * @param having
     * @param orderBy
     * @return ArrayList<ArrayList<String>>
     */
    public ArrayList<ArrayList<String>> selectRecordsFromDBList(
            String tableName, String[] tableColumns, String whereClase,
            String whereArgs[], String groupBy, String having, String orderBy) {
        ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
        ArrayList<String> list = new ArrayList<String>();
        Cursor cursor = myDataBase.query(tableName, tableColumns, whereClase,
                whereArgs, groupBy, having, orderBy);
        if (cursor.moveToFirst()) {
            do {
                list = new ArrayList<String>();
                for (int i = 0; i < cursor.getColumnCount(); i++) {
                    list.add(cursor.getString(i));
                }
                retList.add(list);
            } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        return retList;

    }

    /**
     * This function used to insert the Record in DB.
     *
     * @param tableName
     * @param nullColumnHack
     * @param initialValues
     * @return the row ID of the newly inserted row, or -1 if an error occurred
     */
    public long insertRecordsInDB(String tableName, String nullColumnHack,
            ContentValues initialValues) {
        return myDataBase.insert(tableName, nullColumnHack, initialValues);
    }

    /**
     * This function used to update the Record in DB.
     *
     * @param tableName
     * @param initialValues
     * @param whereClause
     * @param whereArgs
     * @return true / false on updating one or more records
     */
    public boolean updateRecordInDB(String tableName,
            ContentValues initialValues, String whereClause, String whereArgs[]) {
        return myDataBase.update(tableName, initialValues, whereClause,
                whereArgs) > 0;
    }

    /**
     * This function used to update the Record in DB.
     *
     * @param tableName
     * @param initialValues
     * @param whereClause
     * @param whereArgs
     * @return 0 in case of failure otherwise return no of row(s) are updated
     */
    public int updateRecordsInDB(String tableName, ContentValues initialValues,
            String whereClause, String whereArgs[]) {
        return myDataBase.update(tableName, initialValues, whereClause,
                whereArgs);
    }

    /**
     * This function used to delete the Record in DB.
     *
     * @param tableName
     * @param whereClause
     * @param whereArgs
     * @return 0 in case of failure otherwise return no of row(s) are deleted.
     */
    public int deleteRecordInDB(String tableName, String whereClause,
            String[] whereArgs) {
        return myDataBase.delete(tableName, whereClause, whereArgs);
    }

    // --------------------- Select Raw Query Functions ---------------------

    /**
     * apply raw Query
     *
     * @param query
     * @param selectionArgs
     * @return Cursor
     */
    public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
        return myDataBase.rawQuery(query, selectionArgs);
    }

    /**
     * apply raw query and return result in list
     *
     * @param query
     * @param selectionArgs
     * @return ArrayList<ArrayList<String>>
     */
    public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query,
            String[] selectionArgs) {
        ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
        ArrayList<String> list = new ArrayList<String>();
        Cursor cursor = myDataBase.rawQuery(query, selectionArgs);
        if (cursor.moveToFirst()) {
            do {
                list = new ArrayList<String>();
                for (int i = 0; i < cursor.getColumnCount(); i++) {
                    list.add(cursor.getString(i));
                }
                retList.add(list);
            } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        return retList;
    }

}

I don't know what I'm doing wrong. How can I insert data from my list into DB? Every help is appreciated. Thank you.


text:
Q: All possible permutations of parameters using Spock's Unroll I have the following parameters for the same test:
  a  |  b  |  c
  1  |  2  |  3
 11  | 22  | 33

Spock provides the @Unroll annotation for tests similar to this (with this set of parameters you can run to same tests with the vectors [1, 2, 3] and  [11, 22, 33]).
However, I need to run the same test for all the possible permutations (e.g [1, 2, 3], [1, 2, 33], [11, 2, 33] and etc, all the 8 combinations). How can I achieve it?
Thanks for any thoughts!

A: You need
where:
[a, b, c] << [[1, 11], [2, 12], [3, 13]].combinations()


text:
Q: Microservice- error in bringing up config server org.springframework.boot.context.properties.bind.BindResult I'm getting below error when trying to bring up config server. Looks incorrect jar version
any suggestions please
Error
 Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.cloud.config.server.composite.CompositeEnvironmentBeanFactoryPostProcessor.bindProperties(CompositeEnvironmentBeanFactoryPostProcessor.java:81)

The following method did not exist:

    'java.lang.Object org.springframework.boot.context.properties.bind.BindResult.orElseCreate(java.lang.Class)'

The method's class, org.springframework.boot.context.properties.bind.BindResult, is available from the following locations:

    *jar:file:/C:/Users/GOPU/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/2.4.0-M1/503562062a9baee246bb7311526d08d16ae05758/spring-boot-2.4.0-M1.jar!/org/springframework/boot/context/properties/bind/BindResult.class*

The class hierarchy was loaded from the following locations:

    org.springframework.boot.context.properties.bind.BindResult: file:/C:/Users/GOPU/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/2.4.0-M1/503562062a9baee246bb7311526d08d16ae05758/spring-boot-2.4.0-M1.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.boot.context.properties.bind.BindResult

Build.gradle
plugins {
    id 'org.springframework.boot' version '2.4.0-M1'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.cloud'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '13'

repositories {
    mavenCentral()
    maven { url 'https://repo.spring.io/milestone' }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.cloud:spring-cloud-config-server'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    implementation 'org.springframework.boot:spring-boot-starter'
}

dependencyManagement {
    imports {
        mavenBom 'org.springframework.cloud:spring-cloud-dependencies:Hoxton.RELEASE'
    }
}

test {
    useJUnitPlatform()
}

Mainfile
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;

@EnableConfigServer
@EnableDiscoveryClient
@SpringBootApplication
public class ConfigApplication {

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

}


text:
Q: On Bootstrap TAB click, init() function is calling everytime in angularJs I am trying to implement dynamic tabs like this on abc.html. I'm using SPA using angularJS and HTML5 and Bootstrap with ($locationProvider.html5Mode(true).hashPrefix('!');) to remove # .
I've abcController.js, Which contains init function like below.
(function init() {
        getUser();
})();

function getUser() {
        // Code
};

Problem: When i click on any tab, the init() function is calling.how to prevent this?  my url looks like this http:localhost:1234/user, on mouseover of X tab it shows http:localhost:1234/user#X


text:
Q: Porting an old fortran program to work with python+numpy I am supposed to be doing research with this huge Fortran 77 program (which I recently ported to Fortran 90 superficially). It is a very old piece of software used for modeling using finite element methods.

*

*It is a monstrosity. It is roughly 240,000 lines.

*Since it began its life in Fortran 77, it uses some really dirty hacks for dynamic memory allocation; basically it uses the functions from the C standard library, mixed programming with C and Fortran. I am yet to fully grasp how allocation works. The program is built to be easily extendable by the user, and the user generally needs to allocate some globally accessible arrays for later use. This is done by having an array of memory addresses, which point to the beginning addresses of dynamically allocable arrays. Of course, which element of the address array pointing to which information all depends on conventions which has to be learned by the user, before one can start to really program. There are two address arrays, one for integers, and the other for floating points.

*By dirty hacks, I mean inconsistent ones. For example an update in the optimization algorithm of the GNU compilers caused the program to exit with random memory leaks.

*The program is far from elegant. Global variable names are generally short (3-4 characters) and cryptic. Passing data across routines is of course accomplished by using common blocks, which include all program switches, and the aforementioned arrays.

*The usage of the program is roughly like that of an interactive shell, albeit a stupid one. First, an input file is read by the program itself, then per choice, the user is dropped into a pseudo-shell, in which the user has to type 4 character wide commands, followed by the parameters. The parser then parses the command, and corresponding subroutine is called with the parameters. You would guess that there is a loop structure in this pseudo-parser (a goto bonanza, rather) which wraps the subroutine behavior in a manner more complex than it should be in the 21st century.

*The format of the input file is the same (commands, then parameters), since it is the same parser. But the syntax is not really consistent (by that, I mean it lacks control structures, and some commands cause the finite state machine to do behavior that contradict with other commands; it lacks definite grammar), time to time causing the end user to discover pitfalls. The user must learn these pitfalls by experience; I did not see them in any documentation of the program. This is a problem that can easily be avoided with python, and it is not even necessary to implement a parser.

What I want to do:

*

*Port parts of the program into python, namely the parts that don't have anything to do with numerical computation. This includes

*

*cleaning up and abstracting the API with an OOP approach in python,

*giving meaningful variable names,

*migrating dynamic allocation to either numpy or Fortran 90 and losing the C part,

*migrating non-numerical execution to python, and wrap the numerical objects using f2py, so there is no loss in performance. Have I told that the program is damn fast in its current state? Hopefully porting the calls to numerical subroutines and I/O to python will not slow it down to an impractical level (or will it?).

*Making use of python's interactive shell as a replacement for the pseudo-shell. This way, there will not be any inconsistencies for the end user. The aforementioned commands will be simply replaced by functions defined in python. This will allow the user to actually access the data. Plus, the user will be able to extend the program without going to deep.

What I wonder:

*

*Is f2py suitable and up-to this task of wrapping numerous subroutines and common blocks without any confusion? I have only seen single-file examples on the net for f2py; I know that numpy has used it to wrap LAPACK and stuff, but I need reassurance that f2py is a tool consistent enough for this task.

*Whether there are any suggestions on the general strategy that I should follow, or pitfalls I should avoid.

*How can & should I implement a system in this python-wrapped Fortran 90 environment, so that I will be able to modify (allocate and assign) globally accessible arrays and variables inside fortran routines. This should preferably omit address arrays and I should preferably be able to inject verbal representations into the namespaces. These variables should preferably be accessible inside both python and fortran.

Notes:

*

*I may have been asking for too much, something beyond the boundaries of the possible realm. In this case, please forgive me for I am a beginner with this aspect of programming; and don't hesitate to correct me.

*The "program" I have been talking about is open source but it is commercial and the license does not allow its distribution, so I decided not to mention its name. However, you could deduce it from the 2nd sentence and the description I gave throughout.

A: I'm doing something depressingly similar. Instead of dynamic memory allocation via C we have a single global array with integer indices (also at global scope), but otherwise it's much the same. Weird, inconsistent input file and all.
I'd advise against trying to rewrite the majority of the program, whether in python or anything else. It's time consuming, unpleasant and largely unnecessary. As an alternative, get the F77 code base to the point whether it compiles cleanly enough that you're willing to trust it, then write an interface routine.
I now have a big, ugly F77 code base which sits behind an interface. The program requires input as a text file so a large part of the interface's job is to produce that text file. Beyond that, the legacy code is reduced to a single gateway routine which takes a few arguments (including a means of identifying the text file) and returns the answer. If you use the iso_c_binding of Fortran 2003 you can expose the interface in a format C understands, at which point you can link it to whatever you wish.
As far as the modern code (mostly optimisation routines) is concerned, the legacy code base is the single subroutine behind the C interface. This is much nicer than trying to modify the old code further and probably a valid strategy for your case as well.

A: For an example how to generate the f2py interface library using multiple fortran files see this post.
f2py might be suitable for your task, but there are some pitfalls that might cause some problems. Some pitfalls concerning f2py are listed here and summarized below:

*

*Concerning your specific problem you might run into problems with your allocatable arrays, because f2py was writen for Fortran77 and does not support many of the Fortran90+ features (such as allocatable arrays).

*I also encountered a problem with an undocumented maximum array size (arround 400 x 200 x 20 x 20). If I used arrays bigger then that f2py would not be able to generate the python library. Especially the large matrices being passed arround in finitie element codes might be too big for interfacing. Therefore you would not have access to those in the Python part of the program.

*Beneficial for you is that f2py should have no Problems with COMMON Blocks, etc. because it was especially written for Fortran77.

*After passing the data through the interface to the Fortran routines, there should be no (or only minimal) slowdown if you do it right. The key is to minimize calculations in the Python part of the program per run. This includes the manipulation of the data arrays (shift, rotate, copy, etc.) but not passing of them (because the interface is pass-by-reference).

As an alternative you should have a look at Cython (also see the Link above and the linked working example therein). I think this might serve you better in the long run.

Implementation Suggestion
This suggestion is how I would do it incorporating my experiences with having done something similar (see Background below). It should largely be independent of how you interface the Python and Fortran code (f2py, Cython, ...).
Of course you should be very careful to not change the behaviour and therefore possibly the results of the program. Therefore generation of some tests and their corresponding reference in- & output files and test documentation including all steps, keystrokes, commands, etc. necessary to reproduce those results should be your first step.
In your case I would try to change the least amount possible of the Fortran program. I would try to wedge the "pseudo-shell" from the Fortran code, e.g. making it its own module, and build an interface to that module. Like that you can use all of the original Fortran code and the modifications, bugfixes and updates from your peers, even in the future. The key is to not distance your code to far from the original/ mainstream because in scientific communities usually not everybody will agree with major changes to the source code and update their workflow or source code accordingly. Therefore future work from your peers might not be made in your version, but in the original source code and it would be your own responsibility to merge those changes into your version, which gets easier the less you change.
Using that interface you can work on your python shell and maybe even build a GUI for it without having to worry about changing anything in the original progam. This reduces the risk to introduce bugs or change the results of the original. Your Shell/ GUI would therefore work as a wrapper around the original program to simplify the workflow and remove inconsistencies. All the "intelligence" and utilities, like error & cross checking of the user-input, help pages, tutorials/ howto, etc. would be implemented in the Python wrapper, which would parse these inputs, translate them to the corresponding commands for your Fortran program, send them and wait for the results.
After you have simplified the usage of the program I would write some automatisation for the tests (setup + evaluation) to complete your utilities suite. Like that even somebody new to the program would be able to make changes to the code without having to worry about unknowingly changing the results. This should enable your tools to benefit the community which will attract new users and therefore encourage further development within the community.
Only as the last step I would replace the parts of the code using C with Fortran90+ methods to simplify the code. This is an extensive change of the codebase and needs a lot of tests to ensure EVERY possible combination of commands is checked and verified before and after the changes.
This method also has the benefit, that you could possibly make your interface/ GUI open source (you have to check the licence of your program of course) as long as it is seperable from the source code of the Fortran program. The Fortran - Python interface would have to be provided, or installed/ generated from source files when your interface is loaded using some simple build skript as seen in the first link of this post.
For the manipulation of internal data I would write a seperate wrapper routine, that only handles the data interface. This should be done in Cython though to enable you to use allocatable arrays, etc. Because this interface would work with "pass-by-reference" you should be able to use the full collection of Python (numpy) tools to manipulate the arrays and data.

Background
I did something similar using our research code for helicopter rotordynamics. This is also a very old and large program written in Fortran77 (e.g. goto bonanza). The newer additions and modifications to the code are usually done in Fortran90/2003.
Using parts of this code (several subroutines & module files) I generated a python library to connect our GUI (Python & Qt) to the Fortran program; mainly for postprocessing of Fortran binary output files.


text:
Q: Unable to create node lables for nodepools in azure AKS I want to create labels for each node under a nodepool , but i dont find this option in azure cli , can someone help me with this?
Expected :
Must be able to label nodepools which can help in autoscaling and pod scheduling.

A: Adding labels is a feature that is still in progress (tracked here: https://github.com/Azure/AKS/issues/1088).
However, you can add Taints using ARM: https://learn.microsoft.com/en-us/rest/api/aks/agentpools/createorupdate#examples or Terraform: https://www.terraform.io/docs/providers/azurerm/r/kubernetes_cluster.html#node_taints (looks like the CLI still lacks the functionality).


text:
Q: Why am I getting a Java IO Exception in this very simple code? The following is some sample code I created to get myself more familiar with Groovy. I have a good understanding of Java and I am trying to now learn this new language.
class Activity {

    static void reverseString() {

        def text

        System.in.withReader{

            println "Enter a string to be reversed:"
            text = it.readLine()
        }

        print "\n";
        for (int i = text.length() - 1; i >= 0; i--){

            print text[i];

        }
    }

    static void main(String[] args) {

        def selection

        System.in.withReader{

            println "Select a project:"
            println "1 - Reverse String"
            selection = it.readLine()

        }

        switch (selection) {

            case "1":
                reverseString()
                break
        }
    }
}

I am able to compile and run this code. I am able to enter '1' and press enter, and then the prompt from my method shows up. At this point I am supposed to enter a string to reverse, but before I can enter I get the IO Exception:

Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
at java.io.BufferedInputStream.read(BufferedInputStream.java:336)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at sun.nio.cs.StreamDecoder.read0(StreamDecoder.java:127)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:112)
at java.io.InputStreamReader.read(InputStreamReader.java:168)
at Activity$_reverseString_closure1.doCall(main.groovy:10)
at Activity.reverseString(main.groovy:7)
at Activity.main(main.groovy:39)

What am I missing here?

A: The purpose of withReader() is to ensure the stream is closed. So after the project selection is input in the main() method, the stream is closed. When reverseString() is executed, it's too late; the stream is closed.
Don't close System.in (directly, or through withReader) . Only close streams that your code creates, not streams that your application receives from a caller, or global instances in the runtime.


text:
Q: How to git merge changes from main branch to orphan branch without adding to orphan's history? I have a git repository for my phd dissertation (in latex). The university policies does not allow me to share the background review chapter of my dissertation with my research adviser, I am free to share and get opinion for other chapters.
To share the repository with my advisor I created an orphan branch (noRevBranch) with the required chapter removed and pushed and tracked this branch to a new repository on github.
I can share this with his and he can not access the removed chapter because there is no history here.
The question is how do I merge any changes I make to the master branch in the future to the noRevBranch without also appending the master branch history to the new merge commit?

A: You can leave the structure as its right now.
What you can do is to use git cherry-pick <range of commits> to commit all the new commits to the "orphan" branch.
git cherry-pick <SHA-1>...<SHA-1>

Apply the change introduced by the commit at the tip of the master branch and create a new commit(s) with this change.

The syntax of the ... is a commit range. grab all commits from start (exclude) to the last one.

Read out the full git cherry-pick documentation for all the options you can use

A: I think you're doing it backwards. You need to think of noRevBranch as master and do all your commits on that branch. If don't push the branch with the background chapter (revBranch) to Github, you can rebase it whenever you need to. History of this branch will never be shared with your adviser because it's a local branch stored only on your computer, and since it was never merged into noRevBranch your advisor won't have access to its history either. But the key is that you're doing your commits (that do not affect the background chapter) on noRevBranch, since this will allow you to easily pull them into revBranch by rebasing.

EDIT in response to jlanza:
If I was starting this from scratch, I would do it like this:

*

*Make master your public branch. Commit all your "public" work so far to this branch. Never commit any "private" work to this branch.

*Make a new private branch based on master. We'll call it private. git checkout -b private. Commit anything that you don't want to share publicly to this branch.

*Whenever you commit work that you want to share publicly, commit that work to master. You can push this branch to wherever your repo is hosted whenever you want. git push origin master:refs/heads/master.

*Whenever you commit work that you don't want to share publicly, commit that work to private. Don't push this branch to any public repositories.

*You can keep private up-to-date with master either by merging or re-basing. Something like git checkout private && git merge master.


text:
Q: switching between cin and ifstream using a function I am trying to manipulate an array with functions while switching between standard cin, cout and ifstream,ostream.
Specifically, I have an array of books and I have some basic functions like search title, publisher, price, etc. I also have 2 functions called "login" and "logout" to open a file and redirect bookList's istream and ostream to that outputfile when login, as well as close it and return back to istream, ostream when logout.
void bookList(istream& in, ostream& out)
{
    //ask for command from istream in
    //command selection loop
}

int load(ofstream& out, book booklist[], int size)
{
    //load list of books from input file
}

void logon(ofstream& out, string filename)
{
    out.open(filename.c_str());
}

void logoff(ofstream& out, string filename)
{
    out.close();
}
// some other functions

I also need to print out notification to the user (either onscreen when logged off or on file when logged on) whenever a function is called.
My tried to put ifstream& as a parameter in each functions, but they only print out to text file not on screen (because its just ifstream, not istream), but doing it the other way won't work.
My question is that is there method that can make function logon redirect istream of bookList to ifstream to the outputfile and vice versa for logoff? Rather than a "is-file-open" condition.

A: This may not be directly what your looking for but can be modified.
/// this buffer will be used to switch output
void IO_Switch(streambuf* buffer);

int main(){
    streambuf *buffer
    ofstream fout;
    fout.open("filename.txt");

    // below you call cout.rdbuf() which directs stream to cout
    IO_Switch(cout.rdbuf());
    cout << "This is coming to the console";
    // below you call fout.rdbuf());
    IO_Switch(fout.rdbuf());
    cout << "I used cout here, but the stream is redirected to fout ("filename.txt")

    return 0;
}

void IO_Switch(streambuf* buffer){
    cout.rdbuf(buffer);
}


text:
Q: Media Player not playing sound properly in Android on charger connection I am new to software developing and i am trying to make an application that will play a sound when it charges. The first time i connect it to the charging cable, it plays the sound two times, which is not expected. Also, when i connect and disconnect the cable too quick, it also plays it twice.
Does anyone know the solution to this problem?
package com.mccharginggimmick;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

IntentFilter intentFilter;
BroadcastReceiver broadcastReceiver;
MediaPlayer mediaPlayerOff;
MediaPlayer mediaPlayerOn;
boolean playedOnceOn;
boolean playedOnceOff;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {

    View decorView = getWindow().getDecorView();
    int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
    decorView.setSystemUiVisibility(uiOptions);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imageView = (ImageView) findViewById(R.id.imageView);
    intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;

            if(isCharging){
            onCharge();
            }
            else{
            onDisconnect();
            }
        }
    };
    MainActivity.this.registerReceiver(broadcastReceiver, intentFilter);
}
public void onCharge(){

    if(!playedOnceOn){
        imageView.setVisibility(View.INVISIBLE);
    mediaPlayerOn = MediaPlayer.create(this, R.raw.btnon);
    mediaPlayerOn.start();
    mediaPlayerOn.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayerOn.stop();
            playedOnceOn = true;
            playedOnceOff = false;
        }
    });
    }
}
public void onDisconnect(){

    if(!playedOnceOff){
        imageView.setVisibility(View.VISIBLE);
    mediaPlayerOff = MediaPlayer.create(this, R.raw.btnoff);
    mediaPlayerOff.start();
    mediaPlayerOff.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayerOff.stop();
            playedOnceOff = true;
            playedOnceOn = false;
        }
    });
    }
}
}

A: define isCabelConnected inside class
boolean isCabelConnected = false;

then in your onClick
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
            boolean isFullCharged = status == BatteryManager.BATTERY_STATUS_FULL;

            if(isCharging && !isCabelConnected){
            onCharge();
            isCabelConnected = true;
            } else if (isFullCharged && isCabelConnected){
            onCharge();
            }
            else{
            onDisconnect();
            isCabelConnected = false;
            }

this code will make a sound when cable connected and another sound when full charge


text: Q: Google Places API: deprecated types I am using Google Places API in my project. Google deprecated the "establishment" type and the notice said that it still be available till 2017 but I can no longer access the data that my application is getting before the type is deprecated. Is there a way of fixing it? Thanks!


text:
Q: Where can we find all the app setting for Azure App Services Where can we find list of app settings for azure app services for example there is
WEBSITES_ENABLE_APP_SERVICE_STORAGE, WEBSITE_ENABLE_SYNC_UPDATE_SITE. What are all the other WEBSITE_....options available.

A: The options available are similar to those you'd put into Web.config, etc.
See Microsoft Docs

A: The API Documentation will list out all the available to those in the App Service though I'm not sure if your asking about these or specific web.config settings as another post answered.

A: Is this what you want?
Configuration > Application Settings. Then you will find the app settings.


text:
Q: PHP - Echo multidimentional array as HTML list I'm looking to write a function that takes an array of pages/categories (from a flat database result) and echo to a nested page/category
 (HTML unordered list) items based on the parent ids. I would like to do this recursively, so that any level of nesting can be done.
+-------+---------------+---------------------------+
|   id  |   parent_id   |           title           |
+-------+---------------+---------------------------+
|   1   |       0       |   Parent Page             |
|   2   |       1       |   Sub Page                |
|   3   |       2       |   Sub Sub Page            |
|   4   |       0       |   Another Parent Page     |
+-------+---------------+---------------------------+

And this is the array I would like to end up with to process in my view files:
Array
(
[0] => Array
    (
        [id] => 1
        [parent_id] => 0
        [title] => Parent Page
        [children] => Array
                    (
                        [0] => Array
                            (
                                [id] => 2
                                [parent_id] => 1
                                [title] => Sub Page
                                [children] => Array
                                            (
                                                [0] => Array
                                                    (
                                                        [id] => 3
                                                        [parent_id] => 1
                                                        [title] => Sub Sub Page
                                                    )
                                            )
                            )
                    )
    )
[1] => Array
    (
        [id] => 4
        [parent_id] => 0
        [title] => Another Parent Page
    )
)

I found this article which is SIMILAR but NOT DUPLICATE to the one I'm posting, which is where I found the below function which could help with the answer.
function buildTree(array $elements, $parentId = 0) {
$branch = array();

foreach ($elements as $element) {
    if ($element->parent_id == $parentId) {
        $children = buildTree($elements, $element->id);
        if ($children) {
            $element->children = $children;
        }
        $branch[] = $element;
    }
}

return $branch;
}

$tree = buildTree($rows);

EDIT:
I want to echo the data in the below structure:

Parent Page

Sub Page

Sub Sub Page

Another Parent Page

A:
Try this function and change as your requirement:

function buildTree(Array $data, $parent = 0) {
$tree = array();
foreach ($data as $d) {
    if ($d['parent'] == $parent) {
        $children = buildTree($data, $d['id']);
        // set a trivial key
        if (!empty($children)) {
            $d['_children'] = $children;
        }
        $tree[] = $d;
    }
}
return $tree;
}

function printTree($tree, $r = 0, $p = null) {
foreach ($tree as $i => $t) {
    $dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) .' ';
    printf("\t<option value='%d'>%s%s</option>\n", $t['id'], $dash, $t['name']);
    if ($t['parent'] == $p) {
        // reset $r
       $r = 0;
    }
    if (isset($t['_children'])) {
        printTree($t['_children'],$sel, ++$r, $t['parent']);
    }
}
}
$rows = array('your array');

$tree = buildTree($rows);

print("<select name='selectionParentpage' class='just_textfield' id='selectionParentpage'><option value=''>--Select Page--</option>\n");
printTree($tree);
print("</select>");

A: Here is what you can do for the view part
function displayRecursive($array){
    echo "
";
        foreach($array as $value){
        echo "
".$value['name']."";
            if(isset($value['children']) && !empty($value['children'])){
                displayRecursive($value['children']);
            }
        }
    echo "
";
}

You can use something like this to get the treeview array:
    function recursive($parentId=0){

    $return = array();

    $titles=$this->db->query("
                SELECT      `t1`. * , `t2`.`id` AS `has_children`
                FROM        `titles` `t1`
                LEFT JOIN   `titles` `t2` ON ( `t1`.id = `t2`.`parent_id` )
                WHERE       `t1`.`parent_id` = '$parentId'
                GROUP BY    `t1`.`id` ")->result_array();
    if(!empty($titles)){
        foreach ($titles as $k=>$title){
            $item = $title;
            if ($title['has_children']>0){
                $item['sub'] = self::recursive($title['id']);
            }
            array_push($return, $item);
        }
    }

    return $return;
}


text:
Q: Grunt uglify - replace original file I have an angular application that uses require.js to load all scripts. The application is deployed to the web server using Hudson CI. When the deploy job runs, I want to:

*

*Minify all JavaScript files but preserve the original file names so that the require.js config file works out of the box.

*Have an option to exclude specific JavaScript files while running uglify.

The JS files are distributed all across the application, which has an ontology similar to the following:
app/
    common/
    controllers/
    factories/
    services/
assets/
    js/

Is there a way to do this?

A: you need grunt-contrib-uglify
for the excluding files requirement:
http://gruntjs.com/configuring-tasks#files


text:
Q: how do i move a object with direction of touch unity I am a beginner at game developing. I am developing a game where I have a ball and I want to move it by touch. I want it to move just like a soccer game where the ball can move in the direction of the touch.
However, right now it can only seem to move in the forward direction! Here is my code:
 public float ThroughSpped;
 public float ArchSpped;
void OnMouseDown() {

         distance = Vector3.Distance (transform.position, Camera.main.transform.position);
         Dragging = true;

     }
     public void OnMouseUp()
     {
         //Instantiate(this) ;
         this.GetComponent<Rigidbody> ().useGravity = true;

     this.GetComponent<Rigidbody> ().velocity += this.transform.forward*ThroughSpped;
         this.GetComponent<Rigidbody> ().velocity += this.transform.up*ArchSpped;
         Dragging = false;

     }

 void DraggingBall()
 {
     if (Dragging)
     {
         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
         Vector3 raypoint = ray.GetPoint (distance);
         transform.position = Vector3.Lerp (this.transform.position, raypoint, Speed * Time.deltaTime);
         Destroy(BallPrefabClone, 1f);
     }
 }

A: You can use touch phase to get the start position of the touch and end position of the touch to calculate the vector/direction of the touch
Then add force to your ball using this new vector
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public Vector2 startPos;
    public Vector2 direction;
    public bool directionChosen;
    void Update()
    {
        // Track a single touch as a direction control.
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            // Handle finger movements based on touch phase.
            switch (touch.phase)
            {
                // Record initial touch position.
                case TouchPhase.Began:
                    startPos = touch.position;
                    directionChosen = false;
                    break;

                // Determine direction by comparing the current touch position with the initial one.
                case TouchPhase.Moved:
                    direction = touch.position - startPos;
                    break;

                // Report that a direction has been chosen when the finger is lifted.
                case TouchPhase.Ended:
                    directionChosen = true;
                    break;
            }
        }
        if (directionChosen)
        {
            // Something that uses the chosen direction...
        }
    }
}

https://docs.unity3d.com/ScriptReference/Touch-phase.html


text:
Q: Add class on body in Wordpress How to add class on body for certain page and that class to be visible for all languages for that page, because my side running on 7 languages?
For example if I have page About us on her body I want to add class and to be visible for other languages for page About us?
I

A: Sample code:
if ( is_page( 'your-page-slug' ) ) {
   add_filter( 'body_class', function( $classes ) {
       return array_merge( $classes, array( 'class-name' ) );
   } );
}

Reference of filter.


text:
Q: How can I get a list of files in a directory I am having difficulty in counting the number of text files in a folder. I used these commands to get path. Now I want to count the number of text files in a folder.
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();

string files = fbd.SelectedPath;
textBox2.Text = files;

A: If you just want to get the count of txt files then use this:
int count = Directory.GetFiles(fbd.SelectedPath, "*.txt").Length;

There's also a third parameter that you can use called searchOption which uses the SearchOption enumeration.
You can specify either AllDirectories or TopDirectoryOnly.

A: just use Directory class
  string [] fileEntries = Directory.GetFiles(fbd.SelectedPath,"*.txt");
  textBox2.Text = fileEntries.Length.ToString() ;


text:
Q: PHP - /tmp permission error Basically, I have an .htaccess file, with php_value session.auto_start set to 1.
So my session will start in any file.
However, now I have a script in my /functions folder, but it gives an error about the permissions of the /tmp, resulting in "Failed to write session data", though it doesn't  use, start or do anything with the session.
Yet this produces an error, and to me, it looks like it cannot find the /tmp folder, which I do have. Files directly in my root folder (/) don't have this a problem.
I also tried setting the permissions of /tmp to 777, to no avail.
Thanks in advance

The error I'm getting
Warning: Unknown: open(/tmp/sess_cfed7db100fd58b62eaca2a519ebaf7a, O_RDWR) failed: Permission denied (13) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0

The script itself:
<?php
define ('INCLUDE_CHECK',true);
require('connect.php'); //This file doesn't use any sessions as well

if(isset($_POST['signupemail'])){
    $email = mysqli_real_escape_string($link, $_POST['signupemail']);
    $thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE email=\"".$email."\""));

    if($thearray[0] > 0){
        echo '"This emailaddress is already in use"';
        exit;
    }
    echo "true";

} else if(isset($_POST['uname'])){

    if(!preg_match('/^[a-zA-Z0-9_-]{3,16}$/ ',$_POST['uname'])){
        echo '"<small>Please only use alphanumeric characters, underscores and hyphens</small>"';
        exit;
    }

    $uname = mysqli_real_escape_string($link, $_POST['uname']);
    $thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE uname=\"".$uname."\""));
    $forbiddennames = array(1 => 'super-user','superuser', 'root', 'admin', 'administrator', 'system', 'website', 'site', 'owner', 'manager', 'founder','moderator');

    if(in_array(strtolower($_POST['uname']), $forbiddennames)) {
        echo '"'.$_POST['uname'].' is a forbidden username"';
        exit;
    }
    if($thearray[0] > 0){
        echo '"This username is already in use, please choose another"';
        exit;
    }

    echo "true";

}
?>

I get the error when I just browse manually to my script, so without any $_POST parameters set. I use this script to verify one's email and/or password, and when checking, it stops, not knowing what to do with the result (gotten by AJAX).

A: I think i remember some php.ini setting that prevents access to files that are not in the webserver's directory tree. I don't know if that applies to files that are generated internally by php, though.
If you're running on Red Hat Enterprise linux, or some derivative like CentOs or Scientific Linux, it might also be a problem with selinux. Check if the problem goes away if you set selinux to permissive (sudo setenforce Permissive). If that "fixes" the problem, think twice about leaving selinux in Permissive mode, especially if your server is reachable from the internet, better learn about selinux and relabeling.

A: Uhm, it turned out to be browser-related.
When I tested it in FireFox, no problem.
In Google Chrome, big problem.
I don't know what it was, but after deleting the cache, cookies, everything from my site, it worked perfectly. Seemed like it was searching for an old session.