Q: json_encode will not encode more than 6670 rows Someone else had this issue back in '07, but it was not answered:  in PHP, json_encode($someArray) silently fails (returns null) if the array has more than 6,670 rows.  Does someone have a workaround.  Limiting the size of the array to 6600, for example produces the expected result.  I can do some do multiple json calls with partial arrays and concatenate results, but that involves some funky string manipulation to get them to stitch together properly, and I would like to avoid that.

A: You could always just first slice the array into 2 parts (assuming it's not bigger then 2 times those rows). After that encode it, and add them together again. In case that isn't a solution, you need to increase your memory limit.
Here is an example, test it here. On @GeertvanDijk suggestion, I made this a flexible function, in order to increase functionality!
<?php
  $bigarray = array(1,2,3,4,5,6,7,8,9);

function json_encode_big($bigarray,$split_over = 6670){
  $parts = ceil((count($bigarray) / $split_over));

  $start = 0;
  $end = $split_over;

  $jsoneconded = [];

  for($part = 0; $part < $parts; $part++){
    $half1 = array_slice($bigarray,$start,$end);
    $name = "json".$part;
    $$name = ltrim(rtrim(json_encode($half1),"]"),"[");
    $jsoneconded[] = $$name;
    $start += $split_over;
  }

  return "[".implode($jsoneconded,",")."]";
}

print_r(json_encode_big($bigarray));
?>

I have now test this with more rows then 6,670. You can test it online here as well.
Now, I have to mention that I tested the normal json_encode() with a million rows, no problem. Yet, I still hope this solves your problem...

In case that you run out of memory, you can set the memory_limit to a higher value. I would advice against this, instead I would retrieve the data in parts, and procces those in parts. As I don't know how you retrieve this data, I can't give an example how to regulate that.  Here is how you change the memory in case you need to (sometimes it is the only option, and still "good").

ini_set("memory_limit","256M");

In this case, it is the dubbel from the default, you can see that it is 128M in this documentation

A: Possibly depends on your PHP version and the memory allowed for use by PHP (and possibly the actual size of all the data in the array, too).
What you could do if all else fails, is this:
Write a function that checks the size of a given array, then split off a smaller part that will encode, then keep doing this until all parts are encoded, then join them again. If this is the route you end up taking, post a comment on this answer, and perhaps I can help you out with it. (This is based on the answer by Nytrix)
EDIT, example below:
function encodeArray($array, $threshold = 6670) {
    $json = array();
    while (count($array) > 0) {
        $partial_array = array_slice($array, 0, $threshold);
        $json[] = ltrim(rtrim(json_encode($partial_array), "]"), "[");
        $array = array_slice($array, $threshold);
    }

    $json = '[' . implode(',', $json) . ']';
    return $json;
}


Q: Trigger event only on specific div when mouse is over I have six list items and I want to animate the single item only on mouse over.
This is my snippet:

Eye

link

Eye

link

  // other same list items

What I trying to do is to remove the "top_out" class when mouse in over the list item.
I tried this:
$("ul li").hover(function(){
    $(".overview").toggleClass("top_out");
});

but what I obtained is that all divs react together.
How can I do this?
Here an example of what to obtain (section Portfolio): Esample site
I want the same icon animation effect
Thanks

A: try:
$('ul li').on('mouseenter mouseleave', function() {
        $(this).find('.overview').toggleClass('top_out');
});

A: You have to use the hovered over li as the context:
$("ul li").hover(function(){
    $(".overview", this).toggleClass("top_out");
});

Rather than .hover(function() ... you may want to use:
.on('mouseenter mouseleave', function() ...

$("ul li").on('mouseenter mouseleave', function(){
    $(".overview", this).toggleClass("top_out");
});
.top_out {
  background-color: black;
  color: white;
  }

Eye

link

Eye

link

A: It seems like you need to toggle the class based on the context of the element you are hovering over.
Use the jQuery selector $(".overview", this) to select .overview elements within the li element that is currently being moused over.
I also change the hover event to mouseover/mouseout.
$("ul li").on('mouseover mouseout', function () {
    $(".overview", this).toggleClass("top_out");
});

Which is essentially equivalent to
$("ul li").on('mouseover mouseout', function () {
    $(this).find(".overview").toggleClass("top_out");
});


Q: Silex security configuration I'm struggling with silex security:
I have the following:
$app->register(new Silex\Provider\SecurityServiceProvider());

and later on :
$app['security.firewalls'] = array(
    'admin' => array(
        'pattern' => '^/admin',
        'http' => true,
        'users' => array(
            // raw password is foo
            'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
        ),
    ),
);

but when i hit path "localhost/admin" Im getting:
Found error: No route found for "GET /admin"

cant understand the docs on page of silex rly.. Should I register security filters with controllers?
Idefined as follows function in controller:
public function admin(){
        return 'Hello';
    }

and route for this is:
$app->get('/admin', 'app.vendor_controller:admin');

now Im getting:
Hello

as soon as i hit path /admin , without authentication form. So there is no authentication proccess included...
EDIT~~~~~~~~~~~~~~~~~~~~~
OK, so now after hitting url/admin I'm getting authentication banner with fields to put, as user and password, I'm typing admin , foo but there is no effect on this.
`A username and password are being requested by http://localhost:8080. The site says: “Secured”`

the code looks as follows:
$app['security.firewalls'] = array(
    'admin' => array(
        'pattern' => '/admin',
        'http' => true,
        'users' => array(
            'admin' => array('ROLE_ADMIN', 'foo')
        )));
$app['security.access_rules'] = array(
    array('/admin', 'ROLE_ADMIN'),
);

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
    'security.firewalls' => array(
    'pattern' => '/admin',
    'http' => true,
    'users' => array(
        // raw password is foo
        'admin' => array('ROLE_ADMIN', 'foo'),
    ))));

A: You configured a firewall that match every /admin* urls, but that don't mean that every URL requires authentication. You can be an anonymous user, and that would be fine. If you want tell silex that "the user need the ROLE_ADMIN to be allowed here", you need to add
$app['security.access_rules'] = array(
    array('^/admin', 'ROLE_ADMIN'),
);


Q: Excel Macro - hide comment after edit I have this for entering a comment on a excel worksheet when user insert C or P, and I need to hide the comment after edit.
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    Set KeyCells = Range("A1:S1000")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

            Select Case Range(Target.Address)
                Case "C":
                    minhaCelula = Target.Address
                    Range(minhaCelula).AddComment ("")
                    Range(minhaCelula).Comment.Visible = True
                Case "P":
                    minhaCelula = Target.Address
                    Range(minhaCelula).AddComment ("")
                    Range(minhaCelula).Comment.Visible = True

            End Select

    End If
End Sub

A: Some problems with that code:

*

*Select Case Range(Target.Address) doesn't make sense - it takes the Target range, takes its address and creates a range from that address, which points to the original Target range, and finally VB takes the default property of that range, because its not being used in an object reference context. So the whole thing should be replaced with Target.Value.

*Later same thing happens to minhaCelula.

*Code under "C" and "P" is the same and should be placed under the same Case branch.

*Colons are not used in VB's Select Case.

*AddComment should be called without parentheses. Even better, you should benefit from the fact AddComment returns the reference to the added comment, so you can directly use that (in which case you must keep the parentheses).

So that should be rewriteen as:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Me.Range("A1:S1000"), Target) Is Nothing Then
        Select Case Target.Value
            Case "C", "P"
                Target.AddComment("").Visible = True
        End Select
    End If
End Sub

As for the question, when you use Comment.Visible, Excel stops managing the comment's visibility. To leave the management on Excel side, make the comment's shape visible instead:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Me.Range("A1:S1000"), Target) Is Nothing Then
        Select Case Target.Value
            Case "C", "P"
                With Target.AddComment("").Shape
                    .Visible = msoTrue
                    .Select
                End With
        End Select
    End If
End Sub


Q: Display one piece of a multidimensional array while entering another from a form? I need to be able to enter a String value, and have it input the id to that row on a table.
I'm trying to get something like a select tag in HTML to work in Ruby. However I need it to programmatically change when new rows are added to the table I'm pulling the values from.
The table itself looks something like this:
Locations
 id    location_cd
| 1  |         SLC|
| 2  |         LAS|

etc.
I used the Location class to pass these values from this table into an array. Here is the Location class.
class Location < ActiveRecord::Base

    def self.select_options
        self.all.sorted.collect{ |q| [q.id, q.location_cd]}
    end

end

Doing this gives me this multidimensional array when I call the select_options method.
[[1, "SLC"], [2, "LAS"]]

Here's what I have in the controller.
def edit
    @pallet = Pallet.find(params[:id])
    @locations = Location.all
  end

  def update
    @pallet = Pallet.find(params[:id])
    if @pallet.update_attributes(pallet_params)
      flash[:notice] = "Pallet Updated Successfully."
      redirect_to(:action => 'show', :id => @pallet.id)
    else
      @pallet_count = Pallet.count
      render('edit')
    end
  end

Pallet is the main class I'm pulling from, and I need to enter the location.id into the pallets table.
Here's what I have in edit.
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>

Update Pallet

    <%= form_for(:pallet, :url => {:action => 'update', :id => @pallet.id}) do |f| %>

        <%= render(:partial => "form", :locals => {:f => f}) %>

            <%= submit_tag("Update Pallet") %>

    <% end %>

This will redirect it to the form, and here's what I have in my form. This is where the problem I'm running into is.

        <%= f.label(:destination) %>

        <%= f.select(:destination, Location.select_options) %>

Doing this will give me a list of the ids like this.
1
2

However I want a list of the location_cds like this.
SLC
LAS

But I need it to be to the point where I can enter SLC, and in the database it would enter 1 instead.
To put this into the perspective of the multidimensional array I need to be able to enter the second value of [[1, "SLC"]] on the user side, and the first value(1) should be entered into the table.

A: I did a lot of digging and I was able to find something that worked.
There is a helper that comes with rails called options_for_select(). What this does is it will take something like this
<%= select_tag(:destination, '<option value="1">SLC</option>...') %>

And it will auto-generate the options using a multidimensional array
Since I already had a multidimensional array by using the select_options method, I was able to use them both in conjunction with each other like so:
<%= select_tag(:destination, options_for_select(Location.select_options)) %>

This pulls up exactly what I needed, and appends the correct value to the database when selected.
Another method is without the options_for_select helper, but it would need to have a parameter for which row is selected available.
@pallet = Pallet.find(2)

