text:
Q: passing multiple data in $.ajax based in if condition I want to pass 4 parameter for role number 7 and 3 parameter for other role.now getting error in if condition.How to pass multiple data in if condition

Uncaught SyntaxError: Unexpected token ==

$.ajax({
                    url: 'bulkUpdate',
                    type: 'get',
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    if(role==7){
                    data: {
                        'ids'  : join_selected_values,
                        'role' :role,
                        'prices':selected_price,
                        'currency':selected_currency
                    },
                    }
                    else{
                    data: {
                        'ids'  : join_selected_values,
                        'role' :role,
                        'comment':comment
                    },
                    }
                    success: function (data) {
                    console.log('success');
                    },
                    });

A: That's because you're providing an incorrect syntax. Simply build the data object outside if the AJAX request:
var ajaxData = {
    ids: join_selected_values,
    role: role
};

if (role === 7) {
    ajaxData['prices'] = selected_price;
    ajaxData['currency'] = selected_currency;
} else {
    ajaxData['comment'] = comment;
}

$.ajax({
    url: 'bulkUpdate',
    type: 'get',
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    data: ajaxData,
    success: function(data) {
        console.log('success');
    },
})

A:

$.ajax({
  url: 'bulkUpdate',
  type: 'get',
  headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},

  data : role==7 ? {
                        'ids'  : join_selected_values,
                        'role' :role,
                        'prices':selected_price,
                        'currency':selected_currency
                    } :  {
                        'ids'  : join_selected_values,
                        'role' :role,
                        'comment':comment
                    },

  success: function (data) {
    console.log('success');
   },

});

