text:
Q: how to speed up PHPExcel reader HI all expert i am newbie in php.
can anyone tell me to speed up PHPExcel and this is my code ,it read 20000 rows with 4 columns . it take more than 15s. thank you so much
function upload_fl($FILES){

$file = $FILES['excel'];

//echo getcwd();
//print_r($file);

require 'phpexcel/PHPExcel.php';

if(move_uploaded_file($file['tmp_name'],'C:/wamp/www/datatable_017/php/upload/'.$file['name'])){

    $data = '../php/upload/'.$file['name'];

    $objPHPExcel = PHPExcel_IOFactory::load($data);
    $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);

    //var_dump($sheetData);

    echo sizeof($sheetData);
    //$writefile = fopen($FILES['excel']['name'].'.txt','w');
    /*
    foreach($sheetData as $row){
        foreach($row as $col->$value){
            //$value_inser = (is_numeric($value) == true ? ''number',''.$value.'',''':''text','',''.$value.''');
            //fwrite($writefile,$cate_set_id[$col].','.$com_id.','.$year.','.$value_insert.'\n');
        }
    }
    -->
    fclose($writefile);
    */
    return 'upload/'.$file['name'].'.txt';
}else{
    return 'upload failed';
}
}//function

A: If you have multiple worksheets, but don't need to load all of them, then you can limit the worksheets that the Reader will load using the setLoadSheetsOnly() method. To load a single named worksheet:
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
$sheetname = 'Data Sheet #2';
/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Advise the Reader of which WorkSheets we want to load  **/
$objReader->setLoadSheetsOnly($sheetname);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

Or you can specify several worksheets with one call to setLoadSheetsOnly() by passing an array of names:
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
$sheetnames = array('Data Sheet #1','Data Sheet #3');
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Advise the Reader of which WorkSheets we want to load **/
$objReader->setLoadSheetsOnly($sheetnames);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

If you only need to access part of a worksheet, then you can define a Read Filter to identify just which cells you actually want to load:
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
$sheetname = 'Data Sheet #3';

/**  Define a Read Filter class implementing PHPExcel_Reader_IReadFilter  */
class MyReadFilter implements PHPExcel_Reader_IReadFilter {
    public function readCell($column, $row, $worksheetName = '') {
        //  Read rows 1 to 7 and columns A to E only
        if ($row >= 1 && $row <= 7) {
           if (in_array($column,range('A','E'))) {
              return true;
           }
        }
        return false;
    }
}

/**  Create an Instance of our Read Filter  **/
$filterSubset = new MyReadFilter();
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Advise the Reader of which WorkSheets we want to load
     It's more efficient to limit sheet loading in this manner rather than coding it into a Read Filter  **/
$objReader->setLoadSheetsOnly($sheetname);
echo 'Loading Sheet using filter';
/**  Tell the Reader that we want to use the Read Filter that we've Instantiated  **/
$objReader->setReadFilter($filterSubset);
/**  Load only the rows and columns that match our filter from $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

If you don't need to load formatting information, but only the worksheet data, then the setReadDataOnly() method will tell the reader only to load cell values, ignoring any cell formatting:
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data, not formatting **/
$objReader->setReadDataOnly(true);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

although note that reading only the raw data like this won't allow you to differentiate between date values and floats

If you want to work with large Excel files, don't build a large PHP array in memory by making that toArray() call, because that's a big overhead in memory usage, and there's also a big cost in performance with the constant need to allocate more and more memory as the array is built..... if you're going to process a row at a time, use the iterators built into PHPExcel, or just use a loop to access each individual row in turn.


text:
Q: Setting colors and size inside aes() and inside geom() in ggplot2 I am a beginner and reading Wickham's ggplot2 book to understand how this thing works. I am a little confused about setting attributes (color, size etc.) inside and outside aes() I have included references I've referred here so far.
I ran XYZ experiments to understand this:
Data:
df <- data.frame(x = c(1,2,3), y = c(1,2,3), z=c("a","b","c"))

Experiment 1:
 ggplot(df, aes(y, y)) +
   geom_point(size = 4, show.legend = TRUE)

This doesn't show the legend although I've set it to TRUE. I am not sure why this is happening.
Experiment 2:
ggplot(df, aes(y, y)) +
   geom_point(size = 4, aes(colour = z)) #I see the legend

This surprisingly shows the legend. I believe that from references, mapping variables to "color" is a valid reason to show the legend. We have mapped a variable to color.
Experiment 3
ggplot(df, aes(y, y)) +
   geom_point(size = 4, aes(colour = z),color = "red")

Here, I believe red color is overridden by my second call i.e. color="red". Am I correct?
Experiment 4:
ggplot(df, aes(y, y)) +
   geom_point(size = 4, aes(colour = z,size=20),color = "red")

I wanted to test whether the size increases if I set size = 20 inside aes. It doesn't. I am not sure why because size = 4 was set before setting size = 20.
Experiment 5:
ggplot(df, aes(y, y)) +
   geom_point(size = 4, color = "red") +
   geom_point(aes(colour = z),size=10) #legend appears, but I have lost border colors.

Finally, I thought of keeping size = 10 outside of aes because I thought setting size = constant inside aes would be defaulting the value of size. This worked in that the size did increase, but I have lost the legend.
I am completely lost -how do I show the legend, increase the size (using variables or manually) or change colors( using variables or manually)? I understand that changing size and colors would be the easiest because I would just have to map them to variables. However, I am not sure when I would want to keep one of them (say size or color) constant.
 ggplot(df, aes(y, y)) +
   geom_point(aes(colour = z, size = x)) ##this maps color and size to variables.

I'd appreciate any thoughts. Finally, I am sorry if my question is too basic for some of you.

References: Difference between passing options in aes() and outside of it in ggplot2

Update from the thread: (after discussions for those of us who are reading this...)
Experiment 1: No legend shows up because there is no need for one. There is no variable is mapped to size. There's nothing to show in the legend in that case.
Experiment 2: There is one layer and it maps to the variable. So, I see the legend.
Experiment 3: I have set the color using variable, but then it's overridden by red color.
Experiment 4 Ditto here. The output of Expt 4 and 3 are the same because of overriding issue.
Experiment 5 The second layer overlays on top of first layer. One way to reverse this would be:
ggplot(df, aes(y, y)) + geom_point(aes(colour = z),size=10) +
   geom_point(size = 4, color = "red")

A: You should read more on defining aesthetics globally, and defining them on local geom_xyz() layers.
The thing is, when you define col as attributes, it overrides your aesthetics (aes()) mapping. You can see that in your Experiment 3.
In the fourth one, you are again overriding the color by mapping it outside of aes().
You should check this link out on aesthetics mapping: http://docs.ggplot2.org/current/aes.html
From the same link:

Aesthetics supplied to ggplot() are used as defaults for every layer
you can override them, or supply different aesthetics for each layer

It's nothing so complicated, you should look at the documentation more carefully and it'll come to you naturally.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby on Rails: How do I correctly define a method in the model to total up a column? I'm trying total up all "amount" columns with a definition in the model like so:
  def self.total
    self.all.collect(&:amount).sum
  end

With that, "Recipe.total" works as expected. However, I'm using a plugin that passes "Recipe.find(:all)", and I can't seem to pass that to the method to find the total. That is:
Recipe.find(:all).total # doesn't work

Is there a way to define the method in my model differently to make Recipe.find(:all).total work like Recipe.total?

A: You can write your method as:
def self.total
  self.sum(:amount)
end

And then you can use it also with named scopes:
Recipe.total # without any scopes
Recipe.my_custom_named_scope.total # with your custom named scope

Another variant is to override find method for that model:
def self.find(*args)
  result = super
  if args[0] && args[0] == :all
    def result.total
      self.sum(&:amount)
    end
  end
  result
end

Then you get exactly what you want, you'll be able to write Recipe.find(:all).total.

A: Check out the Calculation Module
It has methods for: sum,average,count, etc ...
Its baked into ActiveRecord.
So you would want to write:
Recipe.sum(:total)
Have fun!


text:
Q: "Unsupported method: SourceProvider.getJniDirectories()" vs "Gradle DSL method not found: 'multiDexEnabled()'" I have an app that has many dependencies "Unable to execute dex: method ID not in [0, 0xffff]: 65536" after update repositories.
Then, I found the solution here.
However, after follow those instructions, I started getting the error "Gradle DSL method not found: 'multiDexEnabled()".
Then, I found that the solution was to update gradle, by adding
"classpath.'com.android.tools.build:gradle:0.14.0'" to dependencies.
Then, I started getting the error "Unsupported method: SourceProvider.getJniDirectories()", and I found many posts saying that the solution is to set gradle back to "0.13.+".
But, gradle 0.13.+ doesn't recognise multiDexEnabled and shows my first error "Gradle DSL method not found: 'multiDexEnabled()'".
I need to use multiDex because of the many dependencies I use and also I use Jni. So, one solution breaks the other one.
[UPDATE] A information that can help: I migrated my project from Eclipse to Android Studio because I didn't find a solution for multidex on Eclipse.
Has anyone had same problem? Is there a solution for that?
Thanks!

A: Just update your Android Studio to 9.+ version. Try Help - Check for update. If no one update was found switch to the Canary channel (Help - Check for update - Updates).


text:
Q: Access 2010 VBA referring to single field in a table I'm currently working on a project where I have to create a prototype system for a Sweet Company/wholesaler. On my form for Customer Order Details, I have a combo box to select whether the items of stock ordered are 'Assigned' or 'Shipped'. I want to have it so that once 'Shipped' is selected, it cannot be changed back. I tried coding in VBA so that once selected the combo box changes to enabled = false. However the problem is it changes for every customer order in the system.
My code looks like this:
Private Sub OrderStatus_Click()
    If OrderStatus = "Shipped" Then
        OrderStatus.Enabled = False
    End If

    ' etc
End Sub

Is there anyway to refer to a single instance of the attribute 'Order Status' (ie. Shipped or Assigned) without affecting every single customer order? Please help!

A: You could add an event to your form for On_Current() so that whenever you switch to a new record it will check to see if the combo box should be enabled for that record.
Private Sub On_Current()
    If OrderStatus = "Shipped" Then
        OrderStatus.Enabled = False
    else
        OrderStatus.Enabled = True
    End If
end Sub


text:
Q: Vertical line at the end of a dataset im kinda new to chart.js, please forgive me if the question is simple :-)
im have a line chart which uses two datasets to display the line. I do this because i want to have different background color for each dataset. This works without problem.
Im trying to draw a horizontal line at the end of the first data set (which is usually in the middle of the chart). I could use scales.right value/2 but this doesnt work allways. I need to figure out the right position of the first dataset. Can anybody help me? thank you very much!
var ctx = document.getElementById("myChart").getContext("2d");