<%= select(:pallet, :destination, Location.select_options) %>

The advantage of this one is that it automatically defaults to what was already there. This makes it easier for when you update something that isn't the location.


Q: Adding API key auth to existing API If we have a .NET API currently validating users through B2C flows on azure where the API validates the token from the FE with B2C.
How could we implement functionality for daemons to consume the API as well if there is no user interaction to get a key from b2c?
I believe this is called client credentials flow, but I know this does not exist on b2c?
Any ideas on how we could achieve this?

A: This workaround may work for your case.
"Although the OAuth 2.0 client credentials grant flow is not currently directly supported by the Azure AD B2C authentication service, you can set up client credential flow using Azure AD and the Microsoft identity platform /token endpoint for an application in your Azure AD B2C tenant. An Azure AD B2C tenant shares some functionality with Azure AD enterprise tenants.
To set up client credential flow, see Azure Active Directory v2.0 and the OAuth 2.0 client credentials flow. A successful authentication results in the receipt of a token formatted so that it can be used by Azure AD as described in Azure AD token reference".


Q: dojo datagrid event attach issue I am working with IBM Content Navigator 2.0.3, that uses DOJO 1.8 for the GUI development. I am new in dojo, and I have to enhance one of the forms: add an event handler to the dataGrid so when the row of the grid is selected one of the buttons become enabled.
dataGrid described in HTML as follows:

