text:
Q: Changing the posts page in Wordpress? The topic title might be a little misleading, but I didn't really know what title to give this question, but since it relates to changing the post page, I figured it would be fine.
So I actually figured out how to change the posts page and set up a static front page. Right now I have a landing page that is my front page and then a journal page, which is where my posts appear.
My issue is that when I click on a post the journal link in my navigation doesn't stay selected. And I would like users to know that when they click on a post they are still in the journal area by having the journal link in the navigation stay selected, but I can't figure out how to get the journal link to remain highlighted as the current link.
When a user goes to journal (the page that displays all of my posts) the journal link in the navigation stays selected. It's only when a user clicks on a post that journal is no longer selected.
So I guess my question is:
How do I get the post page link to stay current/selected when on a post?
I mean, I think I have an idea why it is not staying selected just by looking at the url's. When I'm on the journal page the url is (by the way I'm working locally which is why I can't link to the site):
http://localhost/wordpress/journal/
And when I'm on a post the url looks like this:
http://localhost/wordpress/example-post/
When really it should look like this:
http://localhost/wordpress/journal/example-post/
so that all the posts recognizes the journal as its parent, but I can't figure out how to do that.
Anyways, any help would be much appreciated. Thanks in advance!

**EDIT*
Turns out simply getting the url to be http://localhost/wordpress/journal/example-post/ didn't work. Which tells me that there is something in the php that needs to be changed, added, and/or edited. So I started inspecting the journal link in the nav and it looks like on the posts page it is getting a few classes that it isn't getting on the post page.
Here is what the journal link looks like on the posts page:

Journal

And here is what the journal link looks like on the post page:

Journal

I compared the two and it looks like the journal link on the post page is missing a few classes that the journal link on the posts page has. Mainly class="current-menu-item current_page_item" which are classes that it would need to show up as selected/current (well, actually it only needs one of those classes to show up as selected/current). Anyways, I tried to find where those classes are being added in the php and it looks like they both appear wp-includes/nav-menu-template.php. The file looked quite complicated and I didn't want to mess with it and break the site, but anyone running Wordpress 3.5.1 should have the same file I have if you want to take a look at it. I'm guessing that is where the issue lies and am thinking I would need to add something in my themes functions to address the problem. I just don't know what that would be :/

**EDIT*
Screenshot of the posts page
This is what the posts page looks like. Notice how JOURNAL is black while the other links are gray. I'm trying to get JOURNAL to stay black/selected/current when on a post

Screenshot of the post page
This is what the post page looks like. Notice how JOURNAL is not black/selected/current. Instead it is gray like all the other nav links. I'm trying to figure out how to get JOURNAL to stay black/selected/current when on both the post and/or the posts page. In other words when you are on the journal page or the journal entry page (journal page displays all journal entries, while journal entry page just displays the entry you are on).

A: Try this: Go to settngs->Permalinks and select custom.  Add this: /journal/%postname%
I just tried this and it worked for me.  Hopefully it will work for you too!
-Lisa

A: try to use the css  class in your stylesheet
ul li.current-menu-item { color:red;}
or other one
ul li.current-menu-item a { color:red;}
it will work for this


text:
Q: How to Action chain using ActionSequence inWebdriverjs Javascript Nodejs ActionSequence? I am chaining my action of clicking Navigation Menu and for that purpose I am trying to use this ActionSequence Class in Javascript/NodeJs Selenium Automation. I know there is fairly straight forward way of action chaining in Java. Is this the analogous thing in Javascript. How do i use this? Below is the Documentation, i referred to and the code i tried. Can somebody write the exact way to write it down not a one line to make it work. I tried several ways and none worked for me. I may be making some silly mistake since i am not familiar a lot with ins and out of javascript selenium.
Class ActionSequence
Class for defining sequences of complex user interactions. Each sequence will not be executed until {@link #perform} is called.
Example:
 new ActionSequence(driver).
     keyDown(Key.SHIFT).
     click(element1).
     click(element2).
     dragAndDrop(element3, element4).
     keyUp(Key.SHIFT).
     perform();

This is the documentation of ActionSequence.
How do i use this class ? Is this the latest thing for action chaining to be used in Javascript Selenium ? If there is something new please show me that.
I have tried to use this inside async function :
  let actionSequence = new webdriver.ActionSequence(driver);

  await  actionSequence
    .mouseMove(NavElementArray[0][1])
    .mouseMove(NavElementArray[2][1])
    .click()
    .perform();

Am i defining actionSequence or using the correct way. Error' webdriver.ActionSequence is not a constructor'
Please do not put answer on how to do it in Java or other bindings. Just stick to Javascript NodeJs webdriverjs. Thank you.

A: not sure which version you're using but
https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/actions_exports_LegacyActionSequence.html
appears deprecated
try importing/new LegacyActions(driver).chain1().chain2()...chainN().perform()

A: Added 3 lines in the index.js file in node-modules/selenium-webdriver of my project.
const actions = require('./lib/actions');

after the first long list of const declarations
const LegacyActionSequence = actions.LegacyActionSequence;

after the next smaller list of declarations
exports.LegacyActionSequence=actions.LegacyActionSequence;

at the end of the exports list at the end of the file.
My code,
await new LegacyActionSequence(driver)
.mouseMove(element,{x:0,y:0})
.perform()

earlier was showing
TypeError: LegacyActionSequence is not a constructor

Working smoothly, for now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: automaticly refreshing excel sheets I made a small console application that refreshes all the excel files in the same directory the program is in.
Its works perfectly well on the pc in wrote it on, but when I use it on a normal-client windows pc it does not even start.
Is there anything that needs to be installed, in order to make it work ?
code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace CNTExcelUpdate_Invisible
{
    class Program
    {
        static string path = System.Reflection.Assembly.GetEntryAssembly().Location;

        static void Main(string[] args)
        {
            path = Path.GetDirectoryName(path);
            updateDirectory(path);
            Environment.Exit(0);
        }

        public static void updateDirectory(string path)
        {
            int amount = 0;
            string[] files;
            files = Directory.GetFiles(path, "*.xlsx", SearchOption.AllDirectories);
            amount += files.Count();

            int counter = 0;
            try
            {
                foreach (var file in Directory.EnumerateFiles(path, "*.xlsx", SearchOption.AllDirectories))
                {
                    string fileName = Path.GetFileName(file);

                    if (fileName.Substring(0, 2).Equals("GK"))
                    {
                        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file,
                        0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                        true, false, 0, true, false, false);
                        excelApp.DisplayAlerts = false;
                        excelWorkbook.RefreshAll();
                        System.Threading.Thread.Sleep(1000);

                        excelApp.Quit();
                        excelApp = null;
                        excelWorkbook.SaveAs(file, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);

                        //excelWorkbook.Close();
                        Marshal.ReleaseComObject(excelWorkbook);
                        excelWorkbook = null;
                    }
                    counter++;

                    Console.Write(counter.ToString() + "/" + amount.ToString() + " Dateien verarbeitet");
                    Console.SetCursorPosition(0,0);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler bei der Verbindung: \r\n" + e.ToString());
            }
        }

    }
}


text:
Q: Rails 3 and delayed_job on production Using delayed_job gem with my rails 3 app on development working great but when I tried to use it on production using capistrano it gives me these error

script/delayed_job: Permission denied

I am using their method
and I followed These Railscast video
http://railscasts.com/episodes/171-delayed-job-revised
https://github.com/collectiveidea/delayed_job/wiki/Rails-3-and-Capistrano

A: Without knowing anything more (what users are you using? how do the permissions on the file look like?), I can't give you a better solution than to try
chmod a+x script/delayed_job

to give everyone execution permission for the script/delayed_job file...


text:
Q: Display problem in IE8 The following page is mucked up in IE8 -- the bulk of the content starts appearing half way down the screen and the tables/divs do not look as they should.  It works in other browsers and in IE8 compatibility mode.  I've inspected the HTML and can't work out what's wrong.  Any help would be appreciated.  Thanks.
http://www.moviemonitor.com/browse/itunes

A: After a quick glance in Firefox and IE8, I'd say there is some malformed HTML in there somewhere.  Looks to me like a mismatched open/close tag that IE8 isn't forgiving.  Run the whole thing through an HTML validator.

A: I suggest removing the min-height: 800px; CSS value from the first DIV element after <div id="mainContent">. Apparently IE8 renders the first child block level element with that height irrespective of any other contained elements.
Then again, those HTML validation results are pretty grim. Try to fix some of the invalid HTML and make sure that all of your tags are closed properly.


text:
Q: Error with HTTP header when submit twice the same request Hi there I'm doing a very simple API using NodeJS, ExpressJS and MySQLJs. I have a little form that make the request login request to the server. The problem I have is when I'm trying to do the same request twice after the first has been finished, the server answer me with a ERR_CONNECTION_REFUSED
I was using this tutorial in order to make my code a little bit cleaner. I've changed a little because I think class makes the code cleaner than using functions.
https://code.tutsplus.com/tutorials/managing-the-asynchronous-nature-of-nodejs--net-36183
This is the full backtrace of the error I have
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at User.<anonymous> (/home/ismael/Projects/internal_project/app.js:84:9)
    at User.emit (events.js:187:15)
    at Query.<anonymous> (/home/ismael/Projects/internal_project/model/user.js:20:14)
    at Query.<anonymous> (/home/ismael/Projects/internal_project/node_modules/mysql/lib/Connection.js:502:10)
    at Query._callback (/home/ismael/Projects/internal_project/node_modules/mysql/lib/Connection.js:468:16)
    at Query.Sequence.end (/home/ismael/Projects/internal_project/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
    at Query._handleFinalResultPacket (/home/ismael/Projects/internal_project/node_modules/mysql/lib/protocol/sequences/Query.js:139:8)
    at Query.EofPacket (/home/ismael/Projects/internal_project/node_modules/mysql/lib/protocol/sequences/Query.js:123:8)
    at Protocol._parsePacket (/home/ismael/Projects/internal_project/node_modules/mysql/lib/protocol/Protocol.js:278:23)

This is my main javascript where I define the main structure of my simple application. In the log I can see that the second request is enter in success callback, what am I missing?
app.post( '/login/', function(req, res){
  user.on('success', function(result){
    logger.debug( '[SUCCESS]' );

    res.cookie('user', { name : result.name, id : result.id  });
    res.setHeader( 'Content-Type', 'application/json' );
    res.status(200).end( JSON.stringify({success : true}) );
  });
  user.on('failure', function(reason){
    logger.debug( '[FAILURE]' );

    res.setHeader( 'Content-Type', 'application/json' );
    res.status(400).send( JSON.stringify({success: false}) );
  });
  user.on('error', function(error){
    // logger.debug( '[ERROR]' );
    //
    // res.setHeader( 'Content-Type', 'application/json' );
    // res.status(500).send( JSON.stringify({ error: 'Internal error' }) );
  });
  user.login( req.body.username, req.body.password );
});

And this is the login method of the User class
login ( username, password ){
    var that = this;

    this.sql.query( "SELECT * FROM user WHERE name = ? AND password = ?", [ username, password ], function(error, result, fields){
      // if ( error ){
      //   that.emit('error', error);
      //   return true;
      // }

      if ( result.length == 0 ){
        that.emit( 'failure' );
        return true;
      }

      if ( result.length >= 1 ){
        that.emit( 'success', result[0] );

        return true;
      }

    });
  }

I'm using this Javascript in front side to get all the values from the login form and send it to the API.
main.js
(function(){
  var _loginForm = {},
      _loginUsername = {},
      _loginPassword = {},
      _loginConfig = {
        url : '/login/',
        method : 'POST'
      },
      _loginRequest = new XMLHttpRequest();

  var
  _onLoginRequest = function(){
    console.log( this );

    if ( this.readyState == 4 ){
      JSON.parse(this.responseText)
    }
  },
  _onLoginSubmit = function(evt){
    evt.preventDefault();

    _loginRequest.onreadystatechange = _onLoginRequest;
    _loginRequest.open( _loginConfig.method, _loginConfig.url, true );
    _loginRequest.setRequestHeader( 'Content-Type', 'application/json' );
    _loginRequest.send(JSON.stringify({
      username : _loginUsername.value,
      password : _loginPassword. value
    }));
  },
  _onDomLoad = function(evt){
    _loginForm = document.getElementById( 'login-form' );
    _loginUsername = document.getElementById( 'username' );
    _loginPassword = document.getElementById( 'password' );

    _loginForm.addEventListener( 'submit', _onLoginSubmit );
  };

  document.addEventListener( 'DOMContentLoaded', _onDomLoad );

})();

Thanks in advance.

A: You are registering event handlers for every request. The problem is, you're not removing any of the request handlers afterwards.
For example, if you did 10 POST requests to the login endpoint, and then you do the 11th. If the 11th's is successful, the success event is triggered for the current request but also all the other 10.
The reason you're getting Cannot set headers after they are sent to the client is because the event listener is being triggered for a HTTP request that already completed.
The solution is to architect this different. The EventListener is not a good model for calling functions and getting results. EventListener is good for things that can trigger many times. In this case you don't want that, you only want 1 success or 1 failure per request.
The right model for this is:
A) A simple function call. It can return information related to it's success and throw an exception if it failed.
B) Return promises. Resolve them if login was successful, Reject them if not.
C) Use async/await. Again: return the result if it was successful, throw an error if not.
D) Use the callback pattern that you're already using with express. So pass a callback with a err and result parameter.
The last option might be preferable because you're working with a framework that doesn't support Promises and async/await well.