Chart.pluginService.register({
afterDraw: function(chart) {

        var ctxPlugin = chart.chart.ctx;

        ctxPlugin.beginPath();
        ctxPlugin.moveTo(chart.scales["x-axis-0"].right/2, 200);
        ctxPlugin.strokeStyle = "#ff0000";
        ctxPlugin.lineTo(chart.scales["x-axis-0"].right/2,20);
        ctxPlugin.stroke();

        ctxPlugin.textAlign = 'center';
        ctxPlugin.fillText("AVERAGE", chart.scales["x-axis-0"].right/2, 40);

}
});

var myChart = new Chart(ctx, {
type: 'line',
data: {

    labels: [0,10,20,30,40,50,60,70,80,90,100],
    datasets: [
  {
    label: "My First dataset",
    data: [0, 20, 30, 40,40,40,null,null,null,null,null],
    backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
        ]
  },
  {
    label: "My Second dataset",
    data: [null,null,null,null,null,40,40,40,40,50,60],
            backgroundColor: [
              "rgba(151,187,205,0.2)"
        ]
        ,
    strokeColor: "rgba(151,187,205,1)",
    pointColor: "rgba(151,187,205,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(151,187,205,1)",
  }
]
},
 title: {
display: true,
text:'d',

}

});

Example of my Chart

A: Try this

var originalLineDraw = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw: function() {
    originalLineDraw.apply(this, arguments);

    var chart = this.chart;
    var ctx = chart.chart.ctx;

    var index = chart.config.data.lineAtIndex;
    if (index) {
      var xaxis = chart.scales['x-axis-0'];
      var yaxis = chart.scales['y-axis-0'];

      ctx.save();
      ctx.beginPath();
      ctx.moveTo(xaxis.getPixelForValue(undefined, index), 200);
      ctx.strokeStyle = '#ff0000';
      ctx.lineTo(xaxis.getPixelForValue(undefined, index), 20);
      ctx.stroke();
      ctx.restore();
      ctx.textAlign = 'center';
      ctx.fillText("AVERAGE", xaxis.getPixelForValue(undefined, index), 40);
    }
  }
});
var config = {
  type: 'line',
  data: {

    labels: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
    lineAtIndex: 5,
    datasets: [{
        label: "My First dataset",
        data: [0, 20, 30, 40, 40, 40, null, null, null, null, null],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
        ]
      },
      {
        label: "My Second dataset",
        data: [null, null, null, null, null, 40, 40, 40, 40, 50, 60],
        backgroundColor: [
          "rgba(151,187,205,0.2)"
        ],
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
      }
    ]
  },
  title: {
    display: true,
    text: 'd',

  },

};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>

<canvas id="myChart" width="400" height="250"></canvas>


text:
Q: ERROR TypeError: Cannot read property '1' of null I am trying to parse card data that is passed through a card reader, however, I am getting an error in regards to the regex. I understand it means that this.match is null but I am not sure why it is null. Any suggestions? (Using Angular 9)
    CardData: string;
    CardPattern = new RegExp("^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+$");
    CardNumber: string;
    FirstName: string;
    LastName: string;
    ExpData: string;
    match: RegExpExecArray;

    constructor(private snackbar: SnackBar) {
    }

    ngOnInit() {
        // getaCardData();
        this.CardData = "%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?"

        this.match = this.CardPattern.exec(this.CardData);

        this.CardNumber = this.match[1]
        this.FirstName = this.match[3];
        this.LastName = this.match[2];
        this.ExpData = this.match[5] + "/" +this.match[4];

        console.log(this.CardNumber);
    }

A: Your pattern does not match because you have an additional character ? at the end of your string:
this.CardData = %B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?"
Replace it with:
this.CardData = "%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111"
or change your pattern instead with:
^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+\?$
Update: Added working code snippet for you reference! Try adding flags and it should work.

const regex = new RegExp(/^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+\?$/, 'gm');
const input = `%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?`;
var match = regex.exec(input);

document.write(match.length);

A: It seems that it has something to do with escape character. I have tried on Chrome Developer tools running the following two lines.
1. Without Template Literal
new RegExp("^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+$").exec('%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?')

result: null

2. With Template Literal
new RegExp($`{"^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+$"}`).exec('%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?')

result: ["O", index: 20, input: "%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?", groups: undefined]

Wrapping your Regex expression in a Template Literal should solve the problem. The compile process has likely took the wild card characters into account during the build, which suggests why it works after compilation.


text:
Q: Impersonation step and elevated account with password close to expiring I have a workflow on SP 2010 with impersonation step. The account that created the workflow probably will have the password expired in the next few days. This will surely cause the workflow to stop working as explained on this forum several times.
What is the best/safest procedure to fix this matter? I was thinking of using a specifically created system account with password set to never expires, log in with that account and re-publish the workflow, would that be enough?

A: Impersonation step is not asking to add password of system account. So may be it will not cause the problem in workflow.
But if problem is there, set password to never expire, it will definitely solve your problem.


text:
Q: changing default h264 profile I need a video stream with main H264 profile. I try to encode it with such command:
`ffmpeg -f mjpeg -use_wallclock_as_timestamps 1 -i  http://sourse/ -vcodec libx264 -profile:v main -vb 64k -preset veryfast -tune film -vsync 1 -f flv rtmp://ip_addres/rtmp/flow`

It's ok, but how can I set this profile for default? Because when I don't put put "-profile:v main" option ffprobe show high profile.

A: The only way is to change the ffmpeg source code and recompile. You can create a preset however.


text:
Q: How to get Employee Number using REST API I have successfully authenticated from my application using OAuth2 and I'm able to get UserName, UserId and few other things, but I can't get EmployeeNumber which is stored in User profile. How that can be done using REST API, for my authenticated user?

A: From the API point of view, EmployeeNumber is just the same as Username, Id and any other field. It may be field level security that is preventing you from seeing it - check the settings on the User object against the profile of the user you're using to access the API.


text:
Q: How to insert eventid calendar into calendar description using google app script I have script below to create calendar events from google form. The script working for now but I want to record its own eventid into that event description. Then when user want to delete their own event, they can refer into description and I will have another form for user to delete their own event using this eventid.
//var calendarId = "id@group.calendar.google.com";

var typeId = 2;
var nameId = 3;
var startDtId = 4;
var endDtId = 5;
var emailId = 6
var eventId = 7

var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();

function getLatestAndSubmitToCalendar() {

  var startDt = sheet.getRange(lr, startDtId, 1, 1).getValue();
  var endDt = sheet.getRange(lr, endDtId, 1, 1).getValue();
  var name = sheet.getRange(lr, nameId, 1, 1).getValue();
  var email = sheet.getRange(lr, emailId, 1, 1).getValue();
  var desc = "text here" + "\n" + "text here" + "\n" + "text here"; //<--possible to insert eventid here?
  var title = sheet.getRange(lr, typeId, 1, 1).getValue() + " " + name;
  //var type = sheet.getRange(lr, typeId, 1, 1).getValue();

  createAllDayEvent(calendarId,title,startDt,endDt,desc,email);
}

function createAllDayEvent(calendarId, title, startDt, endDt, desc, email) {
  var cal = CalendarApp.getCalendarById(calendarId);
  var start = new Date(startDt);
  var end = new Date(endDt);
  end.setDate(end.getDate() + 1);
  var email = email;
  var title = title;
  //var type = type;

  var event = cal.createAllDayEvent(title, start, end, {
        description : desc,
        guests: email
    });
  event.setGuestsCanModify(true);

  var eventid = event.getId();
  sheet.getRange(lr, eventId, 1, 1).setValue(eventid);

}

A: I believe your goal is as follows.

*

*You want to add the event ID to the description when the event is created using your showing script.

In this case, how about the following modification?
From:
var eventid = event.getId();

To:
var eventid = event.getId();
event.setDescription(desc + "\n" + eventid);

In this modification, the event ID is added as a new line in the description. So, please modify \n for your actual situation.
Or, if you want to put only the event ID, please modify as follows.
var eventid = event.getId();
event.setDescription(eventid);

Or, if you want to use the event ID using Calendar API, please use the event ID as var eventid = event.getId().split("@")[0];.

*

*When this modification is reflected in your showing script, when the event is created, the event ID retrieved from the created event is put to the description.

Reference:

*

*setDescription(description)


text:
Q: Running SQL from file MySQL - User Input? I'm running MySQL from the command line and executing SQL stored in files. What I'm trying to do, is prompt the user to enter input so that I can include this in the SQL script? Is there a way to do this with MySQL?
Many thanks,
James

A: If you want to execute sql script from the file try this:
mysql -u USER -p -D DATABASE < input_filename.sql


text:
Q: MongoDB object property check if $exists with certain value in nested array I have a DB collection like this.
  {
      "name" : "test",
      "gender" : "male",
      "attributes" : [
          {
              "field_id" : "123",
              "field_value" : "['Public']"
          },
          {
              "field_id" : "124",
              "field_value" : "true"
          },
          {
              "field_id" : "125",
              "field_value" : "['Single']"
          },
      ]
  },
  {
      "name" : "test2",
      "gender" : "male",
      "attributes" : [

          {
              "field_id" : "125",
              "field_value" : "['Married']"
          },
      ]
  },
  {
      "name" : "test3",
      "gender" : "male",
      "attributes" : [
          {
              "field_id" : "123",
              "field_value" : "['Public']"
          },
          {
              "field_id" : "125",
              "field_value" : "['Married']"
          },
      ]
  },
  {
      "name" : "test4",
      "gender" : "male",
      "attributes" : [
          {
              "field_id" : "123",
              "field_value" : "['Private']"
          },
      ]
  },
  {
      "name" : "test4",
      "gender" : "male",
      "attributes" : [

      ]
  }

]

I want to fetch all records which have field_id as 123 and field_value as "Public"; + records in which field_id
123 doesn't exist under attributes.
I tried
var condition = { "attributes" :  {$elemMatch:{field_id:"123",field_value:{ $in:["Public"] }}}};

queryObj.push(condition);

this works fine to fetch records having  field_id as 123 and field_value as Public
But I also want to get records in which field_id as 123 doesn't exists, I tried this
var condition1 =
{ "attributes" :  {$elemMatch:{field_id:"123",$exists:false}}}

queryObj.push(condition1);

