text:
Q: Creating dynamic folder with imacro I have a list of URLs for which I am taking screenshots with their respective domain names,now I want these screenshots to be stored in the folders with their respective domain names, which I want to be created dynamically, so is there any way to create a folder using imacro at runtime.
Following is the piece of code which I am using
var iterations = prompt("Please enter total count of URLs");
var file1 =  prompt("Please enter file name of URLs");
file1 = file1.concat(".csv");
var macro2 = "";

macro2 += "CODE:" + "\n";
macro2 += "VERSION BUILD=8920312 RECORDER=FX" + "\n";
macro2 += "SET !ERRORIGNORE YES" + "\n";
macro2 +="WAIT SECONDS=2" + "\n";
macro2 +="SET !DATASOURCE {{f1}}" + "\n";
macro2 +="SET !DATASOURCE_LINE {{i}}" + "\n";

macro2 +="SAVEAS TYPE=PNG FOLDER=C:\Users\omkar.somji\Documents\iMacros\Downloads\{{!COL1}} FILE={{!COL1}}" + "\n";

for(var i=1; i<=iterations ; i++){

iimSet('i', i );
iimSet('f1', file1 );
iimPlay(macro2);

}

Thanking you in advance.

A: You can create folders "on fly" with the help of this code as an example:
var folderToCreate = "D:\\Temp\\www.domain.com";
imns.FIO.makeDirectory(folderToCreate);

(Only 'iMacros' for Firefox.)


text:
Q: Automated azure sql export fails I need to get the .bacpac files exported to blob storage automatically.
In the azure management portal I have configured it so that it export the db. But it fails again and again it says in the operation logs:"...failed in creating temporary database.." and the an email like this "...The temporary database copy to export from could not be made.
You can view more details for this Automated SQL Export in the Windows Azure
Management Portal ". Somebody have a clue.? regards