A: Create User object inside app.post api call instead of creating it globally.


text:
Q: Stub Lightning Data Service response in Lightning Test Service (Jasmine) Using Jasmine I can simply stub response as this before $T.createComponent:
  $A.enqueueAction = jasmine.createSpy().and.callFake((action) => {
    var cb = action.getCallback("SUCCESS")
    cb.fn.apply(cb.s, [{
      getState: function() {
        return "SUCCESS";
      },
      getReturnValue: function() {
        return [{
          "Name": "Edge Communications",
          "Id": "0010q00000000000A2"
        }, {
          "Name": "Burlington Textiles Corp of America",
          "Id": "0010q00000000000A3"
        }]
      }
    }]);
  });

How can I do the same with Lightning Data Service?


text:
Q: Dtls client doesn't send ClientHello with cookie I'm implementing dtls support for my sip client, using openssl. My SSL_connect returns SSL_ERROR_WANT_READ, my 'select' to handle it always timeout. In wireshark I saw a first ClientHello and HelloVerifyRequest, but second ClientHello with cookie never came.

A: it turns out that there was another socket listening on the same port.  I fixed that and there was second ClientHello with cookie. I still have other problem later on, but will raise another question. Thanks.


text:
Q: C# Calculate total of row I created a pos payform, but when the same product is detected it automatically detect it and it is incrementing the quantity row but not the final price row. Here is my code :
private void Dodadivotabela()
{
    bool Found = false;

    if (dataGridView1.Rows.Count > 0)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (Convert.ToString(row.Cells[0].Value) == txtBarajKod.Text)
            {
                row.Cells[3].Value =
                Convert.ToString(1 + Convert.ToInt64(row.Cells[3].Value));
                Found = true;
                break;
            }
        }
    }

    if (!Found)
    {
        price = float.Parse(txtCena.Text);
        quantity = float.Parse(txtKolicina.Text);
        finalprice = price *  quantity;

        var firstrow = txtBarajKod.Text;
        var secrow = txtNaziv.Text;
        var thirdrow = price;
        var forthrow = quantity;
        var fifthrow = finalprice;

        dataGridView1.Rows.Add(prvred, vtorred, tretred, cetvrtred, pettired);
    }
}

And here is my calculation of total row:
 public void PresmetajTotal()
 {
     var vkp = 0;
     for (var i = 0; i < dataGridView1.Rows.Count; i++)
     {
         vkp += Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value);
         txtTotal.Text = vkp.ToString();
     }
 }

The problem is that there are 4 rows in the DGV, and the quantity row gets updated but the row with the final price stays the same.

A: It looks like you are running the calculation when Found is false when you want to run it when "Found" is true
If(Found){...}

Rather than
If(!Found){...}


text:
Q: Inserting a full-size HTML page into a confluence page (in this case a gitgraph page) I'm writing a documentation for my codebase in Confluence and I want to add dynamically generated gitgraphs (https://gitgraphjs.com/).
Doing it with images is obviously possible, but I'd like to insert the HTML instead so that modifications can be done directly in the confluence page.
I've managed to use 'HTML Macro' to insert the HTML code, but it only renders as a tiny square inside the confluence page.
I tried fiddling around with CSS and tried to backwards-engineer the classes that Confluence was using, without success. I'm using Confluence 6.13.10
Thanks for the help

A: What do you use within the HTML macro? An <iframe>?
If iframe is used, then pass it some parameters:
<iframe src="https://gitgraphjs.com/..." frameborder=0 width="100%" height="1080px" scrolling="no"></iframe>


text:
Q: MySQL Maximum Row Length - Possible to increase? I was wondering if it is possible to increase the maximum row length of MySQL with InnoDB engine. The current is 8KB.
I would also like to know what enforces this limitation. I do not remember having such a limitation with Oracle 10 or MSSQL 2005.
Thank you!

A: You have to change the inno_db_page_size, check http://www.mysqlperformanceblog.com/2006/06/04/innodb-page-size/ It can be 8K, 16K, 32K or 64K, 16K is the default.

A: MS SQL Server has this limitation as well. To get around this, you may use LOBs (like CLOB, BLOB, TEXT, etc) since they are not part of the record itself.
Alternatively you may split your table into two tables linked 1:1. Maybe you could give some background what you try to achieve and why your table is that big.

A: This is a restriction on InnoDB tables and cannot be changed. According to the docs:

The maximum row length, except for
  variable-length columns (VARBINARY,
  VARCHAR, BLOB and TEXT), is slightly
  less than half of a database page.
  That is, the maximum row length is
  about 8000 bytes.

You will have to think about redesigning your table.


text:
Q: Trigger ON DELETE using MariaDB I have two tables 'topic' and 'answer':
Table 1-> topic
+-----+------------+
+  id +   name     +
+=====+============+
+  17 +  question1 +
+-----+------------+
+  18 +  question2 +
+-----+------------+

Table 2 -> answer
+----+---------+----------+
+ id + idtopic +   val    +
+----+---------+----------+
+  1 +  17     +  anwer1  +
+----+---------+----------+
+  2 +  18     +  answer2 +
+----+---------+----------+

I'm simply trying to create a trigger to delete items from table 'answer', when deleting items from table 'topic'.
If tried this code, but there is problem with MariaDB syntax I think:
CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
    WHERE answer.idtopic = topic.id;
END

A: Here is the version that will work.
DELIMITER //
CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
    WHERE answer.idtopic = OLD.id;
END
//
DELIMITER ;

A: Use the OLD keyword to refer to the current row in topic that is being deleted.
CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
    WHERE answer.idtopic = OLD.id;
END

However, I wonder why you're writing a trigger instead of using a foreign key with cascading delete. Are you not using InnoDB for this table?


text:
Q: List iterator find function error in c++ I have a compilation error: "no matching function for call to find(std::_List_iterator<Process>, std::_List_iterator<Process>, Process&)" in my c++ program.
The mfqueue class looks like:
MFQueue::MFQueue() {
        list<Process> queue;
        vector<int> ran;
        int time_quantum = 0;
        int run_for = 0;
}

MFQueue::MFQueue(int quantum) {
        list<Process> queue;
        vector<int> ran;
        int time_quantum = quantum;
        int run_for = 0;
}

"Process" is one of my class
bool MFQueue::contains(Process p) {
        list<Process>::iterator itr = find(queue.begin(), queue.end(), p);
        return (p == *itr);;
}

Does anyone know how to fix this problem? Thanks in advance!

A: Add #include <algorithm> to your CPP file.

A: You need to overload operator== for std::find algorithm, assume you want to compare id of Process
say:
 bool operator==(const Process &lhs, const Process& rhs)
 {
   return lhs.id== rhs.id;
 }

now, you can get it working
#include <algorithm>
std::list<Process>::iterator itr = std::find(queue.begin(), queue.end(), p);

A: Why are you declaring list<Process> queue; in the constructors not using them?


text:
Q: Django clean field model form Is it necessary to clean the fields in views or just in forms.py?
How does the clean method work in ModelForm?
class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)

class BookForm(ModelForm):
    class Meta:
        model = Book
        fields = ['name', 'authors']

   def clean_name(self):
       pass

def create(request):
    if request.method == 'post':
        form = Bookform(request.POST)
        if form.is_valid():
        #there itc necessary to do:
        book.name = form.cleaned_data['name'] ?