And the JS file that controls the form behavior mentioned this _selectedDataGrid only once, in the postCreate function:
postCreate: function() {
    this.inherited(arguments);
    this.textDir = has("text-direction");
    this.hoverHelpList = [];
    domClass.add(this._selectedDataGridContainer, "hasSorting");
    this._renderSelectedGrid();

_renderSelectedGrid() is being executed, which contains the only mention:
_renderSelectedGrid: function() {
    .......
    this._selectedDataGrid.appendChild(this._selectedGrid.domNode);

I've tried to add an data-dojo-attach-event onRowClick: enableRemoveUsersButton in the HTML and a
enableRemoveUsersButton: function(evt){
    this.removeUsersButton.set('disabled', true);
},

in js file. Didn't help.
Then I tried:
dojo.connect(myGrid, "onRowclick", function update() {
    this.removeUsersButton.set('disabled', true); });

but I couldn't acquire myGrid object using:
`var myGrid  = dojo.byId("_selectedDataGrid");`

Can anyone tell me how to acquire the grid object and/or add an event handler to this grid, that fires when the row of the grid is selected?
Thank you!

A: You won't be able to get the grid object by dojo.byId("_selectedDataGrid"). It is better to keep the myGrid object at class level (widget level) and connect using dojo.hitch.
dojo.connect(this.myGrid, 'onRowClick', dojo.hitch(this, function(){
        //access myGrid using this.myGrid and do the handling
}));

A: From what you have share, I can see that the node "_selectedDataGrid" is just a Div tag. and your dataGrid widget may be "this._selectedGrid" so you should be add the event on that widget not the container node.
Also there is dijit.byId to get the instance of dijits/widgets. and dojo.byId is used to search of dom nodes.
Hope this was helpful.


Q: Android remove window background when it's not shown? I was watching Romain Guy's video(23:27) about how to make android's UI fast and efficient and I discovered that the window background is always redrawn, even if it can't be seen. However, as it's an old video, I'd like to know if this problem has been addressed or not? Is it a good practice to always set a nobackground theme to activities that don't need it?


Q: Aggregate series from DataFrame based on specific conditions I have the following data structure:
       sls   srx    stx  hostname    m                          @timestamp
0        1  21.1  389.2         A  dev 2021-03-05 05:00:00.112965476+00:00
1        0  0.0   352.4         A  dev 2021-03-05 05:00:00.263778044+00:00
2        0  0.0   351.5         A  dev 2021-03-05 05:00:00.463778044+00:00
3        0  0.0   333.6         A  dev 2021-03-05 05:00:00.663778044+00:00
4        1  13.8  379.1         A  dev 2021-03-05 05:00:00.811431112+00:00
5        1  14.6  369.2         A  dev 2021-03-05 05:00:01.011431112+00:00
6        1  15.4  359.3         A  dev 2021-03-05 05:00:01.211431112+00:00
7        0  0.0   371.5         A  dev 2021-03-05 05:00:01.459895995+00:00
8        1  64.1  353.8         A  dev 2021-03-05 05:00:01.608929154+00:00

And I'm trying to compute a dataframe or series that looks like this:
                                  start                                   end                duration
0   2021-03-05 05:00:00.263778044+00:00 2021-03-05 05:00:00.811431112+00:00 0 days 00:00:00.547653068
1   2021-03-05 05:00:01.459895995+00:00 2021-03-05 05:00:01.608929154+00:00 0 days 00:00:00.149033159

So that I can compute the following things:

*

*Count of 0 to 1 transitions (including 0, 0, 0, 0, 1 sequences) - e.g. 2 for the above data

*Total duration of these 0 to 1 transitions - e.g. 0.696686227 for the above data

So the query is looking for the first row where sls is 0, then for the first row that is 1 after that. And it needs to do this for every occurrence of 0 (excluding those that are between a 0 and a 1).
My naive impl. using pandas is:
# @timestamp is a ISO8601 datetime string
df['@timestamp'] = pd.to_datetime(df['@timestamp'])

df['status_change'] = df['sls'].ne(df['sls'].shift())
df = df.drop(df.index[0])

start = df.loc[(df['sls'] == 0) & (
    df['status_change'] == True)].reset_index()
end = df.loc[(df['sls'] == 1) & (
    df['status_change'] == True)].reset_index()

series = pd.DataFrame()
series['start'] = start['@timestamp']
series['end'] = end['@timestamp']
series['duration'] = series['end'] - series['start']

But I feel like there must be an easier way of doing this that would also result in better performance (currently, for 4M documents, it takes about 0:01:06.819145 which is not great).
I'm just not sure how else to query the data in the way I described it so that performance is at least 2x better.

A: perhaps you're lookig for groupby?
df.groupby(by=["sls"]).sum()
group by docs:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html


Q: Mongodb: use $sample after $group I have the following data set:
{company:"One",  employee:"John"},
{company:"One",  employee:"Mike"},
{company:"One",  employee:"Donald"},
{company:"One",  employee:"Mickey"},
{company:"Two",  employee:"Johnny"},
{company:"Two",  employee:"David"},

Ideally, I want a query that returns all distinct companies, number of employees for each company, random employee for each company
{Company: "One" , employee_count=4, randomemployee="Donald"},
{Company: "Two" , employee_count=2, randomemployee="David"},

I do find a way to get company and employee_count using aggregate/group
However I don't find a way to add the randomemployee with the same query.
My aggregation:
function aggr (collection,cb){
   collection.aggregate(([{$group:{_id:'$company',total:{$sum:1}}},{$sort:{total:-1}}]),function(err, l1){
   cb(null, l1)
})
}

I began an other Sample function:
function onesample (collection,arg,cb){
    collection.aggregate(([{ $match: { "company": arg }},{ $sample: { size: 1 }}]),function(err, item){
   cb(null, item[0].employee)
})
}

But i'm loosing myself with callbacks and loop.
Any elegant way to do this within one query?
Thanks a lot.
following your answer, I tried the following code.
I have an issue with the callback of async.foreachof, seems it doesn't finish before leaving to next step: any clue?
var async = require("async");
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/eyc0';

async.waterfall ([
     function(cb) {
            MongoClient.connect(url, function(err, db) {
            cb(null,db)
             })
    },
     function (db, cb) {
             db.collection('kodes', function(err, coll) {
            cb(null,db,coll)
             })
    },
      function (db,coll, cb) {
                 var pipeline = [
                {"$group": {"_id": "$ouat","total": { "$sum": 1}}},
                {"$sort":{"total":-1} },
                {"$project":{"_id": 0,"total":1,"company": "$_id"}}];

                coll.aggregate(pipeline).toArray(function(err, dlist){
                cb(null,db,coll,dlist)
                })
    },
        function (db,coll,dlist, cb) {
            // console.log(dlist)
            cb(null,db,coll,dlist)
    },
          function (db,coll,dlist, cb) {
             var dlist2 = []
                async.forEachOf(
                    dlist,
                    function(item, key, cb){
                        var pipeline = [{ "$match": { "ouat": item.company } },{ "$sample": { size: 1 } }];
                        coll.aggregate(pipeline, function (err, data) {
                        item["randref"] = data[0].code;
                        console.log(item.company)
                        dlist2.push(item)
                        cb()
                    });

                    }
                );
                 cb(null,db,coll,dlist,dlist2);

    },
        function (db,coll,dlist,dlist2, cb) {
            console.log(dlist2)
            console.log(dlist)
    },
    ])

A: There's one approach that involves one query, it could be close but not as performant (as it uses $unwind) and won't give you the desired result (only the filtered company):
var pipeline = [
    {
        "$group": {
            "_id": "$company",
            "total": { "$sum": 1 },
            "employees": { "$push": "$employee" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "company": "$_id",
            "employee_count": "$total"
            "randomemployee": "$employees"
        }
    },
    { "$unwind": "$randomemployee" },
    { "$match": { "company": arg } },
    { "$sample": { size: 1 } }
];
collection.aggregate(pipeline, function(err, result){
    console.log(result);
});

However, for a solution that uses callbacks from multiple queries, this can be handled easily with use of async module.
To get all distinct companies, number of employees for each company, random employee for each company consider using the async.waterfall() function where the first task returns the aggregation results with all distinct companies and number of employees for each company.
The second task uses the results from taks 1 above to iterate over using async.forEachOf(). This allows you to perform an asynchronous task for each item, and when they're all done do something else. With each document from the array, run the aggregation operation that uses the $sample operator to get a random document with the specified company. With each result, create an extra field with the random employee and push that to an array with the final results that you can access at the end of each task.
Below shows this approach:
var async = require("async");
async.waterfall([

        // Load full aggregation results (won't be called before task 1's "task callback" has been called)
        function(callback) {
            var pipeline = [
                {
                    "$group": {
                        "_id": "$company",
                        "total": { "$sum": 1 }
                    }
                },
                {
                    "$project": {
                        "_id": 0,
                        "company": "$_id",
                        "employee_count": "total"
                    }
                }
            ];
            collection.aggregate(pipeline, function(err, results){
                if (err) return callback(err);
                callback(results);
            });
        },

        // Load random employee for each of the aggregated results in task 1
        function(results, callback) {
            var docs = []
            async.forEachOf(
                results,
                function(value, key, callback) {
                    var pipeline = [
                        { "$match": { "company": value.company } },
                        { "$sample": { size: 1 } }
                    ];
                    collection.aggregate(pipeline, function (err, data) {
                        if (err) return callback(err);
                        value["randomemployee"] = data[0].employee;
                        docs.push(value);
                        callback();
                    });
                },
                function(err)
                    callback(null, docs);
                }
            );
        },
    ], function(err, result) {
        if (err) return next(err);
        console.log(JSON.stringify(result, null, 4));
    }
);

With the the async.series() function, this is useful if you need to execute a set of async functions in a certain order.
Consider the following approach if you wish to get the all the distinct companies and their employee count as one result and the other random employee as another:
var async = require("async"),
    locals = {},
    company = "One";
async.series([
        // Load random company
        function(callback) {
            var pipeline = [
                { "$match": { "company": company } },
                { "$sample": { size: 1 } }
            ];
            collection.aggregate(pipeline, function(err, result){
                if (err) return callback(err);
                locals.randomcompany = result[0];
                callback();
            });
        },
        // Load full aggregation results (won't be called before task 1's "task callback" has been called)
        function(callback) {
            var pipeline = [
                {
                    "$group": {
                        "_id": "$company",
                        "total": { "$sum": 1 }
                    }
                },
                {
                    "$project": {
                        "_id": 0,
                        "company": "$_id",
                        "employee_count": "total"
                    }
                }
            ];
            collection.aggregate(pipeline, function(err, result){
                if (err) return callback(err);
                locals.aggregation = result;
                callback();
            });
        }
    ], function(err) { //This function gets called after the two tasks have called their "task callbacks"
        if (err) return next(err);
        //Here locals will be populated with 'randomcompany' and 'aggregation'
        console.log(JSON.stringify(locals, null, 4));
    }
);

A: db.comp.aggregate([
{$group:{_id:'$company',emp:{$addToSet:'$employee'}}},
{$project:{emp:1,employee_count:{'$size':'$emp'},
                 randomvalue:{'$literal':Math.random()}}},
{$project:{emp:1,employee_count:1,
           randomposition:{'$floor':
                    {'$multiply':['$randomvalue', '$employee_count']}}}},
{$project:{'Company':'$_id', _id:0, employee_count:1,
            randomemployee:{'$arrayElemAt':['$emp','$randomposition']}}},
{$sort:{Company:1}} ])

Seems to work!
A couple of results:
{ "employee_count" : 4, "Company" : "One", "randomemployee" : "Mike" }
{ "employee_count" : 2, "Company" : "Two", "randomemployee" : "Johnny" }

{ "employee_count" : 4, "Company" : "One", "randomemployee" : "Mickey" }
{ "employee_count" : 2, "Company" : "Two", "randomemployee" : "David" }


Q: can't enable windows authentication in IIS I've disabled anonymous authentication and I've enabled Windows authentication on my website in IIS 7.
Now, when I browse to the website (http://webserver), Internet Explorer keeps prompting me for a username/password. Since I'm on the intranet, IE should pass on my credentials automatically...
What's more is that if I enter my credentials, they are not even recognized.
I'm out of ideas, if anyone could help....


Q: Plone/Paster - What could cause "paster addcontent dexterity_content" to not work? I'm trying to use paster to create a dexterity content type.
I did a new standalone installation of Plone 4.3.4 in a target folder that's different from the one I was previously working with so it was buildout-cache would be clean.
The OS I am using is Ubuntu 14.04.  So in my downloads folder, in the installer's folder I extracted, I type in the terminal:
./install.sh --target=/home/myusername/Plone2 --instance=MyProject standalone

That installs correctly.  Then I go to MyProject in Plone2.  I edit the buildout to change my password, and the run buildout:
buildout -c develop.cfg

Then I goto the src folder and create a new product with zopeskel:
../bin/zopeskel dexterity project.house

Then I edit my buildout and under eggs I add project.house and under develop, src/project.house.  Then I run buildout again and it builds out correctly.  Then in the project.house folder under sources, I try running paster.
../../bin/paster addcontent dexterity_content

Then I end up with an error:
Traceback (most recent call last):
  File "../../bin/paster", line 264, in <module>
    sys.exit(paste.script.command.run())
  File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 104, in run
    invoke(command, command_name, options, args[1:])
  File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 143, in invoke
    exit_code = runner.run(args)
  File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 238, in run
    result = self.command()
  File "/home/pjdowney/Plone2/buildout-cache/eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/localcommands/__init__.py", line 70, in command
    self._extend_templates(templates, args[0])
  File "/home/pjdowney/Plone2/buildout-cache/eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/localcommands/__init__.py", line 204, in _extend_templates
    tmpl = entry.load()(entry.name)
  File "/home/pjdowney/Plone2/buildout-cache/eggs/setuptools-7.0-py2.7.egg/pkg_resources.py", line 2184, in load
    ['__name__'])
ImportError: No module named dexterity.localcommands.dexterity

I did recently install Plone 4.3.6 in another target folder.  Unfortunately, I never tried using paster because I was creating dexterity content through the web.  Could switching to 4.3.6 have ruined everything?
My earlier target folder works still though.

A: Throwing ""ImportError: No module named dexterity.localcommands.dexterity" + "plone" into a searchengine leads straight to Plone 4.3.4 - ImportError: No module named dexterity.localcommands.dexterity where S. McMahon states it's a bug reported in https://github.com/plone/Installers-UnifiedInstaller/issues/33 and already fixed for Plone-5-installers, but not for Plone-4.
The bug is likely caused of the newest setuptools-version and FWIW, I accidentally found these infos one day in the tweets of "glyph", which look  helpful:

"Public Service Announcement: make @dstufft’s life easier, and do not
  use the `python-pip´ package from Debian or Ubuntu. It’s broken." (1)
"Instead, install pip and virtualenv with get-pip.py, ideally into
  your home directory. (Sadly, https://pip2014.com/  is still
  relevant.)" (2)

I will have a closer look at the salvation-promising-script get-pip.py, when running into probs again, but for now, I simply don't upgrade anything :-D
(1)https://twitter.com/glyph/status/640980540691234816
(2)https://twitter.com/glyph/status/640980540691234816

A: (copied from my own comment on a similar issue in github)

I've had fights like this in the past with zopeskel / paster. Nowadays though I avoid it.... choosing to use:

*

*mrbob for templating eggs

*creating dexterity types through the web see plone training

*OR alternatively creating dexterity types directly in code without templating - there's a lot less boilerplate code in dexterity cf archetypes

I suspect your issue is because your install of 4.3.6 may have upgraded zopeskel or one of it's dependencies to something with different requirements on localcommands/templates.  If you want to continue this fight (and I don't recommend it), then you could try pinning all your zopeskel dependencies to latest versions (though Zopeskel has to be less than 3.0 I believe)


Q: How to create groups of N elements from a PCollection Apache Beam Python I am trying to accomplish something like this:
Batch PCollection in Beam/Dataflow
The answer in the above link is in Java, whereas the language I'm working with is Python. Thus, I require some help getting a similar construction.
Specifically I have this:
 p = beam.Pipeline (options = pipeline_options)
 lines = p | 'File reading' >> ReadFromText (known_args.input)

After this, I need to create another PCollection but with a List of N rows of "lines" since my use case requires a group of rows. I can not operate line by line.
I tried a ParDo Function using variables for count associating with the counter N rows and after groupBy using Map. But these are reset every 1000 records, so it's not the solution I am looking for. I read the example in the link but I do not know how to do something like that in Python.
I tried saving the counters in Datastore, however, the speed difference between Dataflow reading and writing with Datastore is quite significant.
What is the correct way to do this? I don't know how else to approach it.
Regards.

A: Assume the grouping order is not important, you can just group inside a DoFn.
class Group(beam.DoFn):
  def __init__(self, n):
     self._n = n
     self._buffer = []

  def process(self, element):
     self._buffer.append(element)
     if len(self._buffer) == self._n:
        yield list(self._buffer)
        self._buffer = []

  def finish_bundle(self):
     if len(self._buffer) != 0:
        yield list(self._buffer)
        self._buffer = []

lines = p | 'File reading' >> ReadFromText(known_args.input)
          | 'Group' >> beam.ParDo(Group(known_args.N)
          ...


Q: Adobe SiteCatalyst:How to export the groups with list of usernames and report suite i am working on Adobe SiteCatalyst.
i am able to download the groups with column names Group Name,Description,Users and Report Suites.
In above list am getting count of users and report suites.but i need a exact name instead of count how this can be done using Adobe Site Catalyst..
Please help me..

A: I don't know of a built in report that will get you this. If there is a small number of users and you don't need to do it very often then you can do this manually. But it would be a pain.
If you think it is worth investing some time into this because you have a lot of users and/or you need to do this report often then you can use the Enterprise API to automate this report.
You will need to create a user with the Web Services permission. Then using that username and secret (be careful to use the exact format from the Admin tools->Company Settings->Web Services as there is a "loginCompany:username" format and special Shared Secret)
Then you can use the APIs assuming you have some development experience. This is a good starting point. https://developer.omniture.com/en_US/get-started/api-explorer#Permissions.GetGroup  and also look at GetGroups.
Best of luck C.


Q: Fluent Validation C# Unique Id in collection I have an entity that has a nested collection as a property which I will receive from a front-end application.
I just want to make sure that each item in this collection(ICollection ChildClassCollection) has a unique Id within the model I have received.
I am using FluentValidation and would like to add this validation using it too for consistency.
It's something very simple I couldn`t find an elegant way to solve..
An example:
public class ParentClass
{
    public string Name { get; set; }

    public ICollection<ChildClass> ChildClassCollection { get; set; }
}

public class ChildClass
{
    public int Id { get; set; }

    public string Name { get; set; }
}

A: Use HashSet. https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=netframework-4.7.2
public class ParentClass
{
    public string Name { get; set; }

    public HashSet<ChildClass> ChildClassCollection { get; set; }
}

public class ChildClass
{
    public int Id { get; set; }

    public string Name { get; set; }
}

A: Here is what I ended up with:
PRetty cleand, plus, when it encounters issue, it will exit
           this.RuleFor(or => or.ChildClassCollection)
               .Must(this.IsDistinct)
               .WithMessage("There are more than one entity with the same Id");

        public bool IsDistinct(List<UpdateRoleDTO> elements)
        {
            var encounteredIds = new HashSet<int>();

            foreach (var element in elements)
            {
                if (!encounteredIds.Contains(element.Id))
                {
                   encounteredIds.Add(element.Id);
                }
                else
                {
                    return false;
                }
            }

            return true;
       }

A: Do you want to use only fluentValidator to achieve this without any relationship?
If so, you can custom a validator,then use some logic to confirm whether there is a duplicate value
in database,like this:
public class ChildClassValidator : AbstractValidator<ChildClass>
{
    private readonly MyDbContext _context;
    public ChildClassValidator(MyDbContext context)
    {
        _context = context;
        RuleFor(x => x.Id).NotEmpty().WithMessage("ID is required.").Must(IsUnique).WithMessage("parent have more than one ids");
    }

    private bool IsUnique(int id)
    {
        var model = _context.ParentClasses.GroupBy(x => x.Id)
           .Where(g => g.Count() > 1)
           .Select(y => y.Key)
           .ToList();  //judge whether parentclass has duplicate id
        if (model==null)
            return true;
        else return false;
    }
}

A: I use mine custom helper, based by ansver: Check a property is unique in list in FluentValidation. Because the helper is much more convenient to use than each time to describe the rules. Such a helper can be easily chained with other validators like IsEmpty.
Code:
public static class FluentValidationHelper
{
    public static IRuleBuilder<T, IEnumerable<TSource>> Unique<T, TSource, TResult>(
        this IRuleBuilder<T, IEnumerable<TSource>> ruleBuilder,
        Func<TSource, TResult> selector, string? message = null)
    {
        if (selector == null)
            throw new ArgumentNullException(nameof(selector), "Cannot pass a null selector.");

        ruleBuilder
            .Must(x =>
            {
                var array = x.Select(selector).ToArray();
                return array.Count() == array.Distinct().Count();
            })
            .WithMessage(message ?? "Elements are not unique.");
        return ruleBuilder;
    }
}

Usage:
For example we want to choose unique id
RuleFor(_ => _.ChildClassCollection!)
    .Unique(_ => _.Id);

Or want choose unique id and name
RuleFor(_ => _.ChildClassCollection!)
    .Unique(_ => new { _.Id, _.Name });

Update
I optimization performance using code from answer YoannaKostova
public static class FluentValidationHelper
{

    public static bool IsDistinct<TSource, TResult>(this IEnumerable<TSource> elements, Func<TSource, TResult> selector)
    {
        var hashSet = new HashSet<TResult>();
        foreach (var element in elements.Select(selector))
        {
            if (!hashSet.Contains(element))
                hashSet.Add(element);
            else
                return false;
        }
        return true;
    }

    public static IRuleBuilder<T, IEnumerable<TSource>> Unique<T, TSource, TResult>(
        this IRuleBuilder<T, IEnumerable<TSource>> ruleBuilder,
        Func<TSource, TResult> selector, string? message = null)
    {
        if (selector == null)
            throw new ArgumentNullException(nameof(selector), "Cannot pass a null selector.");

        ruleBuilder
            .Must(x => x.IsDistinct(selector))
            .WithMessage(message ?? "Elements are not unique.");
        return ruleBuilder;
    }
}


Q: Storing information from php script I m working on an html page that contains a form allowing users to enter their informations and upload files. all informations will be inserted in Mysql database.
in Javascript, im using XMLHttpRequest to send the files to the server and "upload.php" to rename (to avoid dupplicated names) and move them in the upload directory.
For better user experience, this will be done before submitting the whole form.
My question is : How can i store the new filenames (defined in upload.php)to use them in the form submission "submit.php"?
the reason for this is that in "submit.php", i insert first the user informations in "user" table and then select the "user_id" (auto increment) that will be inserted with filenames in the "files" table.
Could php sessions be an approach to do this ? is there another way? Thanks for your help
html:
<form action="submit.php" method="post" id="submitform">

<--!user info part1-->

    <input type="file" id="filesList" multiple>

<--!user info part2-->

javascript:
var fd = new FormData()
var xhr = new XMLHttpRequest()
for (var i=0,nb = fichiers.length; i<nb; i++) {
    var fichier = fichiers[i]
    fd.append(fichier.name,fichier)
}
xhr.open('POST', 'upload.php', true)

upload.php :
<?php
foreach($_FILES as $file){
    $filename = date('Y') . date('m') . date('d') . date('H') . date('i') . basename($_FILES[$file]['name']);
    move_uploaded_file( $file['tmp_name'],"../upload_dir/" .$filename);
    }
exit;

A: I would consider using something like md5 for unique filenames.
Nevertheless you can push filenames into some array, and than return those filenames, as a result of post request, and put them back into some input field.
To retrieve the response simply add this lines to your code below open
xhr.onreadystatechange = function {
// If the request completed and status is OK
  if (req.readyState == 4 && req.status == 200) {
    // keep in mind that fileNames here are JSON string
    // as you should call json_encode($arrayOfFilenames)
    // in your php script (upload.php)
    var fileNames = xhr.responseText;
  }
}

If you'd like consider using a simple library for AJAX requests, like axios. It's promise based HTTP client for the browser, really simple to use and saves you some time and effort cause you don't have to memorize all this stuff you and I have just written.
This is one approach, but I think you can use $_SESSION as well, and it's perfectly valid. My guess is you don't have logged in user at this point, so my idea is as follows:

*

*put filenames into the $_SESSION

*use db transactions - as @Marc B suggested - to connect files with
user

*if there were no errors just remove filenames from $_SESSION, if there was some, just redirect the user back to the form (possibly with some info what went wrong), and this way he doesn't have to reupload files, cause you have filenames still in $_SESSION


Q: NSMetadataQuery doesn't send a notification when finished (or doesn't finish) I'm trying to access some files stored in the application's documents directory by using an NSMetadataQuery but the NSMetadataQueryDidFinishGatheringNotification doesn't notify my application. I found this question but the answer was to make the NSMetadataQuery an ivar, which I have already done.
Here's the code I am using:
self.query = [[NSMetadataQuery alloc] init];
[self.query setSearchScopes:[NSArray arrayWithObject:documentsDirectoryURL]];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K ENDSWITH '_task'", NSMetadataItemFSNameKey];
[self.query setPredicate:pred];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:self.query];