A: We encountered the same issue with our automated sql azure backups. As part of our troubleshooting, we first tried to export to blob storage manually via the "export" link in the newer azure portal (portal.azure.com). When that failed - or actually just never completed with no errors in the "notifications" side tab, we decided to move to the older azure portal (manage.windowsazure.com) in hopes of receiving a more detailed error message.
When we manually kicked off the export in the older portal, we soon received a very detailed error message down the bottom part of the screen where you find the notifications.
The error specifically for us was related to a stored procedure we had created to help us troubleshoot the performance of our indexes. Some folks may be familiar with the stored procedure: sp_AskBrent (http://www.brentozar.com/askbrent/).
Essentially what happened was sql azure allowed us to create the stored procedure and execute it. However, the backup/export functionality was failing with that stored procedure in our database. The cause was the fact that the sp was referencing tempdb.
We ended up dropping the sp_AskBrent stored procedure, after which the backup/export started working again. Hope this helps someone.

A: This error is generally due a schema change in the database which has resulted in an object becoming invalid.
You can see if this is the case by doing a manual export in the portal.  The export will fail, with a red notification being generated saying "Export database 'db_name' failed.  Clicking on the "Details" will show another line with an arrow in a circle which will contain the actual error message.
The error message will likely look like:
 Error encountered during the service operation.
 Validation of the schema model for data package failed.
 Error SQL71501: Error validating element....

In most cases this is the result of a schema change that has rendered a stored procedure, view or function invalid.  The simplest example of this is dropping a column that is referenced in a stored procedure or view.
The reason for this is that a bacpac file also generates the commands needed to replicate the schema.  If some of these commands fail (because they reference a non existent column), then the entire restore would fail.
Simply fix any views/stored procedures/functions that are mentioned in the error log and the export should resume.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to return JSON using plumber api in R I am new to R . I am supposed to expose rest service using R , So i found plumber to expose rest service using R ,
I Successfully implemented plumber in R , but in response i am receiving a json array like below

[{"name":"Rajesh","age":"10"}]

how to remove the array from the above response
my expected output is like below

{"name":"Rajesh","age":"10"}

Code
 library(plumber)
r <- plumb("MyFile.R")
r$run(port=8000)

My File .R is mentioned below
    #* @post /sum
addTwo <- function(){
  name<-c("Rajesh")
  age<-c("10")
  df<-data.frame(name,age)

  return(df)

}

A: library(jsonlite)

df <- jsonlite::toJSON(data.frame(name, age, auto_unbox=TRUE))


text:
Q: Comparing XML file to an array I'm trying to compare to XML files. I have pulled the new.xml apart and put all the barcodes into an array. I am then trying to loop through the old.xml file and testing if the barcode exists in the array. If the barcode does exist then I want to echo a table row. When I get that working I will flip it to print if it ! exist. The XML files are structured like this:
<Products>
    <Product>
       <Id>2209</Id>
       <Barcode>4890888123702</Barcode>
    </Product>
</products>

My HTML and PHP looks like this:

    <title>Feeds = $$$$</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

<?php
//Get the old XML file
if (file_exists('old.xml')) {
    $oldxml = simplexml_load_file('old.xml');

    //Load all the old product IDs into an array
    $oldproducts = array();
    foreach($oldxml->Product as $oldproduct){
        $oldproducts[] = $oldproduct->Id;
    }
}else{
    echo "Old XML does not exist";
}

//Get the new xml file
if (file_exists('new.xml')){
    $newxml = simplexml_load_file('new.xml');

    //Load all the new product IDs into an array
    $newproducts = array();
    foreach ($newxml->Product as $newproduct){
        $newproducts[] = $newproduct->Id;
    }
}else{
    echo "New XML file does not exist";
}
?>

        <?php
            foreach($oldxml->Product as $oldproduct) {
                $x = $oldproduct->Id;
                if(in_array($x, $newproducts)){
                    echo '
';
                    echo '' . $x . ' has been taken out of stock' . '	';
                    echo '
';
                }

            }
        ?>

The loop doesn't return anything. If I use a hard coded barcode instead of the $x, it will find it and work properly.

A: As you are playing with SimpleXML, you may need to type cast your ID's when adding them to the arrays and performing your comparisons.
For example, adding (int) may help here:
foreach ($newxml->Product as $newproduct){
    $newproducts[] = (int) $newproduct->Id;
}

as well as here:
$x = (int) $oldproduct->Id;

For an attempt at further clarification to this answer, $newproduct->Id still a SimpleXMLElement when performing the comparison, at this stage it's quite possible that multiple ID elements could exist in the XML structure, when you cast it to an INT it will take the first ID element's text node and use that in the conversion to an integer.
When you echo $newproduct->Id it performs the __tostring() conversion because the context is know. It does not know the context when used in a comparison.

A: Please correct you xml file its wrong formatted and change your condition with this :
if (in_array($x, (array)$newproducts[0])) {
      echo '
';
      echo '' . $x . ' has been taken out of stock' . '	';
      echo '
';
}

Hope this will help you.


text:
Q: Access table - How to look through table, pull the I am looking to pull the 2 most recent weeks and return all project numbers for projects that had both a status of 3 for the most recent date they were reported on and anything but 3 for the second most recent date that the respective projects were reported on. I in essence want to take each project number as the unique ID and, for each project, compare the status for its 2 most recent dates reported, and return all projects that are currently a status of 3 in the most recent report date but also in the last report date were not a 3 . Hopefully this makes sense.  The table is below.
ID  Report Date Dept    Cost Center     Sub Segment  Status  Project Number
1   1/16/2015   Tech    121                  C&R           1        21046
2   1/21/2015   Tech    122                  Mobil         3        21333
3   1/16/2015   Acct    121                 C&R            2        21333
4   1/21/2015   Acct    122                 Mobil          1        21046
5   1/16/2015   Fin     121                  C&R           3        24567
6   1/21/2015   Fin     122                  Mobil         2        24888
7   1/16/2015   Tech    121                   C&R          1        24888
8   1/21/2015   Tech    122                 Mobil          2        24567
9   1/16/2015   Acct    121                 C&R            3        24777
10  1/21/2015   Acct    122                Mobil           1        25555
11  1/16/2015   Fin     121                 C&R            2        25555
12  1/21/2015   Fin     122                Mobil           3        24777
13  1/16/2015   Tech    121                C&R             3        55567
14  1/21/2015   Tech    122                Mobil           3`       55567

A: Here is one method that uses two conditions in the where clause:
select pn.project_number
from (select project_number, max(report_date) as maxrd
      from t
      group by project_number
     ) as pn
where 3 = (select t2.status
           from t as t2
           where t2.project_number = t.project_number and t2.date = pn.maxrd
          ) and
      3 <> (select top 1 t2.status
            from t t2
            where t2.project_number = t.project_number and
                  t2.report_date < pn.maxrd
            order by t2.report_date desc
           );

The two conditions pretty much follow your logic.  These do assume that there are no duplicates for the project/report date pair.


text:
Q: How to set text of Button as ON and OFF on each click in winforms? I am working on winform application. i have one button and its default text is ON. now when I click on button, its text should be changed to OFF an if i again click the button. is text should be changed back to ON . i have no idea how to do so i used counter logic. but i am not sure in it and not comfortable withit.
one more thing. if text is ON then employee can receive notification. so accept_notf = 1 and if text is OFF employee can not receive notification. so accept_notf =0
i have tried this.:
private void btnNotification_Click(object sender, EventArgs e)
{
    var btn = sender as Button;
    if (btn != null)
    {
        if (btn.Text == "ON")
        {
            accept_notif = "1";
            btn.Text = "OFF";
        }
        else  (btn.Text == "OFF")
        {
            accept_notif = "0";
            btn.Text = "ON";
        }
    }
}

A: Set default text to "ON", When the button is clicked if the text is "ON" set it to "OFF" else set it to "ON"
private void btnNotification_Click(object sender, EventArgs e)
{
    var btn = sender as Button;
    if (btn != null)
    {
        if (btn.Text == "ON")
        {
            btn.Text = "OFF";
            accept_notif = "0";
        }
        else if (btn.Text == "OFF")
        {
            btn.Text = "ON";
            accept_notif = "1";
        }
    }
}

A: It's simple. First, in our event handler we get our button instance from event arguments and Downcast it back to Button type. Then we use conditional operator to find out is it set to "ON" and if it's so we set it to "OFF" otherwise (operator ':') we set it to "ON"
private void btnNotification_Click(object sender, EventArgs e)
{
    var button = sender as Button;
    if (button == null) return;
    button.Text = button.Text == "ON"? "OFF" : "ON";
    accept_notf = button.Text == "ON"? 1 : 0;
}

A: In your click handler method you should examine if the text of your button is "ON" or "OFF" (because the changes depend on this).
For example like this:
if ((sender as Button).Text == "ON")
    (sender as Button).Text = "OFF";
else
    (sender as Button).Text = "ON";

...
or you can create a variable and work with that:
Button tmpButton = (sender as Button);

or you can use directly the button itself for accessing its text (I prefer this way when there is only 1 button).
if (btnStatusIndicator.Text == "ON")
{
    btnStatusIndicator.Text = "OFF";
    acceptNotif = 0; // learn camelCase when you write C# code! :)
}
else
{
    btnStatusIndicator.Text = "ON";
    acceptNotif = 1;
}

and if the program allows more values than just ON or OFF, you can use switch statement to determine the text (with this you can prepare your program to deal with other situations, when the text is not either ON or OFF).
switch (btnStatusIndicator.Text)
{
    case "OFF": ... break;
    case "ON": ... break;
    case "your other value": ... break;
    case "your other value": ... break;
    case "your other value": ... break;
    default: ... break;
}


text:
Q: Disable google sheet download from everyone except owner How can I disable the download from all the editors of the sheet. The data is confidential and I don't want employees (who are editors) to download the sheet.
I have enabled the following as well

*

*Prevent editors from changing access and adding new people

*Disable options to download, print, and copy for commenters and viewers

*I Have put protected sheets only accessible to owner of the sheet and disable for all the other editors

However, the editors can still download the google sheet (csv and other formats)
Is there a way we can restrict any downloads?
Thanks

A: You did correct:

But If your employees want to download your data, they will do it, here are few basic ways:

*

*Make screenshots and send to personal emails or store on pendrive

*Make photos with phones, drones, telescopes

*Write on paper, sole boot

*Memorize..


text:
Q: UDP Packet Creation With Scapy I am having trouble sending custom UDP packets with Scapy on Python3 with a MacBook.
 want to send a UDP packet with a custom Source IP of 192.168.1.11 to my current machine with the IP of, 192.168.1.17 that is hosting a UDP Server on port 6789. I want to send a message saying "Hi" using Scapy so I wrote the following code,
from scapy.all import *
from random import randrange
sendp(IP(src="192.168.11",dst="192.168.1.17")/UDP(sport=randrange(80,65535),dport=6789)/"Hi",iface="en0",count=10)

Then I have a server waiting to respond once data is received and print the message received to the screen. But when executing this code with elevated privileges, scapy says
the packets were sent but the server didn't receive the response.
So I went to en0 the wireless interface on my Mac to debug. This is what I found:
Wireshark says
the source is Applicon_11:f8:61, the destination is 45:00:00:1e:00:01, the protocol is 0xc0a8(Unknown) and the data is 16 bytes of Hex: 0000   45 00 00 1e 00 01 00 00 40 11 f8 61 c0 a8 00 0b ASCII Dump:  E.......@.øaÀ¨..
0010   c0 a8 01 11 67 18 1a 85 00 0a b3 66 48 69         À¨..g.....³fHi

I have no idea what any of that means or what I am doing wrong here can anyone help to point me in the right direction?

A: sendp is for sending at layer 2
send is for sending at layer 3
In your case, you should either use

*

*at layer 2: sendp(Ether()/IP(..)....). (Replace Ether by Loopback if needed)

*at layer 3: send(IP(...))


text:
Q: How to sort 3 parallel arrays? I currently have 3 arrays of information and am unsure of how to sort them based on one of the values:
int[] rank = { 1, 3, 4, 2, 5 };
String[] game = { "Snake", "Mines", "Fragged", "Siege", "Tower" };
int[] year = { 1980, 1983, 1981, 1995, 1992 };

I'm wanting to sort it by rank, and I've seen many examples of people using comparators to sort 2 parallel arrays, but I haven't seen any example for sorting more than 2.
My first thought was to create a class with a variable for each and then sort that object, but is an extra class really necessary for a sort?

A: I think creating a new class would be the cleanest solution. You could manually implement a new sort function to duplicate swaps to the other 2 arrays whenever you apply a swap to the first array (rank), but that gets messy very quickly.
Something like the following would be all you need:
public class Game implements Comparable<Game>{
    private int rank = 0;
    private int year = 0;
    private String name = "";
    ...
    // Constructor +
    // Usual getters and setters here
    ..
    public int compareTo(Game anotherGame) {
       return this.rank - anotherGame.getRank();
    }
}

And then you can simply do:
List<Game> games = new ArrayList<Game>();
...
// Add some games to your games list
...
Collections.sort(games);

A: Is the extra class necessary? Well no, of course not. You could come up with a sorting routine that would keep everything consistent. However, what happens if next week you decide you need a 4th array, such as a publisher? Now your sorting routine won't work and you have to write a new one.
If you instead write a class to hold these fields as properties, you can simplify the sorting logic immensely, plus you only have to worry about one array. Any extra work you do now will be recouped very quickly then next time you have to maintain this code.

A:
My first thought was to create a class with a variable for each and then sort that object, but is an extra class really necessary for a sort?

It's not strictly necessary - you could definitely write some code to avoid it if you really wanted to. However, I'd say it's a thoroughly good thing.
You don't really have three collections of separate items here: you have one collection of items, each of which has three properties. So make your code match that. Whenever you find you have parallel collections, such that a[0] is related to b[0] is related to c[0] etc, you should think about encapsulating that information in a separate class. It will make your code much easier to maintain, and enforces more consistency.
For example, it would make no sense for those arrays to have different lengths: but there's nothing inherent in the declaration to stop that. If you have one collection, you can't possibly have different numbers of items for the different properties, precisely because you've got one collection.


text:
Q: Entity Framework, Entity Model creation clarification I'm trying to learn ASP.NET MVC + Entity Framework by developing a small project. I have created basic structure of Database as required & now trying to Connect database to the MVC project.
When I check few MVC EF tutorials, There are two methods to create entity classes to map Database (as I understood) :

*

*Creating EDMX file using existing database

*Creating Entity Classes manually as required

What I need to clarify is whether there is any difference in using these methods (limitations, advantages, or disadvantages)?
Sorry if I'm asking something very simple or irrelevant...

A: You can check :

*

*Demystifying Entity Framework Strategies: Model Creation Workflow

*Update to Data Points Column

*Is Entity Framework Code First really third distinct option?
All these will teach you about options how to approach Entity Framework's model.


text:
Q: Create a socket that receives promiscuous packets My driver is already in promiscuous mode, and I can even log the promiscuous packets within the driver where the destination MAC and IP are something other than my machines MAC and IP. Where I am stuck is creating a socket to pull the packets from the mux layer. I am using vxworks, so I do not have some of the defines from linux, such as ETH_P_ALL etc.Ive played around with my socket creation and I can receive any packet in the application layer thats destined for my machine, regardless of the source. But the application does not receive the promiscuous packets, even though my driver does. Is a socket the only way to connect the mux to my application to receive these promiscuous packets? If so, can anyone shed some light on why my socket doesn't pull the packets that aren't for my MAC/IP? Thank you in advance.
Ive tried using SOCK_RAW, IPPROTO_UDP, IPPROTO_RAW etc, but maybe I just haven't had the right combination.
    std::string newIP = "0.0.0.0";
    descriptor = socket(AF_INET, SOCK_DGRAM, 0);
    if(descriptor == -1)
    {
        reportError(errno, "Couldn't open socket", __PRETTY_FUNCTION__);
        return;
    }

    remoteAddress = makeSockaddr(remotePort);

    if(inet_aton(const_cast<char *>(newIP.c_str()), &remoteAddress.sin_addr) == -1)
    {
        reportError(errno, "Failed to translate address", __PRETTY_FUNCTION__);
        return;
    }
    other = remoteAddress;

    sockaddr_in localAddr = makeSockaddr(localPort);
    if(inet_aton(const_cast<char *>(newIP.c_str()), &localAddr.sin_addr) == -1)
    {
        reportError(errno, "Failed to translate address", __PRETTY_FUNCTION__);
        return;
    }

    if(bind(descriptor, (sockaddr *)&localAddr, sizeof(localAddr)) == -1)
    {
        reportError(errno, "Failed to bind socket", __PRETTY_FUNCTION__);
        return;
    }


text:
Q: Deselecting default screen shots option using Apple Script I am trying to make an apple script through which I can deselect this option:
System Preferences > Hardware > Keyboard > Keyboard Shortcuts > Screen Shots > Save picture of selected area as a file
Can anyone suggest me some sample script for it?
Thanks,
Miraaj

A: System Preferences are not scriptable by default. You will have to use GUI Scripting, but that will be a little bit different for everyone depending on what preferences they have installed. There is a an excellent example over at www.macosxautomation.com that will get you started.

A: I am a bit late to this but, here's what worked for me:
     tell application "System Preferences"
       --activate
       reveal anchor "shortcutsTab" of pane id "com.apple.preference.keyboard"
     end tell

     tell application "System Events" to tell process "System Preferences"
        select row 4 of table 1 of scroll area 1 of splitter group 1 of tab group 1 of window 1
        repeat with r in rows of outline 1 of scroll area 2 of splitter group 1 of tab group 1 of window 1
          click checkbox 1 of UI element 1 of r
        end repeat
     end tell

     quit application "System Preferences"

Note this disable all checkboxes and not just "Save picture of selected area as a file". To disable just that replace the repeat block with:
click checkbox 1 of UI element 1 of row 4 of outline 1 of scroll area 2 of splitter group 1 of tab group 1 of window 1

You can enable or disable any other screenshot shortcut by replacing row 4 with the row number of the correct shortcut


text:
Q: WPF MiniGame Project - using two key events in the same time I have a mini game project to do in WPF c#.
The game is about shooting and most of the game is almost done.
The problem is that I'm using KeyDown event for move up and down, and need also to fire with the space key.
every thing works fine until i'm trying to move up or down and also try to shot.
I tried to put the fire event in the KeyUp, but still, when moving and shot together its just dont work.
please ley me know if you have any ideas for that.
BTW, I know WPF dosnt meant to creat games, but its has to be done in WPF.
Thanks!

A: Set booleans like IsMovingUp, IsFiring, and so on to true in the KeyDown event, and mark the events as handled.
Set those booleans to false on KeyUp event.
Then in your main game loop, you can check the booleans and act accordingly.


text:
Q: Approximation of arbitrary convex function I am currently studying Jürgen Moser's "A New Proof of de Giorgi's Theorem Concerning the Regularity Problem for Elliptic Differential Equations". During the proof of the first lemma, he claims that an arbitrary convex function $f$ can be approximated by a sequence of twice continously differentiable convex functions $f_m$, such that $f_m''(u)=0$ for large $|u|$, $f_m \rightarrow f$ and $f_m'(u) \rightarrow f'(u)$, where $f'(u)$ exists.
Having looked in several books about convex analysis (Rockafellar), I found out that a convex function should be twice differentiable almost everywhere. I further found in one of Rockafellar's books (convex analysis, thm. 25.7) a Theorem that shows the claim, except for the restriction on $f''$.
Now the question is how can we come up with that restriction on $f''$ and maybe someone has a reference for a book as well, since I would be interested in seeing the proof.

A: So I figured it out a few days ago and wanted to share it with you.
Most importantly it is a well known result that an arbitrary convex function can be uniformly approximated by a convex $C^{\infty}$-function on any closed bounded subinterval of the domain. I personally am not interested in the construction, but if you are, you might find some answers in the later mentioned references. Since this Approximation is applied on the Lemma of Fatou and the Lemma of Lebesgue, pointwise convergence of the Approximation is actually enough.
Assume $g$ is the function which approximates our convex function $f$ uniformly on the set $[-n,n]$. Then define
$\tilde{g}_n:= \mathbb{1}_{(-\infty,-n)} (g_n(-n)+g_n'(-n)(x+n)) + \mathbb{1}_{[-n,n]} g_n +\mathbb{1}_{(n,\infty)}(g_n(n)+g_n'(n)(x-n))$.
This function then approximates the convex function $f$ pointwise, and the second derivative vanishes outside the bounded set $[-n,n]$.
Some good references on approximation of convex functions might be:
D. Azagra, "Global and fine approximation of convex functions," Proc. London Math. Soc., vol. 107, p. 799–824, 2013
A. D. Alexandroff, Almost everywhere existence of the second differential of a convex function and some properties of convex surfaces connected with it, Leningrad State University Annals
J. J. Koliha, "APPROXIMATION OF CONVEX FUNCTIONS", Real Analysis Exchange, Vol. 29(1), 2003/2004, pp. 465–471
R. Tyrrell Rockafellar, "SECOND-ORDER CONVEX ANALYSIS", Journal of Nonlinear and Convex Analysis 1 (1999), 1-16


text:
Q: How to read a matrix from the console and print the sum of all matrix elements I'm learning C#, and now I am on Multidimensional Arrays. I want to write a program that reads a matrix from the console and print:

*

*Count of rows

*Count of columns

*Sum of all matrix elements

So, on the next [rows] lines I will get elements for each column separated with comma and space. I made a foreach for the sum but I do not understand how to insert the elements into the matrix. I would be very grateful if you could help me!
int[] dimensions = Console.ReadLine()
.Split(", ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();

int rows = dimensions[0];
int columns = dimensions[1];

int[,] matrix = new int[rows,columns];

for (int i = 0; i < rows; i++)
{
    int[] numbers = Console.ReadLine()
        .Split(", ", StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse)
        .ToArray();
//I do not know how to add the elements here
}

int sum = 0;
foreach (var element in matrix)
{
    sum += element;
}

A: You can use Linq Sum() to calculate sum for all rows
As you are iterating through each row of input data already, then you can assign one temparary variable called sum =0 and for each row calculate sum of all numbers of that row and add it to temporary variable i.e. sum.
int sum = 0;
for (int i = 0; i < rows; i++)
{
    int[] numbers = Console.ReadLine()
        .Split(", ", StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse)
        .ToArray();
    sum += numbers.Sum(); //Calculate sum of all numbers in a row and add it to existing sum variable.
//I do not know how to add the elements here
}

Console.WriteLine("Sum of all numbers" + sum); //print sum of all numbers i.e. 76

A: Elements in 2-d array are being accessed using two indices:
for (int i = 0; i < rows; i++)
{
    int[] numbers = Console.ReadLine()
        .Split(", ", StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse)
        .ToArray();

    for (int j = 0; j < columns; j++)
    {
        matrix[i,j]=numbers[j];
    }
}

int sum = 0;
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns; j++)
    {
        sum += matrix[i,j];
    }
}


text:
Q: Integrate Salesforce Marketing cloud with ecommerce process We are going to start a salesforce marketing cloud implementation project and I have this use case where we want to identify customers that are on our e-commerce process and that drop after the form fill. We want to communicate to those customers with specific emails after they drop.
My question is, do we have a technical way to implement such use case? and what type of component should we use?

A: You can use the Transactional Email feature for this. Email templates are stored in Marketing Cloud, and you can populate them with data from the e-commerce process.
I believe what you want to achieve is abandoned cart functionality?
You can pass on information on cart content in JSON format in the REST cll, and iterate through the JSON object using AMPscript.
An example on triggering transactional emails with REST API can be found here: https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-apis.meta/mc-apis/messageDefinitionSends.htm

A: Running a similar project at the moment. In the client's use case, transactional emails are fired by hybris (client's e commerce engine) using to send trigger (SOAP API Call) an email and add the customer details to a data extension. You can extend this with REST Calls to various other modules (e.g. Journey Builder).
For getting familiar with API calls, visit: https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-apis.meta/mc-apis/index-api.htm

A: So we are going to use predictive intelligence as we need some other aspects of the product like banner display on the website.
Thank you for your help :-)


text:
Q: Java - MariaDB Perfoming slow with Hibernate criteria Environment:
mariadb-java-client-2.7.0
DB : MariaDB 10.5.7
ojdbc8 - Oracle 11.2.0.3.0 JDBC 4.0
DB : Oracle Database 11g
Hibernate 4.3.8
Code :
        Session session = sessionFactory.openSession();
        Criteria fetchCriteria = session.createCriteria("Student");

        Disjunction disjunction = Restrictions.disjunction();

        for (int i = 1; i <= 10000; i++) {
            Conjunction conjunction = Restrictions.conjunction();
            conjunction.add(Restrictions.eq("RollNumber", i+""));
            disjunction.add(conjunction);
        }

        fetchCriteria.add(disjunction);
          long start1 = System.currentTimeMillis();
        List  resultList = fetchCriteria.setFirstResult(0).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
         long end1 = System.currentTimeMillis();
         System.out.println("Time took :"+(end1-start1) +"ms");

Issue

*

*If i run above code with Hibernate 4.3.8 + Oracle 8 it taking less than 5000 milliseconds.

*If i run above code with Hibernate 4.3.8  +mariadb-java-client-2.7.0 it taking more than 40,000 milliseconds.

Extra Configuration :
I have set hibernate.jdbc.fetch_size to 100 in hibernate.cfg.xml
along with jdbc URL ,username and password.
Findings:

*

*The query generated in both cases are same and if i execute those
query with SQL Client it takes 10-11 seconds for ORACLE and 41-42 seconds for MariaDB.

*The query which is generated by both database if i invoke using JDBC
program (both for ORACLE and MariaDB) it is taking approx 600 milliseconds

Note: Both tables (Oracle and MariaDB) have 15,000 records.
Can anyone help me why MariaDB is taking time?
or some extra settings are required to improve the MariaDB performance.
I have tried defaultFetchSize which is mentioned in https://mariadb.com/kb/en/about-mariadb-connector-j/ but no luck.
SQL Query Generated by the databases:
select  this_.rollNo as RollNo1_0_0_, this_.VersionID as Version2_0_0_,
        this_.Name as Name3_0_0_, this_.dept as dept4_0_0_,
        this_.favSubj as favSubj5_0_0_,
        this_.ID as ID33_0_0_
    from  Student this_
    where  ((this_.ID='1')
              or  (this_.ID='2')
              or  (this_.ID='3')
              or  ....
              or  (this_.ID='10000')

MariaDB DDL
CREATE TABLE `student` (
  `RollNo` bigint(20) NOT NULL ,
  `VersionID` bigint(20) NOT NULL,
  `Name` varchar(100) COLLATE ucs2_bin DEFAULT NULL,
  `dept` varchar(100) COLLATE ucs2_bin DEFAULT NULL,
  `favSubj` varchar(100) COLLATE ucs2_bin DEFAULT NULL,
  `ID` varchar(100) COLLATE ucs2_bin DEFAULT NULL,
   PRIMARY KEY (`RollNo`),
  UNIQUE KEY `UK_student` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=20258138 DEFAULT CHARSET=ucs2 COLLATE=ucs2_bin

Oracle DDL
CREATE TABLE student (
  RollNo NUMBER(19,0),
  VersionID NUMBER(19,0) NOT NULL ENABLE,
  Name VARCHAR2(100),
  dept  VARCHAR2(100),
  favSubj VARCHAR2(100),
  ID VARCHAR2(100),
  PRIMARY KEY ("RollNo"),
  CONSTRAINT "UK_student" UNIQUE ("ID")
)

MariaDB explain select query output

id
select_type
table
type
possible_keys
key
key_len
ref
rows
Extra

1
SIMPLE
this_
range
UK_Student
UK_Student
203
NULL
10000
Using index condition

A: An OR with 10K items takes a long time to parse.  Faster would be an IN:
 where  this_.ID IN ('1', '2', ..., '10000')

However, even that is likely to take a long time to run.
In the case of MariaDB, I think the Optimizer will say

*

*Oh, that's too many items for me to look up each one, so

*I will, instead, simply scan the table, checking each row for an ID in that list (using some kind of efficient lookup in the 10K-long list).

However, if there are 20M rows in the table, that will take a long time.
Can you provide the query plan (EXPLAIN) so we can confirm what I am hypothecating?
This seems logical and faster, but will not work correctly:
 where  this_.ID BETWEEN '1' AND '10000'

because it is a VARCHAR!!
Performance -- Make id an INT, not a VARCHAR!


text:
Q: Why doesn't mySQL give an error for "{" when trying to rename a database? I am working with mySQL in NetBeans and I am trying to rename a database. The updated syntax can be found here:http://dev.mysql.com/doc/refman/5.1/en/alter-database.html. This is the one I am using.
ALTER {DATABASE | NBUSER} DATABASE UPGRADE DATA DIRECTORY NAME;

I keep getting this error:
Error code -1, SQL state 42X01: Syntax error: Encountered "{" at line 1, column 7.
Any suggestions to why I am getting this error?
Thanks for any advice

A: The syntax provided is to tell you that you can use either of the 2 objects.
So try only
ALTER DATABASE UPGRADE DATA DIRECTORY NAME;

But from the documentation it seems that you also must specify the database name.
Have a look at their example
ALTER DATABASE `#mysql50#a-b-c` UPGRADE DATA DIRECTORY NAME;


text:
Q: OAuth2 endpoints for EWS access to office365 I have an app that uses Basic Authentication to access office365 via EWS, is there any documentation on how to do OAuth2 with EWS?
What endpoints do I authenticate with?
I have searched google but cant seem to find information on using OAuth2 with EWS.

A: You use the Standard Azure oAuth tokens and endpoints (using the ADAL library if you wish which makes things easy) there is a step by step document for doing this https://msdn.microsoft.com/en-us/library/office/dn903761(v=exchg.150).aspx . The only point to remember is that EWS only has one authentication scope which is Full Mailbox Access. All the other Mail,Calendar,Contacts scopes are for the new REST API only.


text:
Q: How to fix anchor tag landing in wrong position I'm new to JavaScript. Sorry if this is a duplicate, but I couldn't find any solution for my needs.
When clicking on the anchor tag, it leads to my desired position. However, I have another anchor tag that is meant to link to the same position as the other. If I click this (After I've already clicked the other anchor tag that leads to the same position as the one I'm about to click now), it does NOT lead me to my desired position.
I understand it must be because I'm using hashchange. I tried using click but that returns -1 for console.log(document.URL.indexOf("#")); instead of 58 when using hashchange.
I figure the click logic is on the right path but I don't understand why it's not doing what I expect. (That being: click runs after you've clicked something clickable on the page).
I also tried using setTimeout but I couldn't figure out a way to correctly manipulate it to 'restart' my fixedAnchor function.
    function fixedAnchor() {
        // if (location.hash.length !== 0) {
            window.scrollTo(window.scrollX, window.scrollY - 130);
            console.log(document.URL.indexOf("#"));
            // console.log(document.URL.indexOf("#") > -1 & document.URL.indexOf("#") <= 58);
            // if (document.URL.indexOf("#") > -1 & document.URL.indexOf("#") < 58) {
            //  console.log(document.URL.indexOf("#") > -1);
                offSetAnchor();
            // }
        // }
    }

    function offSetAnchor() {
        if (document.URL.indexOf("#") != 58){
            window.scrollTo(window.scrollX, window.scrollY - 130);
        }
        // setTimeout(function(){
        //  window.scrollTo(window.scrollX, window.scrollY - 130);
        //  // fixedAnchor();
        // }, 1000);
    }

    window.addEventListener('hashchange', fixedAnchor);
    // window.addEventListener('click', fixedAnchor);

A: This can be done with named anchors using just HTML. Please find code below in which 2 links take to same position
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

    click 1 to gohere

Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

click 1 to gohereWhy do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

 Selected Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

A: This is a great use for jQuery's .click() event handler. You can create an anchor class for the anchor elements and bind the .click() event.
$(".anchor").click(function(){
    window.scrollTo(0, 130)
})

Here's a working example.
You can do something similar without jQuery with addEventListener('onClick').


text:
Q: Defining functions from strings Blank symbol (_) is moved when applying ToExpression to the following string:
"g[q[1]_ \[TensorProduct] q[2]_ \[TensorProduct] q[3]_ \[TensorProduct] q[4]_]"

I want to define many functions, with varying arguments and forms, so it is easy to me to construct first the strings. If you have another solution to my problem it will be welcome. Basically I want to define functions from their arguments automatically.
Thanks in advance.

A: If it is easy for you to construct strings like
"g[q[1]_ \[TensorProduct] q[2]_ \[TensorProduct] q[3]_ \[TensorProduct] q[4]_]"

consider dropping the [ and ] brackets for each q, so that you end up with
"g[q1_ \[TensorProduct] q2_ \[TensorProduct] q3_ \[TensorProduct] q4_]"

then it will behave as you want.
For example, given a list of potential function arguments
list = {q[1], q[2] , q[3] , q[4]};

you could do
(ToString@#[[0]] <> ToString@#[[1]] <> "_") & /@ list

{"q1_", "q2_", "q3_", "q4_"}

Additionally, if your wrapper g already implies the \[TensorProduct] for all entries, you could simply use a comma separator g[a,b,c,d] etc. which might make things more stable.
EDIT:
A little example:
Starting from a function with an explicit argument
fun = g[q[1] \[TensorProduct] q[2] \[TensorProduct] q[3] \[TensorProduct] q[4] ];

note that internally it looks like
fun // FullForm

g[TensorProduct[q[1],q[2],q[3],q[4]]]

So we can turn the arguments into a pattern by using a custom function like
patternize[in_]:= ToExpression@(ToString@in[[0]] <> ToString@in[[1]] <>  "_")

so that
fun[[1]] = patternize /@ fun[[1]]

q1_\[TensorProduct]q2_\[TensorProduct]q3_\[TensorProduct]q4_

and
fun

g[q1_\[TensorProduct]q2_\[TensorProduct]q3_\[TensorProduct]q4_]


text:
Q: Why must I implement concrete destructor on abstract class? I am new to C++11, and I am trying to build a classic interface / implementation pair. Consider the following sample:
#include <iostream>
#include <memory>

// Interface
class IFace {
public:
    virtual ~IFace () = 0;
};
// Why must I define this concrete implementation?
inline IFace::~IFace () { }

// Implementation
class Impl : public IFace {
public:
    virtual ~Impl () { }
};

int main (int argc, char ** argv) {
    auto impl = std::shared_ptr<Impl> (new Impl ());
    return 0;
}

If I comment out the undesirable concrete destructor on the interface inline IFace::~IFace () { }, I get link errors
Undefined symbols for architecture x86_64:
  "IFace::~IFace()", referenced from:
      Impl::~Impl() in ifac_impl.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I must do this even if the interface and implementation are templated:
// Template IFace2
template <typename T>
class IFace2 {
public:
    virtual ~IFace2 () = 0;
};
// I have to do this even if the pair is templated.
template <typename T>
inline IFace2<T>::~IFace2<T> () { }

template <typename T>
class Impl2 : public IFace2<T> {
public:
    virtual ~Impl2 () { }
};

int main (int argc, char ** argv) {
    auto impl = std::shared_ptr<Impl> (new Impl ());
    auto impl2 = std::shared_ptr<Impl2<double> > (new Impl2<double> ());
    return 0;
}

Why?
A second question is "am I going about this the wrong way?" That is, is there a better pattern (idiom?) for what I want to do?  I am admittedly trying to fit a conceptual pattern I developed with C# into C++11. Is this sane? If not, what is the sane way?

A: When you override a virtual function in the derived class, and then invoke it, the base implementation is not called, unless you explicitly call it.
For instance,
struct base
{
  virtual void foo() {}
};

struct derived : base
{
  void foo() override {}
};

base *b = new derived;
b->foo();  // this will not call base::foo

The same applies to pure virtual functions as well.
However, in the case of a (pure) virtual destructor, the base destructor will be called (because the base sub-object needs to be destroyed). Hence, if you have a pure virtual destructor, you must provide an implementation. Otherwise you'll never be able to instantiate any derived class.

A: The destructor should not be pure virtual. That would make the class abstract and therefore not possible to instantiate. Just define it as default:
class IFace {
public:
    virtual ~IFace () = default;
};

Live demo


text:
Q: Cómo utilizar subcarpetas dentro de Modules Controllers usando nWidart Buen día a todos.
Estoy usando módulos dentro del proyecto, construidos mediante el desarrollo de nWidart.
Aunque en su documentación menciona la posibilidad de manejar carpetas dentro de la carpeta de Controllers, no detalla como hacerlo y no he podido hacerlo andar. Supongo que es algo muy sencillo, pero no he dado en lo correcto.
Les comento que es lo que tengo hecho, a ver si me pueden ayudar.
Esta es la estructura deseada:
miProyecto
  Modules
    Solicitud
      Http
        Controllers
          back
            AdminController.php
          front
            VisitController.php

Este es mi Modules/Solicita/Routes/web.php
Route::group(array('prefix' => 'admin', 'namespace' => 'admin'), function()
{
    Route::get('/', ['as' => 'solicita', 'uses' => 'SolicitaController@index']);
});

Y este es Modules/Http/Controllers/Admin/SolicitaController.php
namespace Admin;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;

class SolicitaController extends Controller
{
    public function index()
    {
        dd('ESTAS EN ADMIN SOLICITA');
        return view('solicita::index');
    }
}

Luego composer dump-autoload, voy a la ruta: localhost/miproyecto/public/admin y me da este error:

Illuminate\Contracts\Container\BindingResolutionException
Target class [Modules\Solicita\Http\Controllers\Admin\SolicitaController] does >not exist.

A: La respuesta era muy sensilla.
Crear las subcarpetas, por ejemplo \Controllers\Front, dentro se coloca el controller. Hay que setear el namespace del controller como namespace Modules\ModuloX\Http\Controllers\Front y en la ruta se coloca Route::get('cliente/listar', 'Front\ClienteController@listar')
La view y lo demás queda igual.


text:
Q: What is the "Slain Monsters Rest in Peace" item property? I've had a look at some of the uniques available here and noticed that Tyrael's Might has a property called "Slain Monsters Rest in Peace". What is this?

A: Nature's Peace is a ring with that effect.

Nature's Peace: "Slain Monsters Rest in Peace" means that the bodies can't be resurrected or they can't be used to raise skeletons (Necromancer). They can't be used for Corpse Explosion either. It will work only if you kill the enemy with a physical damage or elemental (Blizzard or Fireball) and not magical damage. The ring will work for the Paladin's Blessed Hammer skill.

A: Slain monsters Rest In Peace effectively stops skills like corpse explosion, find item/potion, redemption, etc from working on the would be corpse. This is specifically useful for hardcore players farming keys from Nihlathak, it basically makes him an easy target with not much killing power.


text:
Q: If every non-trivial subset of a set C has non-empty boundary in C, then C is connected I came across this proposition in Functional analysis book by Joseph Muscat. I am having problem in applying this to following example. Let's say C = [-1,1] \ {0}, then C is not connected. But I am not able to find a subset with non-empty boundary. Subset A = [-1,0) has non-empty boundary {-1} in C. Please help me understand what I am missing. Thanks.

A: The boundary of your set $A$ is empty. $-1$ is an interior point of $A$ in your space $C$ since $[-1,0)$ is an open subset of $C$ containing $-1$ which is contained in $A$. .


text:
Q: Call Function From An Vector of Pointers of Abstract Class I have an abstract class with 2 pure virtual functions:
class CCobjectBase
{
public:
    CCobjectBase();
    virtual void setCordFigure(double *, int) = 0;
    virtual double* getCord() = 0;
};

And a class that is derived from the abstract one:
class CTriangle : public CCobjectBase
{
public:
    CTriangle();
    ~CTriangle();
    void setCordFigure(double *, int);
    double* getCord();

private:
    double *m_cord;
    int m_size;
}

void CTriangle :: setCordFigure(double *cord, int size)
{
    m_cord = cord;
    m_size = size;
}

double * CTriangle :: getCord()
{
    return m_cord;
}

I used a vector of pointers to the abstract class:
std::vector<CCobjectBase *> m_objectBaseList;

And i create and store some values in this vector as follow:
 m_objectBaseList.push_back(new CTriangle());
 m_objectBaseList.at(m_objectBaseList.size() - 1) -> setCordFigure(coordonate, size);

The problem occurs when i try to display the values from the vector:
for(size_t i=0; i< m_objectBaseList.size(); i++)
{
    double * cord = m_objectBaseList.at(i) -> getCord();
    out<<cord[0]<<" "<<cord[1]<<" "<<cord[2]<<" "<<cord[3]<<" "<<cord[4]<<" "<<cord[5]<<endl;
}

It seems that all the objects have the same values stored. I tried multiple solution but i can not simply figure it out. If i give inputs as follow:
Object1: 1 2 3 4 5 6
Object2: 3 2 3 3 5 5
...
Objectn: 1 1 2 2 1 1

All objects have the value of Objectn:
Object1: 1 1 2 2 1 1
Object2: 1 1 2 2 1 1
...
Objectn: 1 1 2 2 1 1

The problem is not from the parameter coordonate because i tested in the setCordFigure(double *cord, int size){} function and it shows fine.
Any possible sugestions?
EDIT:
The portion of the code where I set the values is actually like this:
void MainWindow :: creazaObiecte(int numarOrdine, double *coordonate, int size)
{
    QTextStream out(stdout);
    switch(numarOrdine)
    {
        case 1:

           m_objectBaseList.push_back(new CTriangle());
           m_objectBaseList.at(m_objectBaseList.size() - 1) -> setCordFigure(coordonate, size);

           break;
       ...
    }
}

I use this function from each line of a file what I read. The portion of the code where I call this function is something like:
while(--condition--)
{
    double coordonate[30]; //coordonate is used to store values as an array Ex: 20 30 12 2 32 12 etc

    //fill coordonate with values from the line of the file

     creazaObiecte(ordinClasa, coordonate, size); //ordinClasa is a variable that stores the index of the object (1 stands for triangle)
}

A: EDIT: My original answer was in a context where I didn't realise m_coord is meant to be an array, so was inappropriate.
Your operation setCordFigure just sets your m_coord member pointer to the passed argument. It does not not copy the underlying array. So in the end all your objects end up pointing to the same array.
You need to actually copy the array in your setCordFigure function. You could do this with naked arrays, but its better to use a vector. So this is possible code:
class CCobjectBase
{
public:
    CCobjectBase();
    virtual void setCordFigure(const std::vector<double>&) = 0;
    virtual std::vector<double>& getCord() = 0;
};

class CTriangle : public CCobjectBase
{
public:
    CTriangle();
    ~CTriangle();
    void setCordFigure(const std::vector<double>&);
    std::vector<double>& getCord();

private:
    std::vector<double> m_cord;
    int m_size;
}

void CTriangle :: setCordFigure(const std::vector<double>& cord)
{
    m_cord = cord;
}

std::vector<double>& CTriangle :: getCord()
{
    return m_cord;
}

Then your creation function becomes:
void MainWindow :: creazaObiecte(int numarOrdine, const std::vector<double>& coordonate)
{
    QTextStream out(stdout);
    switch(numarOrdine)
    {
        case 1:

           m_objectBaseList.push_back(new CTriangle());
           m_objectBaseList.at(m_objectBaseList.size() - 1) -> setCordFigure(coordonate);

           break;
       ...
    }
}

And your population function becomes:
while(--condition--)
{
    std::vector<double> coordonate(30); //coordonate is used to store values as an array Ex: 20 30 12 2 32 12 etc

    //fill coordonate with values from the line of the file

     creazaObiecte(ordinClasa, coordonate); //ordinClasa is a variable that stores the index of the object (1 stands for triangle)
}

A: double *m_cord;

You are storing a pointer to the coordinate in your class.
void CTriangle :: setCordFigure(double *cord, int size)

Then, probably, you are reading the "input" into some variables, which are then referenced in  your CTriangle objects. So as the values of the variables are changed, all of the objects are really pointing to the same stuff.


text:
Q: Upper bound of difference of squares of quantile standard normal Let $\Phi$ denotes the cummulative standard normal distribution and $\Phi^{-1}$ denotes its inverse. Given  $u,v\in[0,1)$. I'am going to find an upper bound of
$$
\left|\left\{\Phi^{-1}(v)\right\}^2-\left\{\Phi^{-1}(u)\right\}^2\right|
$$
in term of "easy" functions like polynomial, trigonometric, logaritmic, etc.
So for, I have obtained as follows:
One can prove that $\phi(\Phi^{-1}(x))\ge \sqrt{\frac2\pi}(x\wedge(1-x)),\forall x\in[0,1),$ where $\phi=\Phi^\prime$.
Hence,
\begin{align}
\left|\Phi^{-1}(v)-\Phi^{-1}(u)\right|&=\left|\int_u^v\frac1{\phi(\Phi^{-1}(w))}dw\right|\\
&\le \sqrt{\frac2\pi}\left|\int_u^v\frac1{w\wedge(1-w)}dw\right|\\
&\le \sqrt{\frac2\pi}\left|\int_u^v\left(\frac1{w}+\frac1{(1-w)}\right)dw\right|\\
&= \sqrt{\frac2\pi}\left|\log\left(\frac{v}{1-v}\right)-\log\left(\frac{u}{1-u}\right)\right|.\\
\end{align}
But then, I haven't been able to handle $$\left|\Phi^{-1}(v)+\Phi^{-1}(u)\right|.$$ Could anyone help me? Or is there a better approach than mine?

A: Well one answer is right in front of you!  By the inequality you are claiming, you have, in particular, for $u = 1/2$, that
$$\left| \Phi^{-1}(v) \right| \leq \sqrt{\frac{2}{\pi}} \left| \log{\frac{v}{1-v}}\right|.$$
Then apply the triangle inequality to get
$$\left| \Phi^{-1}(v) + \Phi^{-1}(u) \right| \leq \sqrt{\frac{2}{\pi}} \left(\left| \log{\frac{v}{1-v}}\right| + \left| \log{\frac{u}{1-u}}\right| \right).$$


text:
Q: How can i deny activity to be destroyed I'm starting the activity "B" from the activity "A". When I'm closing the activity B using the back button or method finish(), the activity  A is recreating. How can i deny activity to be destroyed?

A: Activities in android are stored in a Stack called activity-stack, when you go to next Activity it's added to the stack, when you go back you pop last element from stack and nothing points at it any more, so not destroying is just waste of space!
Even if you override the back button to launch previous activity with noHistory or clearTop flag, current activity would be destroyed.
I suggest that you read more on activity lifecycle


text:
Q: Stanford NER precedence I'm using Stanford NER for training, I have 2 questions!
1)How do i give precedence to a particular class label.
for example if a "word" is trained as Class A and the same "word" is Class B, and when "word" is found in the text I want it to overcome the conflict and be labelled as Class B only, irrespective of how many occurrence "word" has when trained for Class A.
2)How to train a token with two words, for example "Mysore" is a City and "Mysore Road" is a Road. But in Stanford NER i need to train both "Mysore" and "Road" separately as Road, so there is a conflict for "Mysore" to be City or Road.


text:
Q: Postfix config under ubuntu 14.04 My dedicated server is running ubuntu 14.04.
It's also configured as a dns server (bind) and my domain toto.be is pointing on it.
I also installed postfix, added mx record, add iptables rules to open input port 53 (udp + tcp).
Ok, now I'm testing.

*

*On my server I can send an email to local user root

*On my server I can send an email to external email address (myname@gmail.com)

*From gmail, I can't send an email to root@toto.be

In my log
Oct  2 14:45:35 mail postfix/smtpd[31278]: connect from mail-qc0-x22b.google.com[2607:f8b0:400d:c01::22b]
Oct  2 14:45:36 mail postfix/smtpd[31278]: NOQUEUE: reject: RCPT from mail-qc0-x22b.google.com[2607:f8b0:400d:c01::22b]: 454 4.7.1 <root@toto.be>: Relay access denied; from=<myname@gmail.com> to=<root@toto.be> proto=ESMTP helo=<mail-qc0-x22b.google.com>
Oct  2 14:45:36 mail postfix/smtpd[31278]: disconnect from mail-qc0-x22b.google.com[2607:f8b0:400d:c01::22b]

In my main.cf I try adding google.com to mynetworks but I don't think it is the solution (what for all others domains ?)
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 google.com

Now the message is accepted but cannot be delivered
Oct  2 14:49:09 mail postfix/smtpd[31484]: connect from mail-qg0-x231.google.com[2607:f8b0:400d:c04::231]
Oct  2 14:49:10 mail postfix/smtpd[31484]: 541357F836: client=mail-qg0-x231.google.com[2607:f8b0:400d:c04::231]
Oct  2 14:49:10 mail postfix/cleanup[31489]: 541357F836: message-id=<CAA-VCPUqg9XmmJGhH5oFAZv5d0FfnLMg4idPwmXkB2CRw@mail.gmail.com>
Oct  2 14:49:10 mail postfix/qmgr[31437]: 541357F836: from=<myname@gmail.com>, size=1754, nrcpt=1 (queue active)
Oct  2 14:49:10 mail postfix/smtp[31490]: 541357F836: to=<root@toto.be>, relay=none, delay=0.31, delays=0.3/0/0/0, dsn=5.4.6, status=bounced (mail for toto.be loops back to myself)
Oct  2 14:49:10 mail postfix/cleanup[31489]: 8EC927F83A: message-id=<20141002124910.8EC927F83A@smtp.toto.be>
Oct  2 14:49:10 mail postfix/bounce[31491]: 541357F836: sender non-delivery notification: 8EC927F83A
Oct  2 14:49:10 mail postfix/qmgr[31437]: 8EC927F83A: from=<>, size=3676, nrcpt=1 (queue active)
Oct  2 14:49:10 mail postfix/qmgr[31437]: 541357F836: removed
Oct  2 14:49:10 mail postfix/smtpd[31484]: disconnect from mail-qg0-x231.google.com[2607:f8b0:400d:c04::231]
Oct  2 14:49:11 mail postfix/smtp[31490]: 8EC927F83A: to=<myname@gmail.com>, relay=gmail-smtp-in.l.google.com[2a00:1450:400c:c02::1b]:25, delay=1, delays=0.03/0/0.17/0.83, dsn=2.0.0, status=sent (250 2.0.0 OK 1412254151 m13si5148612wjw.140 - gsmtp)
Oct  2 14:49:11 mail postfix/qmgr[31437]: 8EC927F83A: removed

What can I do ?
postconf -n

alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
inet_interfaces = all
mailbox_size_limit = 0
mydestination = smtp.toto.be, localhost, localhost.localdomain, localhost
myhostname = smtp.toto.be
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 google.com
myorigin = /etc/mailname
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated     defer_unauth_destination
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes

/etc/mailname
toto.be

A: The first problem I see is that you are only allowing email meant for smtp.toto.be; nowhere is there a mention that you accept delivery for toto.be, so...
myhostname = smtp.toto.be
mydomain = toto.be
mydestination = $myhostname, $mydomain, $mynetworks, localhost, localhost.localdomain
myorigin = $mydomain

A: One thing to do is in postfix.conf make sure that you have 'myorigin' set to your domain of toto.be so that local users are mapped to @toto.be.  This can be done a couple ways:
myorigin = $mydomain

(if you have $mydomain set somewhere ), or:
myorigin = /etc/mailname

(if you have a file called /etc/mailname with toto.be as the first line), or even explicitly like:
myorigin = toto.be

Also, the error '(mail for toto.be loops back to myself)' indicates that something is messed up with routing.  I had this problem once and found that removing 'relayhost = $myhostname' from postfix.conf fixed it.
Reference:  http://www.postfix.org/postconf.5.html#myorigin


text:
Q: Is it possible to load a texture into OpenGL without first loading the entire texture into regular RAM? Usually, when we load a texture into OpenGL, we more or less do it like this

*

*open file

*read all the bytes into system RAM

*call glTexImage2D() which sends the bytes into VRAM

*free the bytes in system RAM

Is there a way to stream/load the bytes into VRAM skipping the whole loading it into system RAM part.  Something like this:
char chunk[1000];

f = openfile("some file")

glBindTexture(....)
glTexParameteri(...)
glTexParameteri(...)
glTexParameteri(...)

while (f.eof == false) {
  chunk = f.read_chunk(1000);
  glTexImage2D..... (here's the chunk)
}
closefile(f);

I'm wondering if there is some new OpenGL extension that can do this.

A: Most image file formats are either compressed or heavily coded. So at least some parts of them must first pass through regular system memory. However it is not necessary to allocate a buffer for the whole image in system RAM, if you use a OpenGL buffer object. It will however likely end up allocating the buffer object in VRAM, so you have the data there twice, at least for some time.
The cliff notes on how to use it is
size_t buffer_size = ...;
GLuint buffer_id;
glGenBuffers(1, &buffer_id);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, buffer_id);
glBufferData(GL_PIXEL_UNPACK_BUFFER, buffer_size, NULL, GL_STATIC_DRAW);

void *buffer_ptr = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
size_t offset_into_buffer = ...;
read_image_pixels_into_buffer((char*)buffer_ptr + offset_into_buffer);
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);