A: cleaned_data or Clean() can only be used after form data is validated (e.g after form.is_valid()) Not necessary but enforcing validation is best practice. So cleaned_data can and should only be nested inside of a is_valid or similar check.
Check out docs
https://docs.djangoproject.com/en/3.2/ref/forms/validation/


text:
Q: How to add orders array in product Whenever a customer checks out its saves an order that has products ordered by a customer and the product id, quantity and customers details like delivery address and customer phone number.
I want the same details to be added to all products in that order also so that the seller can also see that his product has been ordered
This i can achieve using each product's id in the orders since every product has its ID . But i dont know how to map the order's products id's and find the products in the products schema then add to them an array called orders.
This is how my orders schema looks like after an order has been placed
{
    "allOrders": [
        {
            "_id": "6249ee9baa59aceb7d88f91d",
            "placedby": "624471321dff6794a802431c",
            "fullname": "Collins Jimu",
            "deliveryaddress": "cnr fourth and herbet chitepo",
            "phonenumber": "0773468496",
            "whatsappphonenumber": "0773468496",
            "ordersList": [
                {
                    "name": "Hp 200 G4Core I5",
                    "qty": 1,
                    "price": 560,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648734312/cwynmzauqqnylrwsgejy.jpg",
                    "id": "6245b0c09390975e16263136"
                },
                {
                    "name": "bed",
                    "qty": 1,
                    "price": 160,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648732217/dtrb8saj0ellgyrcjpyy.jpg",
                    "id": "6245a88cf22df558d8d69162"
                },
                {
                    "name": "Sunglass",
                    "qty": 1,
                    "price": 6,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648738341/rtpiptqc1le6kywmuisf.jpg",
                    "id": "6245c03bf22df558d8d6a739"
                },
                {
                    "name": "sofas",
                    "qty": 1,
                    "price": 890,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648732837/xae655b5e9wovodfkvqn.jpg",
                    "id": "6245aacdf22df558d8d6939f"
                }
            ],
            "paymentmethod": "cashondeliver",
            "orderstatus": "placed",
            "createdAt": "2022-04-03T18:59:39.681Z",
            "updatedAt": "2022-04-03T18:59:39.681Z",
            "__v": 0
        },
        {
            "_id": "6249fdc602cefac4faa36dde",
            "placedby": "624471321dff6794a802431c",
            "fullname": "My MUM",
            "deliveryaddress": "123 HARARE STREET",
            "phonenumber": "0773550804",
            "whatsappphonenumber": "0773550804",
            "ordersList": [
                {
                    "name": "out door benches",
                    "qty": 1,
                    "price": 25,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648736078/in8rumwcm6rrebrmgb1q.jpg",
                    "id": "6245b792be41db13f9220867"
                },
                {
                    "name": "hammer",
                    "qty": 1,
                    "price": 10,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648735570/joceetdkx4penomtab8s.jpg",
                    "id": "6245b5849390975e16263647"
                },
                {
                    "name": "Watches",
                    "qty": 1,
                    "price": 4,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648735962/r4jmwlj7ltgc0njdtfdc.jpg",
                    "id": "6245b71abe41db13f92207ac"
                },
                {
                    "name": "iPhone X",
                    "qty": 1,
                    "price": 350,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648729600/ekcb86lmtkr0uniirb2i.jpg",
                    "id": "62459fc3be41db13f921f27a"
                },
                {
                    "name": "REFRIDGERATOR",
                    "qty": 1,
                    "price": 370,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648731962/fjrlvfnotdbonqnt9pjn.jpg",
                    "id": "6245a750be41db13f921f796"
                }
            ],
            "paymentmethod": "cashondeliver",
            "orderstatus": "placed",
            "createdAt": "2022-04-03T20:04:22.349Z",
            "updatedAt": "2022-04-03T20:04:22.349Z",
            "__v": 0
        },
        {
            "_id": "624a12ea02cefac4faa431fd",
            "placedby": "624471321dff6794a802431c",
            "fullname": "Munyaradzi Makosa",
            "deliveryaddress": "cnr fourth and herbet",
            "phonenumber": "0777727363663",
            "whatsappphonenumber": "0777727363663",
            "ordersList": [
                {
                    "name": "Wheels",
                    "qty": 1,
                    "price": 35,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648741496/xs9zpht0rhxpijrzyqrz.jpg",
                    "id": "6245cc859390975e162657ce"
                },
                {
                    "name": "MacBook Pro 2021",
                    "qty": 1,
                    "price": 1250,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648731661/h0dcvvhwntdy06mzgpah.webp",
                    "id": "6245a6649390975e16262737"
                },
                {
                    "name": "electric kettle",
                    "qty": 1,
                    "price": 22,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648734446/tyrdlrayn3opm7gagwmi.jpg",
                    "id": "6245b1239390975e162631e3"
                }
            ],
            "paymentmethod": "cashondeliver",
            "orderstatus": "placed",
            "createdAt": "2022-04-03T21:34:34.721Z",
            "updatedAt": "2022-04-03T21:34:34.721Z",
            "__v": 0
        },
        {
            "_id": "624aa7cd02cefac4faa4750c",
            "placedby": "624aa7a102cefac4faa474f3",
            "fullname": "Ryan Katayi",
            "deliveryaddress": "4164 Gwabalanda",
            "phonenumber": "0718518438",
            "whatsappphonenumber": "0718518438",
            "ordersList": [
                {
                    "name": "Budi 2017",
                    "qty": 1,
                    "price": 250,
                    "imgUrl": "/assets/images/products/Automotive/2.Audi2017.png",
                    "id": "6270512109915791"
                }
            ],
            "paymentmethod": "cashondeliver",
            "orderstatus": "placed",
            "createdAt": "2022-04-04T08:09:49.618Z",
            "updatedAt": "2022-04-04T08:09:49.618Z",
            "__v": 0
        },
        {
            "_id": "624c0e770d2cf94693988609",
            "placedby": "624aa7a102cefac4faa474f3",
            "fullname": "Ryan Katayi",
            "deliveryaddress": "4164 Gwabalanda",
            "phonenumber": "0718518438",
            "whatsappphonenumber": "0778687452",
            "ordersList": [
                {
                    "name": "Nike Airforce",
                    "qty": 2,
                    "price": 40,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1649082553/hoodaley8bzrwa8xi2tr.jpg",
                    "id": "624b01250d2cf94693982652"
                },
                {
                    "name": "iPhone X",
                    "qty": 1,
                    "price": 350,
                    "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648729600/ekcb86lmtkr0uniirb2i.jpg",
                    "id": "62459fc3be41db13f921f27a"
                }
            ],
            "paymentmethod": "cashondeliver",
            "orderstatus": "placed",
            "createdAt": "2022-04-05T09:40:07.719Z",
            "updatedAt": "2022-04-05T09:40:07.719Z",
            "__v": 0
        }
    ]
}

i have managed to get the ids of all the orders. But my challenge is i am stuck with only the products ids not sure how to use them and find each products and then patch them with an orders details array
const sellerProductsOrdered = asyncHandler (async (req, res) => {
    const Orders = await Order.find();
    const ordersList =  Orders.map(order => {
        return order
    })

    const ordersListProductsIds = ordersList.map(product => {
        return product.id
    })

    console.log(ordersListProductsIds);
})


text:
Q: Elixir - Folder does not copy if there is a dot in the directory name I am using Laravel 5.2 with elixir.
I have found that if I use elixir on a directory that contains a dot, it will only copy the folder, but not the contents inside.
For example consider copying a folder called a.something at the root of the project:
exlixir(function(mix) {
    mix.copy('a.something', 'public/a.something');
});

The above will only make an empty directory called a.something and not copy its contents.
On the other hand the following works fine if the folder is called a:
exlixir(function(mix) {
    mix.copy('a', 'public/a');
});

A: This issue was a bug and is now fixed!
https://github.com/laravel/elixir/issues/559


text:
Q: How to get value with mouse event drag I have in my UI one QScrollArea with an image, and I want to get some value when I click on the image.
Being more explict, I need to change the brightness of an image, and I will get the value with the mouse. I already see the MouseMoveEvent but I don't know how to use it.
If I get the position of the mouse when I click and drag, I can extract one value to change the bright of my image, that I know. I just don't know how I will get the position.
Does anyone know how I can do this?
Ps.: My QScrollArea was created on Design, so I don't have any code writed by me with the specifications of the QScrollArea.

A: there is a small correction . when i programmed like this i was getting the movements a liitle jerky . so i tried to modified the code and now working perfect .
heres how i changed
   const int deltaX = event->scenePos().x() - m_lastClickPosition.x();
    if ( deltaX > 10 )// to the right
    {
       moveBy(10,0);
       m_lastClickPosition = event->scenePos();
    }
    else if ( deltaX <-10 )
    {
        moveBy(-10,0);
        m_lastClickPosition = event->scenePos();
    }

A: All the information you need is in the QMouseEvent object that is sent to the mouseMoveEvent handler of your widget.
QMouseEvent::buttons()
QMouseEvent::pos()
A simple way to do what you're after is to change the brightness of the image whenever you receive a "mouse movement event" and the QMouseEvent object reports a button down (this means the user is moving the mouse while holding down a button).
void MyWidget::mousePressEvent( QMouseEvent* event )
{
    if ( event->button() == Qt::LeftButton )
    {
        // Keep the clicking position in some private member of type 'QPoint.'

        m_lastClickPosition = event->pos();
    }
}

void MyWidget::mouseMoveEvent( QMouseEvent* event )
{
    // The user is moving the cursor.
    // See if the user is pressing down the left mouse button.

    if ( event->buttons() & Qt::LeftButton )
    {
        const int deltaX = event->pos().x() - m_lastClickPosition.x();
        if ( deltaX > 0 )
        {
            // The user is moving the cursor to the RIGHT.
            // ...
        }
        else if ( deltaX < 0 ) // This second IF is necessary in case the movement was all vertical.
        {
            // The user is moving the cursor to the LEFT.
            // ...
        }
    }
}


text:
Q: How to iterate in url and find specific character in c# I have a below URLs and I want to iterate in it but I want to start in "Test" location. If there is no "Test" then I will skip it.
https://sharepoint.com/sites/documentlibrary/project1/Test/newfolder
https://sharepoint.com/sites/documentlibrary/BudgetTracking/Test/folder1
https://sharepoint.com/sites/documentlibrary/project3/Subfolder