[self.query enableUpdates];

[self.query startQuery];

Thanks for your help!

A: This is from the Apple document, "About File Metadata Queries" :
iOS allows metadata searches within iCloud to find files corresponding files. It provides only the Objective-C interface to file metadata query, NSMetadataQuery and NSMetadataItem, as well as only supporting the search scope that searches iCloud.
Unlike the desktop, the iOS application’s sandbox is not searchable using the metadata classes. In order to search your application’s sandbox, you will need to traverse the files within the sandbox file system recursively using the NSFileManager class. Once matching file or files is found, you can access that file in the manner that you require. You are also able to use the NSMedatataItem class to retrieve metadata for that particular file.
So, you have to use NSFileManager instead.


Q: Pass dynamic content to bootstrap modal 3.2 What i'm trying to do is to pass the data-id value to an external link via JQuery ajax.
The modal will show up but the data-id attribute is not sending to the external link. I think something is wrong with my Jquery script. But i can't find it.
This is my link:
Show Me

This is my Jquery ajax script:

This is my code for the modal:

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Dynamic Content

                Content is loading...

                <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-info">Save changes</button>

Can anyone help me out here?

I want to load the content of the page found by test-modal.
The code of test-modal.php is simple, see below:
<?php
$uid = $_GET['id'];
echo id: '. $uid;
?>

I have tried to make a jsfiddle: http://jsfiddle.net/2dp12ft8/3/ but it's totally not working.
I have changed the js code but it will still not work.
I see the modal showing up but only the word 'undefined' is showing up and not the content of the external file.

A: Dont mix onclick attributes with event handlers, its messy and can cause errors (such as mistaking the scope of this, which i believe is you main issue here).
If you are using jquery make use of it:
First add a class to the links you want to attach the event to, here i use the class showme:
Show Me

Then attach to the click event on those links:

To access the variable in php:
$uid = $_GET['id']; //NOT $_GET['uid'] as you mention in a comment

A: Try the load method instead.  I'm taking a guess here, but it seems like you want to actually load the contents of the page found at test-modal.php.  If that's correct, replace your ajax call as follows:
function showAjaxModal()
    {
        var uid = $(this).data('id');
        var url = "test-modal.php?id=" + uid;
        jQuery('#modal-7').modal('show', {backdrop: 'static'});
        jQuery('#modal-7 .modal-body').load(url);

    }

If your test-modal.php page contains more than a fragment (e.g., it has html and body tags), you can target just a portion of the page by passing an id of the containing element for the content that you want to load, such as:
jQuery('#modal-7 .modal-body').load(url+' #container');

which would only load the contents of the element with the id container from your test-modal.php page into the modal-body.


Q: Can't make 2 buttons play 2 different songs on my HTML Firstly, I'm super (SUPER) new to coding in general. I'm doing a college project for a site, and I wanted to make a certain page have 2 buttons that play songs, 2 different versions, one for each button. I copied the code  from stack overflow, can't remember where but I'll be forever thankful for that one answer. I'm new to SO too so I hope I put the code here the right way :|

    <button id="ASong" onClick="playPause()" >
  <audio
    src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3"
    autoplay
    loop
  ></audio>

</button>

    <button id="ASong2" onClick="playPause()" >
  <audio
    src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3"
    autoplay
    loop
  ></audio>

</button>

The only thing I really tried was changing the ID name for the second song. What happens is. I choose a button and click it first. That one button, with that specific song is the one that'll play (edit, it's not the first one I click, it's only one of the songs :/ it switched which one it was when I changed the ID name) , even if I try to press the other button afterwards. It's like both of them become the same button, they function the same. What I wanted is that each one of them worked separately. I want to be able to click, start one song, pause it, click on the other button and start the other song, which is not what's happening right now. I hope that makes sense D=