glTexImage2D(..., (void*)((uintptr_t)offset_into_buffer));

glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glDeleteBuffers(1, &buffer_id);

Take note that performance and efficiency might suffer if buffer objects are used naively, as in the code above. Usually buffer objects are used as memory pools from which chunks are cut on as-required base and buffers not constantly created and deletes. However there's also streaming via buffer orphaning, which does in fact re-create buffers: https://www.khronos.org/opengl/wiki/Buffer_Object_Streaming
Update regarding @BDL's comment
With OpenGL you really don't have any control of how things will happen, but you can nudge the taken code path into a certain direction. One thing one always has to keep in mind is, that OpenGL doesn't have a memory model at all. Things are just supposed to work… somehow.
A side effect of that is, that in order to fulfill the requirements, a GPU based OpenGL implementation may at any moment be forced to evice some of the data in GPU memory somewhere else. …most likely system RAM, but maybe even disk swap space. Since modern operating systems tend to overcommit memory, it's this very likely, that a OpenGL implementation will simply keep the same amount of actually page-faulted memory around as is required for all allocated OpenGL objects. And for non-streaming data it makes a lot of sense, to have a copy of the data in system memory (or swap) all the time, because this turns eviction into clearing some VRAM memory allocation entry.
Now in the case of buffer objects, the very code path I outlined above may in fact avoid one extra copy, by buffer region renaming, i.e. when loading the data into the texture, no data is actually copied, but just the texture descriptor set to point at that particular region in the buffer object… until that region in the buffer is overwritten, which then triggers the creation of a copy. However deleting the buffer object (name) immediately after loading it into the texture may in fact relegate the whole memory of the buffer to the texture object. _This however is just a potential optimization, a OpenGL implementation could implement, but doesn't have to.__
The whole OpenGL specification is extremely vague, which makes developing a high-performance OpenGL implementation ming boggingly hard work.