A: Based off the small amount of information you've provided, you can use the IndexOf method to get the staring index of a string within a string. Then we can use the Substring method to get the string that begins with the search term.
For example:
var urls = new List<string>
{
    "https://sharepoint.com/sites/documentlibrary/project1/Test/Subfolder",
    "https://sharepoint.com/sites/documentlibrary/BudgetTracking/Test/Subfolder",
    "https://sharepoint.com/sites/documentlibrary/project3/Subfolder",
};

foreach (var url in urls)
{
    var testIndex = url.IndexOf("Test", 0, StringComparison.OrdinalIgnoreCase);
    if (testIndex == -1) continue;
    var stringToSearch = url.Substring(testIndex);

    Console.WriteLine($"We will search for our character in this string: {stringToSearch}");
}

A: You can try something like this
List<string> urls = new List<string>
{
    "https://sharepoint.com/sites/documentlibrary/project1/Test/Subfolder",
    "https://sharepoint.com/sites/documentlibrary/BudgetTracking/Test/Subfolder",
    "https://sharepoint.com/sites/documentlibrary/project3/Subfolder",
};

foreach (string urlWithTest in urls.Where(url => url.Contains("Test")))
{
    string partialUrl = urlWithTest.Substring(urlWithTest.IndexOf("Test"));
    //Do what you want here
}

A: Not quite sure what you're asking but you can check to see if Test exists in each url in a foreach or whatever you want to use and then return whatever is after Test/
Something like this while iterating thru the URL's:
 string url = "https://blah.com/test/findme";
        if(url.Contains("/test"))
        {
            string toBeSearched = "/test";
            string code = url.Substring(url.IndexOf(toBeSearched) + toBeSearched.Length);

            Console.WriteLine(code);//This will write "/findme"
        }


text:
Q: How does Tenacity work? Previously, only the Mercury's Treads reduced the effect of any kind of CC (by 1 second if my memory is ok).
Now we have 3 items that allow you to reduce any kind of CC: Mercury's Treads, Moonflair Spellblade and Cloak and Dagger. All of these items gives you +35 Tenacity.
How does Tenacity work? Is it a kind of percent reduction based on the duration of the CC or it is a specific amount of static time for all the CCs?

A:
Tenacity is a mechanic that reduces the duration of crowd control
  effects. It does not affect the potency/strength of the effect.
Tenacity works on: Blind, Forced Actions (Charm, Fear and Taunt), Pacify, Silence, Snare, Slow and Stun.
Tenacity does not work on: Airborne (Knockback, Knockup and Pull) and Suppression.

Contrary to Deotronic's answer, Tenacity does not reduce the amount of slow. It only reduces the duration of the any of the CC that is affected by Tenacity. The reduction is reduced by a percentage equal to the Tenacity value. So a champion with 35 Tenacity will have all affected CC reduced by 35% duration.
EDITED to reflect changes to Season 3 tenacity items:
Please note that Tenacity does not stack. There are currently 3 items which provide Tenacity, and they all give 35 Tenacity. If you buy two of these items, you will not get 70 tenacity. You will only benefit from 35.

*

*Mercury Treads

*Spirit of the Ancient Golem

*Zephyr

Source

A: They don't stack, you can only get the effect from one of the tenacity items. Each point of tenacity reduces the CC by 1%, so any of the tenacity items will reduce it by a total of 35%.

A: Tenacity is covered fairly well on its Wikia entry.
However, in general you're correct: It's a percentage reduction of many, but not all, CC effects. The percentage reduction is the same as the value of the stat; i.e., 35 Tenacity means a 35% reduction of CC effects.
It does not work on Displacement Effects (knockups, knockbacks, and pulls) or on suppression. As Jay points out, it also does not impact the magnitude of a slow, but only the duration of the slow.
You cannot stack Tenacity items, so at this point, you can only get 35 Tenacity (as all items give the same amount). However, Tenacity does stack multiplicatively with other forms of CC reduction. For example, at max level Trundle's Contaminate gives him 40% CC reduction. If you have 35 Tenacity, your final CC reduction is 54% (35% of 40 is 14, 40 + 14 = 54).

A: 35 tenacity = 35 % = stronk. See here.


text:
Q: Converting only selected columns to transpose using melt and pivot? I have dataframe like this:
id  Gender        TV        Radio
0   M            Daily      Daily
1   F            Monthly    Weekly
2   M            Weekly     Weekly
3   F            Daily      Daily

I need to change the columns into values and values into column, This is my desired output.
id  Gender             Daily    Monthly      Weekly
0   M                   TV       NaN          NaN
0   M                   Radio    NaN          NaN
1   F                   NaN      TV           Weekly
2   M                   NaN      NaN          TV
2   M                   NaN      NaN          Radio
3   F                   TV       NaN          NaN
3   F                   Radio    NaN          NaN

I am using melt+pivot but i lose information. Here is what i am using.
idx = ['id', 'Gender']
m = df.melt(idx).pivot_table(index=idx,columns='value',values='variable',aggfunc='first')
out = m.reset_index(idx).rename_axis(index=None,columns=None)

But i am getting only the first value. For example if the daily occur for tv and radio then i am geting only the first value.. I know i am aggregating only first but dont know which function i can use to get all the values.
 id    Gender               Daily   Monthly      Weekly
    0   M                   TV       NaN          NaN
    1   F                   NaN      TV           Weekly
    2   M                   NaN      NaN          TV
    3   F                   TV       NaN          NaN

A: Use DataFrame.melt with GroupBy.cumcount for counter by duplicated values and then Series.unstack for reshape:
idx = ['id', 'Gender']
m = df.melt(idx)
m['g'] = m.groupby(idx).cumcount()
m = m.set_index(idx + ['g', 'value'])['variable'].unstack()
out = m.reset_index(idx).rename_axis(index=None,columns=None)
print (out)
   id Gender  Daily Monthly Weekly
0   0      M     TV     NaN    NaN
1   0      M  Radio     NaN    NaN
0   1      F    NaN      TV    NaN
1   1      F    NaN     NaN  Radio
0   2      M    NaN     NaN     TV
1   2      M    NaN     NaN  Radio
0   3      F     TV     NaN    NaN
1   3      F  Radio     NaN    NaN


text:
Q: Double image in binoculars How can I reduce the double image seen when looking through binoculars? I recently got a new pair, but have been having troubles using them because I am seeing double...

A: The double image is almost certainly because you have the axes misaligned with your eyes.
The three adjustments you can make are (usually):

*

*physical separation of the two lens assemblies

*main focus

*supplementary focus for one lens

(sometimes you have totally independent focus, but the above is more common)
The focus options will make things blurry, but having the barrels too wide apart, or too close together can mean your eyes can't easily resolve to a single image.
try adjusting the separation first. If that doesn't help, it is possible you have a badly aligned pair of binoculars...


text:
Q: ¿En NodeJS cada conexión con mysql2, al ejecutar un query obvio que la conexión se establece , al conscluir la conexión se cierra automaticamente? Parcial del código de dbms.js:
let wnNumeroID = 'V5116687'
let wcSQLCmd   = "Select * from Personas where PersNroIde = '" + wnNumeroID + "';"

const oMySQL = require('mysql2/promise');

async function fncCnxDBMS () {
  const oCnx = await oMySQL.createConnection({
      host: 'localhost',
      user: 'root',
      password: 'xyz',
      database: 'dbscheme_name'
//      ssl: {rejectUnauthorized:false}
  });

  const [oPersonas, oColumnas] = await oCnx.query(wcSQLCmd)

  console.log(oPersonas)
}

module.exports = fncCnxDBMS

------------------------------------------------------
const oDBCnx = require('...../dbms.js')
oDBCnx()


text:
Q: How to create variables with incremental names I have some probles to understand how to do this
I have a variable created to hold an object:
var myobject = new object();

everything is fine; the name is 'my object' and the content is a new object.
If I want 10 variables, I need to type 10 variable names.
var myobject1 = new object();
var myobject2 = new object();
var myobject3 = new object();
var myobject4 = new object();
.... and so on

now; I would like to increment the name of the variable (not the content), with a counter, so it doesn't matter how many times I need a new object; the name will just change in incremental way (I can't reuse the same name for the variable, it is a long story). So the result will be the same as above, but without me actually writing 10 times (on n times) the variable name.
In sh, I can refer to either myobject for the name, or $myobject for the content of that variable; but JS doesn't seems to have this approach.
I tried to put down the logic, but I can't see how you actually increment the variable name:
//global variables
var counter=0;
var tempname;

function makeplentyofobj(){

    if (temp name)
        tempname= new object(); //this should make myobjectN
    else
        myobject= new object(); //this makes myobject1
    counter ++;
    tempname ='myobject'+counter; //this make a name for the next object)
}

When I run this, the compiler will put in myobject, the new object (counter goes to 1, temp name contains the string 'myobject1').
if I call the function 2 times, the second time I will have counter=1, and tempname will contain the string 'myobject1'. which is what I want to use as name of the next variable . Since tempname is not empty, I branch in the else condition, but the CONTENT of tempname will be changed from string to object.
Instead, I want to obtain a new variable name, which increment with the counter, so every time that I call var my object = new object(); as the counter increment, I get
myobject1=new object();
myobject2= new object();
....

How can I obtain this in JS?
EDIT:
Thanks for the reply; it is a duplicate; altho my question took quite a while to go trough a reasoning of what I did, while the other is a plain "how do I do that".
It took efforts to do mine; I guess next time I will just skip the effort :)

A: The usual solution to this kind of problem is to put your objects in an array.  That simplifies both storing them and retrieving them.
var objArray = [];
objArray.push(new object());
objArray.push(new object());
objArray.push(new object());
objArray.push(new object());

Or, you can even put them in the initial declaration:
var objArray = [new object(), new object(), new object(), new object()];

If you really just want generic objects, it can be as simple as this:
var objArray = [{}, {}, {}, {}, {}];

Then, referencing a given element is as simple as
var obj = objArray[n];

Keep in mind that arrays start with index 0 as in objArray[0].


text:
Q: Python dataframe : converting columns into rows I have a dataframe as follows
d = {'Movie' : ['The Shawshank Redemption', 'The Godfather'],
        'FirstName1': ['Tim', 'Marlon'],
        'FirstName2': ['Morgan', 'Al'],
        'LastName1': ['Robbins', 'Brando'],
        'LastName2': ['Freeman', 'Pacino'],
        'ID1': ['TM', 'MB'],
        'ID2': ['MF', 'AP']
        }
df = pd.DataFrame(d)
df

