Writing data to text file in windows 8

Question: I'm developing a Windows 8 application using HTML5. The application requires some user data to create a new event. The event has a title, description, date and time. I want to store this data in a text file in JSON format after the user has filled the form so that it can be visible the next time user opens the application.
I can find different methods of writing JSON objects to text file but I can't find anything related to appending data at the end of the text file. Basically, I have one events.txt from which I read and display data and I want to append events to the same .txt after user adds an event.
My events.txt looks like this
[
        {
        "key": "event1",
        "title": "title1",
        "description": "description1",
        "date": "<sample date>",
        "time": "<sample time>",
        "backgroundImage": "../images/logo.png"
        }
]

I'm reading the events from this file using the following code
WinJS.xhr({ url: "../data/events.txt" }).then(function (xhr) {
        var events = JSON.parse(xhr.responseText);

        events.forEach(function (feed) {
            event.push({
                group: feed,
                key: feed.key,
                title: feed.title,
                description: feed.description,
                date: feed.date,
                time: feed.time,
                backgroundImage: feed.backgroundImage
            });
        });
    });

Any kind of help will be greatly appreciated as I'm running tight on a deadline here.
Thanks.
Comment: If you think this is not the best way to do what I'm doing, then please let me know how to proceed. Like I said, any kind of help will be appreciated.
Answer: Are you looking for this File Access sample for Consumer Preview?
If I understood your question correctly, I think here are some important API that you want to use.
// Create a file
var eventFile;
Windows.Storage.KnownFolders.documentsLibrary.createFileAsync("event.txt", Windows.Storage.CreationCollisionOption.openIfExists).done(function (file) {
        eventFile = file;
    });

// Write Text to a file
Windows.Storage.FileIO.writeTextAsync(eventFile, JSON.stringify(yourJSONObject));

// Append Text to a file
Windows.Storage.FileIO.appendTextAsync(eventFile, JSON.stringify(yourJSONObject));

More reference to FileIO API:
http://msdn.microsoft.com/en-us/library/windows/apps/hh701440.aspx
In addition, why don't you consider using local storage or indexedDB to store your event info?
Comment: Thanks for the reply. I had gone through the File Access sample. From what I understand, the file is created everytime the application is opened, right? I'm just trying out the API again. I want the updated data to be available everytime the user opens the app.
Comment: @user870681 From my own experience, the data is persistent. As long as you don't remove it, it should be there. You can use `Windows.Storage.CreationCollisionOption.OpenIfExists` to avoid overwriting the file.
Comment: I have been trying this since then, but the application kept crashing. I then tried 'Windows.Storage.ApplicationData.current.local.createFileAsync("events.txt");'
I am able to write the data in the file using this but now I have problems reading it. any ideas? Do you want me to post the full code?
Comment: I guess you would probably wanna fix the Crash first, cuz it's going to overwrite existing file, right? Do you know where it crashes? p.s. why do you want to use a file instead of localStorage? Using file will require you to ask for additional permissions, but localStorage doesn't.
Comment: By local storage, you mean `Windows.Storage.ApplicationData.current.local.createFileAsync("events.txt");` ? Or is there something else to it?
Comment: It's HTML5 feature. `window.localStorage`. Follow these links http://www.w3.org/TR/2009/WD-webstorage-20091029/#the-localstorage-attribute and https://developer.mozilla.org/en/DOM/Storage and http://msdn.microsoft.com/en-us/library/windows/apps/hh466046.aspx

Writing data to text file in windows 8


Passar String para matriz (Xml);