A: I'm going to modernize this a bit. Inline event handlers listeners are not the way to go these days. I'' use addEventListener instead.
Next, I'm going to use one lot of code to handle the actions. One concept to get used to as you learn to program is DRY: Don't Repeat Yourself. To facilitate the state of your playback I'll use a data attribute on the button

/*Get the buttons*/
document.querySelectorAll(".playPause").forEach(function(el) {
  /*Add a click event listener*/
  el.addEventListener("click", function() {
    /*Get the first audio tag in the clicked button*/
    var aud = this.querySelector("audio");
    /*Check the data attirbute on the button if playing*/
    if (this.dataset.isplaying === "true") {
      /*Debug line*/
      console.log("Pausing " + aud.src)
      /*Change the status of the data attribute*/
      this.dataset.isplaying = "false";
      /*Pause the audio element*/
      aud.pause();
    } else {
      /*Debug line*/
      console.log("Playing " + aud.src)
      /*Change the status of the data attribute*/
      this.dataset.isplaying = "true";
      /*PLay the audio element*/
      aud.play();
    }
  })
});
<button id="ASong" class="playPause" data-isplaying="false">
  <audio
    src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3"
    autoplay
    loop
  ></audio>

</button>
<button id="ASong2" class="playPause" data-isplaying="false">
  <audio
    src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3"
    autoplay
    loop
  ></audio>

</button>


Q: Javascript es6 - is it reassigning or a parameter? Can someone please explain what's happening here? I know these are middleware for express, I'm looking at the syntax.
I understand the es6 syntax for mustBeLoggedIn but I'm not sure what const forbidden = message => (req, res, next) => { is doing. Is message another parameter that comes before req, res, next? If so, why isn't it in the parenthesis? I originally  thought this was just assigning another variable name to the function. So I could call it either forbidden() or message(), no? But looking at how it's being used it looks more like a parameter...
Another interesting thing I noticed is that the middleware forbidden is being invoked in the get request and mustBeLoggedIn is only being passed and not invoked. Why?

   const mustBeLoggedIn = (req, res, next) => {
      if (!req.user) {
        return res.status(401).send('You must be logged in')
      }
      next()
    }

    const forbidden = message => (req, res, next) => {
      res.status(403).send(message)
    }

module.exports = require('express').Router()
 .get('/', forbidden('only admins can list users'), (req, res, next) =>
  User.findAll()
  .then(users => res.json(users))
  .catch(next))
 .post('/', (req, res, next) =>
  User.create(req.body)
  .then(user => res.status(201).json(user))
  .catch(next))
 .get('/:id', mustBeLoggedIn, (req, res, next) =>
  User.findById(req.params.id)
  .then(user => res.json(user))
  .catch(next))

A: I dislike this use of the ES6 syntax as it obscures the meaning of the code only in the interest of brevity.  The best code is not always the shortest possible way to write it.  Give people tools and they will sometimes use them inappropriately.
forbidden() is a function that takes one argument message that returns a middleware handler that uses that one argument.  So, it's a way of making a customized middleware handler that has a parameter pre-built-in.  When you call forbidden(msg), it returns a middleware handler function which you can then use as middleware.
The ES5 way of writing this (ignoring for a moment the difference in this which would be different, but is not used here) would look like this:
const forbidden = function(message) {
   return function(req, res, next) {
       res.status(403).send(message);
   }
}

So, when you call forbidden(someMsg), you get back a function that can be used as middleware.

If so, why isn't it in the parenthesis?

With the ES6 arrow syntax, a single argument does not have to be in parentheses.  Only multiple arguments require parentheses.

Another interesting thing I noticed is that the middleware forbidden is being invoked in the get request

This is because invoking it returns the actual middleware function so you have to execute to get the return value which is then passed as the middleware.

and mustBeLoggedIn is only being passed and not invoked. Why?

Because it's already a middleware function, so you just want to pass a reference to it, not invoke it yet.

FYI, this route:
.get('/', forbidden('only admins can list users'), (req, res, next) =>
    User.findAll()
    .then(users => res.json(users))
    .catch(next))

does not make sense to me based on the code you've shown because forbidden() will return a middleware that will ALWAYS return a 403 response and will not allow the next handler to get called.  This would only make sense to me if forbidden() had logic in it to check if the current user is actually an admin or not (which you don't show).


Q: How to fetch file type data (image) on JQuery page and send to PHP page for image upload I want to upload an image using jQuery asynchronously with data... but cannot upload it... Only data variables can be fetch there in process page but cannot get the image file using $_FILES......
img_upload.php
<form name="frm" id="frm" novalidate enctype="multipart/form-data">
    <input type="text" id="txt_name" name="txt_name" />
    <input type="file" name="img_upload" id="img_upload">
</form>

img_upload.js
$(function() {

    $("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour

        var txt_name =  $("input#txt_name").val();

        var FileImgData = $('#img_upload').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', FileImgData);

            $.ajax({
                url: "./img_upload_p.php",
                type: "POST",
                data: {
                    txt_name: txt_name,
                    upload_photo: FileImgData
                },
                cache: false,
            })
        },
    });
});

img_upload_p.php
$str_name="";
if(isset($_POST["txt_name"])) { $str_name=trim($_POST["txt_name"]); }

$str_upload_photo="";
if(isset($_FILES['file_photo']))
{ $str_upload_photo = trim($_FILES['file_photo']['name']); }

Please suggest me that image variable declared (upload_photo: FileImgData) in JQuery file "img_upload_p.js" is correct or not.
Also, the way image file variable is fetched in "img_upload_p.php" is correct or not.
if any of them are wrong then how can I assign that image variable in JQuery file and fetch in PHP process page...
PHP image upload code is ready and in working condition... but just having issue with above two mentioned points...

A: One of the best way to do this is use Dropzone js, this is a best library for uploading files using ajax and it also provides progress bar. You can use your own PHP(or any other server side language) code at server side.
I hope it will helpful.

A: img_upload.js
$(function() {

    $("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour

            var formData = new FormData();
            formData.append("hdn_pkid", $("input#hdn_pkid").val()); // if hidden variable is passed
            formData.append("txt_name",$("input#txt_name").val()); // if other input types are passed like textbox, textarea, select etc...
            formData.append('img_upload', $('input[type=file]')[0].files[0]); // if image or other file is passed

            $.ajax({
                url: "./img_upload_p.php",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                cache: false,
            })
        },
    });
});

img_upload_p.php

*

*Get all variables' value using POST method and store them in new variables to use and process on this page as usual.

*Get file variable like below mentioned code and then upload image using normal PHP function or your own way.
if(isset($_FILES['img_upload']))
{ $str_ = trim($_FILES['img_upload']['name']); }