but it returns an error as it's not right syntax.
Please guide how do I fetch as desired.
This is the expected output, As these records have only Public Value for 123 field_id or field_id as 123 DOES NOT EXIST in these.
[
  {
      "name" : "test",
      "gender" : "male",
      "attributes" : [
          {
              "field_id" : "123",
              "field_value" : "['Public']"
          },
          {
              "field_id" : "124",
              "field_value" : "true"
          },
          {
              "field_id" : "125",
              "field_value" : "['Single']"
          },
      ]
  },
  {
      "name" : "test3",
      "gender" : "male",
      "attributes" : [
          {
              "field_id" : "123",
              "field_value" : "['Public']"
          },
          {
              "field_id" : "125",
              "field_value" : "['Married']"
          },
      ]
  },
  {
      "name" : "test2",
      "gender" : "male",
      "attributes" : [

          {
              "field_id" : "125",
              "field_value" : "['Married']"
          },
      ]
  },
  {
      "name" : "test4",
      "gender" : "male",
      "attributes" : [

      ]
  }

]

A: you should use two $elemMatch with $or operator.
your query should be something like this.
db.collection.find({
  $or: [
    {
      "attributes": {
        "$elemMatch": {
          field_id: "123",
          field_value: "['Public']"
        }
      }
    },
    {
      "attributes": {
        "$not": {
          "$elemMatch": {
            field_id: "123"
          }
        }
      }
    }
  ]
})

working example: https://mongoplayground.net/p/CP3HSKmNpKM


text:
Q: Correctly updating stand-alone QGIS install on Windows? I want to update QGIS 2.14.6 to 2.14.12 in Windows.
Aims:

*

*Receive all projects

*Receive all additional third party plugins

My plan at the moment is:

*

*Copy folder "plugins" within .qgis/python

*Delete folder .qgis

*Delete QGIS 2.14.6 and their desktop assignments

*Install 2.14.12

*Paste folder "plugins"

Question:

*

*Is anything wrong in 1-5, if yes: What?

*Any other points that need to be considered?

A: Folder .qgis is not used since QGIS 2.0, .qgis2is used instead.
You can do step 1, step 2 is not necessary, and the next ones are done by the installer of QGIS 2.14.12.
The last step is not necessary, because nothing in that folder gets touched by the installer.
Your steps might be relevant for the next big release, QGIS 3.0.


text:
Q: How can a symbol table be designed to support function overloading? I'm creating a compiler and really struggling with the semantic analysis phase. I'm not sure how to deal with function overloading in a symbol table. I can't seem to find any resources that describe this particular problem. I think that name mangling must be used somewhere and I'm pretty sure that types from the AST should be converted to strings.
Multiple functions with the same name are allowed to be declared in the same scope as long as each declaration has a different set of parameters. The following snippet is an example in my language (it's quite similar to Swift).
func add(a: Int, b: Int) {
  return a + b;
}
func add(a: Float, b: Float) {
  return a + b;
}

I don't know how to store functions in the symbol table. This is part of my symbol table data structure.
struct Symbol {};

struct Var final : Symbol {
  std::string type;
};

using FuncParams = std::vector<std::string>;
struct Func final : Symbol {
  std::string ret;
  FuncParams params;
};

using Table = std::unordered_map<std::string, std::unique_ptr<Symbol>>;
struct Scope {
  Table table;
  Scope *parent = nullptr;
};
using Scopes = std::vector<std::unique_ptr<Scope>>;

I could use a std::unordered_multimap and store the function name add as the key and store the names of the parameters in the symbol object. I could use a std::unordered_map and store the function name decorated with the parameters add_Int_Int as the key and store the names of the parameters in the symbol object as well.
Also, should Symbol be a base class or should I put all kinds of symbols in the one Symbol object? I've seen many examples of using an enum to differentiate between functions, variables and type declarations but a function stores return type and parameter types. Should I use a tagged union?
I feel like there's a smart and simple way of solving this but I just can't find it.
Update:
I've taken a suggestion from @NeilButterworth and used unmangled function names as the symbol keys and this seems to be the way to go (but what do I know!). Answers to my other questions or some advice on this topic would be appreciated.

A: The solution is to do what @NeilButtworth said in the comments. But you will want to build some logic around creating "compatible" type trees. Becuase you want a function to have parameters that are compatible. I would recommend some function that returns if a type is a child of another type like isTypeCompatible(actualType,formalType). Then from there you can try and find the function that has the most specific signature that matches the call. So f(5) should call f(int) since 5 is an explicit int but only an implicit float. One way of doing this is by seeing which signature minimizes the distance up a type tree from the given types and the formal types.
EDIT: By "compatible" type trees it essentially the same as inheritance. Like how if we have g(float) g(5) works since an int literal is convertible to a float literal. The type trees are much easier to construct with custom user classes since you AST should already construct upon parsing and type checking.


text:
Q: SwiftUI Preview MPMediaItemArtwork I've got an array based on a structure that includes song title and artist as strings, and its artwork as type MPMediaItemArtwork. To get the preview to work in Swift UI I refer to
struct TrackRow_Previews: PreviewProvider {
    static var previews: some View {
        TrackRow(track: Track(name: "Track 1", artist: "Artist 1", artwork: [MPMediaItemArtwork]))
    }
}

The view works fine when I've commented out the preview, and I've therefore been able to print to the console a selected MPMediaItemArtwork -- which is MPConcreteMediaItemArtwork: 0x281efb890. But it doesn't accept that either. What value can I put in for the preview artwork to make the preview provider work?
Extra Details:
struct Track: Hashable {
    var name: String
    var artist: String
    var artwork: MPMediaItemArtwork
}

func getTracks(chosenPlaylist: String) {
        trackArray = []
        for playlist in playlists! {
            if (playlist.value(forProperty: MPMediaPlaylistPropertyName)as! String) == chosenPlaylist {
                let songs = playlist.items
                            for song in songs {
                                if song.artwork != nil {
                                trackArray.append(Track(name: (song.value(forProperty: MPMediaItemPropertyTitle) as! String), artist:(song.value(forProperty: MPMediaItemPropertyArtist) as! String), artwork: song.artwork!))
                                }
                            }
                sortArray()
            }
        }
    }

A: My issue was that I hadn't imported MediaPlayer, as I hadn't needed it for the view, but obviously did for preview view. The code that works is as follows:
struct TrackRow_Previews: PreviewProvider {
    static var previews: some View {
        TrackRow(track: Track(name: "Track 1", artist: "Artist 1", artwork:MPMediaItemArtwork(image: UIImage(imageLiteralResourceName: "Artwork"))))
    }
}

A: I'm going to assume artwork is an array of MPMediaItemArtwork so for the preview I would just grab the first item in the array like the following:
struct MPMediaItemArtwork {
   var name: String
}

struct Track {
    var name: String
    var artist: String
    var artwork: [MPMediaItemArtwork]
}

struct ContentView_Previews: PreviewProvider {
    static var artwork = MPMediaItemArtwork(name: "0x281efb890")
    static var mediaArray: [MPMediaItemArtwork] = [artwork]

    static var previews: some View {
        TrackRow(track: Track(name: "Track 1", artist: "Artist 1", artwork: [mediaArray[0]]))
    }
}


text:
Q: FUSE Camel route (using JAXB) can not convert the XML to Java object if it has the interface, any idea to solve it Recently, I have a project, it will use the FUSE Camel route to accept the XML as POST payload, and convert to Java object.
from(ENDPOINT_SAMPLE)
   .convertBodyTo(TestClass.class)
It suppose to convert the XML to TestClass object, but the TestClass is from the third party, it implements some interface, which cause lots of problem. Such as
2014-09-12 14:15:54,304 | WARN  | qtp1407394366-68 | AbstractJAXBProvider             | ?                                   ? |
170 - org.apache.cxf.cxf-rt-frontend-jaxrs - 2.7.0.redhat-610379 | com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 3 counts  of IllegalAnnotationExceptions
com.BBB.TestIF is an interface, and JAXB can't handle interfaces.
        this problem is related to the following location:
                at com.BBB.TestIF
                .......
I used to use the XStream to convert the XML from/to Java, it works with interface, but JAXB can not do it, since this is handled by Camel internally, I can not change it to XStream.
   Please share your experience or give me some advice, I understand that I can mimic my own TestClass, but it may not be the good solution (since it is very complicated).
   Thanks.

A: If xstream works for you, then why don't you use xstream in camel as well?
from("foo:bar").unmarshal().xstream().to("bar:foo");

http://camel.apache.org/xstream


text:
Q: Multi-Lingual Site using Cookies im a newbie to php/javascript/jquery,etc. How do I implement cookies into a multilingual/multiregional (wordpress.org) website layed out with architecture like explained below?
http://domain.com/ takes users to a page that asks for which country they are in, they have the option of four different countries, Canada, UK, Australia and US. Then if for example, they select Canada, they are taken to http://ca.domain.com/ and it asks for language, English, French, Spanish and below that is a dropdown for other languages. If they click english, they will be taken to the final result of a wordpress blog at http://ca.domain.com/en/
How may I set cookies so that next time they visit http://domain.com/ or even jump to http://ca.domain.com/ that it would immediately send them the the wordpress blog that they saw last time, also would these cookies (not the same one set on their desktop) be able to work if a user is a mobile client? Can I also make a link back to the language and region selection process?
Thanks in advance!
By the Way, I am using WP Multisite for the countries and maybe set up some sort of php translation at the end of the subdomain multisite urls
Extension to question: Remember language selection - then redirect to home page in subsequent visits


text:
Q: Python readline Auto-Complete I want to implement auto-complete in Command Line Interface for the following :
Food :
  Fruits:
    Apples
    Oranges
  Vegetables:
    Carrot
    Beetroot
  Snacks:
    Chocolate

The output for the <TAB> would be :
food
and so on...
Commands would be like :
Food Fruits Apples
or Food Snacks Chocolate
Came across this https://pymotw.com/2/readline/ while googling. But I don't understand how begin/end works. And how it will change for further nesting.
Any sort of help is appreciated. (Writing code in python. Prefer to use readline library)

A: If you use a library like click for making your CLI you will get this mostly for free http://click.pocoo.org/5/bashcomplete/


text:
Q: Can I use singleShot(true) to make a running QTimer to stop after next shot? I have a QTimer triggering periodical events.
I don't want to stop the timer directly because I want to sync some special signals to the last event.
Can I achieve this by setting setSingleShot(true) on this QTimer so that its next shot will be a single shot, and the timer stops after the next shot?
Edit:
It seems to work. but setSingleShot(true) seems not atomic: I sometimes observe 2 shots before the timmer stops.

A: Yes. Yes you can. In fact, there is no difference between "regular" and single-shot timers - other than this flag. Each time the timer times out, it check the single-shot flag. If it is set, the timer unregisters itself and thus doesn't fire again until you restart it.


text:
Q: ¿Cómo colocar una etiqueta como oculta para que se muestre al presionar un botón? He escrito el contenido "oculto" y el botón de esta forma:
<button id="mostrarMsj">Mostrar mensaje</button>

Lorem ipsum

Y el código en JQuery de esta manera:
 $('#mostrarMsj').on('click', function(){
    $('.oculto').show(0, function(){
        console.log('Aqui va el resto de mi código');
    })
 });

Sin embargo, el mensaje aparece cuando ejecuto el código.

A: Ejemplo funcional utilizando jQuery. desarrollas mas escribiendo menos y lo mejor!!... es multi plataforma:

$(function() {
  $("button").on("click", function() {
    $("#mensaje").show(0, function() {
      setTimeout(function() {
        $("#mensaje").hide(1000);
      }, 2000);
    });
  });
});

<button>Mostrar Mensaje</button>

Mensaje oculto!! ;))