Since $.ajax({}) accepts a object if(role==7){ will not work directly.
So either user ternary operator or decide the value prior to calling ajax function.
var data = {};

if(role==7){
 data =  { 'ids'  : join_selected_values,
            'role' :role,
             'prices':selected_price,
             'currency':selected_currency
          },
 }else{
   data =  {'ids'  : join_selected_values,
             'role' :role,
            'comment':comment
          },
  }

A: You are using if-else in $.ajax object. So, what you can do is that you can compare your condition and then create a data object outside the $.ajax call. Using this will prevent that error.
var role = 10;
var data;
if(role == 7){
      data = {
          'ids'  : join_selected_values,
          'role' :role,
          'prices':selected_price,
          'currency':selected_currency
        }
      }else {
      data = {
          'ids'  : join_selected_values,
          'role' :role,
          'comment':comment
      }
}
$.ajax({
        url: 'bulkUpdate',
        type: 'get',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: data,
        success: function (data) {
          console.log('success');
        }
});

A: You can do it like below
 var datatosend = { ids: join_selected_values, role: role}
    $.ajax({
        url: 'bulkUpdate',
        type: 'get',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: {data:datatosend},
        success: function(data) {
            console.log('success');
        },
    });

You will get all your parameters in server side and do your other procedures as per role.


text:
Q: How to make a trigger fire correctly with a union of inserts I am trying to build a trigger for a table called B. The trigger will fire when rows are inserted into B, and decrement a column by one (called seats, that starts at 10) in another table(called F).
My problem is that I am forced to insert into B with a union of inserts, and the trigger only updates the relevant column in F once for each key, instead of for each row inserted.
My tables look like this
 B                                  F
------------------                 ------------------
CODE   DATE   id                   CODE  DATE  seats

so code and date is the relevant foreign key between the two tables.
An example of the insert statement I must follow is
    Insert into B;
    select 'JA100','11/30/16',81108 union
    select 'JA110','11/28/16',38003 union
    select 'JA110','11/28/16',87822 union
    select 'JA130','11/28/16',33850 union
    select 'JA100','11/30/16',69696 union
    select 'JA100','11/30/16',75657 union

The trigger I have written is
 BEGIN
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
    BEGIN
        UPDATE F
        SET seats = seats - 1
        FROM F F, inserted I
        WHERE I.code = F.code AND I.date = F.date
    END

What I end up getting from this is 9 in the seats column for all three F's when it should be 7 for JA100, 8 for JA110, and 9 for JA130.
How do I fix this so it works? Thanks for your time.

A: You would have to aggregate seats per id/date and decrement the aggregate from the table that tracks seat count.
Updated version of trigger below. Also see http://sqlfiddle.com/#!18/bb0da/1 for working example.
create trigger insert_DecrementSeats on b
for insert
as
begin
    ;WITH seatsAggregated AS (
        SELECT [code], [date], COUNT(*) AS seats
        FROM
            inserted i
        GROUP BY [code], [date]
    ) UPDATE f
    SET f.seats = f.seats - a.seats
    FROM
        f
        INNER JOIN seatsAggregated a ON f.[code] = a.[code] AND f.[date] = a.[date]
end

go

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unexpected behavior using BSON: @load in Julia So, I am training a neural network model using Flux package in Julia. During training, each iteration that acquires an improvement in the model, the latter is saved in my computer.
For this, I use the line:
if acc_te[epoch_i] >= best_acc
     @info(" -> New best accuracy! Saving model out to mymodel.bson")
     @save "mymodel.bson" m
     best_acc = acc_te[epoch_i];
     last_improvement = epoch_i;
end

Which I assume is pretty standard (I extracted it from model-Zoo).
At the end of the training, it is fair to assume that the saved model "mymodel.bson" is the best I got. So far so good!.
Now, the problem:
Next morning, I open a terminal and this is what happens (every time is the same):
julia>using Flux;
julia>using BSON: @save
julia>using BSON: @load
julia> @load "mymodel.bson" model
ERROR: KeyError: key :model not found
Stacktrace:
 [1] getindex(::Dict{Symbol,Any}, ::Symbol) at ./dict.jl:477
 [2] top-level scope at /home/gbrunini/.julia/packages/BSON/XAts7/src/BSON.jl:53
julia>
julia> #maybe try another name
julia> @load "mymodel.bson" someothername
ERROR: KeyError: key :someothername not found
Stacktrace:
 [1] getindex(::Dict{Symbol,Any}, ::Symbol) at ./dict.jl:477
 [2] top-level scope at /home/gbrunini/.julia/packages/BSON/XAts7/src/BSON.jl:53
julia> #maybe try another name
.....same error...
julia> #maybe try another name
.... same error....
julia> #maybe try another name
.... same error....
julia> #maybe try another name
julia>@load "mymodel.bson" m     # eureca! this name works!

Why is this happening? Are there some forbidden names?
Sometimes it works with other names, but I always have to try at least 5-6 different names until I find someone that works! t's getting annoying
What am I doing wrong?
Thanks in advance and stay safe!

A: The macros BSON.@save and BSON.@load store the variable with the exact given name. You cannot restore it under a different name.
using BSON
x=5
BSON.@save "mydoc.bson" x

This has stored the value 5 together with the name x.
If you try to recover it using wrong name it will not be found:
julia> BSON.@load "mydoc.bson" y
ERROR: KeyError: key :y not found

Rather than that - you need to recover with the original name - looks how the value gets overwritten:
julia> x=999
999

julia> BSON.@load "mydoc.bson" x

julia> x
5

So what to do when you need more flexibility? Use the BSON.parse function that returns a Dict and you can do with it whatever you need:
julia> BSON.parse("mydoc.bson")
Dict{Symbol,Any} with 1 entry:
  :x => 5

A: BSON uses Dicts to save and load
BSON does saving and loading based on a top-level Dict, which usually stores the variables by their name as their key (m in your case).
If you do the loading of your .bson you retrieve that dictionary and again instantiate the respective variables giving them their dict key as their name and their dict value as their value.
Taking a look at the README.md of BSON.jl showcases that already.
So in case you would want more flexibility you could directly save a Dict via BSON (check out the mentioned README.md) and do something like:
if acc_te[epoch_i] >= best_acc
     @info(" -> New best accuracy! Saving model out to mymodel.bson")
     bson("mymodel.bson", Dict(:model => m, <...other key-value stuff you want to save...>)
     best_acc = acc_te[epoch_i];
     last_improvement = epoch_i;
end

Bonus / Opinion
BSON offers better interoperability between the languages, but when it comes to saving/loading performance and file size, I found Serialization doing a better job. So just in case you want to check out alternatives depending on your use case.
[edit: fixed typo]

A: Since the BSON save the data as a dictionary, you can choose the key (keyname string) for the variable(s) you wish to save by supplying them explicitly (model->MNIST_model):
BSON.bson( "./models/MNISTmodel2023b.bson" , MNIST_model = model )

so the variable is 'model' which is save under the keyname MNIST_model which can be inspected
BSON.parse( "./models/MNISTmodel2023b.bson" )
->Dict{Symbol, Any} with 1 entry:
  :MNIST_model => Dict{Symbol, Any}(:tag=>"struct", :type=>Dict{Symbol, Any}(:t…

and now you can load it under the new name you provided
@load "./models/MNISTmodel2023b.bson" MNIST_model

and use it as so,
test_res = MNIST_model( xtest_batch )

If you forget the names of the keys for the file, you can always do
dict_bson = BSON.parse( "./models/MNISTmodel2023b.bson" )
string.( collect( keys( dict_bson ) ) )
1-element Vector{String}:
 "MNIST_model"


text:
Q: NSKeyedArchiver and iCloud Right now in my application I have a top level object with an -(void)archive method that will archive itself to the application's documents directory.
I'm wondering if it's possible to simply save the archive to iCloud rather than locally, by changing the file path.
I've read quite a bit on using iCloud, but I haven't seen this question addressed.  I'm guessing it is not possible, but I want to know for sure.
Thank you.

A: You shouldn't save a file directly to iCloud but save it locally and then move it to the iCloud folder associated with your app.
First you need to look at file coordination which you should use to save a file to iCloud.
Then you simply retrieve the URL or path for the file you want to save. You get your iCloud directory by calling: [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:@"myIdentifier"]; Then append the appropriate path components.
Finally you save the file (e.g.myFile.dat) to a temporary local folder like the Application's documents directory and then call: [[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:/*local URL*/ destinationURL:/*Cloud URL*/ error:&error]; This will  move the file from the local folder to the iCloud folder and then the OS' syncing daemon does the rest.
If you save into the iCloud documents directory, your file will be visible to the user via iCloud drive. If you save into a different iCloud directory, the user will not be able to see the file.
NOTE: you need to use NSMetadataQuery to discover files saved to iCloud by another device. Also iOS devices do not automatically download files that you save to iCloud; you need to specifically call [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:url error:&error]; to initiate a download. OS X devices will automatically download iCloud files. You can use the NSFilePresenter protocol to watch for changes to your iCloud directory during your app's lifetime (to detect files saved by another device).


text:
Q: How to send email in c# with Port id 465 and ssl "true" Can't send email by using this code,
Exception thrown "The Operation has time out."
Code:
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("xxx@gmail.com");
mailMessage.From = new MailAddress("yyy@domainName.com", "No-Reply");
mailMessage.Subject = "Test Mail";
mailMessage.Body = "E-Mail Testing...........";
mailMessage.IsBodyHtml = true;

SmtpClient client = new SmtpClient();
//client.Timeout = 200000;
client.UseDefaultCredentials = false;
client.Credentials =
   new System.Net.NetworkCredential("yyy@domainName.com", "--Password--");
client.Port = 465;
client.Host = "mail.domainName.com.np";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(mailMessage);

A: The EnableSsl option will NOT implicitly use SSL. That means it will not immediately begin SSL negotiations after connecting.
The EnableSsl option will enable explicit SSL. Which means SSL will be negotiated with the server using the STARTTLS command as described in RFC 3207.
System.Net.Mail does not support implicit SSL. You may have another port available from the server that you can use explicit SSL on. Otherwise you have to reconfigure your server.


text:
Q: Accessing base class typedef in derived class template I am trying to access a typedef member in base class from derived class template. In template name of template parameter is same as name of typdef in base class.
#include <iostream>

using namespace std;
class no {
    public :
    typedef int T;
};
template<typename T> class no1 : public no {
    public :
    T obj;
};
int main() {
    // your code goes here
    no1<string> o ; o.obj = "1";
    return 0;
}

14:24: error: invalid conversion from 'const char*' to 'no::T {aka int}' [-fpermissive]
  no1<string> o ; o.obj = "1";

In above code T is obj is always of type int. How can I force obj to be of template parameter and not typdef declared in base class ?
Thanks

A: this works for me :
template<typename T> class no1;
template<typename T>
struct underlying_type_of;

template<typename T>
struct underlying_type_of<no1<T> >
{
   typedef T type;
};
template<typename T> class no1 : public no {
public :
  typename underlying_type_of<no1>::type obj;
};


text:
Q: Create progress line using VBA excel I try to create progress line by using VBA Excel command
I have all of data to define what progress is but
I don't know how to use VBA for creating progress line
for an example I tried to use connector line but It's seem not work
ActiveSheet.Shapes.AddConnector(msoConnectorStraight, 60, 405,800, 477).Select
Range("Z20").Select
ActiveSheet.Shapes.Range(Array("Straight Connector 11671")).Select

A: I would not use a shape for a progress bar, instead use the data bars conditional formatting on a cell where the cell value is updated by the code
Create a named range on one cell on the worksheet as, for example, "ProgressBar"
Adjust the width to suit your needs
Format the cell as a Percentage
Choose Conditional Formatting -> New Rule -> Format all cells based on their values
In the "Format Style" drop down, choose "Data Bar"
Select the "Show Bar Only" checkbox
In the "Type" drop downs, for Minimum and Maximum, choose "Number"
In the "Value" text boxes, enter 0 for Minimum, 1 for Maximum
Set the formatting as you wish
In the VB Editor, enter the code below
Sub UpdateProgressBar()
    Dim Rows As Integer
    Dim RowItem As Integer

    Rows = 1000
    For RowItem = 0 To Rows
        Sheet1.Range("ProgressBar").Value = RowItem / Rows
    Next RowItem
    MsgBox "Done!"
    Sheet1.Range("ProgressBar").Value = 0
End Sub

This will then update the value in the cell and the data bar will grow as the value increases.
You will need to adapt to your own code, but this should be a starting point.

A: some ways of doing a progress bar:
use the application.statusbar
or, use a userform, in wich you change the width property of any rectangle type (i use a button with nice picture font)
use a shape, from wich you change the size by altering its width property.
the hard part is more making it fast enough so it doesn't affect performance, and sometimes
when adding application.screenupdating=false in conjonction to doevents, it might blink... (or not)
if you need some code i can provide you a sample, and you can change it according to your needs


text:
Q: Using pace.js on loading appended images I wanted to use pace.js to show a progress bar while the appended images are being loaded, they provided an API but I have no idea how it works.
$('#loadImg').click(function() {
  Pace.start();
  var $con = $('#content');
  $con.append('<img src="http://lorempixel.com/500/500/">').imagesLoaded(function() {
    console.log('done!');
    Pace.stop();
  });
});

I used it with desandro/imagesloaded to call Pace.stop() but I don't see any progress bars.
I made a demo plunk for your convenience.

A: You first need to disable pace on page load using:
"startOnPageLoad" : false

Also quoting from pace documentation:

Elements being rendered to the screen is one way for us to decide that the page has been rendered.

So we can say that loading of 'image' should successfully complete the pace progress:
"elements": {
    "selectors": ["#image"] // assign id="image" to img
}

Load the pace with these options provided in script tag:
data-pace-options='{ "elements": { "selectors": ["#image"] }, "startOnPageLoad": false }'

Now just call Pace.restart() every time click on link 'Load Image'.
No need to call Pace.stop(). (it automatically detects that #image is done loading)
Updated plunk


text:
Q: How can I use 2d array in Django's template in jQuery? I have a 2d array named "pre" in views.py . I have passed the same array in the template.html . I want to use the values of second column of each row of pre array as initial value for text boxes. Script is shown below.
Variable i.toString() is working fine with name of input tag but in values it is not working.
I want the value of {{pre.0.2}} as values of 1st textbox,{{ pre.1.2}} as value of second one and so on. How can I achieve that ?
<script>
    $(document).ready(function() {
        var max_fields = 10; //maximum input boxes allowed
        var wrapper = $(".input_fields_wrap"); //Fields wrapper
        var add_button = $(".add_field_button"); //Add button ID

        var x = {{branches}}; //initlal text box count

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

            if(x < max_fields){ //max input box allowed

                $(wrapper).append('<input name="main_address_'+i.toString()+'" value="{{pre.'+i.toString()+'.2}}" type="text" required=""><br>'); //add input box
            }

        }
</script>

If you have any other way to achieve the same result please share it with me.

A: That's very true that I don't need to use jQuery here. It can be easily implemented by {% for loop %} {% endfor %} in Django. Thanks for your comments.
{% for p in pre %}<input name="main_address_{{forloop.counter}}" value="{{p.2}}" type="text" required="">{% endfor %}


text:
Q: How can I recover MediaWiki pages from an old MAMP install? I have a three year old or so MAMP install (a copy of the application folder and all its contents, databases, etc.) with a three year old MediWiki (version 1.19) installed on it, several pages, and a few images.  I would like to know how I can access those pages (or at least the content on them) and import them or copy them over to a fresh install I made today with the latest versions of MAMP and MediaWiki.
I already tried copying the database folder (MAMP/db/mysql/my_database; contains .frm files) from the old install to the same location in the new install but it doesn't seem to have changed anything.  I even looked at the contents of the tables with phpMyAdmin but I didn't find any of the old content.  Where do I go from here?
I installed MAMP on my MacBook Pro running OSX Yosemite.  I'm hosting locally (e.g. using localhost).  I am able to install a fresh MediaWiki on my localhost MAMP server and it works fine (there's just no content).
UPDATE: After seeing this I changed $wgMainCacheType = CACHE_ACCEL to $wgMainCacheType = CACHE_ANYTHING in the MediaWiki local settings file and now I get an error page that looks like this:

Do I need to somehow upgrade my databases?  They are old after all.  How should I go about doing this?

A: Shutdown mysql
Just copying the MAMP/db/mysql/my_database is not enough
Copy the contents of your db folder and below to the new
MAMP db folder
Note i assume your new MAMP is pretty virgin
Poached it from here :
http://joejoomla.com/sound-off/157-how-to-upgrade-mamp.html
Start new mysql
Will incl necessary config files
It is not as if you should have expected MAMP to recurse directories
It needs config files from old and you don't have them yet
I have never done it on MAMP

Edit:
Concerning warning that resulted
Make sure that XCache is installed with the new version of PHP. The most likely cause is the new version of PHP simply doesn't have xcache installed. You can do this by creating a php file with just the code
<?php phpinfo(); ?>

and then viewing it in a web browser.
Setting $wgMainCacheType = CACHE_NONE; will disable all caching, which would prevent the error, but make things slow.
From: http://m.mediawiki.org/wiki/Thread:Project:Support_desk/%22CACHE_ACCEL_requested_but_no_suitable_object_cache_is_present.%22

A: Advice : for this kind of software, use a Virtual Machine, it will save your time : my own mediawiki is running for 8 years under debian, hosted on a several different Apple machines.
But for now, if you still have the former stack running :
0 . (always) save your database content + files

*

*for the database :
https://www.youtube.com/watch?v=NnOE0KWHGkY

*for the files :
tar cfvz my-old-mediawiki.tar.gz path-to-mediawiki-directory

This will allow you to rollback if something goes wrong

*

*Export your content and history

*

*go to the special page : "Export pages", list your pages.

*if needed, use the special page : "List all pages".

this will produce an xml file.

*Save your images somewhere on your file system

*

*use the special page : "List all files".

you now have exported your pages and files

3) Switch stack

check that the new virgin mediawiki is working well

*import your pages

*

*go to the special page : "import pages", upload the xml file produced in step 1

you now have a similar wiki, minus the files

*import your images :

*

*after the step 4, each file page has been created without its content.

*you can upload manually each image exported at step 2) if you have only some of them,

*if that is too much files (>30), you can use this procedure : https://www.mediawiki.org/wiki/Manual:ImportImages.php

keep in mind also to reinstall any extensions installed previously.


text:
Q: Ruby: How to pass the result of an block as an argument Can I some how pass the result of an evaluated block as an argument to a function?
This illustrates what I want to do by using a helper function (do_yield):
#!/usr/bin/env ruby

def do_yield
    yield
end

def foo a
   #'a' must be an array
   puts "A: [#{a.join(", ")}]"
end

foo (do_yield{
    a = []
    a << 1
})

Can I do this without creating my own helper function? Preferably by using facilities in the language, if the language does not offer a way to do it, then is there an existing function I can use instead of my own do_yield

A: So, you want to pass a result of executing some code into some other code? You just need to convert your "block" to an expression (by making it a proper method, for example)
def bar
  a = []
  a << 1
end

foo bar

If your code is really this simple (create array and append element), you can use the code grouping constructs (which combine several statements/expressions into one expression)
foo((a = []; a << 1))

or
foo(begin
  a = []
  a << 1
end)

Personally, I'd definitely go with the method. Much simpler to read.

A: The piece of terminology you probably want to search for here is lambda - a lambda being an anonymous function that can be passed around as a parameter.
So to do what you are describing with a Lambda you might do this:
my_lambda = lambda do
  a = []
  a << 1
end

def foo a
   #'a' must be an array
   puts "A: [#{a.join(", ")}]"
end

foo my_lambda.call

Of course you can have parameterised lambdas and if foo was expecting a lambda you could have it call #{a.call.join(", ")}] ( your actual code has double-quotes everywhere so not sure it would work ) so that the evaluation only happened when it was passed.
This is an interesting and powerful part of Ruby so it is worth learning about.


text:
Q: "Web site created using create-react-app." showing as description on all pages of my React App When I deploy my React site, "Web site created using create-react-app" show as the description on all pages rather than the Helmet description I have added.
I searched my entire project for "Web site created using create-react-app." and there are no results found. Where is this description coming from?

A: Look in /public/index.html, by default on line 10 you will see:

"Web site created using create-react-app"

A: You need to change your metadata in your index.html. In your meta tag, which, as Harley Lang pointed out would be on line 10 by default, you need to change your description to whatever description you want it to be, this description is the one that will show up in search engines.


text:
Q: Protobuf build fail in Yocto I'm using bitbake 1.32.0, Yocto 2.2.2 (Poky) trying to add protobuf-c to my build.  I keep getting a build failure on protobuf_2.6.1 (protobuf-c depends on protobuf).
I can manually download the Protobuf source code and cross-compile it without any problems.  But for some reason Yocto can't build it.
During the Yocto build process, libprotobuf-lite.so links okay, but libprotobuf.so fails linking due to these errors:
| /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/libc_nonshared.a(elf-init.oS): In function `__libc_csu_init':
| /usr/src/debug/glibc/2.24-r0/git/csu/elf-init.c:87: undefined reference to `__init_array_end'
| /usr/src/debug/glibc/2.24-r0/git/csu/elf-init.c:87: undefined reference to `__init_array_start'
| /home/cjholmes/gen4/build/tmp/sysroots/x86_64-linux/usr/libexec/arm-agl-linux-gnueabi/gcc/arm-agl-linux-gnueabi/6.2.0/ld: .libs/libprotobuf.so.9.0.1: hidden symbol `__init_array_end' isn't defined
| /home/cjholmes/gen4/build/tmp/sysroots/x86_64-linux/usr/libexec/arm-agl-linux-gnueabi/gcc/arm-agl-linux-gnueabi/6.2.0/ld: final link failed: Bad value

I have tried looking through the .o files that are part of libprotobuf.so but are not included in libprotobuf-lite.so, to see if anything directly references the missing symbols, but I haven't found anything useful yet.
For a while I thought the culprit was -nostdlib.  But then I saw libprotobuf-lite compiles just fine with that flag, and the -lc and -lgcc flags are included in the link command.
The recipe is a very straightforward autotools setup.
SUMMARY = "Protocol Buffers - structured data serialisation mechanism"
DESCRIPTION = "Protocol Buffers are a way of encoding structured data in an \
efficient yet extensible format. Google uses Protocol Buffers for almost \
all of its internal RPC protocols and file formats."
HOMEPAGE = "https://github.com/google/protobuf"
SECTION = "console/tools"
LICENSE = "BSD-3-Clause"

PACKAGE_BEFORE_PN = "${PN}-compiler"

DEPENDS = "zlib"
RDEPENDS_${PN}-compiler = "${PN}"
RDEPENDS_${PN}-dev += "${PN}-compiler"

LIC_FILES_CHKSUM =
    "file://LICENSE;md5=af6809583bfde9a31595a58bb4a24514"

SRCREV = "bba83652e1be610bdb7ee1566ad18346d98b843c"

PV = "2.6.1+git${SRCPV}"

SRC_URI = "git://github.com/google/protobuf.git"

EXTRA_OECONF += " --with-protoc=echo"

inherit autotools

S = "${WORKDIR}/git"

FILES_${PN}-compiler = "${bindir} ${libdir}/libprotoc${SOLIBS}"

BBCLASSEXTEND = "native nativesdk"

Here is the more complete error statement:
| arm-agl-linux-gnueabi-libtool: link: arm-agl-linux-gnueabi-g++  -march=armv7-a -marm -mfpu=neon  -mfloat-abi=softfp -mcpu=cortex-a9 --sysroot=/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4  -fPIC -DPIC -shared -nostdlib /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/Scrt1.o /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/crti.o /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/arm-agl-linux-gnueabi/6.2.0/crtbeginS.o  google/protobuf/stubs/.libs/atomicops_internals_x86_gcc.o google/protobuf/stubs/.libs/atomicops_internals_x86_msvc.o google/protobuf/stubs/.libs/common.o google/protobuf/stubs/.libs/once.o google/protobuf/stubs/.libs/stringprintf.o google/protobuf/.libs/extension_set.o google/protobuf/.libs/generated_message_util.o google/protobuf/.libs/message_lite.o google/protobuf/.libs/repeated_field.o google/protobuf/.libs/wire_format_lite.o google/protobuf/io/.libs/coded_stream.o google/protobuf/io/.libs/zero_copy_stream.o google/protobuf/io/.libs/zero_copy_stream_impl_lite.o google/protobuf/stubs/.libs/strutil.o google/protobuf/stubs/.libs/substitute.o google/protobuf/stubs/.libs/structurally_valid.o google/protobuf/.libs/descriptor.o google/protobuf/.libs/descriptor.pb.o google/protobuf/.libs/descriptor_database.o google/protobuf/.libs/dynamic_message.o google/protobuf/.libs/extension_set_heavy.o google/protobuf/.libs/generated_message_reflection.o google/protobuf/.libs/message.o google/protobuf/.libs/reflection_ops.o google/protobuf/.libs/service.o google/protobuf/.libs/text_format.o google/protobuf/.libs/unknown_field_set.o google/protobuf/.libs/wire_format.o google/protobuf/io/.libs/gzip_stream.o google/protobuf/io/.libs/printer.o google/protobuf/io/.libs/strtod.o google/protobuf/io/.libs/tokenizer.o google/protobuf/io/.libs/zero_copy_stream_impl.o google/protobuf/compiler/.libs/importer.o google/protobuf/compiler/.libs/parser.o   -lpthread -lz -L/home/cjholmes/gen4/build/tmp/sysroots/x86_64-linux/usr/lib/arm-agl-linux-gnueabi/gcc/arm-agl-linux-gnueabi/6.2.0 -L/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/lib -L/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/arm-agl-linux-gnueabi/6.2.0 -L/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/libstdc++.so -lm /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/libssp_nonshared.a -lc -lgcc_s -lgcc /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/arm-agl-linux-gnueabi/6.2.0/crtendS.o /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/crtn.o  -march=armv7-a -marm -mfpu=neon -mfloat-abi=softfp -mcpu=cortex-a9 --sysroot=/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4 -pthread -O2 -g -fstack-protector-strong -Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z -Wl,relro -Wl,-z -Wl,now   -pthread -Wl,-soname -Wl,libprotobuf.so.9 -o .libs/libprotobuf.so.9.0.1
| arm-agl-linux-gnueabi-libtool: link: arm-agl-linux-gnueabi-g++  -march=armv7-a -marm -mfpu=neon  -mfloat-abi=softfp -mcpu=cortex-a9 --sysroot=/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4  -fPIC -DPIC -shared -nostdlib /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/Scrt1.o /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/crti.o /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/arm-agl-linux-gnueabi/6.2.0/crtbeginS.o  google/protobuf/stubs/.libs/atomicops_internals_x86_gcc.o google/protobuf/stubs/.libs/atomicops_internals_x86_msvc.o google/protobuf/stubs/.libs/common.o google/protobuf/stubs/.libs/once.o google/protobuf/stubs/.libs/stringprintf.o google/protobuf/.libs/extension_set.o google/protobuf/.libs/generated_message_util.o google/protobuf/.libs/message_lite.o google/protobuf/.libs/repeated_field.o google/protobuf/.libs/wire_format_lite.o google/protobuf/io/.libs/coded_stream.o google/protobuf/io/.libs/zero_copy_stream.o google/protobuf/io/.libs/zero_copy_stream_impl_lite.o   -lpthread -lz -L/home/cjholmes/gen4/build/tmp/sysroots/x86_64-linux/usr/lib/arm-agl-linux-gnueabi/gcc/arm-agl-linux-gnueabi/6.2.0 -L/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/lib -L/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/arm-agl-linux-gnueabi/6.2.0 -L/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/libstdc++.so -lm /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/libssp_nonshared.a -lc -lgcc_s -lgcc /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/arm-agl-linux-gnueabi/6.2.0/crtendS.o /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/crtn.o  -march=armv7-a -marm -mfpu=neon -mfloat-abi=softfp -mcpu=cortex-a9 --sysroot=/home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4 -pthread -O2 -g -fstack-protector-strong -Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z -Wl,relro -Wl,-z -Wl,now   -pthread -Wl,-soname -Wl,libprotobuf-lite.so.9 -o .libs/libprotobuf-lite.so.9.0.1
| ERROR: oe_runmake failed
| /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/libc_nonshared.a(elf-init.oS): In function `__libc_csu_init':
| /usr/src/debug/glibc/2.24-r0/git/csu/elf-init.c:87: undefined reference to `__init_array_end'
| /usr/src/debug/glibc/2.24-r0/git/csu/elf-init.c:87: undefined reference to `__init_array_start'
| /home/cjholmes/gen4/build/tmp/sysroots/x86_64-linux/usr/libexec/arm-agl-linux-gnueabi/gcc/arm-agl-linux-gnueabi/6.2.0/ld: .libs/libprotobuf-lite.so.9.0.1: hidden symbol `__init_array_end' isn't defined
| /home/cjholmes/gen4/build/tmp/sysroots/x86_64-linux/usr/libexec/arm-agl-linux-gnueabi/gcc/arm-agl-linux-gnueabi/6.2.0/ld: final link failed: Bad value
| collect2: error: ld returned 1 exit status
| make[3]: *** [libprotobuf-lite.la] Error 1
| make[3]: *** Waiting for unfinished jobs....
| /home/cjholmes/gen4/build/tmp/sysroots/imx6dlleargen4/usr/lib/libc_nonshared.a(elf-init.oS): In function `__libc_csu_init':
| /usr/src/debug/glibc/2.24-r0/git/csu/elf-init.c:87: undefined reference to `__init_array_end'
| /usr/src/debug/glibc/2.24-r0/git/csu/elf-init.c:87: undefined reference to `__init_array_start'
| /home/cjholmes/gen4/build/tmp/sysroots/x86_64-linux/usr/libexec/arm-agl-linux-gnueabi/gcc/arm-agl-linux-gnueabi/6.2.0/ld: .libs/libprotobuf.so.9.0.1: hidden symbol `__init_array_end' isn't defined
| /home/cjholmes/gen4/build/tmp/sysroots/x86_64-linux/usr/libexec/arm-agl-linux-gnueabi/gcc/arm-agl-linux-gnueabi/6.2.0/ld: final link failed: Bad value
| collect2: error: ld returned 1 exit status
| make[3]: *** [libprotobuf.la] Error 1
| make[3]: Leaving directory `/home/cjholmes/gen4/build/tmp/work/cortexa9-neon-agl-linux-gnueabi/protobuf/2.6.1+gitAUTOINC+bba83652e1-r0/build/src'
| make[2]: *** [all] Error 2
| make[2]: Leaving directory `/home/cjholmes/gen4/build/tmp/work/cortexa9-neon-agl-linux-gnueabi/protobuf/2.6.1+gitAUTOINC+bba83652e1-r0/build/src'
| make[1]: *** [all-recursive] Error 1
| make[1]: Leaving directory `/home/cjholmes/gen4/build/tmp/work/cortexa9-neon-agl-linux-gnueabi/protobuf/2.6.1+gitAUTOINC+bba83652e1-r0/build'
| make: *** [all] Error 2
| WARNING: /home/cjholmes/gen4/build/tmp/work/cortexa9-neon-agl-linux-gnueabi/protobuf/2.6.1+gitAUTOINC+bba83652e1-r0/temp/run.do_compile.121250:1 exit 1 from 'exit 1'
| ERROR: Function failed: do_compile (log file is located at /home/cjholmes/gen4/build/tmp/work/cortexa9-neon-agl-linux-gnueabi/protobuf/2.6.1+gitAUTOINC+bba83652e1-r0/temp/log.do_compile.121250)

I could really use some pointers on what to look at next.  This has eaten a lot of hours already.


text:
Q: When to use the static keyword before a method in a React class component I'm use to writing methods in react like so:
class Someclass extends Component{
  ...
  someMethod () => ...
}

Latley I've seen a lot of code with static before the method name:
static someMethod() {...}

*

*What's the static for in the context of a JavaScript Class?

*And in the context of a React component?

A: Methods are defined on the class´s prototype, static methods are not, they are functions on the class itself. You can call a static method without creating the instance of the class.
More information on the subject here


text:
Q: Spring boot: LocalTime serialization with ISO format In a very simple Spring-boot reactive project, with no specific configuration (but the one attempted below), I need to serialize LocalTime (and related classes like LocalDate too) in an ISO form. By default each property is serialized individually, which makes sense from an Object point of view. But I need single string property in ISO format.
Several mentions of that issue have been made, like here, here or in lesser extent here.
None work. I wonder what I do wrong or if these links are just outdated and the mechanism in spring updated/changed since.
The central test I've made is by having a bean register the appropriate module:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class MyConfiguration {

    @Bean
    @Primary
    public ObjectMapper customJson() {
        ObjectMapper mapper = new Jackson2ObjectMapperBuilder()
                .build();

        mapper.registerModule(new JavaTimeModule());
        return mapper;
    }
}

My way of identifying that the serialization is not in the ISO format is by looking at my swagger-ui description of my object showing my endTime property as follows (when the actual result I'm trying to achieve is "endTime": "some ISO string"):
"endTime": {
  "hour": 0,
  "minute": 0,
  "nano": 0,
  "second": 0
},

So the question is: How do I configure single string formatting for LocalDate in Spring Boot (Reactive)?

A: You will need to do something like this:
public static void main(String[] args) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    System.out.println(objectMapper.writeValueAsString(new Entity()));
}

static class Entity {
    LocalTime time = LocalTime.now();

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss.SSS")
    public ZonedDateTime getTime() {
        return time;
    }
}

This is a modified quote from this this question

A: You can achieve your objective by disabling the WRITE_DATES_AS_TIMESTAMPS feature in jackson
ObjectMapper mapper = Jackson2ObjectMapperBuilder.json()
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .modules(new JavaTimeModule())
                .build();

This will make is serialize it in ISO format


text:
Q: C++ LibCurl makes program crash for some reason I have trouble executing a LibCurl statement, at least it seems. I try to send off a 15MB file to a port where a script is listening that will process the file and return a response. However, before I get any response, the program crashes (only on 1 pptx file of 15MB, which is way larger than 'normal' other files)
However, does anyone see something strange in the LibCurl logs:
* timeout on name lookup is not supported
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 13621 (#0)
> PUT //File processing argument//
Host: localhost:13621
Accept: application/json
Accept: application/json
Content-Length: 15828910

* We are completely uploaded and fine
< HTTP/1.1 200 OK
< Content-Type: application/json
< Date: Tue, 14 Mar 2017 20:37:41 GMT
< Transfer-Encoding: chunked
< Server: Jetty(8.y.z-SNAPSHOT)
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact

Process returned -1073741571 (0xC00000FD)   execution time : 12.682 s

The code I use:
curl = curl_easy_init();
if (curl) {
    CurlResponse = "";
    host = "localhost:13621";
    LibcurlHeaders = curl_slist_append(LibcurlHeaders, "Expect:");
    LibcurlHeaders = curl_slist_append(LibcurlHeaders, "Accept: application/json");
    curl_easy_setopt(curl, CURLOPT_URL, (host).c_str());
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
    curl_easy_setopt(curl, CURLOPT_READDATA, fd);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, LibcurlHeaders);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, CurlVerbose);
    curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_info.st_size);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, LibcurlResponse);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &CurlResponse);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    }
curl_global_cleanup();

Thanks for your reply


text:
Q: Programming Menu for Game, Mouse detection method not working Here is the code for my method that is supposed to detect whether or not a mouse click is within a rectangle that I defined.
 private boolean mouseOver(int mx,int my,int x, int y, int width, int height){

    if((x < mx  && mx < x + width)&&(y < my && my < y + height)){
        System.out.print(mx+"\n"+my+"\n"+x+"\n"+y+"\n"+width+"\n"+height+"\n");
    return true;

    }else
       System.out.print(mx+"\n"+my+"\n"+x+"\n"+y+"\n"+width+"\n"+height+"\n");
        return false;

}

This is where I am defining the rectangles (with text).
public void render(Graphics g){
    Font fnt = new Font("arial", 1, 50);
    Font fnt1 = new Font("arial", 1, 30);
    g.setColor(Color.white);

    g.setFont(fnt);
    g.drawString("Menu", 240,70);
    g.setFont(fnt1);
    g.drawString("Play", 270,190);
    g.drawRect(210, 150, 200, 64);
    g.drawString("Scores", 270,290);
    g.drawRect(210, 250, 200, 64);
    g.drawString("Quit", 270,390);
    g.drawRect(210, 350, 200, 64);
}

Here is where the method is used.
public void mousePressed(MouseEvent e){
    int mx = e.getY();
    int my = e.getX();
    //play button
    if (mouseOver(mx ,my ,210, 150, 200, 64)){
        game.gameState = STATE.Game;
    }
    //quit button
    if (mouseOver(mx ,my ,210, 350, 200, 64)){

        System.exit(1);

    }
}

When the method is called I commanded it to spit out the fields it takes, and here is an example.
mx = 185 my = 344 x = 210 y = 350 width = 200 height = 64
That data was from clicking the mouse inside of the rectangle, so it should have returned true if it was working properly.
Maybe it's returning the wrong coordinates of the mouse press?
Any ideas?
I'm using a mac if that makes any difference.

A: One easy way to see where a Mouse Point is to use a Rectangle object and its contains(Point p) method.
For instance:
// constant section of your program
private static final STATE_RECTANGLE = new Rectangle(210, 150, 200, 64);
private static final QUIT_RECTANGLE = new Rectangle(210, 350, 200, 64);

// elsewhere
public void mousePressed(MouseEvent e){
    //play button
    if (STATE_RECTANGLE.contains(e.getPoint())) {
        game.gameState = STATE.Game;
    }
    //quit button
    if (QUIT_RECTANGLE.contains(e.getPoint())){
        System.exit(1);
    }
}

You can and should even use the same Rectangles to draw with after converting your Graphics object into a Graphics2D object by casting.
But having said this, we're only treating a symptom and not the disease as your program structure worries me. For one You've got way too many magic numbers, and that risks hard to debug errors. Also you're hard-coding your data which makes your program rigid and thus difficult to enhance and extend. Also you are mixing your view fully with your model, also making your code much more complex than it has to be and thus very difficult to debug, modify and enhance.

A: Your inequality operators are wrong.
(mx < x  && mx < x + width)&&(my < y && my < y + height)

Should be:
(x < mx  && mx < x + width)&&(y < my && my < y + height)

Before, you were just checking if the mouse's x and y position were lower than any point on the rectangle.

A: I solved it. I was sending the x coordinate data to the y value in the equation and visa versa.


text:
Q: Convert a javascript object to CSV file I have a script which reads a file line by line, generate an object with some fields from certain lines and now I want to put that generated object into a CSV file.
How can I do the following:

*

*From the script itself generate a CSV file

*Give initial fields (headers) to the file

*Update that file line by line (add to the file one line at a time)
Some clarifications, I don't know the size of the CSV in advance, so the file must by dynamically changed.
Thanks in advance.

A: Looking at what you have said:

*

*From the script itself generate a csv file

*

*Have a look at node-csv-generate which lets you generate csv strings easily

*Give initial fields (headers) to the file & 3. Update that file line by line (add to the file one line at a time)

*

*Check out the node-csv-generate stream functionality to write individually line by line (i.e. inital headers first)

Now since you said you need to run it locally, I would recommend Rhino if just using JS but if node.js is required then check out Rhinodo. These will let you run the program locally on the JVM basically (you could call the JS from within Java if you wanted to).
To export the CSV file there are plenty examples online this SO thread being one... i.e.
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

Where csvContent is the complete string of your csv. I am not sure how supported this is on Rhinodo, but I'm pretty sure it'll all work on Rhino.

If this is intended to be a purely desktop based application, I would look at using Java (or your preferred language Python or C# might be nicer depending on what you are used to :-) ) rather than JS if everything needs to be local and it intends on being widely used. That way you have a much cleaner interaction with the OS and a lot more control.
I hope this helps!


text:
Q: Emgu CV image load notworking I am using emgu cv version 3. I try to load image to process. but it will provide error for me. According to the error it will say image cannot be read. But i have a image under that location.
This is my code line..
Image<Bgr, Byte> image = new Image<Bgr, Byte>("image.jpg");

A: Code line that you have provided is correct. Please check this with absolute path. It will be worked because if your image is not within your source directory your relative path (you have given only name of image that means your image is within your source directory) will not work. Its good to check with your absolute path. Like as follows
Image<Bgr, Byte> image = new Image<Bgr, Byte>(@"E:\Downloads\image.jpg");

Image "image.jpg" is within E:\Downloads location.


text:
Q: how to disable x-mod-ps header how disable this header ? googled ,no reply;
X-Mod-Pagespeed: 0.9.14.6-358
I attempt:         RequestHeader unset X-Mod-Pagespeed
It's does nothing

A: It's generated because mod_pagespeed for apache is installed and enabled in your apache server.
On ubuntu/debian you can disable it easily by doing:
"a2dismod pagespeed"

You can check the exact name of the module launching a2dismod without argument.
The other way is to go to your apache config folder and remove the pagespeed symlink in mods-enabled.
Don't forget to restart apache through "/etc/init.d/apacche2 restart".

A: You'll need to edit the source code for mod_pagespeed and recompile - look for a line starting with something like.....
apr_table_add(request->headers_out, "X-Mod-Pagespeed"....

A: It's a response header, not a request header -- so just use Header unset not RequestHeader.


text:
Q: Short story about person being replaced/rebuilt by tiny creatures I remember reading a story in 7th grade, around 1983-84, where somehow in it a man realizes that he is slowly being replaced from the inside by tiny bugs/aliens/robots that work together as a unit.
He tries to struggle against it/them but winds up losing the fight and disappearing even though it looks like he is still there to others (it's actually the tiny Invaders).


text:
Q: How to sample data from the proximity of existing data? I have data for xor as below -

x
y
z
x ^ y ^ z

0
0
1
1

0
1
0
1

1
0
0
1

1
1
1
1

Kept only the ones that make the xor of all three equal to 1.
I want to generate synthetic data around the already available data within some range uniformly at random. The above table can be thought of as seed data. An example of expected table will be as follows:

x
y
z
x ^ y ^ z

0.1
0.3
0.8
0.9

0.25
0.87
0.03
0.99

0.79
0.09
0.28
0.82

0.97
0.76
0.91
0.89

Above table is sampled with a range of 0 to 0.3 for 0 value and with range 0.7 to 1 for value 1.
I want to achieve this using pytorch.

A: For a problem such as this, you are able to completely synthesise data without using a reference because it has a simple solution. For zero (0-0.3) you can use the torch.rand function to generate uniformly random data for 0-1 and scale it. For one (0.7-1) you can do the same and just offset it:
N = 5
p = 0.5 #change this to bias your outputs
x_is_1 = torch.rand(N)>p #decide if x is going to be 1 or 0
y_is_1 = torch.rand(N)>p #decide if y is going to be 1 or 0
not_all_0 = ~(x_is_1 & y_is_1) #get rid of the x ^ y ^ z = 0 elements
x_is_1,y_is_1 = x_is_1[not_all_0],y_is_1[not_all_0]
N = x_is_1.shape[0]
x = torch.rand(N) * 0.3
x = torch.where(x_is_1,x+0.7,x)
y = torch.rand(N) * 0.3
y = torch.where(y_is_1,y+0.7,y)
z = torch.logical_xor(x_is_1,y_is_1).float()
triple_xor = 1 - torch.rand(z.shape)*0.3
print(torch.stack([x,y,z,triple_xor]).T)
       #x        y       z       x^y^z
tensor([[0.2615, 0.7676, 1.0000, 0.8832],
    [0.9895, 0.0370, 1.0000, 0.9796],
    [0.1406, 0.9203, 1.0000, 0.9646],
    [0.1799, 0.9722, 1.0000, 0.9327]])

Or, to treat your data as the basis (for more complex data), there is a preprocessing tool known as gaussian noise injection which seems to be what you're after. Or you can just define a function and call it a bunch of times.
def add_noise(x,y,z,triple_xor,range=0.3):
     def proc(dat,range):
        return torch.where(dat>0.5,torch.rand(dat.shape)*range+1-range,torch.rand(dat.shape)*range)
     return proc(x,range),proc(y,range),proc(z,range),proc(triple_xor,range)

gen_new_data = torch.cat([torch.stack(add_noise(x,y,z,triple_xor)).T for _ in range(5)])


text:
Q: Nested structures not sorted correctly I am looping over a query, building an array of structures
<cffunction name="QueryConvert" returntype="any" output="false">
    <cfargument name="q" type="query" required="yes">
    <cfargument name="page" type="numeric" required="no" default="1">
    <cfargument name="rows" type="numeric" required="no" default="500">
    <cfset var result = structnew()>
    <cfset var rowStruct = structnew()>
    <cfset var col = "">
    <cfset result["page"] = arguments.page>
    <cfset result["total"] = ceiling(arguments.q.TotalrecordCount/arguments.rows)>
    <cfset result["records"] = arguments.q.TotalrecordCount>
    <cfset result["rows"] = arraynew(1)>
    <cfset queryDeleteColumn(arguments.q,'TotalrecordCount')>
    <cfset queryDeleteColumn(arguments.q,'rowNum')>
    <cfset columnLabels = QueryColumnArray(arguments.q)>
    <cfset rowStruct = [:]><!--- Tada an ordered struct --->
    <cfloop array="#columnLabels#" item="col">
         <cfset rowStruct[col] = q["#col#"]>
    </cfloop>
    <cfdump var="#result#" abort>
    <cfreturn result />
</cffunction>

but when I view the nested structures, the order of the keys is all mixed up. I expected them to match the order of the column names in the database table.

A: The short answer is you need to use a ordered struct. The long version looks like this:
First we need to look at some sample data
 <cfscript>
 q = queryNew("id,name,category","Integer,Varchar,Varchar",
     [{id=1, name="One", category="Cat"},{id=2, name="Two", category="Dog"}]
 );

 writedump(q);
 </cfscript>

Let's look at out sample data. Note that the columns are not as expected.

Now let's get our columnLabels ready to go. Note that we are creating an array.
 </cfscript>
 result.rows = [];

 columnLabels = q.getMeta().getColumnLabels();
 writedump(columnLabels);
 </cfscript>

<cfloop query="q">
   <cfset rowStruct = [:]><!--- Tada an ordered struct --->
   <cfloop array="#columnLabels#" item="col">
       <cfset rowStruct[col] = q["#col#"]>
   </cfloop>

   <cfset arrayappend(result.rows, rowStruct)>
</cfloop>

<cfdump var="#result.rows#">

Tada

Furthermore
This is all easier to read with cfscript
<cfscript>
for (row in q)  {
    rowStruct = [:];
    for (col in columnLabels)    {
        rowStruct[col] = q["#col#"];
    }
    result.rows.append(rowStruct);
}
</cfscript>

For a live version see: CFFiddle.com


text:
Q: A way to sit 2 Divs next to each other when 1st Div width is unknown? this is my first post on this forum. I've used this forum a tone before to find out help and it's always been really helpful and useful. Straight forward help.
My problem I have is I want 2 divs to sit directly next to each other. I'm making a blog page for a community dance group. I have the div siting next to each other by utilising the float:left property in CSS. I found that solution on StackOverflow, thanks!!
But I don't know the width of Div 1, as I want it to sit in the middle of the page.
My CSS code:
.contentsWrapper{
margin-left:100px;
margin-right:100px;
margin-bottom:10px;
overflow:auto;
}
.blogWrapper{
float:left;
}
.archievesWrapper{
width:250px;
float:right;
}

Any help would be great!!

A: You can try
display: inline-block

on both your divs.  That should get them to show next to eachother.

A: May be that's you want. Write like this:
HTML

right

left

CSS
.left{
    background:red;
    overflow:hidden;
    height:30px;
}
.right{
    float:right;
    background:green;
    height:30px;
    width:250px;
}

Check this http://jsfiddle.net/6EufF/1/

A: What you want to search for is "fluid layout".
There are different ways to do it. This kind of problematic have been addressed many times on different websites.
Here's one link to help you out, but you can find, many, many more.
http://www.vanseodesign.com/css/fluid-layout-code/


text:
Q: Correlation matrix and redundant information I am using a neural network model for a classification task with 13 inputs.
I study through the connection weights to depict the relevant variables. I have also made a correlation matrix to check the relationship between them:

Some groups of variables seem to have strong positive and negative relationships. My fear is that I would have to remove some because they are redundant (?). However, I may consider keeping them to let the network decide by itself which ones to use among those to get rid of.
Is it generally advised to remove redundant information (if highly correlated) when training neural networks?
My study aims at defining the best variables to use (for similar future classification task) so that we get the best prediction performance at the end. In this purpose, I have removed some of the highly correlated variables but got lower prediction accuracy.

A:
Is it generally advised to remove redundant information (if highly
  correlated) when training neural networks?

It depends.
Is it necessary? No.

Since a neural network with an appropriate architecture can model any
  (!) function, you can safely assume, that it also could first model
  the PAT and then do whatever it also should do -- e.g. classification,
  regression, etc. (source)

and

In principal, the linear transformation performed by PCA can be
  performed just as well by by the input layer weights of the neural
  network, so it isn't strictly speaking necessary (source)

This is because Neural Nets could be used as a non-linear dimensionality reduction tool:

High-dimensional data can be converted to low-dimensional codes by
  training a multilayer neural network with a small central layer to
  reconstruct high-dimensional input vectors (source)

In this context, it is also worth mentioning auto-encoders.
Can it help? Yes, it speeds up things.

However, as the number of weights in the network increases, the
  amount of data needed to be able to reliably determine the weights of
  the network also increases (often quite rapidly), and over-fitting
  becomes more of an issue (using regularisation is also a good idea).
  The benefit of dimensionality reduction is that it reduces the size of
  the network, and hence the amount of data needed to train it (source)

Speed comes at a cost /slash/ bears a risk

The disadvantage of using PCA is that the discriminative information
  that distinguishes one class from another might be in the low variance
  components, so using PCA can make performance worse (source)

This might really be what you have experienced in your experiment.


text:
Q: Image fade in at scrolling of the page I'm trying to do one simple thing. When I scroll the page an image fixed at the top should appear and disappear when scrolling at the top. I have set visibility hidden in the img selector in this way when the page load it will be hidden. unfortunately the following code doesn't work
here it is the jsfiddle http://jsfiddle.net/vhe3rhLd/ and the jquery function:
UPDATED
$(window).bind('scroll', function(event) {
  if ($(this).scrollTop() > 100) {
    $('img').fadeTo(1000, 1, function() {
      $(this).css({visibility: 'visible'});
    });
  } else {
    $('img').fadeTo(1000, 0, function() {
      $(this).css({visibility: 'hidden'});
    });
  }
  event.preventDefault();
  });

A: You are using the function fadeTo() wrong.
The parameters of fadeTo() are:
fadeTo(duration,opacity,callback)

So a correct way of using that is as follows:
$(window).bind('scroll', function(event) {
  if ($(this).scrollTop() > 100) {
    $('img').fadeTo(500, 1, function() {
      $(this).css({visibility: 'visible'});
    });
  } else {
    $('img').fadeTo(500, 0, function() {
      $(this).css({visibility: 'hidden'});
    });
  }
  event.preventDefault();
  });

Also, the use of opacity (fadeTo) and visibility in the callback could bring you unexpected behaviour because you set de visibility after the fadeIn or fadeOut completly execute. Maybe you could avoid using the visibility and only play with the opacity like this:
    $(window).bind('scroll', function(event) {
      if ($(this).scrollTop() > 100) {
        $('img').fadeTo(500, 1);
      } else {
        $('img').fadeTo(500, 0);
      }
      event.preventDefault();
      });
$('img').hide();//Hide the image at start

I make  jsFiddle to show it. Check if it fits your needs.

A: Js Fiddle
the js
$(window).bind('scroll', function(event) {
  if ($(this).scrollTop() > 100) {
         $('img').fadeIn(600);
      } else {
         $('img').fadeOut(600);
      }
   event.preventDefault();
  });

and the css
body {
height: 2800px;
}

img {
position: fixed;
width: 300px;
display:none;

}

A: http://jsfiddle.net/vhe3rhLd/7/
HTML:
<img class='hidecontent'  src='http://upload.wikimedia.org/wikipedia/commons/a/af/Bonsai_IMG_6426.jpg' />

CSS
body {
height: 2800px;
}

img {
 position: fixed;
width: 300px;

}
.hidecontent{
opacity:0;
z-index:-999;
transition:all 0.5s ease;
}

.showcontent{
opacity:1;
z-index:999;
transition:all 0.5s ease;
}

JS
$(window).bind('scroll', function(event) {
 if ($(this).scrollTop() > 100) {
  $('img').removeClass('hidecontent').addClass('showcontent');
 } else {
  $('img').addClass('hidecontent').removeClass('showcontent');
}
event.preventDefault();
});

A: Make your image visible before fading it out.
$(window).bind('scroll', function(event) {
    if ($(this).scrollTop() > 100) {
        $('img').css({visibility: 'visible'});
        $('img').fadeTo(500, 0, function() {

    });
    } else {
         $('img').fadeTo(0, 500, function() {
         $(this).css({visibility: 'hidden'});
    });
 }
 event.preventDefault();
});


text:
Q: Why are there four mono C# compilers? This page explains about the four different mono compilers - mcs/gmcs/smcs/dmcs.
To me, it's a little bit weird to have four C# compilers. As normally the newer version of compiler maintains backward compatibility.
I assume that's because of runtime support issues, but Microsoft's C# has one csc.exe that supports all of the runtime versions.

A: It's because Mono's compiler is written in C# and uses System.Reflection, which means it can only access mscorlib from the runtime that it's running on. Therefore, for example, smcs doesn't just target 2.1, it actually uses 2.1 corlib, etc.
There have been plan for a while to have *mcs use either Mono.Cecil or Ikvm.Reflection instead of System.Reflection, which would mean there could then be a single mcs compiler with arguments to target different runtimes.
Microsoft's compiler doesn't have this limitation because it doesn't use .NET Reflection (it's written in native code).

A: For the same reason you can still do development in .NET 2.0 with Visual Studio 2005.  Sure, you could use VS2010 and start a .NET 4.0 project with only .NET 2.0 code, but some companies are afraid of upgrading frameworks/compiler versions if they already have something working properly.
Just because the new compiler version is backwards compatible does not mean that teams will want to upgrade.
Having the different compiler versions ensures all of Mono's users can still use whatever compiler version they choose and are comfortable with.

*

*mcs: compiler to target 1.1 runtime (to be deprecated with Mono 2.8).

*gmcs: compiler to target the 2.0 runtime.

*smcs: compiler to target the 2.1 runtime, to build Moonlight applications.

*dmcs: Starting with Mono 2.6 this command is the C# 4.0 compiler, and references the 4.0 runtime.

Personally, I like upgrading whenever I can, but some companies and teams are unable to do so for some reason or another.


text:
Q: What is the geometrical meaning of $\ i^i $? What is the geometrical meaning of $ i^i $ ? Is there any meaning at all?
If I write $ i= e^{i* \pi/2}$, I get $ i^i =  e^{- \pi/2}$.
But if I write $ i= e^{5i \pi/2}$ I get its value  $e^{-5 \pi/2}$.
Since $i^i$ cannot be defined uniquely, it appears to me that it should not be defined. Also, what geometrical operation is going on here?
In case this is defined, can you show me any of its applications?

A: $i^i$ is multivalued !
First, we need the logarithms of $i$. They are given by
$\log i =\log|i|+i \arg i+2k \pi i=\frac{i \pi}{2}+2 k  \pi i$ with $k \in \mathbb Z.$
Then we have
$i \log i=\frac{- \pi}{2}-2 k  \pi $ with $k \in \mathbb Z.$
Hence
$$i^i \in \{e^{- \pi/2}e^{-2k \pi}: k \in \mathbb Z\}.$$

A: The problem comes down to how you are to define $u^w$ when $u$ and $w$ both are nonreal complex numbers. The only way would be $\exp(w\log(u))$, where I'm writing $\exp(z)$ for $e^z$. No problem ever in defining $\exp(z)$, it's a good everywhere-defined function. But that can not be said for the logarithm, as you probably know. We do use the log, with due caution because it has no consistent definition for all nonzero complex numbers. That means, for $\log(z)$, choosing one of the infinitely many numbers $w$ such that $\exp(w)=z$.
Same thing for $u^w$: it is not well defined, but as long as we're aware that there are infinitely many possible values, we may be able to use the expression fruitfully. But always with care.

A: Let us consider the expression
$$z^i$$ for some complex $z$, and let $z=re^{i\theta}$.
Using the logarithm, we have
$$z^i=e^{i(\log r+i\theta)}=e^{-\theta+i\log r}.$$
This is a complex number, let $se^{i\phi}$ with
$$s=e^{-\theta},\\e^{\phi}=r.$$
These two relations describe logarithmic spirals, with opposite orientation.
To construct $z^i$,

*

*draw the logarithmic spiral (blue);

*draw the vector $z^*$ (conjugate, green);

*draw the line of support of $z^*$ (green) and intersect the spiral, to get the modulus;

*draw a circle centered at the origin, through $z^*$ (green), and intersect the spiral, to get the argument;

*the requested $z^i$ is the intersection (red) of the circle by the first point (orange) and the line by the second (orange).


text:
Q: wpf binding brush color I have a custom textblock that has various text properties for left, right and same text as dependency properties. I use "Run" for making them have different foreground colors. It was like this in a method inside the control:
Inlines.Add(new Run(_leftValue[i]) { Foreground = Brushes.Red });
I added a dependency property for brush. How can I set it in my custom control's cs file?
Thanks in advance

A: You have given us precious little to go on, but I'll give you an answer anyway. The format for setting a dependency proeprty is this:
[instance of the dependency object].SetValue(YourDependencyObject.TheDependencyProperty, value);

so for the example of a DP taking a brush, this should so it:
this.SetValue(MyCustomControl.ForegroundBrush, Brushes.Red);

Note that MyCustomControl is the literal name of your type, and this should be castable to a DependencyObject (if your control derives from Window, Control, FrameworkElement, etc. then it derives from DependencyObject).


text:
Q: How do I create and initialise a simple struct without providing a constructor? Suppose I have this type:
struct T
{
  SomeType a;
  OtherType b;
};

I think there is some way to declare an object of type T and defining the initialised values of a and b in line, but I can't remember how this worked, or even what it's called so I can look it up. Something like T t(a, b) where a and b are of type SomeType and OtherType respectively.
How do I achieve this without declaring a constructor, and what is it called?

A: You can write T t = {a, b}. That only works with PODs aggregates though (or with a propper constructors of course).

A: You tagged with c++11, so do very simply this:
#include <iostream>

struct T
{
    int a;
    float b;
};

int main()
{
    T t{1,2.2};

    std::cout << t.a << ":" << t.b << std::endl;

}

A: C++11 suports unified inicializatoin list with "{}", which means you can init. classes with "{}" as a struct before
you can initialize the the struct like this
T t{someTypeA, otherTypeB};// someTypeA and someTypeB must be defined

here is a simple test code
#include <iostream>
using namespace std;

class B
{
public:
    int a;
};

class C
{
public:
    int a;
};

struct A
{
    B b;
    C c;
};

int main(int argc, char** argv)
{
    B b;
    C c;
    b.a = 1;
    c.a = 2;
    A a{b, c};
    cout << a.b.a << a.c.a << endl;
    return 0;
}


text:
Q: recurrence relation using Frobenius method I've been posed the following question:

I've differentiated and substituted the Frobenius equation into the ODE to obtain the indicial equation and tried solving for the recurrence relation using the larger of the two indicial roots. However, i've tried to solve it many times and can't seem to get it. Any help or suggestions will be appreciated. My attempt is in the image (part d)
edit 1: On another attempt, i obtained $a_{m+1} = \frac{-6a_{m-1}}{(m+1)(m+5)}$
edit 2: On yet another attempt, i obtained $a_{m+1} = \frac{-6a_{m-1}}{(m+7)(m+1)}$
edit 3: it seems edit 2 was the correct answer, now how can i find the first 3 non-zero terms if the power series depends on $a_{-1}$ ?

A: The assumed solution is $y=x^6\sum_0 a_nx^n = \sum_0 a_nx^{n+6}$.
Now, $y' = \sum_0 (n+6)a_nx^{n+5}$ and $y'' = \sum_0 (n+6)(n+5)a_nx^{n+4}$
Substituting in the equation given (when converted to the normal form of the Frobenius equation - $x^2y''+x(-5)y'+6x^2y=0$), we get -
$$\sum_0 (n+6)(n+5)a_nx^{n+6}-5\sum_0 (n+6)a_nx^{n+5}+6\sum_0 a_nx^{n+8}=0$$
$$\implies \sum_0 n(n+6)a_nx^{n+6}+6\sum_0 a_nx^{n+8}$$
Thus, collecting all powers of $x$, we get -
$$0.6.a_0=0\qquad(\text{from $x^6$})$$
$$1.7.a_1=0\qquad(\text{from $x^7$})$$
$$(n+2)(n+8)a_{n+2}+6a_n=0\qquad(\text{from $x^n$, $n\geq8$})$$
Thus, we get $$a_1=0$$
$$a_{n+2}=-\frac{6a_n}{(n+2)(n+8)}$$
Hence, we see that all terms with odd indices are $=0$, while even indices can be evaluated in terms of $a_0$.


text:
Q: PostgreSQL pg_database_size different from sum of pg_total_relation_size Currently, my development database is taking up way more disk space than it probably should. The project uses Django, Docker-Machine, and PostgreSQL. The weird thing is that when I use pg_database_size(), it says that around 9MB of disk space is used (the uploaded file is only 20KB). However, when I sum up the sizes of all the tables (i.e. summing up the results of doing pg_total_relation_size() on each table name returned by the query SELECT relname FROM pg_class WHERE relkind='r' AND relname !~ '^(pg_|sql_)';), the total size reported is only 1.8MB. I'm using psycopg2 to query my database.
Why exactly is there such a difference in sizes? I saw a similar sort of question where the answer seemed to be to vacuum any LOBs that weren't properly deleted. I did the following:
docker exec -it <name_of_database_container> vacuumlo -U postgres -W -v postgres

and it reported that it successfully removed 0 LOBs, so it seems like LOBs were never my issue. What else could be going on? Am I not correctly getting all the table names using the SELECT relname.... query?

A: Your pg_total_relation_size query is excluding system tables that start with pg_.  Those tables do still take up space.
The minimum possible (non-broken) database is around 7.2MB in my hands.  So the numbers you give work out.

A: The documentation for pg_total_relation_size says that it includes the size of indexes with it, but that wasn't the case with my database.  That may have been because I created the indexes with an explicit name rather than anonymous indexes.
Here are some queries to help track down where space is going:
-- total database size on disk
select * from pg_size_pretty(pg_database_size('etlq'));

-- total sizes by schema
select nspname, pg_size_pretty(sum(pg_total_relation_size(C.oid)))
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
GROUP BY nspname;

-- total size by relation
select nspname, relname, pg_size_pretty(pg_total_relation_size(C.oid)), pg_total_relation_size(c.oid)
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE true
and pg_total_relation_size(C.oid) > 10 * 1024 * 1024 -- greater than 10MB
ORDER BY pg_total_relation_size(C.oid) DESC, nspname;


text:
Q: What is the algorithm for checking logical equivalence of specifications? Consider I have an audience target group defined as:
age >= 13 && gender == Gender.Female
or as
gender == Gender.Female && age >= 13
These are equivalent specifications, which differ slightly in definition. However, specifications can be hierarchical and quite complex, forming an expression tree.
Is there a performant algorithm of checking logical equivalence of expressions/specifications?


text:
Q: zpool import Failure: can I recover data? I have a personal zpool server that was going down, and I want to know if there is a way to recover what I have.  Most of my critical data (photos, tax into, etc) got backuped to OneDrive, so I am mostly ok, but would like the rest of the data if possible.
I watched the LTT video on ZFS maintenance/data loss, saw I have never done a scrub either, so I ran it, hit a bunch of checksum errors, a couple read errors.  So, I am planning to upgrade from a 3+1 2TB drives to 3+1 6TB drives and have the drives now.  I took the server down to put in a 4TB drive to back everything up (only ~1.5TB ZFS full), and I think I started all my issues by doing that, as at least the zpool was up, now it won't even power up anymore...
When I run zpool import, I get this report:
   pool: raid
     id: 12795258809798297580
  state: FAULTED
 status: One or more devices contains corrupted data.
 action: The pool cannot be imported due to damaged devices or data.
        The pool may be active on another system, but can be imported using
        the '-f' flag.
   see: http://zfsonlinux.org/msg/ZFS-8000-5E
 config:

        raid        FAULTED  corrupted data
          raidz1-0  DEGRADED
            sdc     ONLINE
            sdc     FAULTED  corrupted data
            sde     ONLINE
            sdf     ONLINE

Now, this shows an issue, sdc is appearing twice, and sdd is missing.  When I run lsblk, I see this:
...
sdb      8:16   0   3.7T  0 disk
├─sdb1   8:17   0    16M  0 part
└─sdb2   8:18   0   3.7T  0 part
sdc      8:32   0   1.8T  0 disk
├─sdc1   8:33   0   1.8T  0 part
└─sdc9   8:41   0     8M  0 part
sdd      8:48   0   1.8T  0 disk
sde      8:64   0   1.8T  0 disk
├─sde1   8:65   0   1.8T  0 part
└─sde9   8:73   0     8M  0 part
sdf      8:80   0   1.8T  0 disk
├─sdf1   8:81   0   1.8T  0 part
└─sdf9   8:89   0     8M  0 part

sdb would be drive I was going to back up to. sdc, sde, and sdf are part of the zfs recovery, but it looks like sdd is now gone/failed.
Is there a way that I can get the zpool back up and running to recover whatever data I can back?  I thought the whole point of raidz1 was any 1 drive could fail, and it was still recoverable... zpool import -f raid fails with:
cannot import 'raid': I/O error
        Destroy and re-create the pool from
        a backup source.

PS: Notes for rebuild...  I think I need to do a zpool export when I get the new ZFS array running.  Also, I should refer to disks by ID instead of devid.

A: If you want to backup zpool, you can research more with key "zfs snapshot", now you can use 2 external tools (I'm using them for backup and restore)
https://www.zfsnap.org/
https://github.com/someone1/zfsbackup-go
Take snapshot zpool with name "music-pool" and rolling-out after 3 days
./zfsnap.sh snapshot -rv -a 3d music-pool

Full backup snapshot to external storage
#List
zfs list -t snapshot

#Do store backup to path /backup/
./zfsbackup-go send music-pool@FULL--3d file://backup/

Incremental backup snapshot to external storage
zfs list -t snapshot
./zfsbackup-go send -i music-pool@FULL--3d music-pool@FULL_inc001--3d file://backup/

Restore from full
./zfsbackup-go receive -F -d music-pool@FULL--3d file://backup/ music-pool

Restore if you had incremental (do the above command to restore full, then incremental)
./zfsbackup-go receive -d -F -i music-pool@FULL--3d music-pool@FULL_inc001--3d file://backup/ music-pool


text:
Q: 2D array isn't reading from a .txt document correctly I am building a simple program for a University exercise that requires data to be read from a .txt file and fed into a 2D array.
The premise of the program is that the user inputs 10 gene chromosomes (floats) separated by spaces, the program then compares these floats to a .txt file containing a number of gene chromosomes and if it matches one in the .txt file, the user is notified there is a match.
Here is my code...
#include <stdio.h>
#include <stdbool.h>

FILE *dnaFile;

int main(){

    //Open the file and assign its address/disk location to file pointer
    dnaFile = fopen("dnaInput.txt", "r"); //Relative pathname used

    //Declaring the Suspect array
    int size = 10;
    float suspect[size];

    //Declaring the Criminal array
    int sizeR = 6;
    int sizeC = 10;
    float criminals[sizeR][sizeC];

    //Read 10 input values into suspect array from keyboard
    printf("\nEnter the 10 chromosomes of the suspect seperated by spaces: \n");
    for (int i = 0; i < size; i++)
        scanf(" %f", &suspect[i]);

    //Read multiple profiles of 10 values into criminals array from file
    for (int i = 0; i < sizeR; i++){
        fscanf(dnaFile, " %f", criminals[i]);

    //Read 10 input values of a criminal into criminals array from the keyboard
    for (int j = 0; j < sizeC; j++)
        fscanf(dnaFile, " %f", &criminals[i][j]);

    }

    //Match user input to the array
    bool match = true;

    for (int i = 0; i < sizeC; i++)
        for (int j = 0; j < sizeR; j++)
            if(suspect[i] != criminals[i][j])
                match = false;

    //Display the result

    if (match)
        printf("\nSuccess: A match was found! \n");
    else
        printf("\nFailure: No match was found \n");

}

And here is the contents of the .txt file...
2.3 3.3 4.5 6.7 7.8 2.1 3.2 4.3 5.2 6.5
2.3 3.3 4.5 6.7 7.8 2.1 3.2 4.3 5.2 6.5
1.3 0.3 9.5 8.7 5.8 4.1 3.2 2.3 6.2 6.9
6.3 9.3 4.3 6.4 7.5 2.9 3.0 4.1 5.3 6.5
6.1 9.4 4.5 6.6 7.4 2.8 3.2 4.4 5.0 6.0
2.3 3.3 4.5 6.6 7.8 2.2 3.2 4.3 5.2 6.5

The program complies and executes without issue, though when entering say the first line of contents of the .txt as the input, even though it matches the .txt file, it gives the user a fail output. I've googled arrays to try and find my issue but haven't come across a solution.
Apologies in advance if I have made a rookie mistake, I have only recently started learning C at University.

A: You need to use nested loops to read into the 2-dimension array:
    //Read multiple profiles of 10 values into criminals array from file
    for (int i = 0; i < sizeR; i++){
        for (int j = 0; j < sizeC; j++) {
            fscanf(dnaFile, " %f", &criminals[i][j]);
        }
    }

Then when you're searching for the suspect in the array, the outer loop should be by rows, not columns, and you should reset match on each row.
Then when comparing suspect with criminals, you should use suspect[j], not suspect[i], since j is the column index.
    //Match user input to the array
    bool found = false;

    for (int i = 0; i < sizeR; i++) {
        bool match = true;
        for (int j = 0; j < sizeC; j++) {
            if(suspect[j] != criminals[i][j]) {
                match = false;
                break;
            }
        }
        if (match) {
            found = true;
            break;
        }
    }


text:
Q: why all exception is being catched by ldap.SERVER_DOWN? i have some code like below, i am trying to connect a server which is not existed to test timeout. after 120 sec, program quits with code 5. and more, i disconnect from lan to test connect_error and it exits with code 5 again. why all exception is being catched by ldap.SERVER_DOWN? how can i test other exceptions?
try:
    ....

    l.simple_bind_s(user, password)

except ldap.CONNECT_ERROR, e:
    sys.exit(1)

except ldap.BUSY, e:
    sys.exit(2)

except ldap.OPT_NETWORK_TIMEOUT, e:
    sys.exit(3)

except ldap.TIMEOUT, e:
    sys.exit(4)

except ldap.SERVER_DOWN, e:
    sys.exit(5)

A: Based on the python-ldap source, it looks like only a NonblockingLDAPObject can raise the exception ldap.TIMEOUT.  You shouldn't have to handle it for a SimpleLDAPObject.

A: To test for BUSY you could bind to a working LDAP server, and then don't close (unbind) the connection. When you try and connect again the server should throw the BUSY error.


text:
Q: array_reduce to use dynamic variables pass in second function I have below $test array
        Array
(
    [0] => Array
        (
            [quantity] => 3
            [stock_id] => _PHONE
        )

    [1] => Array
        (
            [quantity] => 3
            [stock_id] => 102
        )

    [2] => Array
        (
            [quantity] => 4
            [stock_id] => _PHONE
        )

    [3] => Array
        (
            [quantity] => 3
            [stock_id] => 102
        )

    [4] => Array
        (
            [quantity] => 4
            [stock_id] => _PHONE
        )

    [5] => Array
        (
            [quantity] => 6
            [stock_id] => _PHONE
        )

    [6] => Array
        (
            [quantity] => 2
            [stock_id] => 102
        )

)

and to sum same stock_id keys to one, i use below functions:
function sum($array, $key){
    isset($array[$key['stock_id']]) ? $array[$key['stock_id']]['quantity'] += $key['quantity'] : $array[$key['stock_id']] = $key;
    return $array;
};

//merge same stock_id and sum the quantity same stock id
$sum_same_stock_id = array_reduce($test, "sum");

and the result went well like below:
$sum_same_stock_id:
Array
(
    [_PHONE] => Array
        (
            [quantity] => 17
            [stock_id] => _PHONE
        )

    [102] => Array
        (
            [quantity] => 8
            [stock_id] => 102
        )

)

So the question here is, I wanted to pass an dynamic keys values not just fixed values stock_id & quantity in sum function above. Have tried variety ways but still can't figured out the way. And can we put those functions into class as well?
Any advise is appreciated!

A: Maybe you can use the "use" function for the callback?
See https://www.php.net/manual/en/functions.anonymous.php


text:
Q: What's a regex to stitch everything inside []? I have text annotated with linguistic tags as follows:
PRE[per]    ART[la] NOUN[creazione] PRE[di] ART[un] NOUN[prodotto]  ADJ[innovativo]     ARTPRE[nel] NOUN[mercato]   ARTPRE[delle]   NOUN[comunicazioni] PRE[senza]  NOUN[fili] PUN[(]   NPR[WiFi]   PUN[)]

What regex will give me back the text inside the square brackets, spaced as one match? That is:
per la creazione di un prodotto innovativo nel mercato delle comunicazioni senza fili (WiFi)

A: You need a regular expression and a loop that concatenates all matches.
Since you have applied the Java tag, the Java code for that is:
    String text = ...;
    Matcher matcher = Pattern.compile("\\[(.*?)\\]").matcher(text);
    StringBuilder result = new StringBuilder();
    while (matcher.find()) {
        result.append(matcher.group(1));
        result.append(' ');
    }
    System.out.println(result);

A: This will work by matching whatever is inside [], although the () will also be spaced:
str.replaceAll(".*?\\[(.*?)\\]", "$1 "));

A: String text = "PRE[per]    ART[la] NOUN[creazione] PRE[di] ART[un] NOUN[prodotto]  ADJ[innovativo]     ARTPRE[nel] NOUN[mercato]   ARTPRE[delle]   NOUN[comunicazioni] PRE[senza]  NOUN[fili] PUN[(]   NPR[WiFi]   PUN[)] ";
Pattern pattern = Pattern.compile("(\\[(\\w+)\\])");
Matcher matcher = pattern.matcher(text);

StringBuilder sb = new StringBuilder();
while(matcher.find()) {
    sb.append(matcher.group(2)).append(" ");
}
System.out.println(sb);


text:
Q: Multiple Models in a View in ASP.NET MVC Entity FrameWork I want two CheckBoxList an index view, those
CheckBoxList dynamically bind from two different tables. One is Sports
and another is Country.
Basically i try through EditorTemplates, but it not working with two
models. i face problem to use two model in a single view.
This is my Index Method in Controller
    SampleDBContext db = new SampleDBContext();
    public ActionResult Index()
    {
        ViewData["Sports"] = db.Sports.ToList();
        ViewData["Country"] = db.Countries.ToList();
        return View(ViewData["Sports"]);// I am confused and i don't know what to write there we can call both table data.
    }

Template View for Sports
@model MVCDEMO.Models.Sports

@Html.HiddenFor(x => x.s_Id)
@Html.CheckBoxFor(x => (bool)x.is_selected)
@Html.DisplayFor( x => x.s_Name)

Template View for Country
@model MVCDEMO.Models.Country

@Html.HiddenFor(x => x.c_Id)
@Html.CheckBoxFor(x => (bool)x.is_selected)
@Html.DisplayFor( x => x.c_Name)

Index View

            Select Sports

            @Html.EditorForModel()//what to write it recognize Sports template

            Select Country

            @Html.EditorForModel()//what to write it recognize Country template

If i work for single Model it work perfectly.

A: I would personaly use a strongly typed view model having Sports and Countries as properties, instead of using ViewData:
public class IndexPageViewModel
{
    public IEnumerable<Sports> Sports { get; set; }
    public IEnumerable<Country> Countries { get; set; }
}

Creating two partial views, one for each class (Sport and Country), would allow you to use the @Html.EditorForModel() helper. Reusing the partial views would also be an added benefit, but this obviously depends on the specific application.
Please note that the 'EditorForModel' helper will render an editor for each property of the model. If you need to have a different kind of editor, for example a dropdown menu, I'm not sure EditorForModel should be used.


text:
Q: If $P$ is the power set of the set $A = \{ x : x^2-x-2=0 \}$, then find $n(P)$
If $P$ is the power set of the set $A= \{ x:x^2-x-2=0 \}$, then find $n(P)$.

My attempt:
$$x^2-x-2=0$$
$$x^2-2x+x-2=0$$
$$x(x-2)+1(x-2)=0$$
$$(x-2)(x+1)=0$$
How do I proceed further?

A: The discriminant of $x^2-x-2$ is $1^2-4(-2)>0$. Hence the equation $x^2-x-2=0$ has two solutions.
$$n(P)=2^{n(A)}=2^2=4$$

A: We have to start reading the definition of the set $A = \{ \ x \mid x^2−x−2=0 \ \}$.
It is the set of roots of the quadratic equation: $x^2−x−2=0$.
You have rewritten the equation as: $(x−2)(x+1)=0$ and thus its roots are: $-1$ and $2$ (see also comment above), that means:

$A = \{ -1, 2 \}$.

Now we have to "build" the power set $P=\mathcal P(A)$ (see comment above).
We know that, for a finite set with $n$ elements, its power set has $2^n$ elements.
We know that $A$ has two elements, i.e. $n(A)=2$, and thus we may conclude that:

$n(P)=4$.


text:
Q: Custom UITableViewCell won't come out of edit mode I study the Apple sample code Lister,I rewrite the program(remove the container group and cloudListCoordinator,and documentMenu,userActivity,only use the localDocument to store the file),It works the same, but I have problem with two custom UITableViewCell,one is listColorCell,other one is listItemCell,I override the setEditing method of TableViewController as the same with the Apple's sample code,when I press the edit button, the listColorCell show in the first row,below is the listItemCell,If I don't touch or change the current color of the listItem,It can move out of edit mode when I press the done button.
So the problem is ONLY when I touch the listColorCell and this make the listItemCell's color changed,and press the done button again,the ListColorCell and ListItemCell seems doesn't move out of edit mode.I check the Storyboard's outlet and content view,use the cavemen debug, still can't find where could be wrong.
1.First,the listItem's color is blue
2.then I press the red colorView on the ListColorCell, listItem color change to red
3.but when I press the done button again,this happen..
Picture Link are:
https://www.dropbox.com/s/g58mru17as2h5g6/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202015-04-27%2015.53.49.png?dl=0
I'm new to here,hoping somebody can help me..

A: just a suggestion, check whether your controller fit to these requirements :
I use usual UIViewController and it works fine - you need to :
make your controller a delegate of UITableViewDelegate, UITableViewDataSource
implement
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
programmatically add EDIT button - self.navigationItem.rightBarButtonItem = self.editButtonItem

(if you add EDIT button from builder you will need to call setEditing : YES manually)
 - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewCellEditingStyleDelete;
    }

    - (void)setEditing:(BOOL)editing animated:(BOOL)animated
    {
        [super setEditing:editing animated:animated];
        [self.tableView setEditing:editing animated:YES];
    }

    - (void)tableView
        :(UITableView *)tableView didSelectRowAtIndexPath
        :(NSIndexPath *)indexPath
    {
        [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
        [self.navigationController popViewControllerAnimated:YES];
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }

    // do not forget interface in header file

    @interface ContactsController : ViewController<
        UITableViewDelegate,
        UITableViewDataSource>

I have given Objective-C code here, You can refer it or you can convert to swift and try


text:
Q: DateTime Comparison in LINQ I am ran into the following issue.
Take a look at the following where clause.
Where(x => x.CreateTS <= dateParameters.CreationDate.ToDateValue &&
           x.CreateTS >= dateParameters.CreationDate.FromDateValue)

CreateTS is a Timestamp column in the table. so when my dateparameters are todate = 01/28/2010  12:00A.M" fromdate= "01/26/2010 12.00A.M" (c# DateTime types) my query doesnot retrivies the table records whose CreateTS look like 01/28/2010 1:45A.M and above just differeing in the timestamps.
I just wanted to do comparison and dont want to compare the timestamps. any help would be appreciated.

A: Just look at the .Date portion of the DateTime:
Where(x => x.CreateTS.Date <= dateParameters.CreationDate.ToDateValue && x.CreateTS.Date >= dateParameters.CreationDate.FromDateValue)

As a side note:
Personally, I would put from first, since it's a bit easier to follow from a readability standpoint:
Where(x => x.CreateTS.Date >= dateParameters.CreationDate.FromDateValue && x.CreateTS.Date <= dateParameters.CreationDate.ToDateValue)

(I find it easier to think of being between two values as being >low and

Edit: You didn't specify that you were using the EF LINQ providers, which do not allow you to do Date.  You can, I believe, handle this by looking forward one day, and using < instead of <= for your "to" comparison:
Where(x => x.CreateTS >= dateParameters.CreationDate.FromDateValue && x.CreateTS.Date < dateParameters.CreationDate.AddDays(1).ToDateValue)

A: @SARAVAN, AFAIK timestamp columns cannot be used in comparisons like that. A timestamp columns are mapped as byte[] (byte array) in EF. If comparisons like that are needed, I suggest to change the timestamp column in database to a datetime one.
only to quote from MSDN:

The SQL Server timestamp data type has nothing to do with times or dates. SQL Server timestamps are binary numbers that indicate the relative sequence in which data modifications took place in a database.

A: Interesting moment here is that
01/28/2010 12:00A.M actually in 24 hour format is 00:00 while 01/28/2010 1:45A.M is 01:45 and that seems to be the reason why those records are not returned. The midday will be 01/28/2010 12:00P.M


text:
Q: Equations making a new line and not lining up in multicol Each equation should sit directly next to its listing ie to the right of the a) not underneath it, just wondering how to fix it, and if my markup can be improved efficiency wise.
What it looks like currently:

\documentclass[fleqn]{article}
\usepackage{amsmath}
\usepackage{multicol}
\usepackage{enumerate}
\begin{document}
\begin{enumerate}
\item \begin{equation*} \text{Factorise the following} \end{equation*}
\begin{multicols}{2}
\begin{enumerate}[(a)]
    \item  \begin{equation*} \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x). \end{equation*}
    \item  \begin{equation*} \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x). \end{equation*}
    \item  \begin{equation*} \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x). \end{equation*}
    \item  \begin{equation*} \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x). \end{equation*}
    \item  \begin{equation*} \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x). \end{equation*}
    \item  \begin{equation*} \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x). \end{equation*}
\end{enumerate}
\end{multicols}
\end{enumerate}

A: Instead of a displayed equation environment that goes underneath the enumerate numbering inline math can be used. \displaystyle chooses the settings for displayed equations.
\documentclass[fleqn]{article}
\usepackage{amsmath}
\usepackage{multicol}
\usepackage{enumerate}
\begin{document}
\begin{enumerate}
\item Factorise the following:
\begin{multicols}{2}
\begin{enumerate}[(a)]
    \item  $\displaystyle \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x)$.
    \item  $\displaystyle \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x)$.
    \item  $\displaystyle \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x)$.
    \item  $\displaystyle \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x)$.
    \item  $\displaystyle \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x)$.
    \item  $\displaystyle \frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x)$.
\end{enumerate}
\end{multicols}
\end{enumerate}
\end{document}

Result:

Edit: Werner's idea of centered equations added.
\documentclass[fleqn]{article}
\usepackage{amsmath}
\usepackage{multicol}
\usepackage{enumerate}
\newenvironment{cmath}{%
  \leavevmode
  \hfill
  $\displaystyle
}{%
  $\hfill\null
}
\begin{document}
\begin{enumerate}
\item Factorise the following:
\begin{multicols}{2}
\begin{enumerate}[(a)]
    \item  \begin{cmath}\frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x).\end{cmath}
    \item  \begin{cmath}\frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x).\end{cmath}
    \item  \begin{cmath}\frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x).\end{cmath}
    \item  \begin{cmath}\frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x).\end{cmath}
    \item  \begin{cmath}\frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x).\end{cmath}
    \item  \begin{cmath}\frac{d}{dx}\left( \int_{0}^{x},du\right)=f(x).\end{cmath}
\end{enumerate}
\end{multicols}
\end{enumerate}
\end{document}

Result:


text:
Q: Difference between "take a taxi" and "get a taxi" What is difference between the following sentences?

*

*I take a taxi/bus/train.

*I get a taxi/bus/train.

A: The rules are different for taxis than for buses and trains.
To get a taxi is to secure the services of a taxi for transportation. To take a taxi is to ride in one. That is, you have to get a taxi before you can take a taxi:

You'll never get a taxi in this neighborhood/at this time of night/in this weather
We got a taxi at the airport and took it to the hotel.

On the other hand, it's pretty unusual to get a bus or a train (though not impossible). It's more common to take or catch a bus or train. As you can see in this ngram, the forms with "get" for buses and trains are much less common.

A: In the realm of travel, to take something is to use it as your mode of transportation:

take (transitive) to use a particular type of transport
take a bus/train/plane/taxi etc: I usually take the bus to work.

In British English, get is more common than take for this usage:

get (transitive) (never passive) to use a particular vehicle to travel somewhere
He usually tries to get the 9.03 train.

In American English, to get a taxi, etc. is to obtain its use. I might ask my hotel concierge to Please get me a car to South Station, or inquire of my host Is it easier to get a cab on Lexington or Park Avenue? Similarly, to get a flight is to reserve a seat on a flight, whereas to actually fly is to take a flight.
There are a variety of other ways to express the same— I can catch my transportation (e.g. catch the Shinjuku Line, catch a flight, catch bus #42), ride in/on it (e.g. we rode the tram back to Palm Springs), or simply go on/in/by something (e.g. Can I reach LAX by Metrorail?) among others. But not all of these may apply to all modes; we fly rather than ride aircraft, for example, even though we are passengers and not pilots most of the time (e.g. We always fly Air New Zealand to Fiji).

A: In the US you take a taxi, not get a taxi. If you say you got a taxi, the listener would assume that you bought a taxi. If you want to go by bus, you say that you want to take the bus. Or you get on the bus and get somewhere.

A: In this case take refers to the physical act of going and get to the process of acquiring. So they roughly mean the same thing, but with a different emphasis.
I call the taxi service to get (acquire) a taxi. When it comes I will take it (ride in it) to my destination.


text:
Q: unable to print augeas for own configuration I have below dtp.conf file for internal requirement.
/opt/dtp/etc/dtp.conf

export CHO='NON-PROD'

but when I print the config file via augtool unable to print the value
/opt/pupet/bin/augtool
augtool> print /files/opt/dtp/etc/dtp_config
augtool>

A: I do not remember Augeas having a specific lens for this file. Augeas cannot guess which lens (parser) to use, it needs to know which lens to associate to which file.
In this case, this looks like a Shellvar type of file, so you can use e.g.:
augtool -At "Shellvars.lns incl /opt/dtp/etc/dtp.conf"

to edit it.
In Puppet, use the shellvar type from the augeasproviders_shellvar Puppet module:
shellvar { 'CHO':
  ensure => exported,
  target => '/opt/dtp/etc/dtp_config',
  value  => 'NON-PROD',
}


text:
Q: How do you refute these conjectures that seem imply contradictory statements? I've formulated two conjectures that seems to imply a strong result when are combined with well known equivalences of the Riemann hypothesis, and I would like to know how get a disproof of such statements.
Let $S(n)=\sum_{k=1}^n\text{n mod k}$ the sum of remainder function, then it is know that for each $n>1$
$$\sigma(n)+S(n)=S(n-1)+2n-1,$$
where $\sigma(n)$ is the sum of divisors function, and let $H_n=1+1/2+\ldots+1/n$ the nth harmonic number.

Conjecture 1. The following asymptotic equivalence holds
  $$\frac{S(n)}{e^{H_n}}\sim\frac{n}{10},$$
  as $n\to\infty$.

On assumption of this Conjecture 1 one has that using Robin's criterion for the Riemann's hypothesis (or also Lagarias equivalence, the computations are the same), $\forall n>5040$
$$\sigma(n)<e^\gamma n\log\log n$$
can be evaluated as
$$\frac{S(n-1)}{e^{\frac{1}{n}}e^{H_{n-1}}}+\frac{2n}{ne^\gamma e^{O(\frac{1}{n})}}<\frac{1}{e^{H_{n}}}+\frac{S(n)}{e^{H_{n}}}+\frac{e^\gamma n\log\log n}{ne^\gamma e^{O(\frac{1}{n})}},$$
since $H_n=\log n+\gamma+O(\frac{1}{n})$, where $\gamma$ is Euler's constant, thus $LHS\sim\frac{n-1}{10}+\frac{2}{e^\gamma}$ and by comparison with $RHS\sim\frac{n}{10}+\log\log n$ one conclude this equivalence with Riemann hypothesis holds asymptotically.
On the other hand, one has for $M(n)=\sum_{k=1}^n\mu(k)$ is the Mertens function, where $\mu(k)$ is Mobius function, then

Conjecture 2. The following holds
  $$(M(n))^2=o\left(e^{H_n}\right)$$
  as $n\to\infty$.

Thus by comparison with the equivalence of Riemann hypothesis stated as $M(x)=O(x^{\frac{1}{2}+\epsilon}),\forall\epsilon>0$, on assumption of this Conjecture 2 one get a contradiction since there is a constant $C>0$ such that
$\lim_{n\to\infty}\frac{(M(n))^2}{e^{H_n}}$ is computed as $$\lim_{n\to\infty}\frac{C\cdot n^{2(\frac{1}{2}+\epsilon)}}{ne^\gamma e^{O(\frac{1}{n})}}=\lim_{n\to\infty}\frac{Cn^{2\epsilon}}{e^\gamma}$$
that is infnite for any $\epsilon>0$, a contradiction with the assumption that $(M(n))^2=o\left(e^{H_n}\right)$ that means $\lim_{n\to\infty}\frac{(M(n))^2}{e^{H_n}}=0$.
I did graphs of such ratios, but I'm assuming that perhaps there are mistakes in my computations or facts that I don't understand, since I understand that my reasoning are very soft for such great unsolved problem. I would like to ask how can we refute these conjectures.

Question. Can you refute each of these conjecture? Then I can learn how you give a mathematical reasoning for my question. Thanks in advance.

A: Conjecture 2 is false. Since $H_n = \log n + \gamma + O(1/n)$, we have that $e^{H_n} = e^{\gamma} n + O(1)$, and so your conjecture $M(n)^2 = o(e^{H_n})$ is equivalent to $M(x) = o(\sqrt{x})$, which is well known to be false.