A: It is possible to skip loading the entire texture at once, and load it chunk-by-chunk as you showed in your code. You just need to upload the chunks with glTexSubImage2D and use a file format that supports reading tiles efficiently (e.g. TIFF):
... open file ...
... create texture ...

for each tile in file {
    tile = f.read_tile();
    glTexSubImage2D(GL_TEXTURE_2D, 0, tilex, tiley, tilew, tileh, format, type, tile);
}

This, however, will probably be slower compared to loading the entire thing and transferring it in one GL call.
It can still be useful if your image loads progressively through a network connection, for example.

A: There is no way how you could pass a texture to OpenGL without loading it first into your RAM. OpenGL doesn't handle file access in any way.
Most of the time (except for uncompressed textures or textures with DDS compression), one has to do some processing anyway to get the compressed file content into a format OpenGL can understand.


text:
Q: Elegant way of validating permission in Android using MVVM So, I'm using MVVM architecture with Repository pattern to make different API calls.
I have a Repository called X, where I have different related API calls.
Before any of these calls are made, I would like to do validation. If that proceeds successfully, only then network request should be made.
fun getSomethingX(data: Data): Single<Data> {
    return if (validation(data)) {
        service.getSomethingX()
                .onErrorResumeNext(...)
                .map { ... ->
                    ...
                }
    } else {
        Single.just(null)
    }
}