Q: How do I continue to perform aggregation on a single thread that has polling? I create a flow, which polls rows from database by status, validate them and after that aggregate to collection. After processing the entire flow, each line is set to the appropriate status. But when I use aggregator with release strategy TimeoutCountSequenceSizeReleaseStrategy, and elapsed time is so small, release group doesn't happen. And after that the following polling occurs in another thread, but previous message group wasn't handled until amount of messages won't reach the target(threshold) in the strategy.
Code of my flow:
@Bean
public IntegrationFlow testFlow(EntityService entityService,
                                EntityValidator entityValidator,
                                EntityFlowProperties properties,
                                EntityChecker checker) {
    return IntegrationFlows
            .from(getMessageSource(entityService::getByStatus, properties.getMaxRowsPerPoll()),
                    e -> e.poller(getPollerSpec(properties)))
            .split()
            .transform(entityValidator::validate)
            .filter(ValidationStatus<Entity>::isValid, filter ->
                    filter.discardFlow(flow -> flow.handle(entityService::handleValidationErrors)))
            .transform(ValidationStatus<Entity>::getEntity)
            .aggregate(aggregatorSpec -> aggregatorSpec.releaseStrategy(new TimeoutCountSequenceSizeReleaseStrategy(5, 10000)))
            .transform(checker::checkOnSomething)
            .split()
            .transform(CheckResultAware<Entity>::getEntity)
            .handle(entityService::saveAndChangeStatus)
            .get();

I expect to perform aggregation on the same thread as polling, and don't make a new polling until the current flow is over.
The way of changing statuses between polling and aggregation isn't suitable.
Is there a way to do this?

A: Why do you need TimeoutCountSequenceSizeReleaseStrategy; your sequences are finite; just use the default SimpleSequenceSizeReleaseStrategy.
However the TimeoutCountSequenceSizeReleaseStrategy should release based on the sequence size anyway.
But, it's not really suitable for your use case because you can be left with a partial group in the store.


Q: Handle arrays in laravel I am learning laravel and trying to create a community with laravel. I stuck at some part and need to ask you guys.
Right now I am trying to displaying posts to reader.
This is what i accomplish so far

with this code :
public $restful = true;
public function get_index($title = '')
{
    //Do we have an arguement?
        if(empty($title))
        {return Redirect::to('dashboard');}

    $view = View::make('entry');
    $query = DB::table('threads')->where('title', '=', $title)->first();

    //Do we have this thread?
        if(!$query)
        {return Redirect::to('entry/suggest');}
    //We have? so lets rock it!
    $view->title = $query->title; //we get the title.

    $thread_id = $query->id;

    //getting posts.

    $posts = DB::table('posts')->where('thread_id', '=', $thread_id)->get();

    $view->posts = $posts;

  return $view;
}

and the view is :

{{$title}}

@foreach($posts as $post)

1{{$post->post_entry}}

{post_row.POST_USERNAME} {post_row.DATE}

@endforeach

But the hard part(for me) is integrate posts with poster's username or other user info like e-mail for moderate privileges. However hey are in 'users' table.
Lets say $posts variable holds data of 10 posts for a thread
 *a post has thread_id , poster_userid, post, posted_date.
How can i grab username from 'users' table and send it to my view? I am sure i need to use foreach after selecting posts from database I just dont know how to handle arrays in foreach.

A: Look up how to set up models and their relationships using Eloquent ORM:
http://laravel.com/docs/database/eloquent
Specifically http://laravel.com/docs/database/eloquent#relationships
You should have three models, Thread, Post and User (change poster_userid to user_id... or you can keep it but I wouldn't suggest it... just keep things simple. You could also use author_id or maybe even poster_id if that floats your boat.. just be sure to change 'user_id' out with what you choose)
//application/models/User.php

class User extends Eloquent {

 public function posts()
 {
      return $this->has_many('Post', 'user_id');
 }
}

and
//application/models/Post.php
class Post extends Eloquent {

 public function author()
 {
    return $this->belongs_to('User', 'user_id');
 }

 public function thread()
 {
    return $this->belongs_to('Thread', 'thread_id');
 }
}

and
 //application/models/Thread.php
    class Thread extends Eloquent {

     public function posts()
     {
          return $this->has_many('Post', 'thread_id');
     }

    }

and instead of
$query = DB::table('threads')->where('title', '=', $title)->first();

//Do we have this thread?
    if(!$query)
    {return Redirect::to('entry/suggest');}
//We have? so lets rock it!
$view->title = $query->title; //we get the title.

$thread_id = $query->id;

//getting posts.

$posts = DB::table('posts')->where('thread_id', '=', $thread_id)->get();

I would just put
$thread = Thread::where('title', '=', $title)->first();

if(!$query)
    {return Redirect::to('entry/suggest');}

$posts = $thread->posts()->get();
//or if you want to eager load the author of the posts:
//$posts = $thread->posts()->with('author')->get();

Then in your view you can look up the user's name by the following:
$post->author->username;

Easy peezy.

A: With Eloquent you can do this in multiple ways.
First, you can add a method to your post model that retrieves the related data. This approach will create a new query for each post, so it's normally not the best choice.
class Post extends Eloquent
{
    public function user()
    {
        return $this->has_one('User');
    }
}

Second, you can modify your initial query to join your desired data and avoid creating undo queries. Know as "Eager Loading".
// Example from Laravel.com

foreach (Book::with('author')->get() as $book)
{
    echo $book->author->name;
}


Q: How to revert multiple pull request merges all at once and preserve history I have a case where the Github repo master currently has a series of individual pull requests that have already been merged into master. I want to revert say the last 20 of those pull request merges but do it from the command line and preserve history.
A similar question was marked as duplicate revert multiple merges
However the answers given as already existing do not really deal with the specific question of what happens when everything you want to revert came from a series of pull requests which are all merges. Using the -m option with git revert is good for one merge at time right? So I think the answer is that there is not a good way (from the command line) to quickly revert a series of individual pull requests that have been merged and preserve history? Please correct me if I am wrong about this. If I have to do one at a time, I might as well just use the Github console and click on revert for each one.

A: If you want to have a single (later) revision where you revert the changes from all those merges, you can do it like this:
git checkout <id-of-revision> # use the ID of the revision you would like to get your project back to (in terms of content)
git reset --soft <the-branch> # the branch where we want to add a revision to revert all of that
git commit -m "Reverting"
# If you like the results
git branch -f <the-branch> # move branch pointer to this new revision
git checkout <the-branch>

A: Step1
Create a new backup branch first and keep it aside. (backup-branch)
Create a new branch from master or dev wherever you want to revert.(working-branch)
git revert commitid1
git revert commitid2
git revert commitid3....
is the best option.
dont do git reset --hard commitid it will mesh up your indexing.
Reverting is the safe option.
i have done 180 revert commits.
Step2
git log -180 --format=%H --no-merges
use this command to print all the commit ids alone.
it will ignore the merge commit id.
commitid1 commitid2 commitid3 ..... it will print like that.
Copy it to sublime ctrl+a -> ctrl +alt + l add
git revert --no-commit commitid1
git revert --no-commit commitid2
git revert --no-commit commitid3
Copy all and paste in the command prompt. All your commits will be reverted. now do a git commit.
Then do git push.
create a merge request to master.
Step3
How to verifiy?
create a new branch (verify-branch).
YOu can verify it by doing a
git reset -hard commitidX. This is the commit id to which you need to revert.
git status It will give you the number of commits behind the master.
git push -f
Now compare this branch with your working-branch by creating a pull request between them. you will see no changes means your working branch successfully reverted back to the version you're looking for.


Q: What is the context for `this` in Node.js when run as a script? From the node REPL:
$ node
> var x = 50
> console.log(x)
50
> console.log(this.x)
50
> console.log(this === global)
true

Everything makes sense. However, when I have a script:
$ cat test_this.js
var x = 50;
console.log(x);
console.log(this.x);
console.log(this === global);
$ node test_this.js
50
undefined
false

Not what I expected.
I don't really have a problem with the REPL behaving differently from a script, but where exactly in the Node documentation does it say something like "NOTE: when you run a script, the value of this is not set to global, but rather to ___________." Does anyone know, what this refers to in the global context when run as a script? Googling "nodejs this global context script" takes me to this page which looks very promising, as it describes contexts for running scripts, but it doesn't seem to mention the use of the this expression anywhere. What am I missing?

A: In Node.js, as of now, every file you create is called a module. So, when you run the program in a file, this will refer the module.exports. You can check that like this
console.log(this === module.exports);
// true

As a matter of fact, exports is just a reference to module.exports, so the following will also print true
console.log(this === exports);
// true

Possibly related: Why 'this' declared in a file and within a function points to different object


Q: Twilio : Calculating estimated wait time in multi queue multi server system I have a system that has multiple queues, whenever a user calls if no agent is available it will wait in the queue. The queue has multiple filters which separates the agent based on their skills. I want to calculate the estimated wait time for each user in the queue based on their position as well as skill.


Q: REACT_APP_VERSION=$npm_package_version not working on build with Webpack I have a React app, initialized with CRA.
on my .env file I have the following env variable, to access on my application the version of the package.json file:
REACT_APP_VERSION=$npm_package_version
When I use nom run build with react-scripts build, the production build takes the env value from the .env file and shows the correct version defined on package.json.
But when I use web pack to build the production app, the version value is not injected to the env variable.
this is my web pack.config.js file:
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
require('dotenv').config({ path: './.env.staging.local' })
const srcFolder = 'src'
const distFolder = 'dist'

module.exports = {
    // entry point for application
    entry: {
        app: path.join(__dirname, srcFolder, 'index.js'),
    },
    mode: 'production',
    resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
        fallback: {
            fs: false,
            crypto: require.resolve('crypto-browserify'),
            stream: require.resolve('stream-browserify'),
        },
    },

    // output file settings
    // path points to web server content folder where the web server will serve
    // the files from file name is the name of the files, where [name] is the
    // name of each entry point
    output: {
        path: path.join(__dirname, distFolder),
        filename: '[name].js',
        publicPath: '.',
    },
    optimization: {
        splitChunks: {
            chunks: 'async',
            minSize: 20000,
            minRemainingSize: 0,
            minChunks: 1,
            maxAsyncRequests: 30,
            maxInitialRequests: 30,
            enforceSizeThreshold: 50000,
            cacheGroups: {
                defaultVendors: {
                    test: /[\\/]node_modules[\\/]/,
                    priority: -10,
                    reuseExistingChunk: true,
                },
                default: {
                    minChunks: 2,
                    priority: -20,
                    reuseExistingChunk: true,
                },
            },
        },
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'public/index.html',
            filename: 'index.html',
        }),
        new CopyWebpackPlugin({
            patterns: [
                { from: 'public/assets', to: './assets' },
                { from: 'public/favicon.ico', to: './favicon.ico' },
                { from: 'public/manifest.json', to: './manifest.json' },
                { from: 'public/robots.txt', to: './robots.txt' },
            ],
        }),
        new webpack.DefinePlugin({
            'process.env': JSON.stringify(process.env),
        }),
    ],
    performance: {
        hints: false,
        maxEntrypointSize: 512000,
        maxAssetSize: 512000,
    },
}

Can someone please point out what should I do to have this value injected on the env variable as with react-scripts build


Q: Css needed to highlight common words in a table I came across this page on slate.com that highlights similar words in a table when you hover over one instance:
http://www.slate.com/blogs/lexicon_valley/2013/09/11/top_swear_words_most_popular_curse_words_on_facebook.html
Does anyone know how this is done?

A: You can do it with jQuery like this:
$('table td').mouseover(function() {
    $('table td').removeClass('highlight')
    var text = $(this).text();
    $('table td').filter(function() { return $(this).text() == text; }).addClass('highlight');
})

Check this jsFiddle

A: using jQuery.data
Always to know how something works, the first step is to read the source code
Check this:
EXAMPLE
$('.interactive_table .cell_word')
    .hover(function(){
        var word = $(this).data('word');
        $(this).parent().parent()
        .find('.word_'+word)
        .addClass('highlighted');
    },function(){
        var word = $(this).data('word');
        $(this).parent().parent()
        .find('.word_'+word)
        .removeClass('highlighted');
});

$('.interactive_table .cell_rank_number')
    .hover(function(){
        $(this).parent()
        .find('.cell_word')
        .addClass('highlighted');
    },function(){
        $(this).parent()
        .find('.cell_word')
        .removeClass('highlighted');
});


Q: Vue radio button v-if with v-model I am very new to html and vue, and trying to create radio button. I use local JSON file which is being used for creating UI. I loop through JSON object and create radio buttons accordingly. I used "defaultedOptionId" to find which one to be checked as default. Here is my JSON:
{ "id": 1,
  "selected": 1,
  "defaultedOptionId": 2,
  "selections": [
    {
      "selectionId": 1,
      "description: "XX"
    },
    ...
},
...

I am using Vue component, which basically holds JSON file. In the template, I have code so when 'defaultedOptionId === selectionId', check as default

     <input v-if="choice.defaultOptionId === selection.selectionId" type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" checked></input>
     <input v-else type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId"></input>
        {{ index+1 }}. {{ selection.description }}

'choice' is basically JSON object.
This works if I change defaultOptionId to something else. HOWEVER, if I want to update JSON object as user selects radio button, I have to add v-model to the input field like this:

     <input v-if="choice.defaultOptionId === selection.selectionId" type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" v-model="choice.selectedOptionId" checked></input>
     <input v-else type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" v-model="choice.selectedOptionId"></input>
        {{ index+1 }}. {{ selection.description }}

With this, radio buttons with 'checked' property doesn't work. It checks first option and even if I change 'defaultOptionId', it doesn't care.
Basically, I want to load different JSON file with different 'defaultOptionId' which changes default check for radio button WHILE when user selects radio button, it updates JSON file's 'selectedOptionId'. I can make it work separately, but not together. I have to use this design since other templates are following the same design.

A: It's difficult to understand what you're trying to do and what the problem is because the question looks like a mess, but I'll try to help anyway.
Demo:
Here's a working example with your data:
https://codepen.io/AlekseiHoffman/pen/XWJmpod?editors=1010
Template:

    <input
      type="radio"
      :id="selection.id"
      :value="selection.selectionId"
      v-model="choice.selected"
    >

      {{selection.description}}

    Selected: {{ choice.selected }}

Script:
choice: {
  "id": 1,
  "selected": 2,
  "selections": [
    {
      "selectionId": 1,
      "description": "Radio One"
    },
    {
      "selectionId": 2,
      "description": "Radio Two"
    }
  ]
}

I simplified the JSON object since the other properties are not needed there to make it work.
Let me know if you're still having difficulties with your task.


Q: Comparison of serializing methods
Possible Duplicate:
Fastest serializer and deserializer with lowest memory footprint in C#?

I'm using BinaryFormatter class to serialize an structure or a class. (after serialization, I'm going to encrypt the serialized file before saving. (And of course decrypt it before deserialization))
But I heard that some other serialization classes are present in .Net Framework. Like  XmlSerializer, JavaScriptSerializer, DataContractSerializer and protobuf-net.
I want to know, which one is best for me?
Less RAM space needed for serialize/deserialize is the most important thing for me. Also speed is important.