I would like to re-arrange it into a 4 column dataframe,
by converting Firstname1, LastName1, FirstName2, LastName2, ID1, ID2 into 3 column rows as FirstName, LastName, ID then column movie repeats as follows.

In sql we do it as follows
select Movie as Movie, FirstName1 as FirstName, LastName1 as LastName, ID1 as ID from table
union
select Movie as Movie, FirstName2 as FirstName, LastName2 as LastName, ID2 as ID from table

Can we achieve it using pandas ?

A: If possible number in column names more like 9 use Series.str.extract for get integers with values before to MultiIndex to columns, so possible DataFrame.stack:
df = df.set_index('Movie')
df1 = df.columns.to_series().str.extract('([a-zA-Z]+)(\d+)')
df.columns = pd.MultiIndex.from_arrays([df1[0], df1[1].astype(int)])

df = df.rename_axis((None, None), axis=1).stack().reset_index(level=1, drop=True).reset_index()
print (df)
                      Movie FirstName  ID LastName
0  The Shawshank Redemption       Tim  TM  Robbins
1  The Shawshank Redemption    Morgan  MF  Freeman
2             The Godfather    Marlon  MB   Brando
3             The Godfather        Al  AP   Pacino

If not use indexing for get last values of columns names with all previous and pass to MultiIndex.from_arrays:
df = df.set_index('Movie')
df.columns = pd.MultiIndex.from_arrays([df.columns.str[:-1], df.columns.str[-1].astype(int)])
df = df.stack().reset_index(level=1, drop=True).reset_index()
print (df)
                      Movie FirstName  ID LastName
0  The Shawshank Redemption       Tim  TM  Robbins
1  The Shawshank Redemption    Morgan  MF  Freeman
2             The Godfather    Marlon  MB   Brando
3             The Godfather        Al  AP   Pacino

A: df = df.set_index('Movie')
df.columns = pd.MultiIndex.from_tuples([(col[:-1], col[-1:]) for col in df.columns])

df.stack()

#                           FirstName  ID LastName
#Movie
#The Shawshank Redemption 1       Tim  TM  Robbins
#                         2    Morgan  MF  Freeman
#The Godfather            1    Marlon  MB   Brando
#                         2        Al  AP   Pacino

Use the power of MultiIndex! With from_tuples you create a DataFrame that has one column for FirstNames, divided in FirstName1 and FirstName2 (see below) and similar for ID and LastName. With stack you convert it into rows for each. Before you do this, make Movie the Index to exclude it from what you are doing. You could use reset_index() to regain everything as columns, but I'm not sure if you want that.

Before stack:
#                         FirstName         LastName           ID
#                                 1       2        1        2   1   2
#Movie
#The Shawshank Redemption       Tim  Morgan  Robbins  Freeman  TM  MF
#The Godfather               Marlon      Al   Brando   Pacino  MB  AP

A: I think an easy way to do this is to use the copy function from Pandas.
You can copy the columns "Movie", "FirstName", "LastName", "ID" to a new table. Then delete the columns you don't need in your first column. You can also create a new table for the other.
new = d['Movie', 'FirstName', 'LastName', 'ID].copy

A: Try below:
d1 = df.filter(regex="1$|Movie").rename(columns=lambda x: x[:-1])
d2 = df.filter(regex="2$|Movie").rename(columns=lambda x: x[:-1])
pd.concat([d1, d2]).rename({'Movi':'Movie'})


text:
Q: How to print and view logs from Hyperledger Fabric chaincode I want to see logs while calling functions in my chaincode, for debugging purposes. I tried something like this:
var logger = shim.NewLogger("chaincode_example02")
logger.Info("get_caller_data called");

I've viewed logs of the peer running the chaincode, but I couldn't find the above log. What am I doing wrong?

A: If you startup your chaincode in dev mode using a command like ./chaincode_example02, then the log statements should be visible in the console where that same process is started.
If you deploy the chaincode in net mode then each peer starts up a docker container that is named something like <networkId>-<peer enroll id>-<chaincode Id> .You can view all the docker containers started up on a peer by using the command docker ps, and view the content of a log by using the command docker logs <container id (get this from the previous command)>


text:
Q: "service hadoop-yarn-resourcemanager start" command not working? Redirecting to /bin/systemctl start  hadoop-yarn-resourcemanager.service

Failed to start hadoop-yarn-resourcemanager.service: Unit not found.
  cluster: Cloudera 5.14

A: may be Due to permission issue it is causing this issue.
sudo chown hdfs:hadoop -R /hdfs/data
sudo chmod 777 -R /hdfs/data
hadoop namenode -format
Run these commands from CLI and try
it again.


text:
Q: Passing parameters to a dynamically created Button from an Entry widget in Tkinter I am looking for a way how to pass the content of a entry widget to a button.
The complicated part for me is that the buttons and entry widgets a dynamically created from a given XML structure see 'xmlString' which is describing a GUI with buttons and parameters, the number of button and parameters is variable.
I simplified  the XML and made a demo code.
I'm aware of the lambda function but I have no idea how to  do this with the dynamic created entry widgets.
from Tkinter import *
import xml.etree.ElementTree as ET

rootframe = Tk()

def runScript(text = 'default text'):
    print 'runScript %s'%text

xmlString = '''
<window>
      <Tab id="tabpage5" name="Debugging" type="custom">
        <command dest="1" mode="CONFIG" unit="4" id="SET_TIMEOUT" type="COMMAND">
          <initiator name="Set Timeout" type="button" />
          <parameter editable="true" param_name="PARAM1">31536000</parameter>
        </command>
        <command dest="1" mode="CONFIG" unit="4" id="SET_thing" type="COMMAND">
          <initiator name="Set Timeout" type="button" />
          <parameter param_name="PARAM1" >31536000</parameter>
          <parameter param_name="PARAM2">5</parameter>
        </command>
        <command />
        </Tab>
</window>
'''

xmlRoot  = ET.fromstring(xmlString)

for tab in xmlRoot.iter('Tab'):
    row = 0
    column = 0

    for command in tab.iter('command'):
        for tag in command.iter() :
            #not sure why command tag is here but skipping it
            if tag.tag == 'command':
                pass
                continue
            if tag.tag == 'initiator' and tag.attrib['type'] == 'button':
                    button = Button(rootframe, text=tag.attrib['name'], command=lambda : runScript('nondefault text'))
                    button.grid(row=row, column=column, sticky='w')
                    column +=1
            elif tag.tag == 'parameter':
                    entry = Entry(rootframe)
                    entry.insert(0,tag.text)
                    entry.grid(row=row, column=column)
                    column +=1
        row +=1
        column = 0

rootframe.mainloop()

A: You could keep a 2D list of all the entries you create. Then when you want to access them, you only need to plug in the row number. Sample implementation:
from Tkinter import *
import xml.etree.ElementTree as ET

rootframe = Tk()

def runScript(text = 'default text', row=None):
    entries = entries_by_row[row] if row is not None else []
    print 'runScript {}. Contents of entries: {}'.format(text, [entry.get() for entry in entries])

xmlString = '''
<window>
      <Tab id="tabpage5" name="Debugging" type="custom">
        <command dest="1" mode="CONFIG" unit="4" id="SET_TIMEOUT" type="COMMAND">
          <initiator name="Set Timeout" type="button" />
          <parameter editable="true" param_name="PARAM1">31536000</parameter>
        </command>
        <command dest="1" mode="CONFIG" unit="4" id="SET_thing" type="COMMAND">
          <initiator name="Set Timeout" type="button" />
          <parameter param_name="PARAM1" >31536000</parameter>
          <parameter param_name="PARAM2">5</parameter>
        </command>
        <command />
        </Tab>
</window>
'''

xmlRoot  = ET.fromstring(xmlString)

entries_by_row = []

for tab in xmlRoot.iter('Tab'):
    row = 0
    column = 0

    for command in tab.iter('command'):
        entries_by_row.append([])
        for tag in command.iter() :
            #not sure why command tag is here but skipping it
            if tag.tag == 'command':
                pass
                continue
            if tag.tag == 'initiator' and tag.attrib['type'] == 'button':
                    button = Button(rootframe, text=tag.attrib['name'], command=lambda row=row: runScript('nondefault text', row))
                    button.grid(row=row, column=column, sticky='w')
                    column +=1
            elif tag.tag == 'parameter':
                    entry = Entry(rootframe)
                    entry.insert(0,tag.text)
                    entry.grid(row=row, column=column)
                    column +=1
                    entries_by_row[-1].append(entry)
        row +=1
        column = 0

rootframe.mainloop()

Result after clicking each button:
runScript nondefault text. Contents of entries: ['31536000']
runScript nondefault text. Contents of entries: ['31536000', '5']


text:
Q: How to add an actionListener as a separate class in java I've been working on a program and my master class with the bulk of the code has over 20 different "addActionListener" methods. How can I instead create this actionListener, itemStateChanged etc etc in a separate class but still perform as it should the way it does now. Any tips would be most welcome as I have run over 4000 lines of code already in this class :( Thank you!

A: public class MyActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent evt) {
        // actionPerformed here...
    }
}

You would use it like:
JButton button = new JButton();
button.addActionListener(new MyActionListener());

// OR

MyActionListener listener = new MyActionListener();
JButton button = new JButton();
button.addActionListener(listener);

A: class Mylistener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e){
         if (e.getSource() == someButton){
             // do something
         } else if (e.getSource() == someOtherButton){
             // do something
         }
         // add more else if statements for other components
         // e.getSource() is the component that fires the event e.g. someButton
    }
}

Say you have two buttons
JButton someButton = new JButton("SOME BUTTON");
JButton someOtherButton = new JButtton("SOME OTHER BUTTON");

ActionListener listener = new MyListener();

someButton.addActionListener(listener);
someOtherButton.addActionListener(listener);

Edit:
public MyClass extends JFrame {

    JButton someButton = new JButton("SOME BUTTON");
    JButton someOtherButton = new JButtton("SOME OTHER BUTTON");

    public MyClass(){

        ActionListener listener = new MyListener();
        someButton.addActionListener(listener);
        someOtherButton.addActionListener(listener);
    }

    class Mylistener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e){
         if (e.getSource() == someButton){
             // do something
         } else if (e.getSource() == someOtherButton){
             // do something
         }
         // add more else if statements for other components
         // e.getSource() is the component that fires the event e.g. someButton
    }
}