Question: Eu estou usando Esse código para ler um mapa de um aquivo xml.
private void loadMap(String mapa) {

        File file = new File(getClass().getResource(mapa).getFile());

        try {

            dbBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            org.w3c.dom.Document doc  = dbBuilder.parse(file);

            NodeList nList = doc.getElementsByTagName("layer");

            for(int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if(node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;

                     // Le o conteudo
                    String conteudo = element.getElementsByTagName("data").item(0).getTextContent();

                }
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

O arquivo seria esse:
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" tiledversion="1.0.2" orientation="orthogonal" renderorder="right-down" width="42" height="34" tilewidth="16" tileheight="16" nextobjectid="1">
 <tileset firstgid="1" name="tileset" tilewidth="16" tileheight="16" tilecount="924" columns="33">
  <image source="tileset.png" trans="003bff" width="528" height="448"/>
 </tileset>
 <layer name="Camada de Tiles 1" width="42" height="34">
  <data encoding="csv">
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,661,662,663,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,694,695,696,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,666,667,668,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,699,700,701,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,732,733,734,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,765,766,767,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,666,667,668,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,699,700,701,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,34,34,34,34,34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,34,34,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,34,34,0,0,0,0,0,0,0,0,0,0,
0,0,0,265,266,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,34,34,0,0,0,0,0,0,0,0,0,0,
0,0,0,298,299,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,34,34,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
</data>
 </layer>
</map>

Mas eu não consegui passar  o conteudo para uma matriz. mapa[34][42]; , Alguém sabe uma maneira de fazer isso?
Answer: Bem, quem estiver com o mesmo problema, consegui fazer assim:
public void loadMap(String path) {

        File file = new File(getClass().getResource(path).getFile());

        try {

            DocumentBuilder dbBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc  = dbBuilder.parse(file);

            NodeList nList = doc.getElementsByTagName("layer");

            for(int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if(node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;

                    String conteudo = element.getElementsByTagName("data").item(0).getTextContent();

                    String[] partes = conteudo.split("\\s+");

                    String regex = ",";
                    for(int row=0; row < altura; row++) { // map Height
                        String[] linha = partes[row + 1].substring(0, partes[row + 1].length()).split(regex);
                        for(int col=0; col < largura; col++) { // map Width
                            int numero = Integer.parseInt(linha[col].trim());
                            mapa[row][col] = (numero - 1);
                        }
                    }
                }
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

Passar String para matriz (Xml);


postMessage handling in IE11

Question: Suppose I have three urls:
1.http://home.com

2.http://loader.com
var oFrame = document.createElement("iframe");
oFrame.src = "http://www.sf.com";
oFrame.onload = function() {
   oFrame.contentWindow.postMessage({ msg: 'hi'}, 'http://sf.com');
}
document.childNodes[0].childNodes[1].appendChild(oFrame);

3.http://sf.com

Now in any "normal" browser (edge/firefox/chrome) load the http://home.com - the chain will load script from "http://loader.com" into an iframe which will load yet another iframe with "http://sf.com" and the last iframe will displays "http://home.com" as the event origin. However in internet explorer 11 the event orgin is set to "about:". Is there a way how to get around this particular quirk ? I haven't found any docs around this particular quirk (ref: https://caniuse.com/#search=postMessage)
Answer: I make a test on my side and reproduce the same issue. I also searched a lot of information but find no clue. I guess if using two iframes cause the issue. So I make another test using only one iframe and the event.origin can get the right url in IE. I use the code like below:

http://home.com
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title></title>

http://loader.com
var oFrame = document.createElement("iframe");
oFrame.src = "http://sf.com";
oFrame.onload = function () {
    oFrame.contentWindow.postMessage({ msg: 'hi' }, 'http://sf.com');
}
document.childNodes[1].childNodes[2].appendChild(oFrame);

http://sf.com
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title></title>

Although not find any document proof but the test result let me think there might be some limitations in IE when using embed iframes. As a workaround, you could try to use only one iframe.

postMessage handling in IE11


View Group By field with mult-value field

Question: I have a field that contains multiple boolean values ( similar to a tag or taxonomy term) which indicates status.  So the field is like this.
application="received, data complete, references, financials,"
I'd like to create a tabular report grouped like this:
Received:
Item A
Item C
Data Complete:
Item A
Item B
References:
Item A
Item B
The problem is that grouping on the field is like this:
Received, Data Complete, References:
Item A
Data Complete, References:
Item B
Received:
Item B
So I need to break up the field in views.  I realize I can create a view in a view or view field, but wondering if there is anything more simple/elegant.
Comment: To clarify - I am not using a taxonomy term (it is the same concept though) and D7 + Views 3.
Answer: You can also uncheck the box "display all values in the same row" under the multiple field settings menu in the configure field settings. Doing this "denormalizes" the data. This works for both content and taxonomy terms - in my case accessed via entity reference. This way you can make the best choice between content and taxonomy in your design.
Answer: Your premises are not quite clear, but assuming that you are in a Drupal 7/Views 3 environment and that your status field leverages Drupal Taxonomy, you could achieve it in this way:

Create a new view.
Choose Taxonomy terms—not Content—from the
    dropdown list after "Show" and select your vocabulary as type.
Your new view will contain Taxonomy term: Name as the only field. To get the titles of the nodes tagged with the terms of your vocabulary, first add the relationship Taxonomy term: Content using {name_of_your_vocabulary}.
Then add the field Content: Title and apply the previously created relationship.
Now exclude the term name field from display and select it as Grouping field in the Format settings.

This method will provide exactly the desired data structure:
data complete
Item A
Item B
received
Item A
Item C
references
Item A
Item B
You might want to adjust the order of the terms by adding term name/weight or other sorting criteria.
=======================
EDIT: If your field is not taxonomy-based but, say, a list field or any other field type capable of containing multiple values, you could get the same result along these lines:

Create a view on nodes, not terms.
Add node title and status (or whatever your field is called like) as fields.
Uncheck the "Display all values in the same row" feature in the status field's Multiple field settings.
Exclude status from display and select it as grouping field.
Add 'status: is not empty' as filter criterion to exclude irrelevant nodes.
Adjust filter and sorting criteria to your needs.


How to change the alias for the core forum landing page?

Question: Core forums sets the landings page to /forum. I need this changed to /another-page/forum. I know I can change the forum posts using pathauto, but I need to change the alias for the top-level forum landing page. Thoughts?
Answer: Why not just use the core path module:
http://example.com/admin/config/search/path/add
Comment: Thank you. I always assumed that core path was only for creating nice seo aliases for node and term ids. thanks.


View for Taxonomy terms?

Question: How can I output nodes which linked with taxonomy term through a view?
How can I link taxonomy vocabulary with a view wich will output appropriate nodes for each term of this vocabulary?
In Drupal 7 we have two modules:

Taxonomy Display (is not present in D8).
Taxonomy Views Integrator (is raw in D8).
Comment: TVI is now available in Beta for Drupal 8. It works well for me.
Answer: You don't need additional modules to create different Taxonomy term pages, in D7 nor D8. Taxonomy Display and Taxonomy Views Integrator modules save steps in certain cases, but you can recreate their functionality with configuring different Views for different cases.
You can reuse the existing Taxonomy term Views (this lists nodes based on the taxonomy term in the URL).
If you need different Taxonomy page settings for each Vocabulary you can Duplicate the Taxonomy term Views (that shows Content tagged with a term) as many times as you have different Vocabularies, and add Filters to each to apply only to one Vocabulary.
Then you can also change all the other options related to how you want different Vocabulary terms Content to be displayed, because you'll have a different View for each Vocabulary.
Comment: How exactly the "Filters" should be configured? I created Contextual filter with this parameters: If value is not in URL - 404, Validator - Taxonomy term ID, Vocabulary - one specific on each view, Validate user has access to the Taxonomy term, Action to do if validation will not pass - 404.
Comment: @Bobík that sounds good. The `Validator` and `Vocabulary` are required in this case (under `When the filter value IS available or a default is provided`), all other options you can set to your liking. Just make sure you don't set to accept multiple arguments, or that the option clash between different Views you've configured specifically for each Vocabulary.
Comment: Hmm, it still loads the view what was last saved (it behaves like configured by Action to do if validation will not pass).
Comment: @Bobík it's impossible to say flying blind. Maybe open a question with all the details?

View for Taxonomy terms?


how to pass parameters from url to phonegap android app

Question: im trying to call my phonegap android app from the URL with parameters.
its working fine but i have no idea how to get the parmeters ive sent with it.
the mainfest looks like that:
            </intent-filter>
                <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="ghtr" android:host="com.mds.ghtr"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>

the link looks like that:

all i want to do is to get var1 in the js.
thanks.
Answer: By split you can get the parameter from location.
$(document).ready(function() {
var var1= location.search.split("?var1=")[1];
}

Or you can get it in Native code .
You need to add this code to  onCreate in MainActivity.java:
@Override
public void onCreate(Bundle savedInstanceState) {
....
Uri data = getIntent().getData();
String var1= data.getQueryParameter("var1");
}

Comment: how i pass var1 to the javascript ?


Pandas Aggregate price and calculate weights/weightage of that of price vs volume data and group by step of 5 prices

Question: I have a dataframe like this:
       price   volume
0     100.0     2500
1     100.5     4100
2     101.0     2311
3     101.5     5066
4     102.0     9585
...    ...       ...

I want to first get a grouping of price and sum the volumes with a step of 5.
For example (using random values):
       price   volume
0     100.0     15000
1     105.0     12000
2     110.0     19000
3     115.0     30000
4     120.0     21000
...    ...       ...

and finally based on individual volume and price I want to give each price a weight/weighted average/score so I can standardise the data to know which volume has the most weight.
For example:
       price   volume     weight
0     100.0     15000        3
1     105.0     12000       2.5
2     110.0     19000       3.5
3     115.0     30000       5
4     120.0     21000       4
...    ...       ...

Can anyone please help me with this?
Comment: what falls in price 100 (anything > 95 and <= 100), what falls in price 105
Comment: yes, 100 will include the sum of volumes from >95 to <=100, 105 will include sum of volume of >100 to <=105
Answer: I used the standard way to round the price so 97.5 to 102.49 will be in group 100.
Weight - I have used simple formula as evident.
data.csv:
price   volume
100.0     2500
103.5     4100
101.0     2311
105.5     5066
109.0     9585

Code:
import pandas as pd
import numpy as np

df = pd.read_csv('data.csv', delimiter='\s+')
print(df)
df['price_grp'] = np.around(df.price.values/5, decimals=0)*5
df['tot_vol'] = df.groupby('price_grp')['volume'].transform('sum')
df['weight'] = np.around(df['volume'] / df['tot_vol'], decimals=2)
print(df)

Output:
   price  volume
0  100.0    2500
1  103.5    4100
2  101.0    2311
3  105.5    5066
4  109.0    9585
   price  volume  price_grp  tot_vol  weight
0  100.0    2500      100.0     4811    0.52
1  103.5    4100      105.0     9166    0.45
2  101.0    2311      100.0     4811    0.48
3  105.5    5066      105.0     9166    0.55
4  109.0    9585      110.0     9585    1.00


Shiny Download File based on File Path

Question: I have a file which i generate in shiny
The user clicks a button and the file should download. However nothing happens
The function export_report generates the excel file and saves it to a location. The function then passes back the file location to the download handler so it will download the file. The problem seems to be that it isnt being returned correctly. I have tested the function (export_report) outside of shiny and it returns everything perfectly so I'm clearly doing something wrong from the shiny perspective.
The file itself is created where it is supposed to be on the server because i can download it within RStudio and see it in the file explorer. Can anyone help
# UI Section
downloadButton("downloadRpt", "Download Report")

# Server Section
output$downloadRpt <- downloadHandler(

  filename = function() {
    mydf <- report()
    dateRange <- input$dates_report
    selection <- input$selection
    myfile <- export_report (mydf, selection, dateRange)
  },
  content = function(file) {
    file.copy(myfile, file)
  }
)

I have seen other examples R Shiny: Download existing file which is what my code is based on
EDIT 1: Adding the export_report function with some fake data to run it
export_report <- function(mydf,selection,dateRange) {

  # Template for where the template excel file is stored

  myoutputTemplate <- '/home/shiny_tutorials/Save to Database/templates/output_template.xlsx'

  start_date <- dateRange[1]
  end_date <- dateRange[2]
  date_range <- paste(start_date ,end_date, sep = " - " )

  # Load workbook the template workbook
  wb <- loadWorkbook(myoutputTemplate)

  # write to the workbook the data frame
  writeWorksheet(wb, mydf, sheet="Details",
             startRow=8, startCol=2,
             header=FALSE)

  # add the the customer the user selected
  writeWorksheet(wb, selection, sheet="Details",
             startRow=3, startCol=3,
             header=FALSE)

  # date
  writeWorksheet(wb, date_range, sheet="Details",
             startRow=5, startCol=3,
             header=FALSE)

  # Create The file Name
  filename <- paste(selection, Sys.Date(), sep = " - ") %>%
    paste(.,"xlsx", sep = ".")

  # removes the % sign and extra qoutes
  filename <- gsub (pattern = '\'|%','', x = filename)

  # output directory
  myoutput <-  paste('/home/shiny_tutorials/Save to Database/output/',
               filename, sep = '')

  # Save workbook
  saveWorkbook(wb, myoutput)

  # Return File Path
  myoutput

}

To call the function you can use the data below
dateRange <- c("2011-09-23","2016-09-23")
selection = "COMPANY_A"
mydf <- iris
myfile <- export_report(mydf,selection,dateRange)

EDIT 2 I have now managed to get an error out of it. When i cat(myfile) in the filename = function() { section of the code i get the error after the correct file path has been returned

Warning in rep(yes, length.out = length(ans)) :
    'x' is NULL so the result will be NULL
  Warning: Error in ifelse: replacement has length zero
  Stack trace (innermost first):
      1: runApp
  Error : replacement has length zero

This error is basically because my file path does not get passed to the segment myfile so
if someone can tell me how to get the filepath generated by my function to the server section of the code below, that should fix my problem
content = function(file) {
    file.copy(myfile, file)
  }

Comment: Does your `export_report` function return a file name or a file path? inside `downloadHandler`, `filename` should be a name only (it's the name of the file user gets), and `content` contains the actual file.
Comment: Hi @warmoverflow, If that is the case, how do you specify where the actual file is to download? For example my file is contained in a folder called root\output\output_company - 29-05-82
Comment: The actual file path is to be used in the `file.copy` command (first argument), while the file name is to be used as the `filename` variable in `downloadHandler`.
Answer: Thank you to everyone who commented and clarified my thinking a bit on how the download handler works.
In the end, i created a new function which split up the export function above
The new function i used is called generate_file() which simply returns the file name
generate_file_name <- function(selection) {

  # Create The file Name
  filename <- paste(selection, Sys.Date(), sep = " - ") %>%
    paste(.,"xlsx", sep = ".")

  # removes the % sign and extra qoutes
  filename <- gsub (pattern = '\'|%','', x = filename)

  # output directory
  myoutput <-  paste('/home/shiny_tutorials/Save to Database/output/',
                 filename, sep = '')

  # Return File Path
  myoutput

}
Then in the server side
output$downloadRpt <- downloadHandler(
  filename = function() {
    selection <- input$company
    generate_file_name(selection)
  },

  content = function(file) {

    mydf <- report()
    dateRange <- input$dates_report
    selection <- input$company
    export_report(mydf,selection,dateRange)
    myfile <- generate_file_name(selection)
    file.copy(myfile, file)

  }
)

This then finds the newly created file and exports it for the user
Answer: I just checked your problem with this example code and it worked:
output$downloadData <- downloadHandler(
    filename = function() {
        data <- mtcars
        myfile <- "data.csv"
        write.csv(data, myfile)
        myfile
    },
    content = function(file) {
        print(file) //prints: [...]\\Local\\Temp\\RtmpEBYDXT\\fileab8c003878.csv
        file.copy(file, file)
    }
)

myfile is the filename of the downloaded file. You cannot use it in file.copy as input, this variable is out of scope. It seems that R creates a temp file name (see the print()).
Comment: Hi @Lars K. Thank you for helping me with this. Can you tell me what exactly the `filename` portion of the `downloadhandler` is for? It doesn't seem to be getting used anywhere how is the path getting passed to the file.copy. My question is because what if two people are running the web page at the same time, how does it know which one to download. Thank you again for your help
Comment: Hi John, I am not that much into Shiny. filename = *myfile* is the output file name, proposed to the user for downloading. But you use it for storing your xlsx file, too. In my tiny example, Shiny keeps data.csv in a common directory for every session. In your case, maybe you store your xlsx to tempfile = "Table(SessionId).xlsx" and return myfile = "Table.xslx". Of course, tempfile should be determined outside downloadHandler in order to be found in content = function(file){file.copy(tempfile, file)}. Hope, I could help!
Answer: Try to use the filename function to define your path or a custom file name, and the write.csv in the content part. Example code:
 output$downloadData <- downloadHandler(
    filename = function() {
        paste(<user_name or date for eg>, ".csv", sep="")
        },
    content = function(file) {
        write.csv(data, file)
    }
 )

I noticed in your comment above, you have asked how the application would generate the correct file when used by multiple users. For this part, you need to use the session.
So if your business logic functions were to come from an R file called foo.R, the server code should look something like:
shinyServer(func = function(input, output, session) {
     source("./foo.R", local=TRUE)
     ......

And this would separate out the session for each user, thereby generating files specific to each, when downloading. Hope this gives you some pointers.

Shiny Download File based on File Path


Why are these the number of operations for each line in this pseudocode?

Question: I am watching a lecture on data structures from my course and I don't really understand the part where the lecturer translates each line into operations.
Can someone please explain how they are obtaining  2n +1, 2(n-1), 2(n-1), 2(n-1), 1 and finally 8n-2. I have tried my best to understand it but I can't.
Answer: The counter denotes the number of operations (e.g. addition, subtraction, multiplication, accessing index etc.). In simple terms, each of these operations can be done in a single (or smallest) unit of time. For example:
currentMax <- A[0]

There are two operations, one accessing the zeroth index. Second, assigning it to the variable currentMax.
Similarly in the loop, if you are doing one operation in each iteration, you will end up doing total "n" operations where n is the length of the array.
for i <- 1 to n-1 do

Let's walk through this line, for the first iteration you are assigning value 1 to i, that will be 1 operation. In each iteration, you will subtract 1 from n (for evaluating n-1) and you also need to compare i with n-1 which will be another operation. So, for n iterations, you will perform n * 2. That's how you get 2n+1 for this statement in pseudocode.
Comment: Apologies, I am still confused, how does this answer my questions I had? How is the lecturer getting those specific numbers for each line? (2n+1, 2(n-1) etc)
Comment: @futuredeveloper, Added one example, let me know if you want any explanation further.
Comment: for the example you did: for i <- 1 to n-1 do, surely this should just be n-1 operations? since lets say n is 10, i = 1, so number of times this loop will run will be 9 times hence n-1?
Comment: @futuredeveloper, Good catch, Total counter for this step should be 2n-1 instead of 2n+1.
Comment: why 2n-1 and not n-1?, where is the 2 coming from? @Devesh
Comment: There are two operations in "for i <- 1 to n-1 do". First subtraction to evaluate n-1, second, comparison "i<n-1". These two operations are repeated n-1 times. So the total will be 2(n-1). And, you have done one assignment "i=1" for the very first time only. Hence grand total for this step becomes 2(n-1) + 1 = 2n-1.
Comment: what i don't understand is for this for loop: for(i=0; i<=2*n; i++), this runs 2n + 1 times simple since it runs from 0 to 2n, so 2n + 1. But the approach you took for for i <- 1 to n-1 do, is different from the approach they took there. @Devesh
Comment: @futuredeveloper, Explain to me what is your understanding in detail and I can fill the gaps for you. I'm giving you a totally unrelated example just for the sake of uderstanding. How many primitive operations does it take to do a comparison? Only 1 but Say you have two numbers and a and b, and you want to check if a is at least 5 units less than b, You will use "a < b - 5", How many primitive operations are you doing for this comparison? The correct answer is 2. How? Well, one is subtraction and another is comparison. Now, ponder are you doing something similar in the loop?


Estimate how coefficient of variation changes as a function of $x$ without replication

Question: Suppose I have data points of the form (x,y) and I know that CV should be constant across all x values. (i.e. heteroskedastic data). That being said, how can I compute the estimated CV if I don't have multiple y values for each x?
Typically, CV is computed on discrete data (ex. repeatedly measuring y values for some given x). But in this case, not all x values have multiple y values. Note that constant variance can be assumed throughout the domain of x.
If anyone could direct me to literature that handles scenarios as this, that would be great.
Comment: Can you assume any relationship between the mean of $y$ and $x$, say linear?
Comment: Yes, linear can be assumed. In any case, a regression can be fit.
Answer: You might fit a robust line (or one of some form that's otherwise hetero-consistent) and then model the squared residuals against $x$ in order to model the variance. Those squared residuals could then be used use that to update weights.
(another way to get starting values would be to consider a transformation to approximately constant variance)
Another approach, possibly simpler, would be to use glms (say a gaussian family with a $\mu^2$ variance function).
Edit: yet another approach: Divide through by $\sqrt{x}$ - let $y^* = y/\sqrt{x}$, and $x^* = x/\sqrt{x}$ (equivalently, $x^* = \sqrt{x}$) and the constant predictor become $x_0^* = 1/\sqrt{x}$. Regress $y^*$ on $x_0^*$ and $x^*$ with no intercept (because $x_0$ represents it). (:end edit)
Finally, one could write the weighted least squares criterion as a function of the mean parameters which also appear in the variance function and calculate the parameters as the solution to a more general optimization problem.
Some possible references for what you were suggesting:
1) The basic iterative (re-)weighted least squares algorithm (IWLS or IRLS), used to fit all manner of things from nonlinear regression to GLMs. It applies to your situation as a special case. If you don't iterate to convergence, you just refer to it as a two-step estimator (estimate model, get  residuals, estimate variance, re-estimate model)
2) You might be able to use the approach in White hetero-consistent estimation (which has a kind of connection to (3) below as an argument for what you want to do.
3)
Here's an approach relating to estimating the variance function, using a method I've seen many times but only today spotted a real reference for:
The idea is you fit some model and take logs of squared residuals (since squared residuals will approximate the variance) and estimate a function to those. These will let you back out relative variances* and hence relative weights (by inverting relative variances) for the original regression.
This might count as sufficient for your case, which is a special case of this.
Wasserman, Larry (2006). All of Nonparametric Statistics. Berlin: Springer-
Verlag. (see p87-88)
*(though if I recall correctly, I think in the linear case Geoff Eagleson established that this is biased for the intercept term so doesn't give a good idea of absolute variances.)
--
Another possibility, though I don't have it to hand to double check, is I think it might be covered in Chapter 4 of Sheather's book A Modern Approach to Regression with R
Comment: the variance is not constant, since CV is constant as x (the mean) increases...
Comment: Can you explain which part of my answer suggests I thought your original variance was constant, rather than the coefficient of variation?
Comment: Sorry, I wasn't referencing part of your answer, I just wanted to clarify that! I was thinking to fit a regression line, compute errors, and find the SD of the error distribution. What do you think of that?
Comment: You mean, along the lines of my first option (the first paragraph), but without starting with an estimate robust to heteroskedasticity, nor updating the line after initially estimating the variance-function? Are you asking why one would bother with those particular additions?
Comment: I suppose, yeah. How would I go about implementing your first answer? Has anyone done this in the literature before, such that you could direct me to an example? If I use this method (the first part of your answer), I'd like to cite it.
Comment: I'll see if I can get you some kind of citation for it. Oh, I am going to add another possibility to my list - check it in a while.
Comment: Hi there, any updates on finding a citation? Thanks!


Chain rule and implicit functions problem

Question: I'm trying to solve a problem involving the implicit function theorem. I've come to a point where I must derive this implicit function with respect to it's coordinates and don't know how to proceed. Here is the problem:

Prove that exists an implicit function $\varphi$ around the point $0$ with $\varphi (0) = 0$ such that $F(\varphi(y),y)=0$
$F: \Bbb R^2 \rightarrow \Bbb R$, $F(x,y)= x^3 - x(y+1)+y^2$
Express $\varphi ' (y)$ in terms of $y$ and $\varphi(y)$
Find the Taylor polynomial of second degree of $g$ around the point $p=(1,-1)$ with $g(x.y)=\varphi(y+x^2)+xe^{y+1}$

The hypothesis for the implicit function theorem are true for $F$ around the point. And $F_x(0,0)\neq0$. So the function exists.
I have $\varphi'(y)=\frac{\varphi(y)-2y}{3 \varphi(y)^2-y-1}$
I want to find the equation for $g$'s taylor polynomial but I'm confused on how to derive with respect to what in $g$.
$g_x(x,y)=\varphi'(y+x^2)2x+e^{1+y}$ and $g_y(x,y)=\varphi'(y+x^2)+xe^{1+y}$
Could anyone help me with this? Thanks.

Update: As I have $\varphi'$ I only need to understand how to get the second order partial derivatives of $g$.
Comment: Note that $\varphi''(y)$  may be computed using the formula for $\varphi'(y)$ that you have already obtained, namely $$\varphi'(y)=\frac{\varphi(y)-2y}{3\varphi(y)^2-y-1}.$$ Given $\varphi''(y)$, computation of the second partials of $g$ is straightforward.
Answer: The Taylor expansion until second degree is:
$g(x,y)=g(1,-1)+(\Delta x g_x(1,-1)+\Delta yg_y(1,-1))+\frac 1 2(\Delta x^2g_{xx}(1,-1)+2\Delta x\Delta yg_{xy}(1,-1)+\Delta y^2g_{yy}(1,-1))+o\left(\lVert(\Delta x,\Delta y\rVert^3\right)$
$$\varphi'(z)(3\varphi(z)^2-z-1)=\varphi(z)-2z$$
$$\varphi''(3\varphi^2-z-1)+\varphi'(6\varphi'\varphi-1)=\varphi'-2$$
$$\varphi''=\frac{\varphi'-2-\varphi'(6\varphi'\varphi-1)}{3\varphi^2-z-1}$$
Now, $z=y+x^2=0$ for $p(1,-1)$, then $\varphi(0)=0\;;\varphi'(0)=0$ and $\varphi''(0)=2$, ready to be substituted into the expressions for the partial derivatives:
$g_x(x,y)=\varphi'(y+x^2)2x+e^{1+y}\;;g_x(1,-1)=1$
$g_{xx}(x,y)=\varphi''(y+x^2)4x^2+\varphi'(y+x^2)2\;;g_{xx}(1,-1)=8$, etc.


join 2 sql queries that involve the same table i need to get the id back

Question: i have these 2 queries
select
    count(1),
    female.first_name,
    female.last_name,
    male.first_name,
    male.last_name
from
    new_person as male
        left join
    new_person as female ON male.spouse_id = female.id
where
    male.spouse_id <> '0'
group by female.first_name , female.last_name , male.first_name , male.last_name;

and the second 1 looks like this
    select
    male.first_name as fnf,
    male.last_name as lnf,
    female.first_name as fnm,
    female.last_name as lnm
from
    new_person as p1
        left join
    new_person as male ON p1.father_id = male.id
        left join
    new_person as female ON p1.mother_id = female.id
where
    p1.last_name <> ''
        and p1.last_name <> 'N.N.'
        and ((male.last_name <> ''
        and male.last_name <> 'N.N.')
        or (female.last_name <> ''
        and female.last_name <> 'N.N.'))

now i want to combine these to like
where maleq1.name = maleq2.name and femaleq1.name = femaleq2
then sow me the id from the male and the female in both q1 and q2
with name i mean first_name and last_name
Comment: Im assuming your group by might make a difference. DiD you try to see if using temp table and finally calling the temp table would solve your requirement.
Comment: Your first query is an aggregate of your records.  In theory it could have many id's, right?
Comment: so what you suggest is make a table in with i put in the first and last name and the old id from both queries and then compair them?
Comment: Didn't look into example data but this sounds to me like an PIVOT query..
Answer: Here is my suggestion:  Make a view out of each query.  Then write a 3rd query using your two views.
However, your first query is a aggregation/ rollup/ whatever of multiple records.  Add new fields to the query with the id's
CREATE VIEW q1 AS
select
    count(1),
    female.first_name,
    female.last_name,
    male.first_name,
    male.last_name,
    GROUP_CONCAT(male.id),
    GROUP_CONCAT(female.id)
from
    new_person as male
        left join
    new_person as female ON male.spouse_id = female.id
where
    male.spouse_id <> '0'
group by female.first_name , female.last_name , male.first_name , male.last_name;

Then your 2nd query
CREATE VIEW q2 AS
select
    male.first_name as fnf,
    male.last_name as lnf,
    female.first_name as fnm,
    female.last_name as lnm,
    male.id AS male_id,
   female.id as female_id
from
    new_person as p1
        left join
    new_person as male ON p1.father_id = male.id
        left join
    new_person as female ON p1.mother_id = female.id
where
    p1.last_name <> ''
        and p1.last_name <> 'N.N.'
        and ((male.last_name <> ''
        and male.last_name <> 'N.N.')
        or (female.last_name <> ''
        and female.last_name <> 'N.N.'))

Use these for the third query


Cisco SNMPv3 Authfail - Can it log username?

Question: I'm wondering if it's possible to receive the username that failed a login attempt with snmp logging on a Cisco ML card.  Can SNMPv3 do this, and if so, what would be the command to enable it?
Thanks!
Answer: If you're running version 12.3(4)T or higher you can use the command login on-failure trap
Router(config)#login on-failure trap ?
  every  Periodicity for logs/traps generated
  <cr>

This is what I show on a wireshark capture:
LOGIN_FAILED0....+......).........Login failed [user: test] [Source: 22.214.171.124]
[localport: 23] [Reason: Login Authentication Failed - BadUser]

http://www.cisco.com/en/US/docs/ios/12_3t/secur/command/reference/sec_k1gt.html#wp1180994
Comment: Thanks.  It seems we're on an unsupported version, but now we know.


Multiple Listviews on tab2 control

Question: Here I have a problem with multiple listview controls on a tab2 control.
In my gui, I have a tab2 control where three of the tabs each have 1 listview control.
My problem is that when I use LV_GetText(), I can't find any way of distinguishing which listview to fetch from.
To compound the problem, there is no way for LV_Add() to distinguish between the listviews either.
Normally, you only have to distinguish between gui windows with mygui:default but there doesn't appear to be this option for listview controls.
How can I do this?
Answer: Actually, there is a way to specify which listview.  It actually mentions this in the docs, too.
Basically, what you do is change the default listview.  You can't really direct your functions to a particular listview, but if you change the default listview, you can then operate on it.  Once changed, all subsequent commands operate on the new default.
You change it like this:
Gui, ListView, ListViewName

or like this, if you need to distinguish also between gui windows:
Gui, 3:ListView, ListViewName

Here is a sample.  Paste this into a script file and run it to see that it does work.

Basic Methodology
#SingleInstance,force
gosub, SHOWGUI
return

SHOWGUI:
    gui, mainui:new, hwndmainui, ListViews On Tab2
    gui, add, tab2, vtabs, one|two|three|four
        gui, tab, one
            gui,add, listview, r5 vlistview1 gListView1Events +altsubmit -multi, col1|col2
            LV_Add("", "bob", "harry")
            LV_Add("", "first", "listview")
        gui, tab, two
            gui,add, listview, r5 vlistview2 gListView2Events +altsubmit -multi, col1|col2
            LV_Add("", "george", "harvey")
            LV_Add("", "second", "listview")
        gui, tab, three
            gui,add, listview, r5 vlistview3 gListView3Events +altsubmit -multi, col1|col2
            LV_Add("", "michael", "richard")
            LV_Add("", "third", "listview")
        gui, tab, four
            gui,add, listview, r5 vlistview4 gListView4Events +altsubmit -multi, col1|col2
            LV_Add("", "harold", "marcel")
            LV_Add("", "fourth", "listview")
    gui, show
RETURN

REPORT:
    LV_GetText(firstcol, A_EventInfo, 1)
    LV_GetText(secondcol, A_EventInfo, 2)
    msgbox, %firstcol% : %secondcol%
RETURN

ListView1Events:
    gui, mainui:listview, listview1
    if(A_GuiEvent == "Normal"){
        gosub, REPORT
    }
RETURN

ListView2Events:
    gui, mainui:listview, listview2
    if(A_GuiEvent == "Normal"){
        gosub, REPORT
    }
RETURN

ListView3Events:
    gui, mainui:listview, listview3
    if(A_GuiEvent == "Normal"){
        gosub, REPORT
    }
RETURN

ListView4Events:
    gui, mainui:listview, listview4
    if(A_GuiEvent == "Normal"){
        gosub, REPORT
    }
RETURN

A Better Way
Actually, there is a better, not-so-clumsy way, thanks go garry to handle the multiple listviews.
In this method, the trick is to name the listviews with the same name plus a sequential number: listview1, listview2, listview3...
This way there can be a single gLabel for the event handler: gui, mainui:listview, listview%Tabnumber%
;-------- http://ahkscript.org/boards/viewtopic.php?f=5&t=3656 ---
MODIFIED=20140531
Tabnumber:=1
    gui, mainui:new, hwndmainui, ListViews On Tab2
    gui,add, Tab2, gtabchange vTabnumber AltSubmit, one|two|three|four
        gui,tab, one
            gui,add, listview, r5 vlistview1 gListViewEvents +altsubmit -multi, col1|col2
            LV_Add("", "bob", "harry")
            LV_Add("", "first", "111111111")
            gosub,width1
        gui,tab, two
            gui,add, listview, r5 vlistview2 gListViewEvents +altsubmit -multi, col1|col2
            LV_Add("", "george", "harvey")
            LV_Add("", "second", "222222")
            gosub,width1
        gui, tab, three
            gui,add, listview, r5 vlistview3 gListViewEvents +altsubmit -multi, col1|col2
            LV_Add("", "michael", "richard")
            LV_Add("", "third", "33333333")
            gosub,width1
        gui, tab, four
            gui,add, listview, r5 vlistview4 gListViewEvents +altsubmit -multi, col1|col2
            LV_Add("", "harold", "marcel")
            LV_Add("", "fourth", "44444")
            gosub,width1
    gui, show
gosub,tabchange
RETURN

mainuiGuiclose:
exitapp

width1:
  T1=70
   T2=140
   LV_ModifyCol(1,T1)
   LV_ModifyCol(2,T2)
   LV_ModifyCol(2,"Integer")
return

;-------------------------------------------------------------------------------------
tabchange:
  GuiControlGet, Tabnumber
Return
;-------------------------------------------------------------------------------------

ListViewEvents:
   gui, mainui:listview, listview%Tabnumber%
    if(A_GuiEvent == "Normal"){
    LV_GetText(firstcol, A_EventInfo, 1)
    LV_GetText(secondcol, A_EventInfo, 2)
    msgbox, %firstcol% : %secondcol%
    }
RETURN

Multiple Listviews on tab2 control


Como enviar dados de um formulário com arquivo em anexo para um e-mail com PHP e AJAX?

Question: Estou tentando enviar um arquivo usando a função mail() do php, problema que estou fazendo os testes e o email é enviado mas não vai o arquivo e o email é enviado totalmente desconfigurado, o que pode ser?
Meus códigos estão assim :
Meu formulário:

    <form id="contactform" action="" name="contactform" method="post" enctype="multipart/form-data">

            <input type="text" name="nome" id="nome" class="form-control" placeholder="Nome">
            <input type="text" name="email" id="email" class="form-control" placeholder="Email">
            <input type="text" name="telefone" id="telefone" class="form-control" placeholder="Telefone">
            <input type="text" name="cpf" id="cpf" class="form-control" placeholder="CPF">

            <input type="text" name="cidade" id="cidade" class="form-control" placeholder="Cidade/Estado">

                        Anexar Arquivo…
                        <input type="file" name="arquivo" id="arquivo" class="form-control" style="display: none;" accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

                <input type="text" class="form-control" name="fileArq" readonly>

            <textarea class="form-control" name="msg" id="msg" rows="6" placeholder="Mensagem"></textarea>
            <button type="submit" value="SEND" id="submit" class="btn btn-lg btn-primary pull-right" onclick="return contato('email2');">ENVIAR</button>

    </form>

Minha função AJAX:
function contato(response) {

    //(function($) {
    // You pass-in jQuery and then alias it with the $-sign
    // So your internal code doesn't change

    var server = 'https://' + window.location.hostname;
    var loader = $('section.loader');
    loader.fadeIn(400);
    $.ajax({
            url: server + "/contato/ajaxResponse.php?acao=" + response,
            data: $("form").serialize(),
            cache: false,
            type: "POST",
            dataType: 'JSON'
        })
        .done(function(ret) {

            if (ret.focus_error) {
                //retorno = true;
                focus_class(ret);

            }

            if (ret.status == 1) {
                alert("seus dados foram enviados com sucesso");
                clear_forms();
                window.location.reload();
            } else {
                console.log(ret);
            }
        })
        .fail(function() {
            alert("Um erro aconteceu, tente novamente");
        });

    loader.fadeOut(400);
    return false;

    // })(jQuery);
}

Meu php pra enviar o email:
extract($_POST);
switch ($_GET['acao']) {

       case 'email2':

try {
        // pontos que vai verificar
    verfy_post(array(
        "nome",
        "email",
        "telefone",
        "cpf",
        "cidade",
            //"msg"
    ));

    $path = $_FILES["arquivo"]["tmp_name"];
    $fileType = $_FILES["arquivo"]["type"];
    $fileName = $_FILES["arquivo"]["name"];
    //var_dump($path);
    //die();
    $fp = fopen($path, "rb");
    $anexo = fread($fp, filesize($path));
    $anexo = base64_encode($anexo);
    fclose($fp);
    //$anexo = "jddd";
    $boundary = "XYZ-".date("dmYis")."-ZYX";
        // corpo da msg
    $mensagem  = "--$boundary" . PHP_EOL;
    $mensagem .= "Content-Type: text/html; charset='utf-8'" . PHP_EOL;
    $mensagem .= "Nome: $nome
";
    $mensagem .= "Email: $email
";
    $mensagem .= "Telefone: $telefone
";
    $mensagem .= "CPF: $cpf
";
    $mensagem .= "Cidade: $cidade
";
    //$mensagem .= "Anexo: $anexo
";
    $mensagem .= "
";
    $mensagem .= "Mensagem:
";
    $mensagem .= nl2br($msg);
    $mensagem .= "--$boundary" . PHP_EOL;

    //anexando o arquivo
    $mensagem .= "Content-Type: ". $fileType ."; name=\"". $fileName . "\"" . PHP_EOL;
    $mensagem .= "Content-Transfer-Encoding: base64" . PHP_EOL;
    $mensagem .= "Content-Disposition: attachment; filename=\"". $fileName . "\"" . PHP_EOL;
    $mensagem .= "$anexo" . PHP_EOL;
    $mensagem .= "--$boundary" . PHP_EOL;
    //console_log($mensagem);

    // envia a msg (nao mexer)

    //$nome = $email;

    enviaEmailComAnexo(array(
        'nome'=> $nome,
        'de'=> $email,
        'para'=> EMAIL_PARA,
        'assunto'=> EMAIL_ASSUNTO. " | Trabalhe Conosco",
        'msg'=>$mensagem
    ), $boundary);

    send(array('status' => '1'));
}

function enviaEmailComAnexo($arr, $boundary){
     extract($arr);
    //$boundary = "XYZ-".date("dmYis")."-ZYX";
    $headers  = 'MIME-Version: 1.0' . PHP_EOL;
    $headers .= "Content-Type: multipart/mixed; ";
    $headers .= "boundary=" . $boundary . PHP_EOL;
    $headers .= "$boundary" . PHP_EOL;
    $headers .= "From: ".$nome." <".$de.">\n";
    // Função que envia o e-mail
    mail($para, $assunto, $msg, $headers);
}

Comment: A função serialize não funciona pra enviar um formulario com arquivos pelo ajax. Você tem que usar a classe FormData do javascript.
Comment: @lvr7como faria isso, pois efetuei a troca aqui acrescentando `data: new FormData(this),` no lugar de `data: $("form").serialize(),` e não foi, fica carregando e não da retorno
Comment: Qual biblioteca está utilizando para envio de emails?
Comment: mail() do PHP mesmo @Oliveira
Answer: Altere o trecho $("form").serialize() e use o FormData para enviar dados do arquivo.  var data = new FormData($("form[name='contactform']")[0]);, coloque também as prorpiedades processData: false e contentType: false e remova o trecho dataType: 'JSON'
function contato(response) {
    var server = 'http://' + window.location.hostname + "/contato/ajaxResponse.php?acao=" + response;
    var loader = $('section.loader');
    loader.fadeIn(400);

    var data = new FormData($("form[name='contactform']")[0]);
    $.ajax({
        url: server,
        data: data,
        cache: false,
        type: "POST",
        processData: false,
        contentType: false
    }).done(function(ret) {
        if (ret.focus_error) {
            //retorno = true;
            focus_class(ret);
        }

        if (ret.status == 1) {
            alert("seus dados foram enviados com sucesso");
            clear_forms();
            window.location.reload();
        } else {
            console.log(ret);
        }
    }).fail(function() {
        alert("Um erro aconteceu, tente novamente");
    });
    //loader.fadeOut(400);
    return false;
}

Comment: Até que deu certo, porém o e-mail não esta sendo enviado tudo configurado, envia somente o anexo sem o corpo do email e dados do remetente


When using the webform module, is it possible to get information on the submitter's device (Mac/Win/Android), browser version, etc.?

Question: I'm using Webform 3 on Drupal 7.  I have a form on my site for people to report problems with the website itself.  Many of these reports ultimately turn out to be browser- or OS-specific, but often users do not add such information in their initial report.
Is there any way to automatically capture the browser and OS information, etc. in Webform upon submission?
Answer: It appears webform allows a default value using %server variables, but only for authenticated users.

In addition to %get and %post, the following super tokens may be used,
  though only with logged-in users: %server, %cookie, and %request. For
  example %server[HTTP_USER_AGENT] or %session[id].

For authenticated users, try adding a User Agent field with a default value of %server[HTTP_USER_AGENT]
If your form submissions come from anonymous users, you may need an alternative way to add the %server tokens.
Other $_SERVER variables documented here: http://php.net/manual/en/reserved.variables.server.php


Significance of (GAM) regression coefficients when model likelihood is not significantly higher than null

Question: I am running a GAM-based regression using the R package gamlss and assuming a zero-inflated beta distribution of the data. I have only a single explanatory variable in my model, so it's basically: mymodel = gamlss(response ~ input, family=BEZI).
The algorithm gives me the coefficient $k$ for the impact of the explanatory variable into the mean ($\mu$) and the associated p-value for $k(\text{input})=0$, something like:
Mu link function:  logit
Mu Coefficients:
              Estimate  Std. Error  t value   Pr(>|t|)
(Intercept)  -2.58051     0.03766  -68.521  0.000e+00
input        -0.09134     0.01683   -5.428  6.118e-08

As you can see in the above example, the hypothesis of $k(\text{input})=0$ is rejected with high confidence.
I then run the null model: null = gamlss(response ~ 1, family=BEZI) and compare the likelihoods using a likelihood-ratio test:
p=1-pchisq(-2*(logLik(null)[1]-logLik(mymodel)[1]), df(mymodel)-df(null)).

In a number of cases, I get $p>0.05$ even when the coefficients at input are reported to be highly significant (as above). I find this quite unusual -- at least it never happened in my experience with linear or logistic regression (in fact, this also never happened when I was using zero-adjusted gamma with gamlss).
My question is: can I still trust the dependence between response and input when this is the case?
Answer: I see no immediate reason why this should be related to GAM. The fact is that you are using two tests for the same thing. Since there is no absolute certainty in statistics, it is very well possible to have one give a significant result and the other not.
Perhaps one of the two tests is simply more powerful (but then maybe relies on some more assumptions), or maybe the single significant one is your one-in-twenty type I error.
A good example is tests for whether samples come from the same distribution: you have very parametric tests for that (the T-test is one that can be used for this: if the means are different, so should the distributions), and also nonparametric ones: it could happen that the parametric one gives a significant result and the nonparametric one doesn't. This could be because the assumptions of the parametric test are false, because the data is simply extraordinary (type I), or because the sample size is not sufficient for the nonparametric test to pick up the difference, or, finally, because the aspect of what you really want to test (different distributions) that is checked by the different tests is just different (different means <-> chance of being "higher than").
If one test result shows significant results, and the other is only slightly non-significant, I wouldn't worry too much.


Update table with another table based on cell value

Question: After searching, I understand I can copy data into a table one at a time using VLOOKUP. However, is it possible to replace an entire table with another if a cell contains a certain value?
For example,
I have a table1. I want to replace table1 with table2 if cell a1="table2"
The reason is I will have many tables and depending on what I put in a cell, A1, I want table 1 to be what ever table I choose. I also want it to be easily updated when I add even more tables.
Edit for more information:
I have one table lets call it table1. Another table, Table2, with columns Name and Values. Also I plan on having more tables, so Table3 with columns Name and Values. I have a cell somewhere on the page, or another page. If I write Table2 in this cell. I would like the entire Table1 to be replaced by table2. Ultimately copying the data in.
I have tried structured tables, but it only copies from the same row. If I put it in another row, i get null basically. Vlookup, I think requires me to have a formula for each row of the table. I might be using this formula wrong.
Comment: What have you already tried?
Comment: And to add to @TMH8885's comment, can you provide more information on how your data are structured?
Comment: I updated the post with more information. Please let me know if i am being too vague.
Answer: Without knowing more, one solution is INDIRECT().
Example workbook sheets:

Table1
Table2
Table3

Assume all Table# tabs have the same cell range.

Make a new tab Input:
     [A]             [B]
[1]  User Input
[2]  Table #         1
[3]
[4]  Reference       ="'Table"&B2&"'!"

The formula in B4 evaluates to 'Table1'!.  Note that the sheet reference includes the apostophes in case the sheet name has spaces.
Make a new tab Summary Table:
     [A]
[1]  =INDIRECT(Inputs!$B$4&ADDRESS(ROW(),COLUMN()))

This formula displays the value in the specified sheet name (from Inputs!B4) and the current row and column (so when this formula is entered in A1, it will display the value of Table1!A1). Then fill this formula across the rows and columns necessary to display the table specified in the Input tab.
Note of course that you could combine the Input and Summary Table tabs, but you would need to adjust the ROW() and/or COLUMN() formulas. This is also the case if your source tables do not begin in cell A1.
Comment: Thanks! Everything works perfectly now. It ended up being ADDRESS(ROW()-2, COLUMN()-4). And I fully understand the concept now, thank you for your help!
Comment: Thank you for your answer, is there a way to combine all 3 sheets into one? I have the inputs, and summary in one page, and the tables at the bottom of this same page, named with headers.
Comment: Combining a single input cell (as in the answer) with the results table should be easy enough by just adding/subtracting to the `ROW()` and `COLUMN()` formulas as necessary. It strikes me as bad practice to include the raw data on the same worksheet, however.
Comment: The only issue is i will have so many tables, and i do not want a bunch of sheets at the bottom of the page. If you are telling me the best way is to keep them seperate, i might do just that.
Comment: Without being in your position, I can't say what is best for your specific task, but in general, I find that having multiple separate data tables on a single Excel worksheet (tab) is usually more complicated and less friendly for analytical purposes than having a single table per worksheet.
Comment: I decided to go with your method, instead i will be Hiding the tables so I won't see them once i create them. The problem now is I cannot get input and summary tables to be in one page. my summary starts at F4 and my reference is at B7. My table on another sheet starts at A1 and the data i want from it is on B2. I have

=INDIRECT($B$7&ADDRESS(ROW(),COLUMN())).

I am not entirely sure how to adjust the formula. I apologize for making you spoon feed me...
Comment: If you put `=ADDRESS(ROW(),COLUMN())` in cell `A1`, `ROW()` = `1`, `COLUMN()` = `1`, and `ADDRESS(1,1)` = `$A$1`. Combining this with the sheet name reference in `B7` makes it return the value in `A1` on the specified sheet. If you want to display the value in `B2` from the specified sheet in cell `A1`, put `ADDRESS(ROW()+1, COLUMN()+1)` into the formula instead. Hopefully this gets you the concept you need to get it working.


FreeBSD 4.7 missing IPFW - How do I install it?

Question: I have two FreeBSD servers that are on 4.7. These are two older servers that were already configure and setup when I got here. Now that the original admins are gone, I've started looking a bit more at these servers and I've come to find there's no firewall installed! The services they run (like ssh and sendmail) are configured well enough within their own respective configurations to filter traffic how we want it. But the fact that I can do a port scan and a list of 20 open ports pops up is concerning.
So I prepped some firewall rules for ipfw and went to install them on the servers only to find that the servers know nothing of IPFW (the binary at /sbin/ipfw doesn't exist). Further, the command I'm used to using to load the kernel modules (kldload) doesn't exist either. I've looked through the ports and there is no port to install it. In the FreeBSD admin guide it said the IPFW was added in the 4.x releases.
Anyone know why I don't have it or how I can get it? Was PF the firewall program that existed before ipfw?
Comment: it's curious that you don't have kldload. may I ask you if you have modload? :) it's a 4.7 alright but maybe it's an openbsd :P
Comment: Nope, no modload command either. Uname tells me it's FreeBSD 4.7-Release-p28
Comment: worth asking. good luck! :)
Answer: In order of preference:
My first suggestion would be to upgrade these machines to a supported version of FreeBSD.
4.x is pretty well ancient at this point, well beyond the end of support life, and you would do better replacing it than trying to keep it alive.  You can also secure the new machines according to current best practices.
Note that there is no supported upgrade path from 4.x to anything recent that doesn't require a reinstall, so we're talking effectively a wholesale replacement of the machines/software.
My second suggestion if you absolutely can't upgrade these machines would be to disable the services you don't need and if you still feel the need to firewall them off to use a dedicated box sitting in front of them as the firewall.
This has the net effect of reducing the open ports, and freeing up RAM, all without having to rebuild your kernel/OS.  Using a dedicated firewall box allows you to set up whatever firewall rules you want without the risk of meddling with the systems themselves (which I assume are stable & working).
My third suggestion, if you still have your heart set on messing with these machines directly, would be to get a copy of the 4.7 source tree (via cvsup), and rebuild world & kernel (configuring the latter with ipfw) -- this will get you patched up to the latest and greatest 4.7 available, and give you the ipfw binary and kernel components you need to set up a firewall.
This is a HUGE risk - in the process of touching these machines you may well cause a domino cascade of things breaking that you will then need to fix.
Comment: Thanks for the great response. These servers are running services that are sun setting (hopefully sooner than later). So at this point reinstalling the entire OS would be a nightmare of a project. I think disabling unneeded services and relying on program specific measures of filtering access is the best option, then pray for a speedy decommission! Thanks for your suggestions.
Comment: @Ryan definitely, especially if the servers are going away.  When dealing with something this old "Replace and Document" (or Retire) is almost always preferable to trying to make changes to a working, if ancient, system :)
Answer: If ipfw was compiled as a module, you should see it in /modules/ipfw.ko
if present, load it into the kernel as root with this :
"kldload ipfw && ipfw add 32000 allow ip from any to any"
extracted from "man ipfw".


Relation between Frobenius norm and trace

Question: Is the following inequality true?
$$\mbox{Tr} \left( \mathrm P \, \mathrm M^T \mathrm M \right) \leq \lambda_{\max}(\mathrm P) \, \|\mathrm M\|_F^2$$
where $\mathrm P$ is a positive definite matrix with appropriate dimension. How about the following?
$$\mbox{Tr}(\mathrm A \mathrm B)\leq \|\mathrm A\|_F \|\mathrm B\|_F$$
Answer: $$\mbox{tr}(\mathrm A \mathrm B) = \left\langle \mathrm A^\top, \mathrm B \right\rangle = \langle \mbox{vec} (\mathrm A^\top), \mbox{vec} (\mathrm B) \rangle \leq \|\mbox{vec} (\mathrm A^\top)\|_2 \|\mbox{vec} (\mathrm B)\|_2 = \|\mathrm A\|_F \|\mathrm B\|_F$$
Answer: The heart of the matter is the following key fact:

The assignment $(A,B) \mapsto \langle A,B \rangle := \operatorname{Tr}(A^T B)$ defines a Euclidean inner product on the real vector space $\mathbb{R}^{m \times n}$ of all $m \times n$ real matrices that induces the Frobenius norm $\|\cdot\|_F$ on $\mathbb{R}^{m\times n}$, in the sense that $$\forall C \in \mathbb{R}^{m \times n}, \quad \|C\|_F = \sqrt{\langle C,C\rangle} = \sqrt{\operatorname{Tr}(C^T C)}.$$

For this, of course, you need the un-normalised trace $\operatorname{Tr}(C) = \sum_{k=1}^n C_{kk}$ on $\mathbb{R}^{n \times n}$.
Once you know this and observe (by whichever definition of the Frobenius norm you prefer) that $\|C^T\|_F = \|C\|_F$ for all $C \in \mathbb{R}^{m \times n}$, the Cauchy–Schwarz inequality for the inner product $\langle \cdot,\cdot \rangle$ immediately yields your second inequality.
The first inequality is a little bit more subtle, but isn't too bad once you recall the following basic fact about traces:

For any orthonormal basis $\{v_1,\dotsc,v_n\}$ of $\mathbb{R}^n$, we have $$\forall C \in \mathbb{R}^{n\times n}, \quad \operatorname{Tr}(C) = \sum_{k=1}^n \langle v_k,Cv_k \rangle.$$

Now, since $P$ is positive definite, let $\{v_1,\dotsc,v_n\}$ be an orthonormal basis for $\mathbb{R}^n$ consisting of eigenvectors of $P$, with $Pv_k = \lambda_k(P)v_k$ for $0 < \lambda_1(P) \leq \cdots \leq \lambda_n(P) = \lambda_{\text{max}}(P)$. If you now write
$$
 \operatorname{Tr}(PM^T M) = \sum_{k=1}^n \langle v_k,P M^T M v_k \rangle = \langle P v_k,M^T M v_k\rangle = \sum_{k=1}^n \lambda_k(P)\langle v_k, M^T M v_k \rangle
$$
in terms of this special orthonormal basis and bound each eigenvalue of $P$ from above by $\lambda_{\text{max}}(P)$, it's now easy to get the first inequality.
Comment: Is the second inequality still valid for $A$ and $B$ members of $R^{n\times m}$ and $R^{m\times q}$? inner product is defined for same matrices.
Comment: The trace is only defined for square matrices, so you'd need $A$ to be $n \times m$ and $B$ to be $m \times n$ for the left-hand side of your second inequality to even make sense, in which case, the key observation is that $\operatorname{Tr}(AB) = \langle A^T, B \rangle$ in terms of that inner product on $\mathbb{R}^{m \times n}$ whose associated norm is the Frobenius norm.
Comment: This proof relies on the fact that $P$ is positive definite. Can we drop this assumption if we replace "largest eigenvalue" with the spectral radius?
Comment: (For motivation, we can drop this assumption if we replace $\lambda_{max}(P)$ with $\|P\|_F$; the bound then follows from Cauchy-Schwarz and the fact that the Frobenius norm is submultiplicative. But the Frobenius norm bounds the spectral radius from above, so this bound is weaker than the desired one.)
Answer: Since $\mathrm P$ is positive definite, $\mathrm P^{\frac 12}$ exists and is symmetric. Hence,
$$\mbox{tr} (\mathrm P \mathrm M^T \mathrm M) = \mbox{tr} (\mathrm P^{\frac 12} \mathrm P^{\frac 12} \mathrm M^T \mathrm M) = \mbox{tr} (\mathrm M \mathrm P^{\frac 12} \mathrm P^{\frac 12} \mathrm M^T) = \mbox{tr} ((\mathrm P^{\frac 12} \mathrm M^T)^T (\mathrm P^{\frac 12} \mathrm M^T)) = \|\mathrm P^{\frac 12} \mathrm M^T\|_F^2$$
We have $\|\mathrm A \mathrm B\|_F \leq \|\mathrm A\|_2 \|\mathrm B\|_F$. Thus,
$$\mbox{tr} (\mathrm P \mathrm M^T \mathrm M) = \|\mathrm P^{\frac 12} \mathrm M^T\|_F^2 \leq \|\mathrm P^{\frac 12}\|_2^2 \|\mathrm M^T\|_F^2 = \lambda_{\max} (\mathrm P) \|\mathrm M\|_F^2$$


CSS attribute selector not working when the attribute is applied using javascript?

Question: .variations_button[style*="display: none;"] + div

This is my CSS selector which works fine if the style attribute is already in the DOM on page load:
http://jsfiddle.net/xn3y3hu0/
However, if i hide the .variations_button div using javascript, the selector is not working anymore:
$(document).click(function(){
    $('.variations_button').hide();
});

http://jsfiddle.net/55seee1r/
Any idea whats wrong? Looks like the CSS is not refreshing, because if i edit another property using the inspector, the color changes red instantly.
Comment: Is the space-character present when JavaScript adds the style?
Comment: if it were my code I'd show/hide the element with a class, and use the class in the selector.
Comment: Of course i tried with the space character. And yes, a class hide/show would be easier, but this is for a WordPress plugin and i don't want to overwrite the core code.
Comment: Make sure to check the second jsfiddle link, just edited the question, because i pasted the wrong link there.
Comment: Might be obvious to some, but CSS atrribute selectors ONLY work on inline CSS (i e. this is what the style property returns, CSS atrribute selectors don't work with CSS set by other stylesheets (that is computed CSS)
Answer: Because the selector you use, [style*="display: none;"], is looking for the presence of the exact string of "display: none;" in the style attribute, it requires the browser's JavaScript engine inserts that precise string, including the white-space character (incidentally in Chrome 39/Windows 8.1 it does). For your particular browser you may need to remove the space, and to target most1 browsers, use both versions of the attribute-value string, giving:
.variations_button[style*="display: none;"] + div,
.variations_button[style*="display:none;"] + div

.variations_button[style*="display: none;"]+div,
.variations_button[style*="display:none;"]+div {
  color: red;
}

asd

test

Of course, it remains much simpler to use classes to hide an element, toggling that class with JavaScript, and using the class as part of the CSS selector, for example:

$('.variations_button + div').on('click', function() {
  $('.variations_button').toggleClass('hidden');
});
.hidden {
  display: none;
}
.hidden + div {
  color: red;
}
.variations_button + div {
  cursor: pointer;
}

asd

test

As I understand it, the problem of the above not working once jQuery is involved, is because jQuery's hide(),show() and toggle() methods seem to update the display property of the element's style property, rather than setting the attribute directly. The updated attribute-value (as represented in the style attribute) seems to be a representation of the style property (derived, presumably, from its cssText). Because the attribute is unchanged, and merely serves as a representation of a property, the CSS attribute-selectors don't, or perhaps can't, match.
That said, a somewhat clunky workaround is to directly set the attribute; in the following demo this uses jQuery's attr() method (though the native DOM node.setAttribute() would work equally well):
  $(document).click(function() {
    // setting the style attribute of the selected element(s),
    // using the attr() method, and the available anonymous function:
    $('.variations_button').attr('style', function(i, style) {
      // i: the index of the current element from the collection,
      // style: the current value (before manipulation) of the attribute.

      // caching the cssText of the node's style object:
      var css = this.style.cssText;

      // if the string 'display' is not found in the cssText:
      if (css.indexOf('display') === -1) {
        // we return the current text plus the appended 'display: none;' string:
        return css + 'display: none;';
      // otherwise:
      } else {
        // we replace the string starting with 'display:', followed by an
        // optional white-space ('\s?'), followed by a matching string of
        // one or more alphabetic characters (grouping that last string,
        // parentheses):
        return css.replace(/display:\s?([a-z]+)/i, function(a, b) {
          // using the anonymous function available to 'replace()',
          // a: the complete match, b: the grouped match (a-z),
          // if b is equal to none we return 'display: block', otherwise
          // we return 'display: none':
          return 'display: ' + (b === 'none' ? 'block' : 'none');
        });
      }
    });
  });

jQuery(document).ready(function($) {

  $(document).click(function() {
    $('.variations_button').attr('style', function(i, style) {
      var css = this.style.cssText;
      if (css.indexOf('display') === -1) {
        return css + 'display: none;';
      } else {
        return css.replace(/display:\s?([a-z]+)/i, function(a, b) {
          return 'display: ' + (b === 'none' ? 'block' : 'none');
        });
      }
    });
  });

});
.variations_button[style*="display: none;"]+div {
  color: red;
}

asd

test

References:

CSS:

Substring Matching Attribute-selectors.

JavaScript:

HTMLElement.style.
JavaScript Regular Expressions.
String.prototype.indexOf().
String.prototype.replace().

jQuery:

attr().
hide().
show().
toggle().
Comment: Sure, i tested with space and without space. As i mentioned in my question, it works without the javascript part. But once the style attribute is added using javascript, it fails to run. Even your example. And sure, toggleClass would be easier, but this is for a WordPress plugin and i don't want to overwrite the core code.
Comment: Can you reproduce this behaviour with a demo? Because it seems that something (but I don't know, and can't see, what) is being left not.
Comment: Jeez, sorry, i inserted the wrong link in my question. Check out the second jsfiddle:)


Bitwise NOT operator returning unexpected and negative value?

Question: I'm trying to get the value of an integer using Bitwise NOT, but i'm not getting  what i expected.
#include <stdio.h>

int main(){
    int i = 16;
    int j = ~i;
    printf("%d", j);
    return 0;
}

Isn't 16 supposed to be:
00000000000000000000000000010000

So ~16 is supposed to be:
11111111111111111111111111101111

Why i'm not getting what i expected and why the result is negative?
This is what i'm trying to do:
I have a number for exemple 27 which is:
00000000000000000000000000011011

And want to check every bit if it's 1 or 0.
So i need to get for exemple this value
11111111111111111111111111110111

The use second one to check if the 3rd bit of the first is set to 1.
Comment: What *are* you getting?
Comment: @rullof, That's correct for most signed integer implementations (and by most, I mean like nearly all of them).
Comment: What result are you getting and do you expect to get?
Comment: See [two's complement](http://en.wikipedia.org/wiki/Two%27s_complement). Try again with unsigned integers.
Comment: in order to get what you are expecting to get you should use unsigned int.
Comment: @chris i'm getting -17
Comment: C/c++ doesn't have any support for binary numbers like that - your extra examples don't help.
Answer: Although there are pedantic points which can be made about compiler behaviour, the simple answer is that a signed int with the top bit set is a negative number.
So if you do something which sets the top bit of an int (a signed int, not an unsigned one), then ask the tools/library to show you the value of that int, you'll see a negative number.
This is not a universal truth, but it's a good approximation to it for most modern systems.
Note that it's printf which is making the representation here - because %d formats numbers as signed. %u may give the result you're expecting.  Just changing the types of the variables won't be enough, because printf doesn't know anything about the types of its arguments.
I would say that as a general rule of thumb, if you're doing bit-twiddling, then use unsigned ints and display them in hexadecimal. Life will be simpler that way, and it most generally fits with the intent. (Fancy accelerated maths tricks are an obvious exception)
Comment: Your edit makes no sense, as the compiler will see those numbers as huge decimal numbers, not binary.
Comment: Not it has a sense (check it)
Answer:
And want to check every bit if it's 1 or 0.

To check an individual bit, you don't NOT the number, you AND it with an appropriate bit mask:
if ((x & 1) != 0) ... // bit 0 is 1
if ((x & 2) != 0) ... // bit 1 is 1
if ((x & 4) != 0) ... // bit 2 is 1
if ((x & 8) != 0) ... // bit 3 is 1
...
if ((x & (1 << n)) != 0) ... // bit n is 1
...
if ((x & 0x80000000) != 0) ... // bit 31 is 1

Answer: In two-complement arithmetic to get a reverse number (for example for value 16 to get value -16) you need reverse each bit and add 1.
In your example, to get -16 from 16 that is represented as
00000000000000000000000000010000

you need reverse each bit. You will get
11111111111111111111111111101111

Now you must add 1 and you will get
11111111111111111111111111110000

As you can see if you add these two values, you will get 0. It proves that you did all correctly.
Answer: If you want to get ones' complement of a number, you need to put that number into an unsigned variable and show it as so.
In C it would be:
unsigned int x = ~16;
printf("%u\n", x);

and you will get 4294967279.
But if you are just trying to get the negative number of a certain one, put the - operator before it.
EDIT: To check whether a bit is 0 or 1, you have to use the bitwise AND.


Triangle inequlity improvment with the angle conditions

Question:
I was working on how to proof $a+b \leq x+y+z$?
Apply triangle inequity to the triangle ADC,
$x+z \geq a$
Apply triangle inequity to the triangle DCB,
$y+b \geq z$
Adding above inequities,
$x+y+z+b \geq a+z$
I am getting
$x+y \geq a-b$ , But  how do I proof
$a+b \leq x+y+z$?
Note that the angles with the horizontal line $AC < 10^\circ$ , $CB < 10^\circ$  $AB < 10^\circ$ and $DB < 10^\circ$
Answer: The claim is simply not true in general. You see that $x+z\approx a$ and also $y+b\approx z$ if the angles are all so small. But then $a+b\approx x+2z-y$ and that is definitely greater than $x+y+z$ as in your sketch $z>2y$.
Answer: Fix $A, B, C$, let $D$ move along $AC$ from $C$ to $A$. By your assumption $BD$ is becoming shorter, so $\min z= b$. It remains to show $AC\ge AB$, this is WRONG! So your inequality is not correct in genaral.


Janus GridEx: Add custom row and select a specific row

Question: I have GridEx object on my form and...

I want to add some items in it with a for...next loop. Actually I couldn't find any method for adding a new row with a custom data.
I want to select a specific row in that GridEx object. For example: I want to select the 6th row, is there anything like mygrid.rows(6).value or something like that?!

Thanks in Advance...
Answer: Assuming you have a GridEX control called grid...
To add new data:
GridEXRow row = grid.AddItem();
row.BeginEdit();
row.Cells[0].Value = "Whatever"; // refer to columns by index or name
...
row.EndEdit();

To retrieve a specific row:
GridEXRow row = grid.GetRow(5); // returns the 6th row

To select a specific row:
grid.MoveTo(5); // moves the selection to the 6th row

Answer: To add new row to gridex called MyGridEX:
object[] data = { "value0", "value1", "value2", ... };
this.MyGridEX.AddItem(data);

To select a specific row:
this.MyGridEX.GetRow(1); // select the second row


making a host port accessible from within a container in Kubernetes

Question: We have set up a Kubernetes cluster on a set of (virtual) Linux hosts. Each host runs an internal HTTP proxy on host's 127.0.0.1:3128. To access external HTTP/HTTPS resources from this network, the proxy must be used.
We would like to make an external network accessible from within containers in the cluster. Containers running on a given host should use an HTTP(s) proxy instance from that host.
How can we make these proxy services available from within containers?
Answer: The Node's IP is always available to the containers via fieldRef:, and one may refer to other env: members using $() syntax (notice it's not shell syntax, it's the kubernetes interpolation syntax)
spec:
  containers:
  - name: use-proxy
    env:
    - name: NODE_IP
      valueFrom:
        fieldRef:
          fieldPath: status.hostIP
    - name: HTTP_PROXY
      value: $(NODE_IP):3128
    - name: HTTPS_PROXY
      value: $(NODE_IP):3128

and don't forget you'll likely need to inject the CA for the HTTPS proxy if it does MITM behavior
Also be aware that if it is literally bound to 127.0.0.1 on the Node, you will not be able to access it from inside the kubernetes cluster since those interfaces are not considered "localhost". You will need to make the proxy available to the CNI interface
Comment: Thank you a lot for the clarification!


Distribution of a pdf-related random variable $Y=f(X)$

Question: Let $X$ be a continuous random variable having cdf $F_{X}$ and pdf $f(x)$ expressed as in the following:
$$
f(x)=
\begin{cases}
x, & x \in [0, 1] \\
\frac{1}{x}, & x \in [1, e^{1/2}]
\end{cases}
$$
I have to study the distribution of the variable $Y=f(X)$:
$$
Y=
\begin{cases}
X, & X\in[0,1]\\
\frac{1}{X}, & X\in [1, e^{1/2}]
\end{cases}
$$
My idea to find the cdf $F_{Y}$ is the following:

if $X$ is in $[0, 1]$, then $Y$ has its values $y$ in the interval $[0,1]$, so:
$$
F_{Y}(y)=\mathbb{P}(Y\leq y)=\mathbb{P}(X\leq y)=\int_{0}^{y}x\, dx=\frac{y^2}{2};
$$

if $X$ is in $[1, e^{1/2}]$, then $Y$ has its values $y$ in the interval $[e^{-1/2}, 1]$, so:
\begin{align}
F_{Y}(y)&=\mathbb{P}(Y\leq y)=\mathbb{P}(Y\leq y)|_{y \in[0,1]}+\mathbb{P}(Y\leq y)|_{y \in[1, e^{1/2}]} \\
&=\mathbb{P}(X\leq y)|_{y \in[0,1]}+\mathbb{P}(\frac{1}{X}\leq y)|_{y \in[1, e^{1/2}]}=\mathbb{P}(X\leq y)+\mathbb{P}\Bigl(X\geq \frac{1}{y}\Bigr)=\int_{0}^{y}x\,dx+1-\int_{e^{1/2}}^{1/y}\frac{1}{x}\,dx \\
&=\frac{1}{2}+\frac{y^2}{2}+log{y}
\end{align}

So the pdf $f_{Y}$ of the random variable $Y$ is:
$$
f_{Y}(y)=\frac{dF_{Y}}{dy}(y)=
\begin{cases}
y, & y \in [0, e^{-1/2}] \\
y+\frac{1}{y}, & y \in [e^{-1/2}, 1]\\
0, & otherwise
\end{cases}
$$
Is this right?
Comment: The result looks reasonable to me, though the justification for the particular split might be clearer
Comment: @Henry How could I justificate the split in a clearer way? Any suggestions?
Answer: No, the way you write the answer is not correct. You cannot split the computation into the two cases because $X$ is a r.v., not a constant.
$$P(Y \leq y)=P(X \in [0,1], X \leq y)+P(X\in (1,e^{1/2}], \frac  1 X \leq y)$$ $$=P(X \in [0,1], X \leq y)+P(X\in (1,e^{1/2}], X \geq \frac 1 y).$$ I will let you do the computations now.
Comment: @met.91 Now it is right. I was only commenting on the way you wrote the answer, not the final result.
Comment: The computations look correct to me
Comment: @Henry You cannot write $F_Y(y)=\frac {y^{2}} 2$ if $X \in [0,1]$. That is non-sense.
Comment: Indeed, though I would not call that a computation. What is correct is that $F_Y(y)=\frac {y^{2}} 2$  and $f_Y(y)=y$ if $y \in \left( 0, e^{-1/2}\right)$, while  $F_Y(y)=\frac12+ \frac {y^{2}} 2+ \log y$  and $f_Y(y)=y+\frac1y$ if $y \in \left(e^{-1/2},1\right)$
Comment: @KaviRamaMurthy I'll not write that $F_{Y}(y)=\frac{y^2}{2}$ if $X \in [0, 1]$, but what I'll say is the following:

(1) if $X \in [0, 1]$, then it's true that $Y=X$, so $y \in [0,1]$;
(2) $X \in (1, e^{1/2}]$, then it's true that $Y=\frac{1}{X}$, so $y \in (e^{-1/2}, 1]$.

So my conclusion is the one written in the last comment by Henry.

Do you say that this is not correct and that the cdf $F_{Y}$ can't be split in two parts?


strace shows long time reading from mysql socket - mysql takes long time to execute query?

Question: My Apache server takes long time to process request. I attached strace to it and can see the two following delays:
1) Very critical (143 seconds to process)
1335       0.000037 write(16, "\235\0\0\0\3INSERT INTO `br_anonymous_user_tokens` (`dtExpires`, `nmToken`, `dtCreated`) VALUES ('2014-08-25', '46e35dc39a41e836b806f48d21621b066ea182a9', '2014-06-25')", 161) = 161
1335       0.000111 read(16, "\t\0\0\1\0\1\374\262\n\2\0\0\0", 16384) = 13
1335     143.588134 gettimeofday({1403675497, 653337}, NULL) = 0

File descriptor #16 seems to be mysql socket:
line from strace
1335       0.000328 socket(PF_LOCAL, SOCK_STREAM, 0) = 16

And here
pidof mysqld
15393
lsof -p 15393
mysqld  15393 mysql   12u  IPv4  26913133       0t0      TCP *:mysql (LISTEN)

So it seems that Apache is waiting for mysql to execute the query which was written to the socket on the previous line. Am I right? Does it mean that I then need to understand why it takes so long for MySQL to execute simple query?
2) Very long
1335       0.000040 poll([{fd=14, events=POLLIN}], 1, 5000) = 0 (Timeout)
1335       5.005295 gettimeofday({1403675502, 686212}, NULL) = 0

Here I tried to locate file descriptor #14 to find out where the timeout comes from. I used techniques described here, but none of them showed the descriptor in question. How can I find out where the timeout comes from?
Comment: Yes, you need to look through MySQL statistics to see why it takes so long to perform that query.
Answer: The issue is resolved. I looked through the PROCESSLIST table in information_schema MySQL database and found that some tables are locked with the state Waiting for table level lock. So then I searched and found that one reason for the lock can be mysqldump backups - and this is exactly what I had configured recently. But because the job was misconfigured, it ran every minute constantly locking MySQL. Now that backups are configured correctly, the server works fine.
Yet the second question with poll remains unresolved.
Comment: Using `--single-transaction` with mysqldump will prevent table locks during the backup, if you are using InnoDB.
Comment: Great advice, thanks! What are the implications of using `--single-transaction`? And how should I use it if I make backups like this: `mysqldump -h example.com -u username -ppassword dbname | gzip > db.zip` ?


How to prevent the logging of a failed request to favorite.ico with ServiceStack

Question: This will be the 5th such question that centers around the favorite.ico and ServiceStack webservice framework. I understand the rationale behind logging resource not found, and most of the workarounds use the built-in not found handler e.g.
appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => {
   if (pathInfo.StartsWith("favicon"))
      return new NotFoundHttpHandler();
});

but this still logs an exception to the logging infrastructure. Is there a way to get the best of both worlds, log when a resource was not found while NOT logging the request for the favorite.ico. Do I have to write code? code scares me :)
Thank you,
Stephen
Answer: The Logging is in the NotFoundHttpHandler itself so to avoid logging you'd return a custom HttpHandler that doesn't log, e.g:
appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => {
   if (pathInfo.StartsWith("/favicon"))
      return new CustomActionHandler((req,res) => {
          res.StatusCode = 404;
          res.StatusDescription = "Favicon not found";
          res.EndRequest();
      });
   return null;
});

Comment: @Stephen returning `null` is essentially a NoOp, where the request continues as normal.
Comment: Returning null instead of the NotFoundHttpHandler won't prevent all other unknow resources from being logged, right?
Comment: mythz - Understood, we're talking about per request, in which case this makes perfect sense.


Rachmaninoff - Piano Concerto No. 2 (1st movement) Tempo I - Bar 86 - why D not D flat?

Question: In Rachmaninoff - Piano Concerto No. 2 (1st movement) Tempo I - Bar 86 -
Red box shows a D.
Green box shows a D.
Blue box shows a D flat.
My question is that what is the logic / why the Green box is not a D flat?
especially that the notes in Green box and Blue box would resonate in the last quarter note beat?
why D not D flat?
Answer: The second half of the bar is a half-step-lower transposition of the first half. Note each voice:

Soprano: C - D  , Cb - Db
Alto:    G - F# , Gb - F
Tenor:   Eb     , D
Bass:    Bb-A-Eb, A-Ab-(Cb)

The Green Box — Blue Box resonance (an enharmonic major seventh) is parallel to the Eb – Red Box resonance (a major seventh).
The horizontal correspondence can also be represented vertically.

                       Beats
    -----------------------------------------------
    1  / 3   |  &  / &   |  2  / 4   |  &    / &
             |           |           |
S:  C  / Cb  |           |  D  / Db  |
A:  G  / Gb  |  F# / F   |           |
T:  Eb / D   |           |           |
B:  Bb / A   |  A  / Ab  |           |  (Eb) / (Cb)

The underlying chord progression is open to interpretation, but it can be convincingly heard as
Ao7 Abo7 Eb/G
Comment: many thanks for the quick answer! +1. So the answer is based on the melody (horizontal note progress). Can we also see from the chord (vertical notes)?
Comment: @wonderich I've added a vertical representation. Please let me know whether or not that's what you're looking for.
Comment: "a half-step-lower transposition of the first half: with some freedom with respect to enharmonic spelling.  Strictly, a half-step-lower transposition of D against E flat should be C sharp against D or D flat against E double-flat.  I'm sure Rachmaninoff had a good reason for doing this instead; without engaging in any serious analysis I would guess that he avoided the C sharp spelling because it's confusing to have lots of sharps for half a bar in a flat-side key, and he avoided the double flat because, well, double flats are also confusing. The interesting result is that the left hand...
Comment: ...repeats the half measure a minor second lower while the right hand repeats it an augmented unison lower.


How to aggregate the sum of a field to a string_Aggregated value Postgres

Question: The query below shows me a list of students with their basic info.
I wanted to aggregate the sum of boys and girls without having to display seperate columns for them. So I created 2 columns, and I took their final sum and displayed it in the final row.
Part 1
with ext as (
select s.studentid as SID,p.surname AS Lastname,
        p.firstname AS Firstname,
        p.sex AS Gender,
        p.birthdate AS BDate,
        ctf.name as Nation,
      SUM(CASE WHEN p.sex = 'MALE' THEN 1 ELSE 0 END) AS BoyCount,
      SUM(CASE WHEN p.sex = 'FEMALE' THEN 1 ELSE 0 END) AS GirlCount
from students s
        join pupil p on p.id = s.pupilid
        join pupilnation pn on pn.pupilid = p.id
        join country ctf on ctf.id = pn.coutnryid
        ...
group by s.studentid, p.surname, p.firstname,p.sex,p.birthdate,ctf.name
)

Part2
select SID,Lastname,Firstname,Gender,BDate,Nation
from ext
union all
select 'Students: ' || cast(count(SID) as varchar(6)),
    null as Lastname,
    null as Firstname,
    'Boys: ' || cast(sum(boycount) as varchar(6)) || '   Girls: ' || cast(sum(girlcount) as varchar(6)),
    null as Bdate,
    string_agg(distinct Nation,',')

Results
SID     Firstname   Gender  Bdate       Nation
723785  Saria       FEMALE  20.01.2012  France
45949   Wenzel      MALE    08.11.2011  Germany
3373    Constantin  MALE    19.03.2006  Germany
727578  Laurin      MALE    08.04.2012  Germany
157     Valerian    MALE    15.01.2008  UK
595959  Attila      MALE    08.06.2012  USA
4172    Sophie      FEMALE  01.11.2004  France
693465  Ibrahim     MALE    16.05.2011  Belgium
…
…
12 Students         8 Males 4 Females   Germany, France, UK, US, Ughanda

Expected Results
I want to have the aggregated final sum of each nation attached to its string in a string aggregation. Would this be possible as shown below?
E.g. Germany: 5, France: 3, UK: 2, US: 1, Ughanda: 1
SID     Firstname   Gender  Bdate       Nation
723785  Saria       FEMALE  20.01.2012  France
45949   Wenzel      MALE    08.11.2011  Germany
…
…
12 Students         8 Males 4 Females   Germany: 5, France: 3, UK: 2, US: 1, Ughanda: 1

Answer: you can write a subquery count by Nation in select then use string_agg function.
select SID,Lastname,Firstname,Gender,BDate,Nation
from ext
union all
select 'Students: ' || cast(count(SID) as varchar(6)),
    null as Lastname,
    null as Firstname,
    'Boys: ' || cast(sum(boycount) as varchar(6)) || '   Girls: ' || cast(sum(girlcount) as varchar(6)),
    null as Bdate,
    (
        select  string_agg(cnt , ', ') from
        (
          SELECT Nation||':'||COUNT(*) cnt
          FROM ext
          GROUP BY Nation
        ) t1
    )
FROM ext

or your can use CROSS JOIN to make it
SELECT
    'Students: ' || cast(totalCnt as varchar(6)),
    null as Lastname,
    null as Firstname,
    'Boys: ' || cast(boyCnt as varchar(6)) || '   Girls: ' || cast(girlCnt as varchar(6)),
    null as Bdate,
    v.Nation
FROM (
    select
       sum(boycount) boyCnt,
       sum(girlcount) girlCnt,
       count(SID) totalCnt
    FROM ext
) t1
CROSS JOIN (
  select string_agg(cnt , ', ') Nation from
  (
    SELECT Nation||':'||COUNT(*) cnt
    FROM ext
    GROUP BY Nation
  ) t1
) v

Comment: you are a genious!!


Multiset Counting Story Problem

Question: Ten friends check their hats with the coatroom clerk. Five are wearing fedoras and five are wearing berets. In how many ways can the clerk return the hats so that no one gets their own hat back if...
$a$. everyone gets the right kind of hat?
$b$. noboby gets the right kind of hat?
$c$. the clerk keeps the fedoras and only returns the 5 berets. In this scenario the five friends that do get a hat back may or may not get the right kind of hat.
--
I at least believe this is utilizing the application of multisets to properly answer the question, I want to be sure though as this specific question is worth a lot of points! I appreciate any answers/tips
Answer: I do not see multisets involved here, but I do not know if another look at this question may use them. Some hints:
a. Let's have a look at the fedora guys: We have five objects (the fedoras) and want to permute them without any fixed point. The number of ways in which that is possible is called the dearrangement number (a fixed point free permutation is called dearrangement): We have
$$ d_5 = \mathord!5 = 44
 $$
Same for the berret guys.
b. This is easier than a., five objects have to be distributed between five people (as nobody gets the right kind of hat, we can permute the berrets between the fedora guys), this is possible in
$$ 5! = 120 $$
ways. Same for the fedoras.
c. One way to approach this is inclusion-exclusion. There are $\binom{10}5$ ways to choose the people that get a hat. We may distribute that hats in $5!$ ways, so there are
$$ \binom{10}5 5! $$
ways to distribute the hats. But stop! Same people may have gotten their own hat. There are five people for which this is possible, one of them chosen ($5$ ways), there remain $\binom 944!$ ways to distribute the remaining hats,
we have
$$ \binom{10}55! - 5\binom 944! $$
ways. But, we have double counted the distributions where two people get their own hats, adding them again, gives $\binom 52$ ways to choose the two people and $\binom 833!$ to distribute the remaining hats
$$ \binom{10}55! - 5\binom 944! + \binom 52 \binom 833! $$
But now, we have not correctly accounted for the distributions where three guys have their own hats, so we continue
$$ \binom{10}55! - 5\binom 944! + \binom 52 \binom 833! - \binom 53\binom 722! $$
I'm sure, you can continue now.
Comment: Really helpful, thanks!

Multiset Counting Story Problem


Update UIView after Locking and Unlocking phone

Question: My app is running an NSURLSession where it downloads a file. However, when the user locks the phone I cannot update the subviews on the screen. They are frozen. I have a method getting called when the phone locks via the app delegate; however, it will not update any subviews.
I have tried placing the updates on main thread or background and nothing works. I simply want to adjust visibility of certain objects but not longer can do that after screen is locked. I hope that is enough info. Any help would be awesome. Thanks guys!
This is what is getting called via the app delegate when the phone is locked
-(void)pauseDownload{

// I want to update the UI!!!!

[session invalidateAndCancel];
bytesSum = 0;
percent = 0;

[HUD hide:YES];
self.downloadButton.hidden = NO;
HUD.progress = percent;
[HUD  setLabelText:[NSString stringWithFormat:@"Loading %.0f%%",(percent*100)]];

}

None of the visibility permissions will work and the objects are un responsive. My guess is that I am losing a pointer to the objects some how when the phone is locked. Can I regain them? Am I way off idk?!
Comment: Updating the views is not something that one would do when the phone is locked. This can easily be done in the method -(void)applicationWillEnterForeground:(UIApplication *)application;
Comment: I am trying to update the view once the phone is unlocked after being locked. The elements that were visible when locked should no longer be visible when unlocked. However I cannot seem to update them.
Answer: Use this in loadView or viewDidLoad:
[[NSNotificationCenter defaultCenter]addObserver:self
  selector:@selector(becomeActive)
    name:UIApplicationDidBecomeActiveNotification
      object:nil];

-(void) becomeActive
{
  NSLog(@"ACTIVE");
  //
}

Comment: It is not the problem of being notified but the problem of being able to update the view. The code is called but the objects are un responsive.
Comment: make sure that you have strong and nonatomic reference to the view you want to update
Answer: You can update UI in viewWillAppear: life cycle view controller method:
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // update UI
}

Also, read apple's doc
Answer: Once device is lock there is no certain methodology or no way to create the background process or continue download process.
The only possible way can be used is we while during the downloading process if user lock the device & app goes into background downloaded content should be saved. So once when application is again  active the downloading process should start from where it stopped.
Comment: I am not trying to even continue the download just update the view so they can then start the download over.
Comment: update UIView at what time ? when it goes to background or when it becomes active ?