fun getSomethingY(data: Data): Single<Data> {
    return if (validation(data)) {
        service.getSomethingX()
                .onErrorResumeNext(...)
                .map { ... ->
                    ...
                }
    } else {
        Single.just(null)
    }
 }

As you can see I might have many network request functions called getSomething..(). I see this as a boiler-plate code.

*

*Is there some other way of dealing with validation (not only token validation but permission in general)? If so, can you show me an example?

*Is it okay to do permission validation in the Repository level?

*Maybe a better approach would be doing validation in Interceptor? But I don't see a clean way of canceling the request if validation does not pass.

A: A better approach will be to keep the validation at repository level only and keeping your viewmodel dumb as possible. It's very simply with Kotlin's Function literals with receiver.
In your repository
fun getSomethingX(
   data: Data,
   onSuccess: (Single<Data>) -> Unit,
   onError: (String) -> Unit
) {
   if (validation(data)) {
      // Do the network call
      onSuccess(//pass result)
   } else onError("Invalid data")
}

In your ViewModel
repository.getSomethingX(
   data,
   onSuccess = {
        //it will give you Single<Data>
        //Update the value
    },
    onError = {
        //Emit error to view
    }
)


text:
Q: Alternative code to read and process array by newline in Ruby My code is supposed to read a file on the server, store its content in an Array, then read the array elements (eventually each element is a line) and split each line into 7 parts by (:)
I wrote this code and it works 100% fine.
lines = File.readlines('/etc/passwd')

lines.each do |line|
line = line.chomp! #I removed the \n
line_arr = line.split(/:/)
puts line_arr.inspect
puts "*************"
end

I just want to know if there is a shortcut to do this since each element of the array ends with \n.
Maybe I am a bit confused between a an array elements ending with \n and a string that contains \n
the content of the file looks like this
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh

As for the output, there's no specific format, because I am going to use this part and extend my code later. As long as I can access those 7 parts that I extracted from the line_arr, i should be fine.
thank you

A: require 'etc'

[].tap {|ary| Etc.passwd {|u|
  ary << [u.name, u.passwd, u.uid, u.gid, u.gecos, u.dir, u.shell, u.change,
          u.uclass, u.expire]
}}

Rule of thumb: never try to reimplement behavior that someone else has already written for you. Unless you are really, really, really, REALLY smart.
Actually, now that you have edited your question, I don't even see why you need those arrays in the first place and cannot just use the Etc.passwd iterator and Struct::Passwd directly.


text:
Q: What's a simple way to list the immediate subdirectories of a given location? Is there a built-in command or a less verbose way of achieving this?
find /var/foo -maxdepth 1 -mindepth 1 -type d

Or should I just make a tiny shell script or function if I'm doing this sort of thing often?

A: ls -d */

"-d" means don't delve into the directories, the "*/" only matches directories.

A: The shortest command seems to be
ls -d /var/foo/{*,.[^.]*,..[^.]*}/

I believe that will non-recursively list all the subdirectories of /var/foo, no matter how stupidly named the directories are or if non-ASCII characters are involved.
user@comp:~$ ls -1d /var/foo/{*,.[^.]*,..[^.]*}/
/var/foo/ . . . . . /
/var/foo/-d/
/var/foo/. . . . . ./
/var/foo/. d/
/var/foo/.-d/
/var/foo/..d/
/var/foo/.d/
/var/foo/.字_Ж/
/var/foo/d/
/var/foo/dir1/
/var/foo/dir2/
/var/foo/字/

However, find /var/foo -maxdepth 1 -mindepth 1 -type d is easier to both remember and type.
Below is my original self-answer.
If one cares not about files beginning with a dot then mibus' answer of
ls -d /var/foo/*/

would be short and effective.  However if one would like the hidden files to be included then one needs to either stick with
find /var/foo -maxdepth 1 -mindepth 1 -type d

or try
ls -FA /var/foo | grep /

The -F places / and the end of directory names (as well as other characters for other types of files).  The -A causes files starting with a dot to be included, except for '.' and '..'.  That is why -a is not used.  The grep won't get any false positives since '/' is not allowed in filenames (at least for POSIX filesystems).
Regarding performance, on my Ubuntu Jaunty installation with just shy of 32k files and directories in /var/foo, find is the fastest, followed by ls -d, and ls -FA with grep comes in last.


text:
Q: jVectorMap on hover do click I've set up a jVectorMap and I want to change the behaviour of it slightly so that when a user hovers over a marker, the same behaviour as the default 'click' behaviour will happen.
Do any of you know how I could go about doing this? Thanks in advance!

A: Just like the onMarkerClick event, there is also an onMarkerOver event as listed in the documentation. http://jvectormap.com/documentation/javascript-api-v1/jvm-worldmap/
onMarkerOver - Will be called on marker mouse over event.
onMarkerClick - Will be called on marker click event.
So any functions you had currently executing on a click can be moved to the onRegionOver event and you should get the functionality you are looking for.


text:
Q: How to fill entry with missing when nothing was writte in in xamarin app? I am doing Import page and if user leave some entry blank and click on import button I want to fill blank entries with Missing. I have tried that like this:
if (liveryEntry.Text == null)
            {
                liveryEntry.Text = "Missing";
            }
            if (registrationEntry.Text == null)
            {
                registrationEntry.Text = "Missing";
            }
            if (airportEntry == null)
            {
                airportEntry.Text = "Missing";
            }
            if (commentEntry == null)
            {
                commentEntry.Text = "Missing";
            }

But sometimes it works and fill it with Missing, sometimes it doesnt work. What is wrong or is there another way to do that?
Here is full code of method:
private async void buttonImport_Clicked(object sender, EventArgs e)
    {
        var db = new SQLiteConnection(_dbPath);
        db.CreateTable<Airplane>();
        collectionPlane.IsVisible = false;
        collectionAirline.IsVisible = false;
        collectionLivery.IsVisible = false;
        collectionRegistration.IsVisible = false;
        collectionAirport.IsVisible = false;
        try
        {
            if (liveryEntry.Text == null)
            {
                liveryEntry.Text = "Missing";
            }
            if (registrationEntry.Text == null)
            {
                registrationEntry.Text = "Missing";
            }
            if (airportEntry == null)
            {
                airportEntry.Text = "Missing";
            }
            if (commentEntry == null)
            {
                commentEntry.Text = "Missing";
            }
            if (planeEntry.Text != null && airlineEntry.Text != null)
            {
                var url = PhotoPick();
                int i = 1;
                int same = 0;
                string fileName = registrationEntry.Text;
                for (int b = 1; b <= GetNumberPhotos(); b++)
                {
                    if (db.Table<Airplane>().FirstOrDefault(d => d.Id == b) != null)
                    {
                        var rowData = db.Table<Airplane>().FirstOrDefault(d => d.Id == b);
                        string match = rowData.Registration;
                        if (fileName == match)
                        {
                            same++;
                        }
                    }
                }
                i = 1 + same;
                fileName = registrationEntry.Text + "-" + i;
                var thumbUrl = CreateThumbnail(await url, fileName);
                var maxPK = db.Table<Airplane>().OrderByDescending(c => c.Id).FirstOrDefault();
                Airplane airplane = new Airplane()
                {
                    Id = (maxPK == null ? 1 : maxPK.Id + 1),
                    SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + datePicker.Date.ToString() + commentEntry.Text,
                    Plane = planeEntry.Text.ToUpper(),
                    Airline = airlineEntry.Text,
                    Livery = liveryEntry.Text,
                    Registration = registrationEntry.Text.ToUpper(),
                    Airport = airportEntry.Text.ToUpper(),
                    Date = datePicker.Date,
                    Comment = commentEntry.Text,
                    Url = await url,
                    ThumbnailUrl = thumbUrl
                };
                db.Insert(airplane);
                await DisplayAlert("Saved", planeEntry.Text + " of " + airlineEntry.Text + " is saved.", "OK");
                planeEntry.Text = "";
                airlineEntry.Text = "";
                liveryEntry.Text = "";
                registrationEntry.Text = "";
                airportEntry.Text = "";
                commentEntry.Text = "";
            }
            else
                await DisplayAlert("Fill all needed fields", "You have to fill all fields except livery and comment", "OK");
        }
        catch
        {
            await DisplayAlert("Error", "Something went wrong", "Try again");
        }
    }

A: It is probably some kind of bug or missunderstanding @Cfun have solved with if ( string.IsNullOrEmpty(liveryEntry.Text)) and it works as expected.


text:
Q: Difference between polymorphism and function overloading in c++ I am a beginner in c++. Can any one explain me on difference between polymorphism and function overloading using some examples or give me some links through which i can learn.

A: overloading is creating a method with the same name with a different amount of parameters, or with parameters which are of another type.
polymorphism is about changing the functionality of a specific method across various types (which all have the same 'base-type').
Function overloading:
public class MyClass
{
    public void DoThingies( int a, int b ) {}

    public void DoThingies( int a, int b, string x ) {}
}

Polymorphism:
public abstract class BaseClass
{
    public abstract DoThingies();
}

public class A : BaseClass
{
    public override DoThingies()
    {
         Console.WriteLine("A");
    }
}

public class B : BaseClass
{
     public override DoThingies()
     {
         Console.WriteLine("B");
     }
}

A: Polymorphism is another important concept of OOP. We can achieve polymorphism  using OOP classes.
There are 2 concepts of polymorphism:
Overloading: Function overloading is a feature where two or more functions can have the same name but different parameters. When a the function is called, it provide output based on the parameters. It happens at the compile time, that's why it is called Compile-Time polymorphism.
The following code may help you to understand.
#include <iostream>
using namespace std;

void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}

int main() {
print(10);
print(10.10);
print("ten");
return 0;
}

It is also called static binding as static binding happens at the compile-time. We may also recognize this as the term of early binding.
Overriding : Override a method in base class by creating similar method in derived class. As it happens while the program runs, it is called Run-Time polymorphism.
The following code may help you to understand.
#include <iostream>
using namespace std;

class Base {
   public:
    void print() {
        cout << "Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() {
        cout << "Derived Function" << endl;
    }
};

int main() {
    Derived derived1;
    derived1.print();
    return 0;
}

It is also called dynamic binding as dynamic binding happens at the runtime. Another term of the feature is late binding.


text:
Q: Windows service to send mail on certain days
Possible Duplicate:
Send mail from asp.net when application is not running

I am writing a windows service to send mail on certain days. I am using sql server table to identify on which days to send out mail, for this I need to check regularly. How can i achieve this.
I wrote code in onStart() event but it only works on Start. OnContinue() doesn't seem to work.
protected override void OnStart(string[] args)
{
    eventLog1.WriteEntry("In OnStart");
    Test();
}

protected override void OnContinue()
{
    eventLog1.WriteEntry("In OnContinue.");
    Test();
}

void Test()
{
   //code to sendout mail
}


text:
Q: import scala.util.Success (or Failure) lead to an "error: value util is not a member of String" my environment shows that I'm using 2.12.10 Scala and 3.1.1 Spark versions:
scala: String = 2.12.10
spark: String = 3.1.1

However, my following code refuse to import scala.util.Failure and import scala.util.Success
while both exists for a long time: I can see them mentioned, here: https://www.scala-lang.org/api/2.12.2/scala/util/Success.html
import java.util.Map;
import fr.ecoemploi.application.etude.swagger.invoker._
import fr.ecoemploi.application.etude.swagger.model.Commune;
import fr.ecoemploi.application.etude.swagger.api.CogControllerApi;
import fr.ecoemploi.application.etude.swagger.invoker.CollectionFormats._
import fr.ecoemploi.application.etude.swagger.invoker.ApiKeyLocations._

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer

implicit val system = ActorSystem("system")
implicit val executionContext = system.dispatcher
implicit val materializer: ActorMaterializer = ActorMaterializer()

import scala.util.Failure
import scala.util.Success

//import scala.concurrent.ExecutionContext.Implicits.global
//import scala.concurrent.Future

val apiInvoker = ApiInvoker()
val cogService = CogControllerApi("http://localhost:9090")
val request = cogService.obtenirCommunes(2022);

val response = apiInvoker.execute(request)

response.onComplete {
    case Success(ApiResponse(code, content, headers)) =>
        System.out.println(s"Status code: $code}")
        System.out.println(s"Response headers: ${headers.mkString(", ")}")
        System.out.println(s"Response body: $content")

    case Failure(error @ ApiError(code, message, responseContent, cause, headers)) =>
        System.err.println("Exception when calling CogControllerApi#obtenirCommunes")
        System.err.println(s"Status code: $code}")
        System.err.println(s"Reason: $responseContent")
        //System.err.println(s"Response headers: ${headers.mkString(", ")}")
        error.printStackTrace();

    case Failure(exception) =>
        System.err.println("Exception when calling CogControllerApi#obtenirCommunes")
        exception.printStackTrace();
}

<console>:40: error: value util is not a member of String
       import scala.util.Failure
                    ^
<console>:41: error: value util is not a member of String
       import scala.util.Success
                    ^
<console>:55: error: not found: value Success
           case Success(ApiResponse(code, content, headers)) =>
                ^
<console>:60: error: not found: value Failure
           case Failure(error @ ApiError(code, message, responseContent, cause, headers)) =>
                ^
<console>:67: error: not found: value Failure
           case Failure(exception) =>


text:
Q: Wake from sleep listener I want to call a method in my app when the android device wakes from sleep.
Here's the whole issue:

*

*I need to refresh the access-token every 30 minutes. So, if the device is not sleeping, and the app is open (be it in the background or foreground), I will call the refresh-token method every 30 minutes.

*But when the device goes to sleep, the refresh-token method doesn't get called.

*So, when the phone wakes after some time (>30 minutes) and the user tries a network request, that would go unauthorized and the user will have to login again.

*Since I don't want the users to login again, I want to apply for the refresh-token as soon as the device wakes up from the sleep mode.
Therefore, I want to call the refresh-token method in the listener to the wake in my app. How can I achieve that?

A: You can register a BroadcastReceiver with IntentFilter for PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED and then you can check if you are in sleep mode using the PowerManager.isDeviceIdleMode and also don't forget to check if your app is in the whitelist with PowerManager.isIgnoringBatteryOptimizations(Context).
Alternatively, you can set a periodic task with:

*

*GcmNetworkManager

*JobScheduler (API 21+)


text:
Q: android - keyboard shows on form despite using adjustResize I want to move my layout up when the keyboards shows on my app . I used adjustResize , adjustPan and both of them for the activity but non of them works and it still shows the keyboard on the form and does not move the layout above .
this is my layout  :
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

          ............... my views

        </LinearLayout>
    </ScrollView>
</RelativeLayout>

how can I make it works ?

A: try like this
final View activityRootView = findViewById(R.id.activityRoot);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
                if (heightDiff > dpToPx(getApplicationContext(), 200)) { // if more than 200 dp, it's probably a keyboard...
                    // ... do something here
                }
            }
        });

 public static float dpToPx(Context context, float valueInDp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
    }

andjust add this in your xml
android:id="@+id/activityRoot"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    **android:id="@+id/activityRoot"**>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

          ............... my views

        </LinearLayout>
    </ScrollView>
</RelativeLayout>


text:
Q: AnalysisException: u"Except can only be performed on tables with the compatible column types I am removing the actual column names as i am not supposed to share those
But her is the glimpse of the error
AnalysisException: u"Except can only be performed on tables with the compatible column types.
string <> boolean at the 28th column of the second table;
;\n'Except false\n:- Filter (cast(inactive_date#111 as string) = '3001-01-01')\n:
+- Project [... 33 more fields]\n:+- Project [ ... 33 more fields]\n:+- SubqueryAlias \n:+-Relation[... 33 more fields] parquet\n
+- Project [... 33 more fields]\n +- Join Inner, (Key#275 = entry#26)\n:- Filter (cast(inactive_date#283 as string) = '3001-01-01')\n:
+- Project [... 33 more fields]\n:
+- Project [... 33 more fields]\n : +- SubqueryAlias  +- Relation[,... 33 more fields] parquet\n
+- Deduplicate [entry#26]\n +- Project [entry#26]\n+- Project [... 13 more fields]\n
+- Project [... 13 more fields]\n  +- SubqueryAlias +- Relation[] parquet\n"

My code looks like this
#old dataframe   (consider it as History )
#daily dataframe ( Consider it as daily  )

#Filtering the Active records based on condition

Active_old_filtered_records= old_history_dataframe.filter(old_history_dataframe["inactive_date"] == '3001-01-01')
Inactive_old_filtered_records= old_history_dataframe.filter(old_history_dataframe["inactive_date"] != '3001-01-01')

#Joining active old records with the matching active records in daily dataframe based on KeyColumnA

left = Active_old_filtered_records
right = Active_new_daily_dataframe.select("keyColumnA").distinct()

Matching_Active_daily_old_dataframe = left.join(right, ["keyColumnA"])
Non_matching_active_daily_old_dateframe = Active_old_filtered_records.**subtract**(Matching_Active_daily_old_dataframe)

Note: Here the daily dataframe and old dataframe have exactly same schema but i am getting analysis exception. can someone help in this regard
Thank you.

A: Finally i was able to resolve this with the following code
#old dataframe   (consider it as History )
#daily dataframe ( Consider it as daily  )

cols = Active_old_filtered_records.columns

#Filtering the Active records based on condition

Active_old_filtered_records= old_history_dataframe.filter(old_history_dataframe["inactive_date"] == '3001-01-01')
Inactive_old_filtered_records= old_history_dataframe.filter(old_history_dataframe["inactive_date"] != '3001-01-01')

#Joining active old records with the matching active records in daily dataframe based on KeyColumnA

left = Active_old_filtered_records
right = Active_new_daily_dataframe.select("keyColumnA").distinct()

Matching_Active_daily_old_dataframe = left.join(right, ["keyColumnA"]).select(cols)

Non_matching_active_daily_old_dateframe = Active_old_filtered_records.subtract(Matching_Active_daily_old_dataframe)

Joining two dataframes with a column from anywhere except start position changes the order of columns in resultant dataframe. so maintained a cols variable and selected the same column in correct order to ensure the resulting steps work correctly :D
And finally i was able to resolve the problem.


text:
Q: Probability Theory and distribution I need to solve the following problem:
There's a cafetria with multiple foods.Every time you roll a dice you're given a different food.
There's a 27/1024 probability that the food will be pizza, and 9.3/1024 probability that it'll be hamburger.
The question asks how many times the dice has to be rolled in order to create a substiantially distinguish the number of pizzas from the number of hamburgers. Take the distinguishing factor to be 1.5.
Thank you very much


text:
Q: What is similar code Buffer.from("String","hex") in flutter What does this code do with the below example?
I have the below code in node.js and I want to do the same code in a flutter.
var iv = 'any string';
iv = new Buffer.from(iv, "hex");

A: Maybe this package will helpBuffer


text:
Q: Time taken to sort numbers in Linked List Does Sorting take the same time if we use the Singly Linked List or Doubly Linked List?
I want to sort random numbers.
(I know it differs greatly in terms of insertion/removal of elements in  Singly/Doubly Linked List)
But Does it take almost same time regardless of which data structure (Singly / Doubly LinkedList) we use or which sorting technique we implement to sort the numbers?

A: One of the fastest sort methods used for linked lists only needs to use the next pointer of a linked list to do a variation of bottom up merge sort, using an array of pointers (typically 26 to 32 pointers) to nodes, where array[i] is NULL or a pointer to a list with 2 to the power i nodes. Example code below.
Sorting a double linked list is going to be slower than sorting a single linked list if time is spent maintaining previous pointers during the sort. If only using next pointers during the sort, the time is about the same, other than larger nodes (since they have previous pointers) consume more cache space.  Doing a single pass to set the previous pointers after the sort should be faster than maintaining previous pointers during the sort.
NODE * MergeLists(NODE *pSrc1, NODE *pSrc2)
{
NODE *pDst = NULL;                      /* destination head ptr */
NODE **ppDst = &pDst;                   /* ptr to head or prev->next */
    if(pSrc1 == NULL)
        return pSrc2;
    if(pSrc2 == NULL)
        return pSrc1;
    while(1){
        if(pSrc2->data < pSrc1->data){  /* if src2 < src1 */
            *ppDst = pSrc2;
            pSrc2 = *(ppDst = &(pSrc2->next));
            if(pSrc2 == NULL){
                *ppDst = pSrc1;
                break;
            }
        } else {                        /* src1 <= src2 */
            *ppDst = pSrc1;
            pSrc1 = *(ppDst = &(pSrc1->next));
            if(pSrc1 == NULL){
                *ppDst = pSrc2;
                break;
            }
        }
    }
    return pDst;
}