A: You want to write a class which implements ActionListener.
I could give you some code here with very little explanation, but I think it is best that I point you to the documentation here: http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
This link will give you some examples, and it will explain in detail how it is working.
I hope this helps.


text:
Q: scipy.stats.gamma.fit В библиотеке scipy.stats согласно документации распределение gamma  имеет только один параметр, но метод scipy.stats.gamma.fit(data) почему то возвращает кортеж из трех значений, а не одно! Почему так и какой из этих трëх является параметром, который затем можно подставить в функцию scipy.stats.gamma.rvs для генерации значений по подобранному закону распределения?

A: А вы не пробовали самостоятельно прочитать документацию к тому методу, который используете?  Там же в самом начале текста указано "The probability density above is defined in the "standardized" form. To shift and/or scale the distribution use the loc and scale parameters".  Т.е. помимо стандартизованной формы распределения вы можете во-первых, сдвигать ваше распределение влево-вправо до оси Х, а также "растягивать" функцию плотности распределения по этой-же оси.
И соответственно при описании метода gamma.fit() тоже  рекомендуется ознакомиться c описанием scipy.stats.rv_continuous.fit() методом -  родителем. А уже там написано, "Estimates for any shape parameters (if applicable), followed by those for location and scale. " .
Вот вам и ваши три параметра, которые fit находит.


text:
Q: I want to select and highlight country on google Geochart when someone click on a html button or div I need a country to be selected and highlighted on google Gecochart when a button or Div is clicked.
I was able to achieve that completely if someone clicks on the country on Geochart, but partially if someone clicks the button/div as the Geochart is not highlighting the country until the user moves the mouse pointer above the geochart.
I am trying to implement that using the code below

var chart='';
google.charts.load('current', {
        'packages':['geochart'],
      });
      google.charts.setOnLoadCallback(drawRegionsMap);

      function drawRegionsMap() {
        var data = google.visualization.arrayToDataTable([
          ['Country', 'Popularity'],
          ['Germany', 200],
          ['United States', 300],
          ['Brazil', 400],
          ['Canada', 500],
          ['France', 600],
          ['RU', 700]
        ]);

        var options = {};
var container =document.getElementById('regions_div');
         chart = new google.visualization.GeoChart(container);
observer = new MutationObserver(function (nodes) {
    Array.prototype.forEach.call(nodes, function (node) {
      // check for new nodes

      if (node.addedNodes.length > 0) {

        Array.prototype.forEach.call(node.addedNodes, function (addedNode) {
          // the tooltip element will also be here, we only want the group elements
          if (addedNode.tagName === 'g') {
            // find children of the group element
            Array.prototype.forEach.call(addedNode.childNodes, function (childNode) {
              // check for path element, change stroke
              if (childNode.tagName === 'path') {
                childNode.setAttribute('stroke', '#FF0000');
                //childNode.setAttribute('fill', '#BE965C');
              }
            });
          }
        });
      }
    });
  });

  // activate mutation observer
observer.observe(container, {
  childList: true,
  subtree: true
});
        chart.draw(data, options);
      }

      function myclick() {
//google.visualization.events.trigger(chart, 'select',[{ row: 3, column: null }]);

      chart.setSelection([{ row: 3, column: null }]);
            console.log( chart.getSelection());
      }

        text

       <button type="button" onclick="myclick()">Click Me!</button>

I also tried to call google.visualization.events.trigger(chart, 'select', chart.getSelection()); to trigger the selection and highlight directly but it didn't work.
Any idea how to to highlight the country when clicking on the button/div directly (without the need to move the mouse over the Gecochart)?
Thank you!
The code can also be found in this snippet https://jsfiddle.net/nmaybar/8p2zruso/

A: I have solved the issue by changing the version from 'current' to '49' by adjusting the following code:
google.charts.load('current', { 'packages':['geochart'],});

To:
google.charts.load('49', {'packages':['geochart'],});

I am not sure why it doesn't work with version 'current' or 'upcoming'. I think it is a bug.