Hola! Hola! Hola!

A: Así si que funciona. Saludos

.oculto{
    display: none;
   }

<meta charset="utf-8">
<button id="mostrarMsj">Mostrar Mensaje</button>

Lorem ipsum


text:
Q: iOS 7 App submission error about Launch Image
Here's somebody that had the same problem, but with PhoneGap: PhoneGap Launch Image iOS Apple Store Submission

I would like to to submit my app (target iOS7, iPhone only) and I'm using the .xcassets folder for
app icons and launch images.
When I click submit I get the following errors:

and

I checked the plist file of my archived application and it already has the necessary keys like
UILaunchImage, UILaunchImageSize. See here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>BuildMachineOSBuild</key>
    <string>14C323</string>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>MyApp</string>
    <key>CFBundleExecutable</key>
    <string>MyApp</string>
    <key>CFBundleIcons</key>
    <dict>
        <key>CFBundlePrimaryIcon</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>AppIcon29x29</string>
                <string>AppIcon40x40</string>
                <string>AppIcon60x60</string>
            </array>
        </dict>
    </dict>
    <key>CFBundleIdentifier</key>
    <string>com.MyApp</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>MyApp</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleResourceSpecification</key>
    <string>ResourceRules.plist</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleSupportedPlatforms</key>
    <array>
        <string>iPhoneOS</string>
    </array>
    <key>CFBundleVersion</key>
    <string>1.0</string>
    <key>DTCompiler</key>
    <string>com.apple.compilers.llvm.clang.1_0</string>
    <key>DTPlatformBuild</key>
    <string>11B506</string>
    <key>DTPlatformName</key>
    <string>iphoneos</string>
    <key>DTPlatformVersion</key>
    <string>7.0</string>
    <key>DTSDKBuild</key>
    <string>11B506</string>
    <key>DTSDKName</key>
    <string>iphoneos7.0</string>
    <key>DTXcode</key>
    <string>0502</string>
    <key>DTXcodeBuild</key>
    <string>5A3005</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>MinimumOSVersion</key>
    <string>7.0</string>
    <key>UIDeviceFamily</key>
    <array>
        <integer>1</integer>
    </array>
    <key>UILaunchImages</key>
    <array>
        <dict>
            <key>UILaunchImageMinimumOSVersion</key>
            <string>7.0</string>
            <key>UILaunchImageName</key>
            <string>LaunchImage-700</string>
            <key>UILaunchImageOrientation</key>
            <string>Portrait</string>
            <key>UILaunchImageSize</key>
            <string>{320, 480}</string>
        </dict>
        <dict>
            <key>UILaunchImageMinimumOSVersion</key>
            <string>7.0</string>
            <key>UILaunchImageName</key>
            <string>LaunchImage-700-568h</string>
            <key>UILaunchImageOrientation</key>
            <string>Portrait</string>
            <key>UILaunchImageSize</key>
            <string>{320, 568}</string>
        </dict>
    </array>
    <key>UIMainStoryboardFile</key>
    <string>Main_iPhone</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
</dict>
</plist>

I have no idea what is going wrong and why apple rejects it as the LaunchImage key apple is complaining about is here.
I'm already trying to solve this since several days, but can't figure it out.
Any help is greatly appreciated!
How could I solve this?
Thanks!

A: Check that your device supports the new iPhone 5 height and make sure that you have the launch images for both of them.

A: What you need is three kinds of images for iPhone,

*

*Default.png (320X480)

*Default@2x.png (640X960)

*Default-568h@2x.png (640X1136)

If you name all your launch images as above and pull them into your project they will automatically be added as your launch images.


text:
Q: Cómo saber si un subinforme está vacío Estoy trabajando con Crystal Reports. Tengo un informe principal, y en una subsección hay un subinforme, siendo el subinforme de el único contenido de la subsección.
Necesito que la subsección no se muestre en el caso de que el subinforme esté vacío. ¿Cómo puedo controlar desde las fórmulas de informe principal si el subinforme está vacío?
Un saludo.

A: En el reporte principal, busca la sección donde colocaste el sub-reporte. Da un clic derecho y selecciona la opción Section Expert, en las opciónes mostradas, selecciona la opcion Suppress Blank Section. Selecciona Aceptar y Aceptar.

Dentro del sub reporte. Si tienes campos fijos (Formulas, labels), vas a colocar una formula en todos los campos. Clic derecho al campo, Agrega la formula en la opción Suppress. En la formula vas a comparar algún campo que regrese tu consulta del sub-reporte. Ejemplo
 IF isnull({sp_qbxselem;1.articulo})
THEN
    TRUE
ELSE
    FALSE

Debes realizar esto para todos los campos del sub-reporte.


text:
Q: Get a Func<> from MethodInfo with private (inaccessible) types Consider the following code:
private class ThirdPartyClass {
    private class InternalPrivateClass { }
    private static InternalPrivateClass Init() {
        return new InternalPrivateClass();
    }
    private static int DoSomething(InternalPrivateClass t1) {
        return 0;
    }
}

Assume I have no control over ThirdPartyClass and reverse-engineering it in any way is cost-prohibitive. I want to be able to quickly call DoSomething without the performance overheads of reflection. So what I have so far:
Type t = typeof(ThirdPartyClass);
object context = t.GetMethod("Init", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);
MethodInfo mi = t.GetMethod("DoSomething", BindingFlags.NonPublic | BindingFlags.Static);
// ...now what?

*

*Calling mi.Invoke(null, new object[]{context}) is of course slow, because it's using reflection.

*Delegate.CreateDelegate(typeof(Func<object, int>), mi);
fails because the Func signature must match exactly and (object, int) doesn't match the MethodInfo's signature (ThirdPartyClass.InternalPrivateClass, int)