A: If your aim is to reduce memory demands, then don't serialize then encrypt: instead - serialize directly to an encrypting Stream. The Stream API is designed to be chained (decorator pattern) to perform multiple transformations without excessive buffering. Likewise: deserialize from a decrypting stream; don't decrypt then deserialize. Done this way, data is encrypted/decrypted on-the-fly as needed; in addition to reducing memory, it is also good for security - since this also means the entire data never exists in decrypted form as a single buffer. See CryptoStream on MSDN for a full example.
Some additional notes; if you do happen to use protobuf-net, there are ways of reducing any in-memory buffering by using "grouped" encoding; you see: the default for sub-messages (including lists) is "length prefixed" - and the way it usually does this is by buffering the data in memory to calculate the length. However, protobuf also supports a format that uses a start/end marker which never requires knowing the length, so never requires buffering - and so the entire sequence can be written in a single pass direct to output (well, it does still use a buffer internally to improve IO, but it pools the buffer here, for maximum re-use). This is as simple as, for sub-objects:
[ProtoMember(11, DatFormat = DataFormat.Grouped)]
public Customer Customer {get;set;} // a sub-object

(where there is no significance in the 11)

A: See http://code.google.com/p/protobuf-net/wiki/Performance for a comparison of performance.


Q: Looking for jQuery find(..) method that  includes the current node The jQuery find(..) traversal method doesn't include the current node - it starts with the children of the current node.  What is the best way to call a find operation that includes the current node in its matching algorithm? Looking through the docs nothing immediately jumps out at me.

A: Define
$.fn.findSelf = function(selector) {
    var result = this.find(selector);
    this.each(function() {
        if ($(this).is(selector)) {
            result.add($(this));
        }
    });
    return result;
};

then use
$.findSelf(selector);

instead of
$find(selector);

Sadly jQuery does not have this built-in. Really strange for so many years of development. My AJAX handlers weren't applied to some top elements due to how .find() works.

A: $('selector').find('otherSelector').add($('selector').filter('otherSelector'))

You can store $('selector') in a variable for speedup. You can even write a custom function for this if you need it a lot:
$.fn.andFind = function(expr) {
  return this.find(expr).add(this.filter(expr));
};

$('selector').andFind('otherSelector')

A: The accepted answer is very inefficient and filters the set of elements that are already matched.
//find descendants that match the selector
var $selection = $context.find(selector);
//filter the parent/context based on the selector and add it
$selection = $selection.add($context.filter(selector);

A: You can't do this directly, the closest I can think of is using .andSelf() and calling .filter(), like this:
$(selector).find(oSelector).andSelf().filter(oSelector)
//or...
$(selector).find('*').andSelf().filter(oSelector);

Unfortunately .andSelf() doesn't take a selector, which would be handy.

A: If you want the chaining to work properly use the snippet below.
$.fn.findBack = function(expr) {
    var r = this.find(expr);
    if (this.is(expr)) r = r.add(this);
    return this.pushStack(r);
};

After the call of the end function it returns the #foo element.
$('#foo')
    .findBack('.red')
        .css('color', 'red')
    .end()
    .removeAttr('id');

Without defining extra plugins, you are stuck with this.
$('#foo')
    .find('.red')
        .addBack('.red')
            .css('color', 'red')
        .end()
    .end()
    .removeAttr('id');

A: In case you are looking for exactly one element, either current element or one inside it, you can use:
result = elem.is(selector) ? elem : elem.find(selector);

In case you are looking for multiple elements you can use:
result = elem.filter(selector).add(elem.find(selector));

The use of andSelf/andBack is pretty rare, not sure why. Perhaps because of the performance issues some guys mentioned before me.
(I now noticed that Tgr already gave that second solution)

A: I know this is an old question, but there's a more correct way. If order is important, for example when you're matching a selector like :first, I wrote up a little function that will return the exact same result as if find() actually included the current set of elements:
$.fn.findAll = function(selector) {
  var $result = $();

  for(var i = 0; i < this.length; i++) {
    $result = $result.add(this.eq(i).filter(selector));
    $result = $result.add(this.eq(i).find(selector));
  }

  return $result.filter(selector);
};

It's not going to be efficient by any means, but it's the best I've come up with to maintain proper order.

A: I was trying to find a solution which does not repeat itself (i.e. not entering the same selector twice).
And this tiny jQuery extention does it:
jQuery.fn.findWithSelf = function(...args) {
  return this.pushStack(this.find(...args).add(this.filter(...args)));
};

It combines find() (only descendants) with filter() (only current set) and supports whatever arguments both eat. The pushStack() allows for .end() to work as expected.
Use like this:
$(element).findWithSelf('.target')

A: For jQuery 1.8 and up, you can use .addBack(). It takes a selector so you don't need to filter the result:
object.find('selector').addBack('selector')

Prior to jQuery 1.8 you were stuck with .andSelf(),  (now deprecated and removed) which then needed filtering:
object.find('selector').andSelf().filter('selector')

A: I think andSelf is what you want:
obj.find(selector).andSelf()

Note that this will always add back the current node, whether or not it matches the selector.

A: If you are strictly looking in the current node(s) the you just simply do
$(html).filter('selector')

A: Here's the right (but sad) truth:
$(selector).parent().find(oSelector).filter($(selector).find('*'))

http://jsfiddle.net/SergeJcqmn/MeQb8/2/


Q: Kendo Grid plumbing I'm trying to get the Kendo UI grid connected in my MVC3 app, but I'm not getting any data displaying. I think it should be simple, but I'm not seeing it. Here is my code:
View:
@model List<pests.web.com.Models.Workitem>

@{
    ViewBag.Title = "Worklist";
    ViewBag.CurrentPage = "Worklist";
}

<link href="../../Styles/kendo.common.min.css" rel="stylesheet" />
<link href="../../Styles/kendo.default.min.css" rel="stylesheet" />

Layout page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Styles/Site.css")" rel="stylesheet" type="text/css" />

        @RenderBody()

Controller code I'm trying to call from the view:
 public class HomeController : Controller
    {
        [HttpPost]
        public ActionResult GetWorklist()
        {
            List<Workitem> worklist = PestsLogic.GetWorklist();
            return View("Home", worklist);
        }
    }

GetWorklist() is returning a few items. They are simple object with a few properties. Here's it is:
public class Workitem
{
    public string PartNumber { get; set; }
    public string ProcurementCode { get; set; }
    public int Priority { get; set; }
    public string Status { get; set; }
}

Is there anything obvious that I've got hooked up wrong? There are no error messages, just a blank page (with a title, though).
Thanks!

A: The problem was simply that I needed to move the references to the JS files to before I tried to use the Kendo grid.


Q: Train Stacked Autoencoder Correctly I try to build a Stacked Autoencoder in Keras (tf.keras). By stacked I do not mean deep. All the examples I found for Keras are generating e.g. 3 encoder layers, 3 decoder layers, they train it and they call it a day. However, it seems the correct way to train a Stacked Autoencoder (SAE) is the one described in this paper: Stacked Denoising Autoencoders: Learning Useful Representations in
a Deep Network with a Local Denoising Criterion
In short, a SAE should be trained layer-wise as shown in the image below. After layer 1 is trained, it's used as input to train layer 2. The reconstruction loss should be compared with the layer 1 and not the input layer.

And here is where my trouble begins. How to tell Keras which layers to use the loss function on?
Here is what I do. Since the Autoencoder module is not existed anymore in Keras, I build the first autoencoder, and I set its encoder's weights (trainable = False) in the 1st layer of a second autoencoder with 2 layers in total. Then when I train that, it obviously compares the reconstructed layer out_s2 with the input layer in_s, instead of the layer 1 hid1.
# autoencoder layer 1
in_s = tf.keras.Input(shape=(input_size,))
noise = tf.keras.layers.Dropout(0.1)(in_s)
hid = tf.keras.layers.Dense(nodes[0], activation='relu')(noise)
out_s = tf.keras.layers.Dense(input_size, activation='sigmoid')(hid)

ae_1 = tf.keras.Model(in_s, out_s, name="ae_1")
ae_1.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['acc'])

# autoencoder layer 2
hid1 = tf.keras.layers.Dense(nodes[0], activation='relu')(in_s)
noise = tf.keras.layers.Dropout(0.1)(hid1)
hid2 = tf.keras.layers.Dense(nodes[1], activation='relu')(noise)
out_s2 = tf.keras.layers.Dense(nodes[0], activation='sigmoid')(hid2)

ae_2 = tf.keras.Model(in_s, out_s2, name="ae_2")
ae_2.layers[0].set_weights(ae_1.layers[0].get_weights())
ae_2.layers[0].trainable = False

ae_2.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['acc'])

The solution should be fairly easy, but I can't see it nor find it online. How do I do that in Keras?