text:
Q: Product backlog management using Excel (or Excel's XML Spreadsheet 2003 feature with SVN merging) We have Product Backlog in an Excel Spreadsheet that we also commit to SVN, so everyone can open use it and update to latest version.
The problem we have is:
How do you enable Excel spreadsheet to be simultaneously used by many people and not override each other's data. Some kind of merging data? Is it at all possible?
We would like to keep our data in Excel spreadsheet since it provides all the functionality we need. We tried Google spreadsheets that are much better in terms of collaboration, but they don't support cell drop-down values...
EDIT
I've found out that I can also save my Excel file in XML format (XML Spreadsheet 2003). This format preserves all formating, formulas, conditional styles etc. Only graphs fall out, but I can live with that. I suppose that SVN Merge tools more or less support XML file merging when multiple people work on it.
So I thought of this feature, but I don't know how much does Excel change XML document between saves. Maybe it reorders a lot of stuff hence making it impossible for merge tools to work with expected results. Anyone has any experience with this?. It would basically make it possible for multiple people working on the same file.
EDIT2
I've tried managing Excel spreadsheets in a plain XML file (XML Spreadsheet 2003 file format) that makes it possible for SVN to merge it since it's a text file. I've learned to not use conditinal formatting, because it doesn't always work, so you'll have problems reopening the file. Also graphs won't be preserved.
Testing outcome: I've tried simultaneous work on the same XML, but Excel works with these files in no particular order (looks like it converts it to Excel and back to XML when saving it), so even if you make a small change to data, your XML will look completely different. So this format is a no go for collaborative purposes with merge capabilities.

FYI note: I've moved my operations from Excel to a more collaborative and similarly capable solution: Google Spreadsheets. Simultaneous collaboration is just working and working great (hopefully Microsoft will someday make collaboration this way on all its Office range) and it supports versioning as well as all the capabilities I'm using in Excel. COnditional formatting and with some additional script code I can use conditional formatting on whole rows based on single cells as well, so I can easily background colour whole rows of when set particular story status to "Completed".

A: Excel data can be merged but it's somewhat hard and error prone.
What I've found useful is to put the svn:needs-lock property on that kind of hard-to-merge files. The file will be read-only by default to communicate "do not edit this" and acquiring a svn lock makes it a read-write file, while preventing other users from acquiring a lock at the same time. It's a communication mechanism, not a 100% foolproof merge conflict prevention mechanism.
More information in svnbook.

A: Excel has a built-in share/merge capability (search the help for "share workbook") but it's meant for live copies on shared drives. Still, for this particular problem that might be a better solution than SVN.

A: Excel doesn't support the scenario you described, you need to use a multi-user database, or an proper work-tracking system.  There are some hosted ones you can try (Jira, FogBugz) but you're not going to get multi-user with Excel (unless you use the shared spreadsheet option, but as David Moles said, that's meant for shared xls files on a file server).

A: SVN allows eveyone to get the latest version and work on the latest version without a "checking out" / "make read-only". This enables multi-users working the same file, and would assume that the Merge features only work on Text docuements (code files)
(This is based on my possibly limited experience with SVN)
Its probabaly time to upgrade from an Excel system to a more systematic multi-user database system.

A: I wonder if you're using the right tools for the job. Perhaps you should be investigating some Scrum tools to help you manage your projects.
Excel works well in a simple, non-shared scenario but I would investigate something more powerful to allow your team to manage the scrum process simultaneously.

A: After hearing about this project on several podcasts, I've started using Zen.  It's based on a kanban board.

A: I'm pretty sure TortoiseSVN has some hooks (merge-docx.js, et al) which enable you to merge complex file types like office documents.
Or perhaps something like this (at a push)

A: have you looked at the Greenhopper planning backlog tool.

A: You could try XLLoop. This lets you write excel functions (UDFs) on an external server. It includes server implementations in many different languages.
So instead of keeping the data on your spreadsheet, you could have it stored in an external database then create a template excel sheet that calls the functions on your server. This will allow the data to be automatically updated and also allow multiple people to use the sheet at the same time.
BTW, I work on the project so let me know if you have any questions.


text:
Q: Python, Copy Subfolders with its Contents into newly created Parent folders I have code with this logic: Make the directory from column "Folder_Name_to_create" if it exists.
I am trying to add to this newly created directories a STATIC set of subfolders with its contents.
Getting subfolders to be copied to the newly created folder:
subfolders_to_create = []
for entry in pl_Template_Dir.glob('*'):
    if entry.is_dir():
        subfolders_to_create.append(entry.name)

Code that creates new directory if exists:
for folder in pl_dest['Folder_Name_to_create']:
    try:
        pathlib.Path(folder).mkdir()
    except FileExistsError:
        pass

What I am trying:
for sd in subfolders_to_create:
            (pl_dest / sd).mkdir()

error: AttributeError: 'DataFrame' object has no attribute 'mkdir'
pl_dest dataframe:
```
     Folder_Name_to_create
0  O:\Stack\Over\Flow\2010
1  O:\Stack\Over\Flow\2011
```

Im having trouble putting this together. I want to create new directories if they exist and bring in the the Template Subfolders and contents to each newly created directory.

A: You are calling mkdir on DataFrame, which has no such method. Although pl_dest / sd appends subdirectories to all parent folders in df, the call still returns a dataframe. You should make individual call on every element of the new df. It would look something like this:
for subfolder in subfolders_to_create:
    for folder_to_create in pl_dest['Folder_Name_to_create'] / subfolder:
        # exist_ok=True instead of try/catch
        folder_to_create.mkdir(exist_ok=True, parents=True)

Edit:
To copy subfolders with contents use shutils. In this example subfolders_to_create contains paths, not only relative names.
import shutils

for src_dir in subfolders_to_create:
    for dst_dir in pl_dest['Folder_Name_to_create']:
        shutils.copytree(src_dir, dst_dir)


text:
Q: React Native Maps I'm busy developing a location-based app and making use of expo, is there anyone who knows how to track user location on the map and tell if they reached a specific destination on expo project similar to GPS.
      <MapViewDirections
      origin={userContext.userLocation}
      destination={userContext.userLocation}
      apikey={googleMapApi}
      mode='DRIVING'
      language='en's
      strokeWidth={8}
      strokeColor="#2A9D8F"
      optimizeWaypoints={true}
      resetOnChange={false}
      precision={"low"}

    />

A: If you are using expo you should use watchPositionAsync from expo-location api
https://docs.expo.io/versions/latest/sdk/location/#locationwatchpositionasyncoptions-callback
You should track here the changes and then put the coordinates in the map.
Usage

async componentWillMount() {

    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if (status === 'granted') {
      this._getLocationAsync();
    } else {
      this.setState({ error: 'Locations services needed' });
    }
  }

  componentWillUnmount() {
     this.location.remove(callback...);
  }

  _getLocationAsync = async () => {
      this.location = await Location.watchPositionAsync(
          {
              enableHighAccuracy: true,
              distanceInterval: 1,
              timeInterval: 10000
          },
          newLocation => {
              let coords = newLocation.coords;
          // this.props.getMyLocation sets my reducer state my_location
          this.props.getMyLocation({
              latitude: parseFloat(coords.latitude),
              longitude: parseFloat(coords.longitude)
          });
        },
        error => console.log(error)
      );
      return location;
  };


text:
Q: Did Phil Foglio introduce the trope that platypuses don't do anything? In Phineas and Ferb, the joke is that humans think platypuses don't do anything, and yet Perry is actually a secret agent.  Even though "Perry doesn't do anything," they love him and he's important to them.
Years earlier, Phil Foglio introduced a The Winslow, a platypus-like indestructible reptile who's important to "everyone," but doesn't do anything.
This is the earliest example of this trope that I have found. Is anyone aware of an earlier example?

A: I very much doubt that "Platypuses don't to anything" is popular enough to be a trope, but if it is then it certainly predates Phil Foglio. If there is a trope, and if it has a start point then it is probably the poem "The Diplomatic Platypus", published in Punch magazine in the thirties. While too old to be well-known now, it was extremely popular in its time and for several decades afterwards.
In the poem a platypus is appointed to the British diplomatic service, and proves to be extremely successful, precisely because he doesn't do anything, and therefore never does anything wrong.

The wisdom of the choice, it soon appeared, was undeniable;
There never was a diplomat more thoroughly reliable.
He never made rash statements his enemies might hold him to,
He never stated anything, for no one ever told him to,


text:
Q: GSDMM Convergence of Clusters (Short Text Clustering) I am using this GSDMM python implementation to cluster a dataset of text messages. GSDMM converges fast (around 5 iterations) according the inital paper. I also have a convergence to a certain number of clusters, but there are still a lot of messages transferred in each iteration, so a lot of messages are still changing their cluster.
My output looks like:
In stage 0: transferred 9511 clusters with 150 clusters populated
In stage 1: transferred 4974 clusters with 138 clusters populated
In stage 2: transferred 2533 clusters with 90 clusters populated
….
In stage 34: transferred 1403 clusters with 47 clusters populated
In stage 35: transferred 1410 clusters with 47 clusters populated
In stage 36: transferred 1430 clusters with 48 clusters populated
In stage 37: transferred 1463 clusters with 48 clusters populated
In stage 38: transferred 1359 clusters with 48 clusters populated

In the initial paper figure 3 shows the same pattern, the number of clusters in nearly constant.

What I can't figure out is how many messages of their dataset where still transfering. My understanding is, that this number should be as small as possible, in best case zero (so every message "found" the right cluster). So the number of clusters might be converging, but that doens´t say much about the quality of the algorithm/clusters. Is my understanding correct?
It also is a possibility that my data is not good enough to get proper clustering.

A: After a deeper dive into the functionality of the GSDMM Algorithm, I can share some new information.
Here is some background information about the algorithm, of course this is not a complete description of how the algorithm works:
•   GSDMM is a soft clustering algorithm
•   Underlaying the allocations of inputs (e.g. messages) to clusters are distributions (Multinomial distributions with Dirichlet Distributions as their Prior)
•   The "Score"-Metric, that shows probability of an input belonging to a cluster, is based on a multinomial distribution and over all clusters adds up to 1
So as long as you don´t have very clear and easy separable clusters there will be inputs that "belong" to several clusters with a significant probability, e.g. Message 1 has a score value of 0.5 for Cluster 1, a score value of 0.4 for Cluster 2 and 0.1 for all the other clusters combined. If there are inputs with score values like that, due to the assignment depending on the multinomial distribution they sometimes will jump for one cluster to another one.
With knowing that I would say it is normal, even after a lot of iterations, to have jumping inputs. To measure the quality of your clustering, you should assign the inputs to the cluster with their highest score value and should not take the clustering based on the last iteration of your training.
Another option would be to leave out inputs that jump a lot or don´t have a cluster with a superior value, because these inputs are not good to fit in clusters (maybe some bad data, of course depending from case to case)


text:
Q: Using TCP Receive Buffer as a Buffer for Multimedia Applications Is it possible to use the TCP receive buffer to buffer data in multimedia streaming applications? What are the respective reasons?

A:
Is it possible to use the TCP receive buffer to buffer data

Yes.

in multimedia streaming applications?

In any applications. That's what a buffer is for. To buffer data.

What are the respective reasons?

Reasons for what?


text:
Q: opening or browsing for mp3 files in windows phone 7 im trying to create a mp3 player for windows phone 7...how do i  create a open file dialog or something that will allow me to access my files on the phone so that i can play them with my app"???
EG:
say i have a folder in my sd card...how do i browse to that folder so that i can imports the songs from that folder into a playlist in my app...

A: There are no standard open file dialogs for WP7. (some choosers excepted.)
If you want to do this you'll have to create the dialog yourself. You can get the details of the songs saved into the Music&Video hub via the MediaLibrary object. (Add a reference to Microsoft.Xna.Framework.dll to use this from Silverlight.)
You'll then have access to lists (collections) of Albums, artists, playlists, songs, etc.
If you want to play tracks you've save in IsolatedStorage you can access these directly yourself.


text:
Q: Delete message using AE.Net.Mail I'm trying to delete some specific emails. I'm using AE.Net.Mail. I tried a few thinks but nothing worked yet. I've read about expunge, somethink that could work. So far it hasn't and i have the feeling it doesn't work with AE.Net.Mail.
So can you guys help me out?
I filter the messages like this:
var Mail = imap.SearchMessages(SearchCondition.Subject("Generated Report"));!

A: Have you tried the following?
List<Lazy<MailMessage>> Mail = imap.SearchMessages(
    SearchCondition.Subject("Generated Report")).ToList();
imap.DeleteMessage(Mail.First().Value);
imap.Expunge();


text:
Q: Safari says "can't open page" but JSON return is normal My homebrew Wi-Fi temperature sensor works when connected to one of my access points, but with another one I get "Safari can't open the page because the server unexpectedly dropped the connection." Yet looking at the device log (in Arduino) it appears to respond correctly with a very short JSON record:
new client
Request: GET /temperature/F HTTP/1.1
Response: {"TempF":65.30}

Client disconnected

Also, accessing the device with curl http://xx.yy.zz.ww/temperature/F produces the desired JSON response.
I don't know where to start looking for the problem (tried it with Chrome and got the same result).
I have Safari's "Develop" menu enabled. I've been through all the router settings and don't see anything that could cause this.
I'm using the Arduino ESP8266 library.

A: I don't have an Arduino board, and not used that library, however I think this can solve your issue.
As for my search of the Arduino ESP8266 library, it is just an TCP and UDP library, not an HTTP library. So you have to implement all the HTTP headers by yourself, which can also be indicated by Request field in your question. Then I think if filling the Response with a valid HTTP response format may solve this issue, for example
Response: HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\n{"TempF":65.30}


text:
Q: Access is denied HRESULT: 0x80070005 I tried debugging one of my projects and while opening a DataTable i ended up with the error below.

Any solutions?

A: You simply have not rights on the Database which the DataTable refers to. The designer of your TableAdapters in Visual Studio, tries to update them self on opening.
So, simply check if your ConnectionString is still accurate.


text:
Q: Rails - form_tag with :remote => true and false I have a form with :remote => true, where is button and submit_tag for sending form.
When I send form through button, I would need to send the form as :remote => true and render some data through AJAX, which works me well.
But if a user send form through the submit_tag, I would need to execute some operations and then redirect_to an another page.
Is there any way, how to do it with :remote => true in the form head?
Thanks

A: Ok, so this is how I have solved it:
render js: %(window.location.href='#{root_url}')

A: Try to use jsvascript. Add remote attribute to form dynamically on button click.


text:
Q: Seeing how Independent Random Variables are Uncorrelated In my textbook for my measure theory class (Marek Capinski and Ekkehard Kopp:
Measure, Integral and Probability), in the chapter on the independence of two random variables, the author(s) make the following claim after defining the covariance of two random variables and correlation:

As we can see $\operatorname{Cov}(X,Y)= \mathbb{E}(XY)-\mathbb{E}(X)\mathbb{E}(Y)$, so clearly independent random variables $X$ and $Y$ are uncorrelated; it is sufficient to take $f(x)=x-\mathbb{E}(X)$ and $g(x)=x-\mathbb{E}(Y)$ in theorem $5.18$.

Where theorem $5.18$ states:
The random variables $X$ and $Y$ are independent if and only if $\mathbb{E}(f(X)g(Y))=\mathbb{E}(f(X))\mathbb{E}(g(Y))$ holds for all Borel measurable bounded functions $f,g$.
My question:
Since the author did not provide a proof, i'm not understanding how using $f(x)=x-\mathbb{E}(X)$ and $g(x)=x-\mathbb{E}(Y)$ in theorem $5.18$ shows that independent random variables $X$ and $Y$ are uncorrelated. If any one could explain or provide insight, it would be a great help.

A: Suppose two random variables are independent. Then (choose identity functions) $E(XY)=E(X)E(Y)$.
It remains to note that
$$Cov(X,Y)=E(XY)-E(X)E(Y).$$
EDIT: Using the given functions, we have
$$Cov(X,Y)=E((X-E(X))(Y-E(Y))=E(X-E(X))E(Y-E(Y))=0$$


text:
Q: Show and prove if $\sum_{j=1}^\infty{ \frac{(1+(1/j))^{2j}}{e^j}}$ converges or diverges Show and prove if the following series converges or diverges

$$\sum_{j=1}^\infty{ \frac{(1+(1/j))^{2j}}{e^j}}$$

"I tried the comparison test, the root test, and the ratio test, but got messed up..."
Thanks!

A: Apply the $\,n$-th root test:
$$\sqrt[n]{\frac{\left(\frac{n+1}n\right)^{2n}}{e^n}}=\frac{\left(\frac{n+1}n\right)^2}{e}\xrightarrow[n\to\infty]{}\frac1e<1\implies\;\text{the series converges}$$

A: $(1+1/j)^j
\to e$ as
$j \to \infty$.
Therefore
$(1+1/j)^{2j}
\to e^2$ as
$j \to \infty$,
so each term is about
$e^2/e^j$
which is exponentially small,
so it converges.

A: HINT: Recall the definition of $e$
$$
e=\lim_{n \to \infty} \bigg(1+\frac{1}{n}\bigg)^n
$$
Notice the numerator can be written as
$$
\bigg(1+\frac{1}{j}\bigg)^{2j}
$$
and that this is similar to the above definition of $e$. What does this imply about your summation?


text:
Q: TypeError('cannot convert dictionary update sequence element #0 to a sequence') @api.get("/subject")
async def subject_type_list(
    db: get_db = Depends(),
) :

    data = (
        db.query(
            SubjectType.id,
            SubjectType.name,
            SubjectType.korean_name,
        ).filter(
            SubjectType.subject_list_id == 1
        ).all()
    )

    return data

Error
fastapi                      | Traceback (most recent call last):
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/fastapi/encoders.py", line 152, in jsonable_encoder
fastapi                      |     data = dict(obj)
fastapi                      | TypeError: cannot convert dictionary update sequence element #0 to a sequence
fastapi                      |
fastapi                      | During handling of the above exception, another exception occurred:
fastapi                      |
fastapi                      | Traceback (most recent call last):
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/fastapi/encoders.py", line 157, in jsonable_encoder
fastapi                      |     data = vars(obj)
fastapi                      | TypeError: vars() argument must have __dict__ attribute
fastapi                      |
fastapi                      | The above exception was the direct cause of the following exception:
fastapi                      |
fastapi                      | Traceback (most recent call last):
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 419, in run_asgi
fastapi                      |     result = await app(  # type: ignore[func-returns-value]
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
fastapi                      |     return await self.app(scope, receive, send)
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/fastapi/applications.py", line 271, in __call__
fastapi                      |     await super().__call__(scope, receive, send)
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/applications.py", line 125, in __call__
fastapi                      |     await self.middleware_stack(scope, receive, send)
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__
fastapi                      |     raise exc
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__
fastapi                      |     await self.app(scope, receive, _send)
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/base.py", line 104, in __call__
fastapi                      |     response = await self.dispatch_func(request, call_next)
fastapi                      |   File "/code/./app/main.py", line 81, in log_request
fastapi                      |     res = await call_next(req)
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/base.py", line 80, in call_next
fastapi                      |     raise app_exc
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/base.py", line 69, in coro
fastapi                      |     await self.app(scope, receive_or_disconnect, send_no_error)
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/cors.py", line 84, in __call__
fastapi                      |     await self.app(scope, receive, send)
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
fastapi                      |     raise exc
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
fastapi                      |     await self.app(scope, receive, sender)
fastapi                      |   File "/usr/local/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 26, in __call__
fastapi                      |     raise dependency_exception
fastapi                      |   File "/code/./app/db/deps.py", line 9, in get_db
fastapi                      |     yield db

fastapi                      | ValueError: [TypeError('cannot convert dictionary update sequence element #0 to a sequence'), TypeError('vars() argument must have __dict__ attribute')]

#docker-file
FROM python:3.8
WORKDIR /code
COPY requirement/dev.txt .
RUN pip install --no-cache-dir --upgrade -r /code/dev.txt
RUN mkdir app
COPY app app

ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1

#docker-compose file
  fastapi:
    container_name: fastapi
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 5000:5000
    command: >
      bash -c "uvicorn app.main:app --host 0.0.0.0 --port 5000 --reload"
    volumes:
      - ./app:/code/app
    env_file:
      - env/dev.env

When I run this code on my local-uvicorn-venv or remote-linux-server, it is working properly. But when I run this code on my local docker container, it makes error as above. how can I solve this problem? I tried remove docker and reinstalled it. but it doesn't work. I don't understand why type error occered.


text:
Q: Pandas how to plot multiple 0/1 distributions in to one figure I have a dataset that looks like this:
label colA colB colC
  0     1    0    0
  0     0    1    0
  1     0    0    1
  1     1    0    1

Each row will be either label 0 or 1, and only one of colA, colB and colC will be 1, other will be 0.
I want to plot one figure that looks something like (Y will be counts, X will be 0/1):

Based on the example given, there will be 6 columns in total since there'll be 3 columns indicating 0 label, and 3 columns for 1 label. How do I do that? I know how to plot one column
df[df['colA']==1]['label'].plot() but not sure how to combine multiple columns together..

A: It looks like you might want a groupby.sum then plot.bar:
df.groupby('label').sum().plot.bar()

NB. if you want the proportion, use df.groupby('label').mean().plot.bar().
Output:

A: If I've understood the question correctly, maybe you are looking for something like this:
import matplotlib.pyplot as plt

X_axis = [int(x) for x in df['labels']]
cols = df.drop(['labels'], axis=1).columns
width = 0.25
color_dict = {0: 'red', 1: 'blue', 2: 'green'}
for i, c in enumerate(cols):
  plt.bar(0 + width*(i - len(cols)//2), len(df[(df['labels'] == 0) & (df[c] == 1)]), width, color=color_dict[i%len(cols)], label=c)
  plt.bar(1 + width*(i - len(cols)//2), len(df[(df['labels'] == 1) & (df[c] == 1)]), width, color=color_dict[i%len(cols)], label=c)
plt.xticks(X_axis, df['labels'])

handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())

For the data you've provided, the result should look as follows


text:
Q: Form css with Flask I´m using Flask framework and the library WTforms and I´ve a problem changing the color of each option in the select fields, because it appears always in black instead of in red
I´ve the next form in the template
    <form method=post class="formulario" action="/rutinas">

                {{ render_field(form.username) }}

                {{ render_field(form.email) }}

                {{ render_field(form.sex) }}

                {{ render_field(form.age) }}

                {{ render_field(form.type_training) }}

                {{ render_field(form.days) }}

                {{ render_field(form.duration) }}

                {{ render_field(form.intensity) }}

<input type=submit class="btn btn-sm btn-default" value=Make>

     </form>

And in css file:
input
    {
        color: black;
    }

select option
    {
        color: red;
    }

A: You can avoid wrapping the form elements in divs to simplify css selection. This means that:

        {{ render_field(form.username) }}

could become:
{{form.username(class='css_class'}}

with no further divs around. Wtform takes care of rendering that specific field as an input field in the html and Jinja takes care of applying the class you are expressing in the parenthesis.
Useful info in the WTForms crash course
From the WTForms crash course:
class LoginForm(Form):
    username = TextField('Username')
    password = PasswordField('Password')

form = LoginForm()

<form method="POST" action="/login">

{{ form.username.label }}: {{ form.username(class="css_class")   }}

{{ form.password.label }}: {{ form.password() }}

</form>

A: I´ve solved it, i´ve written the css as:
select {
    color: black;
    border: none;
    -webkit-appearance:  cover;
}

Finally it works if I include the last line, I think it´s because i´m using Bootstrap framework too. Thanks for your answers.


text:
Q: Android SWITCH . how do I change the on color to green Below is code to add a switch to a table layout. When the switch is touch it turns RED.  I need it to be GREEN.
I have tried everything to change the ON color to green with no success.
 Switch sw1 = new Switch(this);
 sw1.setTag(i);
 if (switchonoff.get(i).equals("true"))
        {
            sw1.setChecked(true);

        }
        else
        {
           sw1.setChecked(false);
         }
        sw1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
             {
                @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                    {
                        System.out.println("____Switch State: isChecked: " + isChecked +  " " + buttonView.getTag() );
                        Integer tmpint = (Integer)buttonView.getTag();
                        if (isChecked)
                        {
                            switchonoff.set(tmpint, "true");
                        }
                        else
                        {
                            switchonoff.set(tmpint, "false");
                        }

                        for (int i=0; i<mnumberofrows; i++ )
                        {
                            System.out.println("________Switch State: isChecked " + i + " " + switchonoff.get(i));
                        }
                    }
                });

A: This answer will help those that will be using SwitchMaterial rather than Switch
Here's an example of a SwitchMaterial in XML. Set a custom theme as seen in the last line of the xml
<com.google.android.material.switchmaterial.SwitchMaterial
    android:id="@+id/switchLocks"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/filter_lock_title"
    android:theme="@style/FilterSwitchThemeGreen" />

In your values/styles.xml add a style for your switch.
<style name="FilterSwitchThemeGreen" parent="AppTheme">
    <item name="colorAccent">#00FF00</item>
</style>

Before:
After:

A: The color of the switch is determined by the theme or style of your app. You will need to create a custom style and apply it to your switch. With
Edit values\styles.xml with the following
<style name="SwitchTheme" parent="Theme.AppCompat.Light">
    <item name="android:colorControlActivated">#148E13</item>
</style>

Now we just need to apply it to the switch.
<Switch
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="New Switch"
  android:id="@+id/switch1"
  android:theme="@style/SwitchTheme" <--- Important line
  android:layout_alignParentTop="true"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="78dp" />

Then we are left with the following:
Before

After

A: Another way to do, change the background color:
setBackgroundColor(android.graphics.Color.GREEN);
As:
holper.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked){

                    buttonView.setBackgroundColor(android.graphics.Color.GREEN);
                }

}


text:
Q: First Responder not Changing Currently i have this tableview in my storyboard i have this structure in my table

i already have placed to each textfield a tag 0 - 6 and i have this piece of code
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if(textField.returnKeyType == UIReturnKeyNext) {
        NSInteger nextTag = textField.tag + 1;
        UIResponder* nextResponder = [textField viewWithTag:nextTag];
        [nextResponder becomeFirstResponder];

    } else if (textField.returnKeyType == UIReturnKeyDone) {
        [textField resignFirstResponder];
    }
    return YES;
}

but for some reason it doesn't change to next textfield any ideas on what am i doing wrong?

A: According to the documentation, the viewWithTag:'s return value is:

Return Value
The view in the receiver's hierarchy whose tag property
  matches the value in the tag parameter.

It seems unlikely that your textField is the parent view of some other text field.  You should probably call this on your table view or the view controller's view property.

A: You can try resigning the old first responder first:
[textField resignFirstResponder];
[nextResponder becomeFirstResponder];

Sometimes it is a bit tricky, if this does not work you can try just if the [textField resignFirstResponder]; works... If it works and it is the [nextResponder becomeFirstResponder]; that does not work you can always try it with a delay: [nextResponder performSelector:@selector(becomeFirstResponder) afterDelay:0.1];
Hope it helps...