*Constructing a properly typed Delegate via reflection (see https://stackoverflow.com/a/40579063/2692950) only lets me call .DynamicInvoke(context) which is still slow. I cannot cast this delegate to a Func to be able to invoke it directly because, again, the signatures don't match.

*I cannot write Func<ThirdPartyClass.InternalPrivateClass, int> - it won't compile since InternalPrivateClass is private.

Solved! (https://stackoverflow.com/a/52652398/2692950)

Example of why I need this:
Take a look at this MD4 hash implementation: https://stackoverflow.com/a/46821287/2692950
(Shortened version: https://stackoverflow.com/a/52640221/2692950)
This works very well, except that every single hashing operation is calling a method via reflection!
In this example, we call via reflection an inaccessible private function System.Security.Cryptography.Utils.HashEnd(SafeProvHandle h), passing a SafeHandle as the parameter. This works because SafeProvHandle inherits from SafeHandle. SafeProvHandle cannot be referenced directly because it's private, hence there appears to be no way invoke this function directly.
(I'm mostly interested in whether a solution exists to the general case at the top of the question, but if anyone knows of a better way to implement obtaining a crypto service provider directly by ALG_ID, I'm all ears :)

A: This is a bit tricky to do but can be done with DynamicMethod in the System.Reflection.Emit namespace. It allows us to emit IL at run time that calls these methods without having to refer to valid, visible identifiers in our code. One of the tricks that this class is able to use is to skip various security and visibility checks which we set via parameters in the constructor. From the example, we need to replace the Utils class. Here is a rewrite of it using DynamicMethod to create delegates:
internal static class DelegateUtils
{
    private static readonly Type UtilsType = Type.GetType("System.Security.Cryptography.Utils");
    private static readonly Func<int, SafeHandle> CreateHashDel;
    private static readonly Action<SafeHandle, byte[], int, int> HashDataDel;
    private static readonly Func<SafeHandle, byte[]> EndHashDel;

    static DelegateUtils()
    {
        CreateHashDel = CreateCreateHashDelegate();
        HashDataDel = CreateHashDataDelegate();
        EndHashDel = CreateEndHashDelegate();
    }

    internal static SafeHandle CreateHash(int algid)
    {
        return CreateHashDel(algid);
    }

    internal static void HashData(SafeHandle h, byte[] data, int ibStart, int cbSize)
    {
        HashDataDel(h, data, ibStart, cbSize);
    }

    internal static byte[] EndHash(SafeHandle h)
    {
        return EndHashDel(h);
    }

    private static Func<int, SafeHandle> CreateCreateHashDelegate()
    {
        var prop = UtilsType.GetProperty("StaticProvHandle", BindingFlags.NonPublic | BindingFlags.Static);

        var createHashMethod = UtilsType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
            .FirstOrDefault(mi => mi.Name == "CreateHash" && mi.GetParameters().Length == 2);

        var createHashDyn = new DynamicMethod("CreateHashDyn", typeof(SafeHandle), new[] { typeof(int) }, typeof(object), true);
        var ilGen = createHashDyn.GetILGenerator();
        ilGen.Emit(OpCodes.Call, prop.GetGetMethod(true));
        ilGen.Emit(OpCodes.Ldarg_0);
        ilGen.Emit(OpCodes.Call, createHashMethod);
        ilGen.Emit(OpCodes.Ret);

        var del = (Func<int, SafeHandle>)createHashDyn.CreateDelegate(typeof(Func<int, SafeHandle>));
        return del;
    }

    private static Action<SafeHandle, byte[], int, int> CreateHashDataDelegate()
    {
        var hashDataMethod = UtilsType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
            .FirstOrDefault(mi => mi.Name == "HashData" && mi.GetParameters().Length == 4);
        var hashDataDyn = new DynamicMethod("HashDataDyn", typeof(void), new[] { typeof(SafeHandle), typeof(byte[]), typeof(int), typeof(int) }, typeof(object), true);
        var ilGen = hashDataDyn.GetILGenerator();
        ilGen.Emit(OpCodes.Ldarg_0);
        ilGen.Emit(OpCodes.Ldarg_1);
        ilGen.Emit(OpCodes.Ldarg_2);
        ilGen.Emit(OpCodes.Ldarg_3);
        ilGen.Emit(OpCodes.Call, hashDataMethod);
        ilGen.Emit(OpCodes.Ret);

        var del = (Action<SafeHandle, byte[], int, int>)hashDataDyn.CreateDelegate(typeof(Action<SafeHandle, byte[], int, int>));
        return del;
    }

    private static Func<SafeHandle, byte[]> CreateEndHashDelegate()
    {
        var endHashMethod = UtilsType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
            .FirstOrDefault(mi => mi.Name == "EndHash" && mi.GetParameters().Length == 1);
        var endHashDyn = new DynamicMethod("EndHashDyn", typeof(byte[]), new[] { typeof(SafeHandle) }, typeof(object), true);
        var ilGen = endHashDyn.GetILGenerator();
        ilGen.Emit(OpCodes.Ldarg_0);
        ilGen.Emit(OpCodes.Call, endHashMethod);
        ilGen.Emit(OpCodes.Ret);

        var del = (Func<SafeHandle, byte[]>)endHashDyn.CreateDelegate(typeof(Func<SafeHandle, byte[]>));
        return del;
    }
}

Next the question is how much of a speed advantage this gives. It gives you something like a 2-4x increase depending on the size of the data you are hashing. Smaller gets a better speed boost probably because we spent less time doing computations there and more time in between method invocations. Here were the results of a quick benchmark:

BenchmarkDotNet=v0.11.1, OS=Windows 10.0.17134.286 (1803/April2018Update/Redstone4)
  Intel Core i5-4200U CPU 1.60GHz (Haswell), 1 CPU, 4 logical and 2 physical cores
  Frequency=2240904 Hz, Resolution=446.2485 ns, Timer=TSC
    [Host]     : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.3163.0
    DefaultJob : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.3163.0
Method  |     N |      Mean |     Error |    StdDev |
  ----------- |------ |----------:|----------:|----------:|
  Reflection |  1000 | 16.239 us | 0.1252 us | 0.1046 us |
    Delegate |  1000 |  4.329 us | 0.0245 us | 0.0230 us |
  Reflection | 10000 | 31.832 us | 0.1599 us | 0.1335 us |
    Delegate | 10000 | 19.703 us | 0.1005 us | 0.0940 us |

Note that N is number of bytes being hashed. This is using all the code provided in OPs links to create a MD4 implementation and then calling ComputeHash on that.
Benchmark code:
public class MD4DelegateVsReflection
{
    private MD4 md4 = MD4.Create();
    private byte[] data;

    [Params(1000, 10000)]
    public int N;

    public void SetupData()
    {
        data = new byte[N];
        new Random(42).NextBytes(data);
    }

    [GlobalSetup(Target = nameof(Reflection))]
    public void ReflectionSetup()
    {
        MD4.SetReflectionUtils();
        SetupData();
    }

    [GlobalSetup(Target = nameof(Delegate))]
    public void DelegateSetup()
    {
        MD4.SetDelegateUtils();
        SetupData();
    }

    [Benchmark]
    public byte[] Reflection() => md4.ComputeHash(data);

    [Benchmark]
    public byte[] Delegate() => md4.ComputeHash(data);
}

A: Here is the general solution to create a Func<> or Action<> from a MethodInfo with inaccessible types:
public static Delegate CreateDelegate(this MethodInfo methodInfo, object target, params Type[] custTypes) {
    Func<Type[], Type> getType;
    bool isAction = methodInfo.ReturnType.Equals((typeof(void))), cust = custTypes.Length > 0;
    Type[] types = cust ? custTypes : methodInfo.GetParameters().Select(p => p.ParameterType).ToArray();
    if (isAction) getType = Expression.GetActionType;
    else {
        getType = Expression.GetFuncType;
        if (!cust) types = types.Concat(new[] { methodInfo.ReturnType }).ToArray();
    }
    if (cust) {
        int i, nargs = types.Length - (isAction ? 0 : 1);
        var dm = new DynamicMethod(methodInfo.Name, isAction ? typeof(void) : types.Last(), types.Take(nargs).ToArray(), typeof(object), true);
        var il = dm.GetILGenerator();
        for (i = 0; i < nargs; i++)
            il.Emit(OpCodes.Ldarg_S, i);
        il.Emit(OpCodes.Call, methodInfo);
        il.Emit(OpCodes.Ret);
        if (methodInfo.IsStatic) return dm.CreateDelegate(getType(types));
        return dm.CreateDelegate(getType(types), target);
    }
    if (methodInfo.IsStatic) return Delegate.CreateDelegate(getType(types), methodInfo);
    return Delegate.CreateDelegate(getType(types), target, methodInfo.Name);
}

In the OP, this function can be called as follows to get a directly invokeable Func<>:
Func<object, int> f = (Func<object, int>)mi.CreateDelegate(null, typeof(object), typeof(int));
f(context);

Thanks to @Sagi (https://stackoverflow.com/a/40579063/2692950) and @mike.z (https://stackoverflow.com/a/52641599/2692950), for leading me to this solution


text:
Q: Possible to add search bar that functions like using (command F) or (CTRL F) inside a website I have a client that wants the function of being able to enter a key word into a search bar and have it start to highlight the results on the page as you are typing (or after you hit search).
This is just like using the ⌘+F function on a Mac (or Ctrl+F on PC) and the browser itself  pops up a search box.
He doesn't want to have to hit ⌘+F though, or have his customers to have to know that command. He wants to just have a search bar already on that page that he can type into and it start highlighting words.
ANY idea how to do this in WordPress? I've searched the internet and cannot find a tutorial on how to do it.
If not a search box, maybe a button they can click that prompts to pull up command F on a mac or Ctrl+F on a pc?
I am at a loss here and cannot figure this out. Any tips or experience with this, I would be very grateful.

A: So I found this on another thread and it seems to work but it only finds the first occurrence. I need it to highlight all the occurrences. Any idea how to get it to do that?

 hello world, hello world, hello world, hello world

    <form action="" id="form2">

            <input type="text" id="search">
            <input type="button" id="submit_form" onclick="checkInput()" value="Submit">

    </form>

A: https://codepen.io/b-jody-spedicato/pen/ExNzqQP

<form name="f1" action=""
    onSubmit="if(this.t1.value!=null && this.t1.value!='') findString(this.t1.value);return false">
    <input type="text" name=t1 value="" size=20>
    <input type="submit" name=b1 value="find">

This is some sample text, do a search above to see how the search bar functions.
You can now add your own CSS styling.

</form>


text:
Q: 'App not Installed' Error on Android I have a program working in the Android Emulator. Every now and again I have been creating a signed .apk and exporting it to my HTC Desire to test. It has all been fine.
On my latest exported .apk I get the error message 'App not installed' when I try to install the .apk. It runs fine on the emulators.
As I have mainly been testing on the emulators and only every now and again exporting to a real phone I am not sure when this happened. What is the likely cause of it not installing on a physical phone but running fine in the emulators?
I have tried rebooting the phone & removing the existing .apk, does not fix the fault.

A: I faced the issue when I update my android from 2.3.2 to 3.0.1 . If this is the case the IDE will automatically considers the following points.
1.You cannot install an app with android:testOnly="true" by conventional means, such as from an Android file manager or from a download off of a Web site
2.Android Studio sets android:testOnly="true" on APKs that are run from
if you run your app directly connecting the device to your system, apk will install and run no problem.
if you sent this apk by copy from build out put and debug folder it will never install in the device.
Solution :go Build ---> Build APK(s) ---> copy the apk file share to your team
then your problem will solve.

A: Sideloading debug apps for testing on a physical phone worked reliably until I upgraded the phone from Android Pie to Android 10. After that, the "App not installed" error came up every time I tried to sideload the app.
Based on a warning in my AndroidManifest.xml, I changed from...
<application
    android:name=".App"
    android:allowBackup="true" ... />

to...
<application
    android:name=".App"
    android:allowBackup="false" ... />

After that, I was able to sideload my app -- once. Then, I encountered the same "App not installed" error again. By changing allowBackup back to true, it worked again (at least once).
It is obvious from the number of answers and the variation in the answers that there are many reasons for this problem. I'm sharing this in case it helps others.

A: If you have a previous version for that application try to erase it first, now my problem was solved by that method.

A: If application's not installing, delete the file .android_secure/smdl2tmpl.asec from the SD card.
If the folder .android_secure is empty in the file manager, delete it from the PC.

A: ARGHHHHH! I was trying to install as Unsigned Release APK when the proper setting was DEBUG SDK.
There goes an hour.

A: In the end I found out that no apps were being installed successfully, not just mine. I set the Install App default from SD card to Automatic. That fixed it.

A: I have also solved this issue,
The problem was that i declared my main activity twice,
On as the first activity to load and i specified also an intent-filter for it
And once again below it i declared it again .
Just make sure you don't declare your activities twice .

A: create keystore file through command line
keytool -genkey -alias key_file_name.keystore -keyalg RSA -validity 1000000000000000 -keystore key_file_name.keystore
export apk through Eclipse, right click on Android project Android Tools > Export Signed Application Package, then give keystore location & password.
this will crate signed apk at the same time apk will be zipaligned. And installable.
If you go through command line for all, some times you may face "Application not installed" error.
(Application not installed error can happen not only, when using command line. It can be some other reasons as well)

A: Using Android Studio, I had previously installed the unsigned debug version of the APK (Build > Build APK) and had to uninstall it before installing the signed release version (Build Variants > Build Variant: release, Build > Generate Signed APK).

A: My problem was similar to that of @Lunatikzx. Because of wrong permission tag which was written as attribute to application:
<application
    android:permission="android.permission.WRITE_EXTERNAL_STORAGE"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:testOnly="false"
    android:debuggable="true">

What fixed it for me was changing permission tag to separate tag like this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A: Apparently this can also be caused by renaming the APK prior to installing it. I wanted to reduce the amount of typing users had to do to get the app from our web site by shortening the file name. After that, they were unable to install it.
Once I reverted to the original file name used when creating and signing the package I was able to update the installed app.

A: In my case it was because I was using the alpha version of support library 28. Looks like Google marks these pre release versions as testOnly. If you really want to release like this (for instance, you want to push an internal beta like I did), you can add this line to your gradle.properties file:
android.injected.testOnly=false

A: In my case I had the declared my launcher activity as android:exported="false"
<activity android:name=".MainActivity"
            android:exported="false">

I recently targeted android 12 and had to put android:exported attribute in my manifest components, but did not know what to put as the value. changing the value to android:exported="true" worked.

A: I faced with the same problem. The problem was the main activity in my AndroidManifest.xml file was written twice. I deleted the duplicate.

A: Check with the Android version.
If you are installing non-market apps, and incompatible version you will get this error.
Ex: Application targetted to 2.3.4
    Your device is 2.2
    Then you will get this error.

A: The "Application not installed" error can also occur if the app has been installed to or moved to the SD card, and then the USB cable has been connected, causing the SD card to unmount.
Turning off USB storage or moving the app back to internal storage would fix the issue in this case.

A: I also encountered this issue.
Kindly try this solution. Make sure that the package name of your project is different from your previous project that was already installed in your mobile phone. I think they get conflict  in their names.   It works in me.

A: You also may encounter this issue because your device manufacturer did not license the Google commercial apps, such as Play Store, YouTube, Google Maps, etc. Follow this answer to solve the problem.

A: This can also occur when making a home screen widget, and your widget XML file has an incorrect Activity specified in its android:configure property.

A: for me the cause was that i had multiple builds using different build variants on same phone:

what happened was that some of these builds were built by me, another one was sent to me by another developer.. trying to install the developers while i had other builds (built by me) caused the above error.
so the fix was simple: delete all the builds on my phone (regardless of build variant).. then install the apk sent by my peer.. and it worked like a charm

A: In my case, it's because Android Studio 3.0 sets android:testOnly="true" on APKs that build from the release Build Variant.

https://commonsware.com/blog/2017/10/31/android-studio-3p0-flag-test-only.html

So run ./gradlew assembleRelease solve my issue

A: open AndroidMainfest then add verionCode, versionName in application tag and make sure debug able equal false:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="...">

<application
    ...
    android:debuggable="false"
    android:versionCode="1"
    android:versionName="1.0"
    tools:ignore="HardcodedDebugMode">
    ...
</application>

then open build.gradle (module:app) make sure verionCode, versionName exited and minsdk <= your mobile sdk:
defaultConfig {
    ...
    minSdkVersion 19
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
   ...
}

look into sources: https://developer.android.com/studio/publish/
&     https://developer.android.com/studio/publish/preparing
&     https://developer.android.com/studio/publish/versioning
and     https://developer.android.com/studio/publish/app-signing

A: Primarily for older phones
I only encountered the App not installed error when trying to install an apk on my phone which runs on 4.4.2 aka KitKat, but my friend did not encounter this error on his phone which runs on 6+. I tried the other solutions such as removing the old/debug version of the app because the apk was a release version, clearing the debug app's data, and even clearing all of my cached data. Then, finally I realized all I had to do was select both signature versions when building my signed apk.

Before I only had V2 (Full APK Signature) selected, but after selecting V1 Jar Signature as well, I was able to successfully install my signed APK on my 4.4.2 device.

A: For those who are using Android Studio 3.
Suryanarayana Reddy's Answer is correct thought it doesn't state steps to solve it, hence.
in your AndroidManifest.xml under the application tag add testOnly="false"  and android:debuggable="true" like so:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:testOnly="false"
    android:debuggable="true"
    >

Edit then in AndroidStudio's menubar Build > Build APK(s)

A: For me, On Android 9 (API 28), disabling Google Play Protect from play store app worked the trick, and i was able to get rid of the App not Installed error.

To disable Google Play Protect. Open "Play Store" application => tap
  on Menu button => select "Play Protect" option => Disable the options
  "Scan device for security threats".

A: This can happen if you have your MainActivity declared twice in your AndroidManifest.xml.
Another possible reason: you changed the launch activity. Hint: never do it with already published applications! Reasons discussed in Android Developers blog.

A: I had the same problem. I did not realise that an app must be signed even for testing.
After self signing it, it installed fine.

A: In Marsmallow in owner and guest user is there.If guest installed the same app we can not install the same app in owner.I fixed this delete the app in guest

A: Open your logCat when trying to install the app. Set it to "No Filters". Search for "InstallAppProgress" package identifier. If the install fails you should see an "Installation error code". In my case it was
D/InstallAppProgress: Installation error code: -7

From here you can use this link to find information about your specific error code.

A: This answer is relevant only for apps that use native libraries (Android NDK).
In my case the problem was that some native libraries were missing from jniLibs for the target phone's CPU architecture. Hence the app was working on the emulator, but on a real phone I got "App not installed".
I had originally copied the compiled native libraries only for the x86 architecture, so the app worked on the emulator. However, the other architectures were missing (x86_64, armeabi_v7a, arm64-v8a). After adding the missing *.so files for all architectures into jniLibs, the "App not installed" error went away.

A: It can also happen if there is not enough space in the internal memory. I had 500Mb free, but it wasn't enough. Try free like 1Gb+.

A: Sometimes it is because you have no enough space on your phone. If so, try to clean up your memory to create space for new installations.

A: I had a similar situation.I was able to install app in debug mode using USB but not a signed version. I was able to install signed version on other phone, but not on my device. Numerous reasons and solutions did not help me. But one direction I got from a solution "uninstall for all users".
What I did is to again install app in debug mode using USB connection, go to app details and "uninstall for all users" from right top 3 dots - to remove debug version. This looks like cleared all kinds of references. I usually do a normal uninstall.
Now I am able to get signed APK on the device and install and its success.

A: I found that if I built my app with compileSdkVersion, buildToolsVersion, and targetSdkVersion all set to the default value of 30 in my build.gradle file, then the app would not install on my phone. However, if I changed them back down to version 29, it worked. What the issue turned out to be was that from SDK 30 onwards you need to select V2 jar signing. For more info see Why does the Android SDK 30 generate invalid APK files?

A: I had a similar issue and it was because I was trying to install an apk on a phone with a previous version of the same apk, and both apks hadn't been signed with the same certificate. I mean when I used the same certificate I was able to overwrite the previous installation, but when I changed the certificate between versions, the installation was not possible. Are you using the same certificate?

A: My problem was: I used the Debug Apk, that was generated while I did the Run command from Android Studio
Solution was: Instead of using this file, clean project and click Build > Build APK(s) from Android Studio. Then you can use the generated APK from the usual folder (app/build/outputs/apk/debug/)
The file that was generated like this installed without a problem.

A: I had the same problem and here is how solved it : Go to the Manifest file and make sure you have the "Debuggable" and the "Test Only" attributes set to false. It worked for me :)

A: I had the same issue, i.e. App showed up as being installed, but would not launched when the icon was tapped. After some head-banging, I found that I had stupidly placed ' android:exported="false" ' for my main launcher activity within the AndroidManifest file.... Once I removed it, the App launched fine..

A: Clearly there are many causes of this problem. For me the situation was this: I had deployed to my nexus 7 (actual device) from within the Android Studio (v1.3.2). All worked fine. I then created a signed apk and uploaded to my Google Drive. After disconnecting my nexus from the usb, I went to the settings/apps and uninstalled my app (App1). I then opened google drive and clicked on my App1.apk and chose to install it (need to ensure you have allowed installation of apks in settings). Then I got the dreaded message "App not Installed"
Solution for me: go back into settings/apps and scroll though all apps and at the bottom was a pale version of my App1 (note the original App1 was at the top in Alphabetical order which was deleted as above). When clicking on the pale version it said "Not installed for this user". (I had set up my nexus to have more than one user). But in the top right corner there is a three dot button. I pressed this and it said "Uninstall for all users". Which I did and it fixed the problem. I was now able to click on App1.apk and it installed fine without the error.

A: I know this is an old post, but for new users may be useful. I had the same problem: my application worked fine while debbuging. When I signed the APK I got the same message: "Application not installed".
I fixed that uninstalled my JDK (I was using jdk-6u14-windows-x64) and installed a new one (jdk-6u29-windows-x64). After export and sign the APK again, everything was ok!
Resuming, my problem was in JAVA version. Thank's Oracle!!

A: My problem was that I have multiple user accounts on the device. I deleted the app on 1 account, but it still was installed on the other account. Thus the namespace collided and did not install. Uninstalling the app from all user fixed it for me.

A: I faced a similar issue today and at first i thought it was my sd card which corrupted it. I tried it on many devices running android 4.4 and up but it kept bringing the same issue.After some googling and research i realized that i didn't select the v1 jar signature which is for devices older than android 7.0 nougat so i applied both of these signatures by selecting the two check boxes and generated a signed apk and it worked.

Link to solution Android – App not installed error when installing a signed APK – How to Fix

A: I had the same type of error this was cauysed by this line in my android manifest XML file.
android:permission="android.permission.INSTALL_LOCATION_PROVIDER"

I removed the line and it solved my issue. Hope this helps

A: When this problem happened to me, I fixed it by deleting some non-essential files that I had in my project folder, like the keystore.
In hindsight, it'd probably be bad to give people the keys to your game.

A: In my case my previous released app had signed by another key, so I've uninstalled it, but on my test phone (LG G4 H-818) 2 users exists so previous app still installed on my phone and didn't uninstalled properly! so when I tried to install it again, it failed...
So I've tried to change user and uninstall previous app, finally app installed properly.
Hope it helps you in future :)

A: I have encountered this issue in various forms, but this time it was a new one:
In this case, I had providers names collision - the same provider name existed in my app and another of my apps.

A: If you are trying to install an apk directly from Google Drive, just restarting the device solved the issue for me.

A: I have experienced this "App not installed" error when the device I was installing to didn't have enough storage. Deleting a few files allowed the app to install. Odd that it didn't give me a "not enough space" message instead. (Note: I was installing an apk manually from an "unknown" location.)

A: If you are using cordova try to uninstall any previous app that is build through cordova.
Strange but this method solved my problem

A: You should save this as Debug and not release, check the two JAR signs and also allow installing apps from where you have downloaded this (WhatsApp, chrome, etc...)

A: I tried all the methods that are generally posted,
Was just about to give up,
The signing thing solved it.
Found some app that literally said "apk signer", and it did it.

A: I ran into this when I had a bug with my custom build tool that would use ADT with a certificate intended for iOS (It certainly wasn't my first guess, since there doesn't seem to be anything special about the Android certificates other than only you should have one, they are just RSA-1024 certs, even self-signed is ok, at least for non-marketplace installs).

A: I'd signed the app with 2 different certs, so removing the older version with the older cert and then reinstalling the new one solved the problem for me

A: I fixed this by not signing the app first and not with Maven. I added this to my build path.
    <plugin>
        <groupId>com.jayway.maven.plugins.android.generation2</groupId>
        <artifactId>android-maven-plugin</artifactId>
        <inherited>true</inherited>
        <configuration>
            <sign>
                <debug>false</debug>
            </sign>
        </configuration>
    </plugin>

After that I signed my app by hand: jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore /home/myself/.android/release.keystore myapp-1.0.apk androidreleasekey

A: try to this change in the AndroidManifest.xml:

*

*setting debuggable to true

*signing the apk

A: Make sure that these tips considered:

*

*Your build variants and Flavors should be same(App installed and new one), usually release

*Signature file must be the same(*.jks file)

*The version you set in build.gradle or AndroidManifest have greater value compared to current version(it is recommended to set version in build.gradle)

*URL is correct(doesn't have typo) and server is reachable(WebService/WebMethod/WIFI is running/available and ...)

*File downloaded completely

*File saved correctly into desired directory

*Setting for Data and Type in setDataAndType is correct

A: I also faced the same issue.
In my application had services in it.
The services was running in the background even after the application was uninstalled, after doing a force stop of the application, got a message saying the application was uninstalled.
Then I installed the application with out any problem.

A: If you tried all the answers above and none of them worked, you might want to try this:
If your build variant is 'debug', then you should add this under buildTypes in the app build gradle for the app to install on your device:
debug {
    minifyEnabled false
}

A: I faced this issue with my latest app release to playstore. The issue is combination of change of MainLauncher and app shortcut .
We have added a splash screen and our entry point is SplashActivity instead of MainActivity. So, people who has previous versions and have app shortcut on their home screen can't open the app. It always says something like App not installed toast. This doesn't happen on every launcher (For us it's more common on Samsungs).
Behind the scenes, App shortcut should be seamlessly update entry point from MainActivity to SplashActivity. But, for some reason many third party launchers are not obeying it. The fix is clear the shortcut and add it again.
If you havn't update your app yet in playstore, go through this article.
Beware when updating the launcher activity.

A: *

*delete .apk file from build>output>apk folder in your app module(project main module).

*delete .idea and .gradle folder from root of the project

*clean the project.

*click on gradle icon from sidebar in android studio and click sync icon to refresh all project.
now run the project and it should work.

A: If someone is having this issue, check the build number. If your build number is less than the installed app build number, your app will not install and you will get the "Corrupted app or apk file".
To fix it just increment your build number until it is equal or greater than the installed build number.

A: In my case i removed Useless permissions that are not required
I Only Needed 1 permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

And remove unwanted permissions that are not required and started giving this error
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />

A: Sometimes storage not available is also should be mention because I face this issue because that the device that needs to be installed doesn't have enough space and also the system is not alert to the user. You can just find out because of debugging

A: In case, you have your app's older version installed from Google Play and you want to test the newer release version of your app:

*

*Open Google Play Console

*Upload the newer release version of your app to Alpha / Beta, but do not release it yet!

*You can now download the derived apk:

Install the downloaded derived apk on your phone now.
The derived apk is re-signed by Google Play with a different key from the release app Android Studio generates.


text:
Q: dyld: Library not loaded: /usr/lib/libcurl.4.dylib curl SSL error I'm not sure what happened to my system but I am having an issue with dyld/curl, affecting my overall computer performance. I am on Yosemite.
I have a feeling it's the Conda openssl. How do I just link to the normal os X openssl?
If I try to use curl ssl (for example, to install rvm with the command:
curl -sSL https://rvm.io/mpapis.asc | gpg --import -

And I get the following error:
dyld: Library not loaded: /usr/lib/libcurl.4.dylib
  Referenced from: /usr/local/bin/gpg
  Reason: no suitable image found.  Did find:
    /usr/lib/libcurl.4.dylib: mach-o, but wrong architecture
    /usr/lib/libcurl.4.dylib: mach-o, but wrong architecture
(23) Failed writing body

I've taken a look at these threads but my problem seems different. Can someone help me out? It seems like I might need to create a link but I don't know what that means or how to make one.
which curl gives:
/opt/local/bin/curl

curl --version gives:
curl 7.39.0 (x86_64-apple-darwin14.0.0) libcurl/7.39.0 OpenSSL/1.0.1j zlib/1.2.8 libidn/1.29

git version is 2.1.3
which openssl gives
`//anaconda/bin/openssl`

Which git gives:
/usr/local/bin/git

A: Your which curl returns this:
/opt/local/bin/curl

Which is odd, since curl is not really a magical program that needs to be installed in the /opt/ directory and which curl on a standard Mac OS X install should be here:
/usr/bin/curl

My guess is the version of curl installed in /opt/local/bin/ is built against another system architecture (32 bit?) but the core system /usr/lib/libcurl.4.dylib stuff is set for 64 bit.
The quickest/safest thing to do if you want to instal Ruby via the method you describe is to explicitly call the core Mac OS X install like this:
/usr/bin/curl -sSL https://rvm.io/mpapis.asc | gpg --import -

But that said, if I were you I would follow the basic instructions on this RVM install page here to get it up and running. Then again, it seems like you have files tossed all over your install conflicting with each other so perhaps the /usr/bin/curl method is the safest? Seems that way to me.


text:
Q: Serial library on Mac OSX Has someone tried to extend the use of the C code in:
http://www.teuniz.net/RS-232/
to Mac OSX ?
It is limited on compilation to Linux and Windows by preprocessor directives. However, it should be extendible to other POSIX OS, like MAc OSX. I saw some code for Mac that uses more or less the same functions. Thanks.


text:
Q: undefined method translate during Rails 2.3 -> 3.2 upgrade Working on upgrading a Rails 2.3.17 app to Rails 3.2.22.2 (running ruby 1.9.3-p551). Was able to get through the painful portion of ugprading all the gems / updating the directory structure / adding in all new/updated rails files.
The rails server is now coming up, but when i try to load up the first page, it fails with this stack trace:
NoMethodError: undefined method `translate' for #   <I18n::Backend::ActiveRecord:0x007ff64dc72400>
/myapp/vendor/bundle/ruby/1.9.1/gems/i18n-0.7.0/lib/i18n/backend/chain.rb:46:in `block (2 levels) in translate'
/myapp/vendor/bundle/ruby/1.9.1/gems/i18n-0.7.0/lib/i18n/backend/chain.rb:44:in `catch'
/myapp/vendor/bundle/ruby/1.9.1/gems/i18n-0.7.0/lib/i18n/backend/chain.rb:44:in `block in translate'
/myapp/vendor/bundle/ruby/1.9.1/gems/i18n-0.7.0/lib/i18n/backend/chain.rb:43:in `each'

...
Additional notes: I have an locale.rb file in the config/initializers/ folder, which has this:
require "i18n/backend/cache"

I18n::Backend::ActiveRecord.send(:include, I18n::Backend::Memoize)
I18n::Backend::ActiveRecord.send(:include, I18n::Backend::Flatten)
I18n::Backend::Simple.send(:include, I18n::Backend::Memoize)
I18n::Backend::Simple.send(:include, I18n::Backend::Pluralization)
I18n::Backend::Chain.send(:include, I18n::Backend::Cache)
I18n.backend = I18n::Backend::ActiveRecord.new
I18n.backend = I18n::Backend::Chain.new(I18n::Backend::Simple.new, I18n.backend)

My Gemfile looks like:
source "http://rubygems.org"

gem "rails", "3.2.22.2"
gem "rake", "11.1.0"
gem "a9n", "0.3.0"
gem "geoip-c"
gem "josevalim-auth_helpers"
gem "delayed_job", "~>3.0.5"
gem "mysql2"
gem "activemerchant", "1.43.3"
gem "liquid"
gem "paperclip"
gem "mechanize", "2.7.4"
gem "net-ssh", "~>2.9.4"
gem "net-sftp", "2.0.5"
gem "authlogic", :git => "git://github.com/binarylogic/authlogic.git"
gem "rd_searchlogic"
gem "rack", "~>1.4.5"
gem "activerecord-mysql2-adapter"
gem "declarative_authorization"
gem "inherited_resources"
gem "acts_as_audited"
gem "rails-indexes"
gem "geocoder"
gem "has_magic_columns"
gem "grimen-delayed_job_mailer"
gem "asset_packager"
gem "recaptcha", "0.4.0"
gem "libxml-ruby"
gem "xml-simple"
gem "haml"
gem "airbrake", "~>4.3.7"
gem "sinatra"
gem "newrelic_rpm"
gem "will_paginate"
gem "rexml-expansion-fix"
gem "hominid"
gem "money"
gem "aasm", "~>3.4.0"
gem "dalli"
gem "acts-as-taggable-on"
gem "i18n"
gem "i18n-active_record", :require => "i18n/active_record"
gem "hpricot"
gem "rest-client"
gem "nokogiri", "~>1.6.8"
gem "exact-target"
gem "pdfkit"
gem "json"
gem "savon"
gem "twilio-ruby"
gem "oj"
gem "httparty"
gem "rforce"
gem "ruby-ntlm"
gem "ffaker"
gem "simple_qs"
gem "time_difference"
gem "aws-sdk-v1"
gem "wkhtmltopdf-binary"
gem "gyoku"
gem "mime-types"
gem "highline"
gem "exifr"
gem "encryptor","~>1.3.0"
gem "docile"
gem "american_date"
gem "gon", "~>4.0.0"
gem "rmagick", "~> 2.0" # for ruby 1.x, since 2.0 it could be removed

group :staging do
gem "ruby-prof"
end

gem "capistrano", "~> 2.15"
  gem "capistrano_deploy_lock"
  gem "hipchat"
end

group :spreadsheet do
  gem "spreadsheet"
end

group :gpg do
  gem "gpgme"
end

group :mail do
  gem "mail"
  gem "bounce_email"
end

group :development, :staging do
  gem "pry"
  gem "pry-remote"
end

group :development, :test do
  gem "rspec-rails", "~> 3.0.0"
  gem "rspec", "~> 3.0.0"
  gem "rspec-core", "~> 3.0.0"
  gem "rspec-expectations", "~> 3.0.0"
  gem "fabrication"
end

group :test do
  gem "bourne", "~> 1.2.1", :require => false
  gem "database_cleaner", "0.9.1"
  gem "mocha", "0.12.7", :require => false
  gem "rack-test"
  gem "simplecov"
  gem "timecop"
  gem "test-unit", "~>3.0"
  gem "shoulda-matchers", "1.0.0", :require => false
end

any ideas why it might be generating that error message ?


text:
Q: Is there are way to open an iMessage extension from within the container app? So far I've been encountering scenarios where you can launch the embedding app from the extension using the openURL: method, but is there a way to achieve the opposite?
I'm interested in knowing whether it would be possible to do something in my container app that creates an MSMessage instance and launches my iMessage app extension. Is this doable?

A: If anyone else is interested, as of Xcode 8.0 beta 6, MFMessageComposeViewController declares a property message of type MSMessage that lets you create an interactive message from within a springboard application so it can be used to achieve what I wanted in the first place. It does not, however, let you open a container app application.
Here's my code:
let message = MSMessage()
message.url = // Your message url
message.layout = MSMessageTemplateLayout()
message.summaryText = // Summary text

let messageViewControler = MFMessageComposeViewController()
messageViewControler.message = message

show(messageViewControler, sender: self)

A: Unfortunately, this is not currently possible. You can read it in this thread: https://forums.developer.apple.com/thread/50375


text:
Q: Show that a solution is linear and find its matrix in the usual basis. On $\mathbb{R}^3$, define $$A(x) = (x \cdot a)a + 2(x \cdot b)b$$  Here $$a = \begin{pmatrix} 1 \\ 0 \\ -1 \end{pmatrix}, b = \begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}$$
Show that A is linear and find its matrix in the usual basis.
I did out the above equation and got $A(x) = (x*a \cdot a^2) + 2(x*b + b^2)$.  This reduces to $0+2x$.
I understand that the usual basis means that $$e_1 = \begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}, e_2 = \begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}, e_3 = \begin{pmatrix} 0 \\ 0 \\ 1 \end{pmatrix}$$
Did I do the matrix algebra incorrectly or is the answer the actually $2x$?  If so, $2x$ is linear, but you cannot reduce that to a basis in $\mathbb{R}^3$.

A: $$A\left(\begin{array}{c}x\\ y\\ z\end{array}\right)=(x-z)\left(\begin{array}{c}1\\ 0\\ -1\end{array}\right)+2y\left(\begin{array}{c}0\\ 1\\ 0\end{array}\right)=\left(\begin{array}{c}x-z\\ 2y\\ -x+z\end{array}\right)=\left(\begin{array}{rrr}1 & 0 & -1\\ 0& 2& 0\\ -1& 0& 1\end{array}\right)\left(\begin{array}{c}x\\ y\\ z\end{array}\right)$$


text:
Q: Php Laravel - How to show xml file in browser I produced xml file in my directory. I want to show this file in browser using php?
(I want to show that as sitemap)
Here is my code :
   public function siteMap()
    {
        $test_array = array (
            'bla' => 'blub',
            'foo' => 'bar',
            'another_array' => array (
                'stack' => 'overflow',
            ),
        );

        $xml_template_info = new \SimpleXMLElement("<?xml version=\"1.0\"?><template></template>");

        $this->array_to_xml($test_array,$xml_template_info);
        $xml_template_info->asXML(dirname(__FILE__)."/sitemap.xml") ;
        header('Content-type: text/xml');
        dd(readfile(dirname(__FILE__)."/sitemap.xml"));
    }

    public function array_to_xml(array $arr, \SimpleXMLElement $xml)
    {
      foreach ($arr as $k => $v) {
          is_array($v)
              ? $this->array_to_xml($v, $xml->addChild($k))
              : $xml->addChild($k, $v);
      }
      return $xml;
   }

And here is sitemap.xml:
<?xml version="1.0"?>
<template><bla>blub</bla><foo>bar</foo><another_array><stack>overflow</stack></another_array></template>

Here is result :

I want show this xml file in my browser, Any idea for doing this correctly?
EDITED : Here is result with header('Content-type: text/plain');

It consist of some extra reports.

A: Assuming that the content of xml is in $xml variable, you can use one of the followings:
return response($xml, 200)->header('Content-Type', 'application/xml');

OR
return response($xml, 200, ['Content-Type' => 'application/xml']);

A: In your view create sitemap.blade.php.
Insert content xml in your sitemap.blade.php.
Create a function called sistemap.
 public function sitemap(){

     return response()->view('sitemap')->header('Content-Type', 'text/xml');

 }

In your routes:
 Route::get('sitemap', function () {
     return view('sitemap');
 });

A: Change your route to this:
Route::get('/sitemap.xml', function (Request $request) {
     return response()->view('sitemap')->header('Content-Type', 'text/xml');
});

A: Try:
<?php

public function array_to_xml(array $data, \SimpleXMLElement $xml) {
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            if (is_numeric($key)) {
                $key = 'item' . $key; //dealing with <0/>..<n/> issues
            }
            $subnode = $xml->addChild($key);
            $this->array_to_xml($value, $subnode);
        } else {
            $xml->addChild("$key", htmlspecialchars("$value"));
        }
    }
}

public function siteMap()
    {
$data = array(
        'bla' => 'blub',
        'foo' => 'bar',
        'another_array' => array(
            'stack' => 'overflow',
        ),
    );

    $xml_template_info = new \SimpleXMLElement("<?xml version=\"1.0\"?><template></template>");
    $this->array_to_xml($data, $xml_template_info);
    $xml_template_info->asXML(dirname(__FILE__) . "/sitemap.xml");
    header('Content-type: text/xml');
    die(readfile(dirname(__FILE__) . "/sitemap.xml"));
//or return readfile(dirname(__FILE__) . "/sitemap.xml");
    }

A: That error is telling you exactly what's wrong with the output. There's a lot of extra content after the </template> tag is closed. Nothing will display it as XML, because it's not valid XML. Something is sending the extra data!
Perhaps try an exit(); after the readfile call.

A: If you want to just show the contents of an xml file in browser same way as they look in xml file,just write name_of_xml_file.xml in url after the base address.
For example:

www.example.com/name_of_xml_file.xml

regardless of where you place it.
It should be in your websites folder and just use a function to redirect to that page if you want to autoload when a certain thing happens.

A: What I did was add the xml file in the public folder of Laravel. Something like sitemap.xml. So you can easily access it with http://yourdomain.com/sitemap.xml.

A: Laravel's dd function outputs a bunch of HTML to let you browse the debugging input. It's intended for debugging, not outputting normal stuff to the page. You shouldn't be using it like this.
Instead of
dd(readfile(dirname(__FILE__)."/sitemap.xml"));

try
return readfile(dirname(__FILE__)."/sitemap.xml");

A: I created a Laravel xml response package: https://github.com/mtownsend5512/response-xml
Install that and it's as simple as:
$test_array = array (
        'bla' => 'blub',
        'foo' => 'bar',
        'another_array' => array (
            'stack' => 'overflow',
        ),
    );
return response()->xml($test_array, 200, [], 'template');

And you get:
<?xml version="1.0"?>
<template>
    <bla>blub</bla>
    <foo>bar</foo>
    <another_array>
        <stack>overflow</stack>
    </another_array>
</template>

A: Create a route:
Route::get('sitemap.xml', 'SitemapController@index')->name('sitemapxml');

Put this code in your controller:
public function index() {
    $posts = Post::where('status', '=', 1)->get();
    return response()->view('sitemap_xml', ['posts' => $posts])->header('Content-Type', 'text/xml');
}

Put this code in your view file:
<?= '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    @foreach ($posts as $post)
        <url>
            <loc>{{ url($post->url) }}</loc>
            <lastmod>{{ $post->updated_at->tz('UTC')->toAtomString() }}</lastmod>
            <changefreq>monthly</changefreq>
            <priority>0.7</priority>
        </url>
    @endforeach
</urlset>


text:
Q: Vue.js dynamic component with dynamic data I'm trying to use the <component> element to dynamically display a chosen component. Each of these displayed components can take one of any number of data objects. Something like:
<div id="containers">
    <component v-bind:is="currentView"></component>
</div>

var myVue = new Vue({
    el:"#containers",
    data:{
        currentView: "my-component-one",
        currentData: {...}
    },
    method: {
        changeView: function(){
            //change this.currentView
            //change this.currentData
        }
    }
});

However, the Vue documentation says the v-bind:is attribute can be used to pass either a component name or the options object.
It is unclear how I would conditionally get an object of values for that component to use and also conditionally change which component is shown.
I am very green with using Vue (coming fresh off a knockout kick) so perhaps I am simply misunderstanding the intention of the component tag.

A: you can simply use v-bind
html
<component v-bind:is="currentView" v-bind="data"></component>

script
data()
{
    return {
        data: {
            currentData: "example"
        }
    }
}

and it will pass currentData down to child. You can also add other properties along with it, including is.
If you need to change the component along with props, then you just change the data property, or whatever you want to call it.
https://codesandbox.io/s/7w81o10mlx

A: This example might help you understand it. https://jsfiddle.net/jacobgoh101/mLbrj5gd/

For passing Component Name
If the component is global, you can pass the component name to v-bind:is
for e.g.,
Vue.component('test1', {
    template: `<div>test1</div>`
})

HTML
<component is="test1"></component>

For passing option
A Vue component is literally just a Javascript object with specific properties
for e.g.,
  <component v-bind:is="{
    template: `<div>test2</div>`
  }"></component>


text:
Q: Led strip light in threejs What could be the best way to simulate a led strip light in threejs like in the image? Is there any example around to make something similar?

A: It really depends on what kind of realism you want. There are always ways of making effects more realistic, but it quickly becomes rather complicated.
If we limit ourselves to THREE.js out-of-the-box functionality, though, we have the following light types at our disposal:

*

*AmbientLight

*DirectionalLight

*HemisphereLight

*PointLight

*RectAreaLight

*SpotLight

And out of these, I would personally recommend RectAreaLight, because it represents an area light (the shape of which you can specify to match that of your led strip lights), which is a rectangle that emits light uniformly across its face. A lamp such as those in your picture do perhaps not emit light completely uniformly, but depending on what your goal is, it might be a close enough approximation. You may also combine several area lights to pursue certain effects.


text:
Q: Behavior of compactly supported functions on boundary Let $v(x, t): \mathbb{R} \times [0, \infty) \rightarrow \mathbb{R}$ be a smooth function with compact support in $\mathbb{R} \times [0, \infty)$. Is there an example of a $v$ which does not satisfy $v(x, 0) = 0$?

A: Sure, take a bump function. Like $\nu(x,t)=e^{-\frac{1}{1-t^2}-\frac{1}{1-x^2}}$ for $\lvert x\rvert,t<1$, 0 else. Then we have $\nu(x,0)\neq 0$ if $\lvert x\rvert<1.$