#define NUMLISTS 32                     /* size of aList[] */
NODE * SortList(NODE *pList)
{
NODE * aList[NUMLISTS];                 /* array of lists */
NODE * pNode;
NODE * pNext;
int i;
    if(pList == NULL)                   /* check for empty list */
        return NULL;
    for(i = 0; i < NUMLISTS; i++)       /* zero array */
        aList[i] = NULL;
    pNode = pList;                      /* merge nodes into array */
    while(pNode != NULL){
        pNext = pNode->next;
        pNode->next = NULL;
        for(i = 0; (i < NUMLISTS) && (aList[i] != NULL); i++){
            pNode = MergeLists(aList[i], pNode);
            aList[i] = NULL;
        }
        if(i == NUMLISTS)
            i--;
        aList[i] = pNode;
        pNode = pNext;
    }
    pNode = NULL;                       /* merge array into one list */
    for(i = 0; i < NUMLISTS; i++)
        pNode = MergeLists(aList[i], pNode);
    return pNode;
}


text:
Q: How to run method from inner class in Android? Hello stackoverflow people. I've got following code.
public class ChangeActivity extends Activity {
EditText myTextBox;

void doProcessing(){ /*do something*/ }
@Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  myTextBox = (EditText) findViewById(R.id.myTextBox);
  myTextBox.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {
   }

   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
     doProcessing();
   }
  });
 }
}

The problem is: I can't access doProcessing() from onTextChanged(). How to resolve it? I need doProcessing for other pieces of code, so I'd like not to put it inside onTextChanged().

A: You can access the outer class from the inner class using the class name and this. For example:
ChangeActivity.this.doProcessing();

A: You CAN access methods from the outer class in the inner class.
Alan's correct on the OuterClass.this syntax BUT you only have to use it if you need to disambiguate between methods with the same name. You don't need to do that in this instance.
To illustrate my point, this simplified but equivalent code compiles just fine...
public class Temp {
    void foo() { }

    public void bar() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                foo();
            }
        });
    }
}

So... When you say you can't access it, what do you mean?