A: It seems like the question is outdated by looking at the comments. But I'll still answer this as the use-case mentioned in this question is not just specific to autoencoders and might be helpful for some other cases.
So, when you say "train the whole network layer by layer", I would rather interpret it as "train small networks with one single layer in a sequence".
Looking at the code posted in this question, it seems that the OP has already built small networks. But both these networks do not consist of one single layer.
The second autoencoder here, takes as input the input of first autoencoder. But, it should actually take as input, the output of first autoencoder.
So then, you train the first autoencoder and collect it's predicitons after it is trained. Then you train the second autoencoder, which takes as input the output (predictions) of first autoencoder.
Now let's focus on this part: "After layer 1 is trained, it's used as input to train layer 2. The reconstruction loss should be compared with the layer 1 and not the input layer."
Since the network takes as input the output of layer 1 (autoencoder 1 in OP's case), it will be comparing it's output with this. The task is achieved.
But to achieve this, you will need to write the model.fit(...) line which is missing in the code provided in the question.
Also, just in case you want the model to calculate loss on input layer, you simply replace the y parameter in model,fit(...) to the input of autoencoder 1.
In short, you just need to decouple these autoencoders into tiny networks with one single layer and then train them as you wish. No need to use trainable = False now, or else use it as you wish.


Q: Can I inherit my WCF DataContract from a shared interface? I have a WCF service and client in the same solution (different projects). The service class itself inherits from an interface, and that interface is shared between client and server (via a linked file). The client uses a service factory to generate a proxy. This has proved a really nice way to link the two sides without referencing the server-side project from the client.
One of the service methods returns an object that includes the DataContract and DataMember attributes, and until recently this class was linked to the client as well, but the server-side logic was excluded from the client using compilation symbols.
I decided it would be more sensible to turn this into an interface as well. But now I get the following exception every time the service method is called from the client:
The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
Its inner exception is as follows:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
So by way of simplified example, my service essentially shares the following interface with the client:
public interface IMyData
{
    [DataMember]
    int Id {get; set;}

    [DataMember]
    string Description {get; set;}
}

The actual object that the interface works with and will return looks something like this:
[DataContract]
public class MyData : IMyData
{
    [DataMember]
    public int Id {get; set;}

    [DataMember]
    public string Description {get; set;}
}

The interface of my service looks something like this:
[ServiceContract]
public interface IMyService
{
    [OperationContract]
    IMyData GetData();
}

The implementation looks something like this:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)]
public class MyService : IMyService
{
    [OperationContract]
    IMyData GetData()
    {
        // Get data.
    }
}

Hope that all makes a little sense! I'm just wondering if I'm doing this all wrong. I'll just go back to sharing the class and sectioning off the server-side-only code if I have to .. but I'd rather use an interface if I can.
Any ideas?

A: There is no benefit to putting an interface on a DataContract as they simply represent data and no logic. You typically put those DataContracts inside the same assembly with the ServiceContracts or a separate assembly all together. This will prevent exposing the business logic to your clients.


Q: The MailChimp PHP library is missing the required GuzzleHttp library I have installed Guzzle on my Godaddy shared hosting via SSH but my Drupal site is still telling me that:

"The MailChimp PHP library is missing the required GuzzleHttp library.
  Please check the installation notes in README.txt."

Any ideas why it would be saying that? it appears to have installed correctly.
godaddy@user [~/public_html]$ php composer.phar require guzzlehttp/guzzle:~6.0
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing guzzlehttp/promises (1.2.0)
    Downloading: 100%

  - Installing psr/http-message (1.0)
    Downloading: 100%

  - Installing guzzlehttp/psr7 (1.3.0)
    Downloading: 100%

  - Installing guzzlehttp/guzzle (6.2.0)
    Downloading: 100%

Writing lock file
Generating autoload files

A: On the library page, if you are using the package https://github.com/thinkshout/mailchimp-api-php/releases which contains everything e.g. v1.0.6-package.zip (and therefore having everything already doesn't require composer to get them), then remove /vendor from .gitignore so that all the files in /vendor - including guzzle are included in your code base so that should you deploy the code from your repo to a production server, all of it will be loaded.
CREDIT: https://www.drupal.org/node/2709615#comment-11888769

A: This fixed the issue, Guzzle needed to be installed into the MailChimp libraries folder?! Guzzle Instructions
godaddy@user [~/public_html]$ cd sites/all/libraries/mailchimp/
godaddy@user [~/public_html/sites/all/libraries/mailchimp]$ curl -sS https://getcomposer.org/installer | php
All settings correct for using Composer
Downloading 1.1.1...

Composer successfully installed to: /home/mysite/public_html/sites/all/libraries/mailchimp/composer.phar
Use it: php composer.phar
godaddy@user [~/public_html/sites/all/libraries/mailchimp]$ ./composer.phar install
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing sebastian/version (1.0.6)
    Downloading: 100%

  - Installing sebastian/global-state (1.1.1)
    Downloading: 100%

  - Installing sebastian/recursion-context (1.0.2)
    Downloading: 100%

  - Installing sebastian/exporter (1.2.1)
    Downloading: 100%

  - Installing sebastian/environment (1.3.7)
    Downloading: 100%

  - Installing sebastian/diff (1.4.1)
    Downloading: 100%

  - Installing sebastian/comparator (1.2.0)
    Downloading: 100%

  - Installing symfony/yaml (v3.0.6)
    Downloading: 100%

  - Installing doctrine/instantiator (1.0.5)
    Downloading: 100%

  - Installing phpdocumentor/reflection-docblock (2.0.4)
    Downloading: 100%

  - Installing phpspec/prophecy (v1.6.0)
    Downloading: 100%

  - Installing phpunit/php-text-template (1.2.1)
    Downloading: 100%

  - Installing phpunit/phpunit-mock-objects (2.3.8)
    Downloading: 100%

  - Installing phpunit/php-timer (1.0.8)
    Downloading: 100%

  - Installing phpunit/php-token-stream (1.4.8)
    Downloading: 100%

  - Installing phpunit/php-file-iterator (1.4.1)
    Downloading: 100%

  - Installing phpunit/php-code-coverage (2.2.4)
    Downloading: 100%

  - Installing phpunit/phpunit (4.8.21)
    Downloading: 100%

  - Installing guzzlehttp/promises (1.2.0)
    Loading from cache

  - Installing psr/http-message (1.0)
    Loading from cache

  - Installing guzzlehttp/psr7 (1.3.0)
    Loading from cache

  - Installing guzzlehttp/guzzle (6.2.0)
    Loading from cache

sebastian/global-state suggests installing ext-uopz (*)
phpdocumentor/reflection-docblock suggests installing dflydev/markdown (~1.0)
phpdocumentor/reflection-docblock suggests installing erusev/parsedown (~1.0)
phpunit/php-code-coverage suggests installing ext-xdebug (>=2.2.1)
phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)
Writing lock file
Generating autoload files


Q: Building Postgresql C function with Multidimensional Array as input I am extending the Postgresql functions using the C SPI. The function needs to be able to take in a Postgres N-Dim Array and get the data out of it. I am able to get the data from a 1D array but I get a segfault when trying to access a N-Dim array.
My first try to just access an element was simply
PG_FUNCTION_INFO_V1(sum_elements);
Datum
matmul(PG_FUNCTION_ARGS)
{

    ArrayType *anyArray = PG_GETARG_ARRAYTYPE_P(0);
    int32 **a = (int32 **)  ARR_DATA_PTR(anyArray);

    PG_RETURN_INT64(a[1][1]);
}

I also tried as if it flattened the matrix into a 1D array but the values that came out were just garbage.
Thanks for the help!

A: You can try using the deconstruct_array (..) function to extract the values. This function will give you a Datum type pointer.
Example of the book:
deconstruct_array(input_array, //one-dimensional array
                  INT4OID, //of integers
                  4,//size of integer in bytes
                  true,//int4 is pass-by value
                  'i',//alignment type is 'i'
                  &datums, &nulls, &count); // result here

"The datums pointer will be set to point to an array filled with actual elements."
You can access the values using:
DatumGetInt32(datums[i]);


Q: How to get the timestamps of lyrics in songs? We have built an application in Python for getting the lyrics of a song that the user searches for. We are using the Genius API for this. However, we also want to know the timestamps of each lyric in the song, so that we know when each lyric plays or shows up. Is there an API or library that we could use to get the timestamp of each lyric? Or would we need to manually recognize each lyric in the song using an audio recognition technique?
Thank you for all of the help.

A: Last time I looked, Genius Lyrics' APIs do not include timestamps unfortunately. There are alternatives out there, such as Musixmatch - although they're not free (and apparently not cheap).
I did find Lyrics Plus though. It's an integration for Spotify. Maybe their code on GitHub could help. Good luck!


Q: How to add generic condition to sp select? I really don't know what to do in this situation, so don't be too harsh.
If I have my select:
declare @Id uniqueidentifier = 'some parent guid'
declare @Type int = 1 -- can be 1, 2 or 3
declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once

if(@Type = 1)
set @UserType = 'and UserType <> 0'
if(@Type = 2)
set @UserType = 'and UserType = 0'
if(@Type = 3)
set @UserType = ''
    select * from users where parentId = @Id + @UserType

What to do in the situation where condition is "generic"? Do i really need to create 3 different Sp?

A: You can use AND/OR logic to simulate the If-else condition in where clause. Try something like this
select * from users
where
parentid= @id
and
(
(@Type = 1 and UserType <> 0)
or
(@Type = 2 and UserType = 0)
or
(@Type = 3)
)

or you can also use Dynamic sql to do this
declare @Id uniqueidentifier = 'some parent guid'
declare @Type int = 1 -- can be 1, 2 or 3
Declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once
Declare @sql nvarchar(max)

if(@Type = 1)
set @UserType = ' and UserType <> 0'
if(@Type = 2)
set @UserType = ' and UserType = 0'
if(@Type = 3)
set @UserType = ''

set @sql = 'select * from users where parentId ='''+ cast(@Id as varchar(25))+''''+ @UserType

--Print @sql

Exec sp_executesql @sql

A: Different select statements would be most efficient since each is a fundamentally different query.  If static SQL becomes unwieldly, use dynamic SQL.  Below is a parameterized example using techniques from http://www.sommarskog.se/dyn-search.html.
declare @sql nvarchar(MAX) = N'select * from users where parentId = @Id';
declare @Id uniqueidentifier = 'some parent guid';
declare @Type int = 1; -- can be 1, 2 or 3
declare @UserType varchar(max); --can be 0, anything else than 0, or all users at once

SET @sql = @sql + CASE @Type
    WHEN 1 THEN N' and UserType <> 0'
    WHEN 2 THEN N' and UserType = 0'
    WHEN 3 THEN N'' END;

EXEC sp_executesql
      @sql
    , N'@Id uniqueidentifier'
    , @Id = @Id;