text:
Q: Invalid Postback or Callback Error - How to find what is causing the error I'm working on an asp.net web application and am running into this error after manipulating some controls client-side (html buttons nested in update panels):
"Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
The stack trace given is:
"[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +9832822
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +114
System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) +65
System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +18
System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +471
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1897"
This stack trace is useless in that it's not telling me what control is causing the issue.  I think I understand the basics of what the error is trying to say, but without a direction to go it's a total crapshoot as to where to start looking, particularly since I'm not manipulating any dropdown lists.
Before I go through the hassle of posting code, how can I get the complete stack trace (showing file and line number) for the error to figure out what is happening?  I've been working on this problem for a week now and I'm pretty well fed up with it.  Thanks.

A: hum, does this occur on a button click? Try moving any control validators to the top of the page, see if that helps. I guess a few more details as to "when" the error occurs. (does it occur on first page load, or due to some button click? And do you have any say JavaScript bits and parts that might have posted the page back before it is 100% rendered? I mean, something added to the page must have "started" this issue to occur. but, we quite much guessing. You could as a test in web config turn off page validation, and at least see if that works, and then try to fix and then re-enable.
Also, are you loading up data into some controls on page load?
Try then placing that "setup" and "data loading" inside of the !IsPostback (which all pages quite much need and have, right??).
So, in page load event, place that data load, and setup code you have inside of the !IsPostBack block like this:
if (!IsPostBack)
{
    page load + setup + data loading code goes here
}

So, adopt the above if you have code to load up say a gridview, or even a dropdown box. I seen the above "simple" change in code fix your error, and a good number of times.


text:
Q: ImageButton does'nt fire OnItemCommand in repeater control everyone!
I'm writing repeater control on my web-page. After I added data paging for repeater I have got problem:
ImageButton does'nt fire any more OnItemCommand event of repeater. Why?
Here, is part of markup code:
 <asp:Repeater ID="PartsRepeater" runat="server"
                    OnItemCommand="partsRepeater_ItemCommand"
                    OnItemDataBound="partsRepeaterItem_Bound">
                    <HeaderTemplate>

                                                <asp:Label runat="server" Text="Name" ID="lblName">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="Number" ID="Label64">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="Category" ID="Label65">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="Description" ID="Label66">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="Models" ID="Label67">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="Price" ID="Label68">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="A Qty" ID="Label69">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="B Qty" ID="Label70">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="Actual Qty" ID="Label71">
                                                </asp:Label>

                                                <asp:Label runat="server" Text="Total Qty" ID="Label72">
                                                </asp:Label>

                    </HeaderTemplate>
                    <ItemTemplate>

                                            <asp:HiddenField runat="server" ID="PartID" Value='<%# Bind("PartID") %>' Visible="false" />
                                            <asp:LinkButton runat="server" ID="Label52" Text='<%#Eval("Name").ToString()%>' CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="Label45" runat="server" Text='<%#Eval("Number").ToString().ToUpper()%>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="Label46" runat="server" Text='<%#Eval("Category").ToString()%>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="Label47" runat="server" Text='<%# GetPartDescr((String)Eval("Description"))%>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="Label48" runat="server" Text='  <%# GetPartDescr((String)Eval("ModelName")) %>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="Label49" runat="server" Text='<%# GetPrice(Eval("Price").ToString(), Eval("sPrice").ToString(), Eval("Price3").ToString())%>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="lblAQTY" runat="server" Text=' <%#Eval("AGradeQty").ToString()%>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="lblBQty" runat="server" Text=' <%# int.Parse(Eval("QtyInStock").ToString()) - int.Parse(Eval("AGradeQty").ToString())%>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="lblActualQTY" runat="server" Text=' <%#Eval("ActualQty").ToString()%>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="Label60" runat="server" Text='<%#Eval("QtyInStock").ToString()%>'
                                                CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="Label63" runat="server" Text='<%#Eval("priceModificationDate").ToString()%>'
                                                Font-Size="Smaller" CommandArgument='<%# Eval("PartID") %>'>
                                            </asp:LinkButton>

                                            <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/Images/edit.png" CausesValidation="False"
                                                CommandName="editRow" CommandArgument='<%# Eval("PartID") %>' OnClientClick='SaveScrollPositions'>
                                            </asp:ImageButton>

                                            <asp:ImageButton ID="btnDelete" runat="server" OnClientClick='<%# GetConfirmMessage(Eval("Name"))%>'
                                                ImageUrl="~/Images/delete.png" CausesValidation="False" CommandName="Delete"
                                                CommandArgument='<%# Eval("PartID") %>'></asp:ImageButton>

                    </ItemTemplate>
                    <FooterTemplate>

                    </FooterTemplate>
                </asp:Repeater>

A: I've tried nany ways to solve this problem and solved it so:
I just replace ImageButton with linkButton with image:
Part og code:

                                            <asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="editRow"
                                                CommandArgument='<%# Eval("PartID") %>' OnClientClick='SaveScrollPositions'>
                                                <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/edit.png" />
                                            </asp:LinkButton>

                                            <asp:LinkButton ID="btnDelete" runat="server" CausesValidation="false" CommandName="Delete"
                                                CommandArgument='<%# Eval("PartID") %>' OnClientClick='<%# GetConfirmMessage(Eval("Name"))%>'>
                                                <asp:Image ID="Image2" runat="server" ImageUrl="~/Images/delete.png" />
                                            </asp:LinkButton>

For more see: http://weblogs.asp.net/justinsaraceno/archive/2008/11/05/linkbutton-with-image-and-text.aspx

A: Sorry I don't have a more specific answer, but it has something to do with ViewState on the repeater and rebinding the repeater on Postback.
Apparently, when the postback occurs and you rebind the repeater, it loses some event binding and instead of running the OnCommand, it treats it as if it's a first page load for ImageButton. AFAIK it only happens on ImageButton and not LinkButton or Button.

A: Put this in code behind it will surely work
if (!Page.IsPostBack)
{
    REPEATERDATABIND(); // Bind method
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction I'm running the following MySQL UPDATE statement:
mysql> update customer set account_import_id = 1;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

I'm not using a transaction, so why would I be getting this error? I even tried restarting my MySQL server and it didn't help.
The table has 406,733 rows.

A: Take a look to see if your database is fine tuned, especially the transaction isolation. It isn't a good idea to increase the innodb_lock_wait_timeout variable.
Check your database transaction isolation level in MySQL:
mysql> SELECT @@GLOBAL.tx_isolation, @@tx_isolation, @@session.tx_isolation;
+-----------------------+-----------------+------------------------+
| @@GLOBAL.tx_isolation | @@tx_isolation  | @@session.tx_isolation |
+-----------------------+-----------------+------------------------+
| REPEATABLE-READ       | REPEATABLE-READ | REPEATABLE-READ        |
+-----------------------+-----------------+------------------------+
1 row in set (0.00 sec)

You could get improvements changing the isolation level. Use the Oracle-like READ COMMITTED instead of REPEATABLE READ. REPEATABLE READ is the InnoDB default.
mysql> SET tx_isolation = 'READ-COMMITTED';
Query OK, 0 rows affected (0.00 sec)

mysql> SET GLOBAL tx_isolation = 'READ-COMMITTED';
Query OK, 0 rows affected (0.00 sec)

Also, try to use SELECT FOR UPDATE only  if necessary.

A: Try to update the below two parameters as they must be having default values.

innodb_lock_wait_timeout = 50

innodb_rollback_on_timeout = ON

For checking parameter value you can use the below SQL.

SHOW GLOBAL VARIABLES LIKE 'innodb_rollback_on_timeout';

A: Can you update any other record within this table,  or is this table heavily used?  What I am thinking is that while it is attempting to acquire a lock that it needs to update this record the timeout that was set has timed out.  You may be able to increase the time which may help.

A: HOW TO FORCE UNLOCK for locked tables in MySQL:
Breaking locks like this may cause atomicity in the database to not be enforced on the sql statements that caused the lock.
This is hackish, and the proper solution is to fix your application that caused the locks. However, when dollars are on the line, a swift kick will get things moving again.
1) Enter MySQL
mysql -u your_user -p

2) Let's see the list of locked tables
mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)
mysql> show processlist;

4) Kill one of these processes
mysql> kill <put_process_id_here>;

A: Something is blocking the execution of the query. Most likely another query updating, inserting or deleting from one of the tables in your query. You have to find out what that is:
SHOW PROCESSLIST;

Once you locate the blocking process, find its id and run :
KILL {id};

Re-run your initial query.

A: If you've just killed a big query, it will take time to rollback. If you issue another query before the killed query is done rolling back, you might get a lock timeout error. That's what happened to me. The solution was just to wait a bit.
Details:
I had issued a DELETE query to remove about 900,000 out of about 1 million rows.
I ran this by mistake (removes only 10% of the rows):
DELETE FROM table WHERE MOD(id,10) = 0
Instead of this (removes 90% of the rows):
DELETE FROM table WHERE MOD(id,10) != 0
I wanted to remove 90% of the rows, not 10%. So I killed the process in the MySQL command line, knowing that it would roll back all the rows it had deleted so far.
Then I ran the correct command immediately, and got a lock timeout exceeded error soon after. I realized that the lock might actually be the rollback of the killed query still happening in the background. So I waited a few seconds and re-ran the query.

A: In our case the problem did not have much to do with the locks themselves.
The issue was that one of our application endpoints needed to open 2 connections in parallel to process a single request.
Example:

*

*Open 1st connection

*Start transaction 1

*Lock 1 row in table1

*Open 2nd connection

*Start transaction 2

*Lock 1 row in table2

*Commit transaction 2

*Release 2nd connection

*Commit transaction 1

*Release 1st connection

Our application had a connection pool limited to 10 connections.
Unfortunately, under load, as soon as all connections were used the application stopped working and we started having this problem.
We had several requests that needed to open a second connection to complete, but could not due to the connection pool limit. As a consequence, those requests were keeping a lock on the table1 row for a long time leading the following requests that needed to lock the same row to throw this error.
Solution:

*

*In the short term, we patched the problem by increasing the connection pool limit.

*In the long term, we removed all nested connections, to fully solve the issue.

Tips:
You can easily check if you have nested connections by trying to lower your connection pool limit to 1 and test your application.

A: You are using a transaction; autocommit does not disable transactions, it just makes them automatically commit at the end of the statement.
What could be happening is, some other thread is holding a record lock on some record (you're updating every record in the table!) for too long, and your thread is being timed out. Or maybe running multiple (2+) UPDATE queries on the same row during a single transaction.
You can see more details of the event by issuing a
SHOW ENGINE INNODB STATUS

after the event (in SQL editor). Ideally do this on a quiet test-machine.

A: The number of rows is not huge... Create an index on account_import_id if its not the primary key.
CREATE INDEX idx_customer_account_import_id ON customer (account_import_id);

A: mysql> set innodb_lock_wait_timeout=100;

Query OK, 0 rows affected (0.02 sec)

mysql> show variables like 'innodb_lock_wait_timeout';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| innodb_lock_wait_timeout | 100   |
+--------------------------+-------+

Now trigger the lock again. You have 100 seconds time to issue a SHOW ENGINE INNODB STATUS\G to the database and see which other transaction is locking yours.

A: mysql->SHOW PROCESSLIST;
kill xxxx;

and then kill which one in sleep. In my case it is 2156.

A: 100% with what MarkR said. autocommit makes each statement a one statement transaction.
SHOW ENGINE INNODB STATUS should give you some clues as to the deadlock reason. Have a good look at your slow query log too to see what else is querying the table and try to remove anything that's doing a full tablescan. Row level locking works well but not when you're trying to lock all of the rows!

A: Make sure the database tables are using InnoDB storage engine and READ-COMMITTED transaction isolation level.
You can check it by SELECT @@GLOBAL.tx_isolation, @@tx_isolation; on mysql console.
If it is not set to be READ-COMMITTED then you must set it. Make sure before setting it that you have SUPER privileges in mysql.
You can take help from http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html.
By setting this I think your problem will be get solved.

You might also want to check you aren't attempting to update this in two processes at once. Users ( @tala ) have encountered similar error messages in this context, maybe double-check that...

A: I came from Google and I just wanted to add the solution that worked for me. My problem was I was trying to delete records of a huge table that had a lot of FK in cascade so I got the same error as the OP.
I disabled the autocommit and then it worked just adding COMMIT at the end of the SQL sentence. As far as I understood this releases the buffer bit by bit instead of waiting at the end of the command.
To keep with the example of the OP, this should have worked:
mysql> set autocommit=0;
mysql> update customer set account_import_id = 1; commit;
Do not forget to reactivate the autocommit again if you want to leave the MySQL config as before.
mysql> set autocommit=1;

A: Late to the party (as usual) however my issue was the fact that I wrote some bad SQL (being a novice) and several processes had a lock on the record(s) <-- not sure the appropriate verbiage. I ended up having to just: SHOW PROCESSLIST and then kill the IDs using KILL <id>

A: This kind of thing happened to me when I was using php
language construct exit; in middle of transaction. Then this
transaction "hangs" and you need to kill mysql process (described above with processlist;)

A: In my instance, I was running an abnormal query to fix data.  If you lock the tables in your query, then you won't have to deal with the Lock timeout:
LOCK TABLES `customer` WRITE;
update customer set account_import_id = 1;
UNLOCK TABLES;

This is probably not a good idea for normal use.
For more info see:  MySQL 8.0 Reference Manual

A: I ran into this having 2 Doctrine DBAL connections, one of those as non-transactional (for important logs), they are intended to run parallel not depending on each other.
CodeExecution(
    TransactionConnectionQuery()
    TransactionlessConnectionQuery()
)

My integration tests were wrapped into transactions for data rollback after very test.
beginTransaction()
CodeExecution(
    TransactionConnectionQuery()
    TransactionlessConnectionQuery() // CONFLICT
)
rollBack()

My solution was to disable the wrapping transaction in those tests and reset the db data in another way.

A: We ran into this issue yesterday and after slogging through just about every suggested solution here, and several others from other answers/forums we ended up resolving it once we realized the actual issue.
Due to some poor planning, our database was stored on a mounted volume that was also receiving our regular automated backups. That volume had reached max capacity.
Once we cleared up some space and restarted, this error was resolved.
Note that we did also manually kill several of the processes: kill <process_id>; so that may still be necessary.
Overall, our takeaway was that it was incredibly frustrating that none of our logs or warnings directly mentioned a lack of disk space, but that did seem to be the root cause.

A: I had similar error when using python to access mysql database.
The python program was using a while and for loop.
Closing cursor and link at appropriate line solved problem
https://github.com/nishishailesh/sensa_host_com/blob/master/sensa_write.py
see line 230
It appears that asking repeated link without closing previous link produced this error

A: I've faced a similar issue when doing some testing.
Reason - In my case transaction was not committed from my spring boot application because I killed the @transactional function during the execution(when the function was updating some rows). Due to which transaction was never committed to the database(MySQL).
Result - not able to update those rows from anywhere. But able to update other rows of the table.
mysql> update some_table set some_value = "Hello World" where id = 1;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

Solution - killed all the MySQL processes using

*

*sudo killall -9 mysqld

*

*sudo killall -9 mysqld_safe (restarting the server when an error occurs and logging runtime information to an error log. Not required in my case)

A: Had this same error, even though I was only updating one table with one entry, but after restarting mysql, it was resolved.


text:
Q: MongoTimeoutError: Server selection timed out after 10000 ms I am trying to create a MERN app and containerize it with docker and manage the containers using kubernetes (minikube).
When I try to run the nodejs container it logs the following error
Server v8 up and running on port 5000 !
MongoTimeoutError: Server selection timed out after 10000 ms
at Timeout._onTimeout (/home/app/node_modules/mongodb-core/lib/sdam/topology.js:773:16)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
[Symbol(mongoErrorContextSymbol)]: {}
}

The code at server.js is as follows:

const express = require("express");
const mongoose = require("mongoose");

const app = express();

// the connection string when using username and password in mongodb-server
// mongodb://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@mongodb-service:27017/exam?authSource=${process.env.MONGO_DB_USERNAME}
mongoose
  .connect("mongodb://mongodb-service/exam", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log(`MongoDB successfully connected`))
  .catch((err) => console.log(err));

The logs in mongodb container are as follows:

{"t":{"$date":"2022-12-16T14:28:58.316+00:00"},"s":"I",  "c":"COMMAND",  "id":51803,   "ctx":"LogicalSessionCacheRefresh","msg":"Slow query","attr":{"type":"command","ns":"config.system.sessions","command":{"createIndexes":"system.sessions","v":2,"indexes":[{"key":{"lastUse":1},"name":"lsidTTLIndex","expireAfterSeconds":1800}],"ignoreUnknownIndexOptions":false,"writeConcern":{},"$db":"config"},"numYields":0,"reslen":114,"locks":{"ParallelBatchWriterMode":{"acquireCount":{"r":5}},"FeatureCompatibilityVersion":{"acquireCount":{"r":5,"w":1}},"ReplicationStateTransition":{"acquireCount":{"w":5}},"Global":{"acquireCount":{"r":5,"w":1}},"Database":{"acquireCount":{"r":4,"w":1}},"Collection":{"acquireCount":{"r":5,"w":1}},"Mutex":{"acquireCount":{"r":8}}},"storage":{},"protocol":"op_msg","durationMillis":529}}

If I should provide more details please tell me
Thanks in advance


text:
Q: Determining whether different groups of users click on certain URLs more frequently? Let's say I have a stream of click data that looks like this:
USER-ID,SHIRT-COLOR,URL
1,blue,http://a.com/apple.html
2,black,http://a.com/banana.html
2,black,http://a.com/apple.html
1,blue,http://a.com/cherry.html
3,red,http://a.com/cherry.html
4,blue,http://a.com/apple.html
4,blue,http://a.com/cherry.html
5,red,http://a.com/banana.html

I'm trying to figure out whether shirt color is a predictor of clicks. So, are certain URLs are more "popular" amongst people with a red shirts than amongst the general population? Or another way to say it: Is someone with a red shirt more likely to click on a URL that is popular amongst red shirts?
The number of URLs and User-IDs are in the thousands, but the short-colors are just a handfull.
I'm hoping someone could help me determine what type of problem this is (Clustering? Fuzzy clustering? Chi-squared?) and any tips on solving it.


text:
Q: Javascript scroll: How to execute function only once with least amount of CPU usage? I have a simple website consisting of a single page. Usage behavior is being tracked via Piwik. Due to the design of the page, users usually resort to scrolling through it instead of using the navbar and clicking on links, making link trackinga very uninformative method to get some insight into how the website is being used. To track user behavior, I have a js function using "scroll" that determines the location of the user on the page and then sends a request to the tracking server:
setInterval(reportposition, 1000);
 function reportposition () {
    $(function () {
             var $win = $(window);

             $win.scroll(function () {
                 if ($win.scrollTop() == 0) {
                     _paq.push(['trackEvent', 'Scroll', 'PageTop']);
}               else if (($(document).height() - $win.scrollTop()
                                < 7540) && ($(document).height() - $win.scrollTop() > 7500 )) {
                     _paq.push(['trackEvent', 'Scroll', 'About']);
}
                 else if ($win.height() + $win.scrollTop()
                                == $(document).height()) {
                     _paq.push(['trackEvent', 'Scroll', 'PageBottom']);
                 }
             });
         });
};

However, every scroll that satisfies one of the conditions does so dozens of times and thus sends dozens of tracking requests to the server. I tried to lower the frequency the function is run with setInterval, but the effect is negligible. Is there any way to get the function to fire off only once when a condition has been met until a different condition is satisfied?
Using scroll to check for the position of the user seems to be rather demanding regarding CPU cycles as sometimes hundreds of events can occur with a simple scroll. Is there any way to solve this problem with as little CPU usage as possible?

A: The solution here is to check if the scrollTop is equal to the scrollTop of the current div the user has scrolled on.
In terms of CPU, look at https://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery . This is one solution; more ideally you should look at using Websockets (i.e., using socket.io with node.js).

A: scroll event is unnecessary in your case, since it is only useful for detecting if the user has scrolled whereas you can check that by only comparing with scrollTop() value of a second ago. You also dont need to access height values if they do not
setInterval(reportposition, 1000);
var $win = $(window);

function reportposition () {
    $(function () {
        if(scrollTop == $win.scrollTop()){
            //same position
        }
        scrollTop = $win.scrollTop();
        winHeight = $win.height();
        docHeight = $(document).height();
        if (scrollTop == 0) {
             _paq.push(['trackEvent', 'Scroll', 'PageTop']);
        }else if ((docHeight - scrollTop < 7540)
            && (docHeight - scrollTop > 7500 )) {
             _paq.push(['trackEvent', 'Scroll', 'About']);
        }else if (winHeight + scrollTop
                        == docHeight) {
             _paq.push(['trackEvent', 'Scroll', 'PageBottom']);
         }
    });
};

Other way around, inside the scroll event, you can check how much time has passed and decide whether to process or not.


text:
Q: enum properties & side effects I have a question regarding enum (it might be a simple one but ....).
This is my program:
public class Hello {
         public enum MyEnum
         {
               ONE(1), TWO(2);
               private int value;
               private MyEnum(int value)
               {
                    System.out.println("hello");
                    this.value = value;
               }
               public int getValue()
               {
                    return value;
               }
        }
        public static void main(String[] args)
        {
              MyEnum e = MyEnum.ONE;
        }
}

and my question is: Why the output is
hello
hello

and not
hello
?
How the code is "going" twice to the constructor ?
When is the first time and when is the second ?
And why the enum constructor can not be public ?
Is it the reason why it print twice and not one time only ?

A: Your constructor invoke twice. The moment of loading your Enum class it will invoke number of time which equals to number of enum types here.
 MyEnum e = MyEnum.ONE; // singleton instance of Enum

consider following
public class Hello {

public enum MyEnum
{
    ONE(1), TWO(2), THREE(3);
    private int value;
    private MyEnum(int value)
    {
        System.out.println("hello"+value);
        this.value = value;
    }
    public int getValue()
    {
        return value;
    }
}
public static void main(String[] args)
{
    MyEnum e = MyEnum.ONE;
}

}
Out put
hello1
hello2
hello3

A: Enums are Singletons and they are instanciated upon loading of the class - so the two "hello"s come from instanciating MyEnum.ONE and MyEnum.TWO (just try printing value as well).
This is also the reason why the constuctor must not be public: the Enum guarantees there will ever only be one instance of each value - which it can't if someone else could fiddle with the constructor.

A: How the code is "going" twice to the constructor ?
Conctructor is invoked for each element of enum. Little change your example for demonstration it:
public class Hello {
    public enum MyEnum {
        ONE(1), TWO(2);
        private int value;
        private MyEnum(int value) {
            this.value = value;
            System.out.println("hello "+this.value);
        }
        public int getValue() {
            return value;
        }
    }
    public static void main(String[] args) {
        MyEnum e = MyEnum.ONE;
    }
}

Output:
hello 1
hello 2


text:
Q: Why is 'vals' being reset to zero every iteration of this while loop? I am writing some code to pack small integer values into a regular int
#include <stdio.h>

#define NUMVALS 6
#define SIZE 5
#define MAX 31

int main() {
int vals = 0;
short curVal, idx = 0;

while(idx != NUMVALS) {
  scanf("%d",&curVal);
  printf("Vals pre shift: %.8X\n",vals);
  vals <<= SIZE;
  printf("Vals post shift: %.8X\n",vals);
  vals |= curVal;
  printf("Vals post new set:%.8X\n\n",vals);
  idx++;
}

When I run this small check, with input string
1 2 3 4 5 6
I get output akin to this
Vals pre shift: 00000000
Vals post shift: 00000000
Vals post new set:00000001

Vals pre shift: 00000000
Vals post shift: 00000000
Vals post new set:00000002

For all six. Why is vals resetting to zero every loop? It doesn't look like I'm touching it at all, but clearly something is resetting it.

A: You are using the wrong format specifier in scanf. This causes undefined behaviour.  One possibility might be that scanf wrote 4 bytes to the 2-byte location of curVal, and the "extra" 2 bytes clobbered vals.
For a short, use %hd. Another option would be to change curVal to be an int.

Another potential problem is with vals <<= SIZE;. Shifting a 1 into the sign bit also causes undefined behaviour.  It might behave roughly sanely on common systems, but all the same, it's easily fixed by making vals have type unsigned int.


text:
Q: Problem setting time.struct_time properties in Python After I parsed a date in Python I need to patch it. But structure time.struct_time has read-only properties only:
parsed = time.strptime("23:59", "%H:%M")
parsed.tm_year = 2011
> TypeError: readonly attribute

How do I get a patched datetime value in a short & clever way?

A: Use datetime:
>>> p = datetime.datetime.strptime("23:59", "%H:%M")
>>> p = p.replace(year=2011)
>>> p
datetime.datetime(2011, 1, 1, 23, 59)


text:
Q: Reacting messages with Emojis in Discord.py I'm making a bot with Python and I want to send messages with emojis.
How can I react a message in discord.py?
I found this method in stackoverflow but How can I react with a :tada:?
#1
message = ctx.send("text")
#2
message = channel.send("text")
#3
message = channel.fetch_message(messageid)
#add reaction to message
emoji = '\N{THUMBS UP SIGN}'
await message.add_reaction(emoji)

A: Try to use the add_reaction method:
await message.add_reaction("")

A: Find unicode name for emoji you want or just use literal emoji in there - python allows for unicode characters. E.g. '\N{OPEN HANDS SIGN}' == ''
Emoji which shows up in discord when you write :tata: is ''. Its unicode name is party popper. So just use '' or '\N{PARTY POPPER}'
For Ubuntu, I found the name in Characters:

The title bar of this small window is your unicode name. You can also directly copy the character to your clipboard by clicking the button. Underneath you have unicode number for the character.
For system-agnostic search and searching by common names (like "tada"), you can use Emojipedia. E.g. search result for "tada" on Emojipedia shows Party Popper page.

A: To get the unicode emoji of any discord emoji,
Type the discord emoji in to the chat like this
Typing the discord emoji
then type a "" character before the emoji
discord emoji with backslash
Then post the message and you will get the unicode version of it,
copy the unicode version and paste it like this
await message.react("")


text:
Q: Trigger Eclipse's code formatter programmatically from a new file wizard I'm writing an Eclipse plugin with a wizard (org.eclipse.jface.wizard.Wizard) which creates a new file with a basic code template. To simplify the "piecing together" of the file contents, I plan to stuff everything into one long string, inject it into the file, and then call my custom Formatter (inherits org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter) to clean up all the indentation and so on.
Question is, how do I go about calling the formatter programmatically?
In the wizard I call IDE.openEditor() and get back a handle to an IEditorPart. What can I do from here?

A: Well, I have found my answer:
IEditorPart editor = IDE.openEditor(page, file, true);
XtextEditor xed = (XtextEditor)editor;
((SourceViewer)xed.getInternalSourceViewer()).doOperation(ISourceViewer.FORMAT);

Maybe that will help someone else looking for something similar!


text:
Q: Perl regex - How to make it less greedy? How do I count the number of empty 'fields' in the following string ?
Empty fields are indicated by -| or |-| or |-
The regex I have cooked up seems to be working except when I have consecutive empty fields ? How do I make it less greedy ?
my $string = 'P|CHNA|string-string|-|-|25.75|-|2562000|-0.06';
my $count = () = ($string=~/(?:^-\||\|-$|\|-\|)/g);
printf("$count\n");

The above code prints 2 instead of 3 which I want.

A: I'd avoid the regex route entirely for this and instead treat this like a list, because it is one:
my $count = grep { /^-$/ } split /\|/, $string;

A: The problem actually doesn't have anything to do with greediness/lazyness (which only applies to repetition operators like * or +).
The problem is the two empty fields right next to each other: |-|-|.  The first one is being matched, but then the second one fails because the opening | has already been consumed, but because you have the beining-of-line marker in the rule ^-|, it doesn't match that one.
I think a much easier approach would be to split your input on | and then look for any fields consisting of only a -:
my $count = 0;
foreach (split(/\|/,$string)) { if( /^-$/ ) { $count++; } }

There's really no way to robustly implement this with a regex since Perl doesn't support variable-length lookbehinds (at least not to my knowledge).  One way to "cheat" would be to append a | at the beginning and end, then you could successfully use lookbehind/lookahead assertions:
$string = "|$string|";
my $count = () = $string=~/(?<=\|)-(?=\|)/g;

(ikegama's answer below has an alternative solution that does use non-variable lookaround assertions without modifying the string, so I was wrong when I said there was "no way to implement this with a regex".  Props to ikegama.  I still think splitting on | is the best way to go for this problem, though.)

A: The trick is to use lookarounds. Someone's first attempt might be the following:
my $count = () = $string =~ /
   (?<\|)  # Preceded by "|"
   (-)
   (?=\|)  # Followed by "|"
/xg;

But that doesn't work. The problem with the above is that it doesn't detect if the first field or last field is empty. Two ways to fix that:
my $count = () = "|$string|" =~ /
   (?<\|)  # Preceded by "|"
   (-)
   (?=\|)  # Followed by "|"
/xg;

or
my $count = () = $string =~ /
   (?<![^|])  # Not preceded by a char other than "|"
   (-)
   (?![^|])   # Not followed by a char other than "|"
/xg;


text:
Q: Is there something in the ninja language that makes it faster than make? I often see the claim made that Ninja is faster than Make, is better at supporting incremental builds, and better at parallelization. Is this a quality of implementation issue or is there something in the Ninja language that enables this?
I understand that Ninja and Make use different file formats to describe the dependency graph of tasks. I understand that Make allows the use of more high level features, such as globs, than ninja. If such high-level features are used then Make performs a more complex task than Ninja and we cannot expect Make to be faster. This is an unfair comparison.
However, assume that such high level features are not used. No globing, no pattern rules, just basic "out_file: in_file1, in_file2\n\tcommand to build" repeated over and over and over. Not using such high-level feature evens the playing field between Make and Ninja in terms of the task that they perform.
My understanding is that, if we limit Makefiles in such a way, that Ninja files and Makefiles can easily be transformed into each other. Is this correct?
Is there any inherent reason why Make executed on limited Makefiles is any slower than Ninja? or is it simply case of the standard Make implementations not being optimized for Makefiles that are structured in this way?

A: In short, Ninja parses faster, and has built-in features that reduce the amount to parse.
From the philosophical overview in the ninja manual:

Where other build systems are high-level languages, Ninja aims to be an assembler.

Ninja files are often "compiled" from other makefiles, making it a two-step process whereas Make is a single step. The two-step can be slower than plain Make. Because only the second step is necessary for most the time the net effect is it being faster. It's somewhat similar to comparing a compiled and interpreted program.
Ninja add several features to Make. Implementing these in a makefile lead to longer, more complicated makefiles and thus much more parsing.


text:
Q: Should a View contain the Model it present? In MVC pattern, should a View contain the Model it is presenting?
For example, I have an Item model, ItemsListView & ItemRowView to display it.
In order to display the list, should I pass the Item model to ItemRowView (1) or I can pass Item.title, Item.details, Item.image, etc to the ItemRowView (2)
In (1), it is violate the MVC design pattern where View does not talk directly to the Model, and the View can also call Model methods
In (2), when make the View dummy, If in another ViewController, we use the ItemsList a gain, we have to duplicate the passing parameters again, and what happend if we need to pass one more properties to the user?
There another way, using ViewModel to wrap around the Model to handle UI Logic, but that will create many classes, and everytime I get a list of models, I also have to map it to ViewModels
example:
class ItemModel {
  var name: String = ""
  var price: Double = 9000
}

Should I assign the model to UITableViewCell like this: (so the cell can update the data itself whenever new data come)
class ItemTableViewCell: UITableViewCell {

  @IBOutlet var titleLabel: UILabel!

  var item: ItemModel! {
    didSet {
      self.updateUI()
    }
  }

  func updateUI() {
    titleLabel.text = item.name
  }
}

Or should I keep the cell dummy, and do the update UI in ViewController:
class ItemTableViewCell: UITableViewCell {
  @IBOutlet var titleLabel: UILabel!
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell: ItemTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ItemTableViewCell", for: indexPath)

  var item = items[indexPath.row]
  cell.titleLabel.text = item.name

  return cell
}

A: Yes. As it enables you to use the base methods of the model itself instead of creating wrapper classes and handling conversion based on design change.
The Rule of thumb nowadays is to have a view-model for each view if that view requires more than one object.This allows you to handle design and data changes without touching the controller.


text:
Q: Email rich formatting: Differences and compatibility between standards I read in Wikipedia that there are several ways of using rich formatting in emails:

*

*HTML e-mail

*Enriched_text

*MIME
But I am not sure I understand the differences between them. More specifically:

*

*Are they all part of the same standard or set of standards?

*Are they all equally supported by the major webmail service providers such as Gmail, Hotmail, etc?

*Which one is used when a user chooses Rich formatting when writing an email in Gmail, Hotmail or a similar email provider?

*What is the degree of compatibility between stand-alone and web-based email clients when it comes to email rich formatting standards?

A: Unlike others you've mentioned, MIME is not a rich text format by itself. While MIME and "Enriched text" are part of the same set of standards designed specifically for email, HTML is a markup format initially developed for the Web by the W3C.
However, nowadays most email clients and services use HTML for rich text formatting. This is because email clients and webmail services can re-use existing HTML rendering engines for displaying email:

*

*webmail is in your browser; it uses your browser's rendering engine

*Microsoft Outlook (at least some versions) uses Internet Explorer's engine

*Apple Mail uses WebKit, the engine powering Safari and Chrome browsers

*Mozilla Thunderbird uses Gecko, the same as Firefox

HTML email also allows for styling with CSS, enabling professionally designed email campaigns.
Therefore, HTML format is used when you use the "Rich formatting" mode for email. It is well-supported in all popular email clients, including webmail. It is the CSS support that varies wildly between clients, especially in webmail where different services (e.g. Gmail, Hotmail) force different limitations on what can be styled and in what way.
I think the reason why "Enriched text" has not seen wide adoption is not that HTML is "better" for email (there are too many reasons why HTML is not well-suited for email to list here), but because people used what they were already familiar with and what they have existing rendering engines for.

There is something else to add here. Not all email clients run in a graphical environment; there is a significant portion of people who prefer to read email from terminal emulators ("from the command-line", in other words). Therefore it's important that all email also carries a plain-text format of its contents. Regardless of whether you use the "Rich formatting" mode while you compose email, Gmail always includes the message body in plain text format. I suspect other modern email clients do the same, although I haven't tested.
When email carries multiple formats—HTML & plaintext, in our case—it's up to the email client that receives it to choose which one it will present to the user. Graphical email clients will render HTML by default, while text-only clients will ignore the HTML version and just show the plain-text one.


text:
Q: Getting Visualforce page name of previous page. I have two Visualforce pages for example Page1 and Page2. From Page1 method, by using Page reference I am calling Page2. In Page2 controller constructor, i am executing code that code has to be executed when ever controller called from Page2, not from Page1.
Page1 Code
PageReference   pageRef = new PageReference('/apex/page2?data='+i+'');
        pageRef.setRedirect(true);

in Page2 constructor
public page2Constructor() {
  panel = true;
}

Above panel=true needs to execute whenever it called from Page2, not from Page1.

A: When setRedirect is set to true a redirect is performed through a client side redirect which means all actions will be client side the the newly added page constructor will not be called, url will also not be changed and view state will also be maintained on the page


text:
Q: Centered ImageView inside a Toast in Android I'm making a simple Webview application for Android. When there's no connection I'm showing a custom toast message which will cover all the screen, but inside the toast I want to show an image with ImageView. The problem is that the toast is covering all the screen since I'm using the following code to do it:
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.FILL_VERTICAL, 0, 0);

How could I put the ImageView inside the toast totally centered? This is ImageView in the toast layout named toast_custom_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="horizontal"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/logo"
        android:background="@color/white" />
</LinearLayout>

And this is code in my activity that will show the toast when there is no connection:
public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
    LayoutInflater inflater = getLayoutInflater();

    View layout = inflater.inflate(R.layout.toast_custom_layout,
            (ViewGroup) findViewById(R.id.toast_layout_root));

    Toast toast = new Toast(getApplicationContext());
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();
    toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.FILL_VERTICAL, 0, 0);
}

I will really appreciate your advice, friends.

A: Try using a RelativeLayout instead
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/logo"
        android:background="@color/white" />

</RelativeLayout>

A: Try:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="horizontal"
android:padding="5dp" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/logo"
    android:background="@color/white"
    android:gravity="center" />
 </LinearLayout>

where the relevant part is android:gravity="center"


text:
Q: How can I define a schema in MySQL as a subset of another schema I have a MySQL schema with 20 tables, two applications are using it, the first one is using all the tables but the second only 10.
How can isolate the tables in such a way that the second app only "see" 10 tables?
I was thinking about using a second schema and synonyms to the tables of the first schema, but MySQL does not support synonyms.
It's all about documentation, it is not a security concern.
How can I proceed?

A: MySQL easily allows you to grant privileges on only some tables to one user, while granting privileges to all tables to another user.
So I recommend simply using ACL granularity to hide the unwanted tables from each application.


text:
Q: Open a password protected sqlite database I have created a password protected sqlite database. I want to be able to view the database so that I can check that things are being inserted correctly during the development of my project. I have downloaded the sqlite database browser but this doesn't seem to let you open an encrypted database.
Is there a way that I can open the database file.
Thanks for any help you can provide.

A: You can open and create a password protected sqlite database with SQLiteStudio:

A: The free SQLite2009 Pro browser will let you open SQLite databases which were encrypted with System.Data.SQLite.
When you open the file you get a warning saying that the file is encrypted or not a database, and are then prompted to select an encryption type, select "RSA".
Edit:
You may find SQLite2009 Pro is not as reliable as sqliteadmin (which does not open databases encrypted with System.Data.SQLite). I just found it crashed upon trying to open a database which had a problem with one of the views.
I ended up removing the encryption, and opening it with sqliteadmin, which did not crash but instead put a little red cross over the view which had a problem. What a nice touch :-)


text:
Q: How to create a mask image for a screenshot when simulating blur effect for a popover I have successfully implemented a blur effect for my app running on iPhone running iOS 7. I used the sample code Apple supplied with their UIImage+ImageEffects category. When I present a modal presentation, I take a screenshot in prepareForSegue and apply the effect, then pass that UIImage to the destinationViewController. In viewDidLoad of that new view controller, I simply set the background to be that of the stored image.
//prepareForSegue
UIImage *imageOfUnderlyingView = [UIImage snapshotImageWithView:[[UIApplication sharedApplication] keyWindow]];
destinationVC.imageOfUnderlyingView = [imageOfUnderlyingView applyBlurWithRadius:15
                                                                       tintColor:[UIColor redColor]
                                                           saturationDeltaFactor:1.2
                                                                       maskImage:nil];

//category method to take the snapshot
+ (UIImage *)snapshotImageWithView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

//viewDidLoad on the presented view controller
self.tableView.backgroundView = [[UIImageView alloc] initWithImage:self.imageOfUnderlyingView];

This works really well because the view controller I present is full-screen, so the entire screen can be blurred and applied to the background. But now that I am optimizing the app for iPad, this isn't working because I no longer present the view controller full-screen but rather as a popover (or still modally but as a Form Sheet). In this case, the snapshot image shrinks and stretches to fit in the popover, which renders the effect useless because it doesn't show what is behind the popover but rather a snapshot of the entire screen which is very odd-looking.
My question is, how can I simulate a blur effect of the underlying view when presenting a  popover, correctly only showing what is behind the popover, not shrinking the entire screen to fit in the popover?
I noticed there is a maskImage one can pass into the the method to generate the effect. How could I create a mask that cuts out the proper area for the popover? Or perhaps another approach would be to change the way in which it adjusts the image to fit such that it doesn't shrink but rather is overlaid without resizing, therefore only showing the proper area and hiding the rest of the image, if that would be possible. Or any other approach, anything to make it work. :)
Note that I will use the iOS 8 native API to achieve this effect in the future but I would like to simulate it now to work with iOS 7.

A: I ultimately decided what I want to achieve would be near impossible, because upon rotating the device the popover would relocate so different UI would lie underneath it, and navigating in this popover could resize the popover as well. So I decided if it's an iPad running iOS 7 then it just gets a solid background color.
But if it's an iPad running iOS 8, then I support the native UIBlurEffect API which is really nice. :)


text:
Q: Custom elements with proxied has, get & set My goal is to create a class ObservableElement extending HTMLElement such that it can be used to define custom elements, e g:
customElements.define('an-observable-elem', class extends ObservableElement {
  construct() {
    super()
    ...
  }
  ...
})

The thing about any element based on ObservableElement is that it should have some particular behaviours wrt to properties.
First, 'whatever' in myElem should always be true. In other words, I'd like a proxy trap for has on the instance, which just always returns true.
Second, setting and getting any props should work. But whenever a prop which is not explicitly defined on the element or in the prototype chain is set, I want to emit a custom event with the name set${propname} and detail: theValue.
It seems there must be a way using es6-proxies. Naively, I first tried:
class ObservableElement extends HTMLElement {
  constructor () {
    super()
    const vals = {}
    return Proxy(this, {
      has: _ => true,
      get: name => {
        if (name in this) return this[name]
        if (name in vals) return vals[name]
        return null
      },
      set: (name, value) => {
        if (name in this) {
          this[name] = value
          return
        }
        if (vals[name] === value) return
        vals[name] = value
        this.dispatchEvent(new CustomEvent(`set${name}`, {detail: value}))
      }
    })
  }
}

But of course that didn't work. Returning the proxy from the constructor did not change the this value in extending classes' constructors. I fumbled around with all sorts of combinations of proxying construct on the class, Object.setPrototypeOf(...) et c to no avail.
I'd much appreciate it if anyone who understands how these things can fit together to achieve what I want would explain it to me. Thanks!

A: What you're trying to do is not supported by the W3C Web Components specification.
According to §2.4 of the W3C Web Components specification, step 10.6.2:

If observedAttributesIterable is not undefined, then set observedAttributes to the result of converting observedAttributesIterable to a sequence<DOMString>. Rethrow any exceptions from the conversion.

This occurs during the customElements.define() execution, which means that you'd have to define an iterable of every conceivable string when the class is defined in order to intercept all attribute changes.
If the component does not find the changed property in that sequence, it does not call the attributeChangedCallback().
Similarly it is impossible to return a proxy from the constructor because of the restriction in §2.2:

A return statement must not appear anywhere inside the constructor body, unless it is a simple early-return (return or return this).


text:
Q: a constructor as a delegate - is it possible in C#? I have a class like below:
class Foo
{
  public Foo(int x) { ... }
}

and I need to pass to a certain method a delegate like this:
delegate Foo FooGenerator(int x);

Is it possible to pass the constructor directly as a FooGenerator value, without having to type:
delegate(int x) { return new Foo(x); }

?
EDIT: For my personal use, the question refers to .NET 2.0, but hints/responses for 3.0+ are welcome as well.

A: I think as concise as you're going to get (without moving to a factory pattern) would be something with anonymous methods, like this:
delegate Foo FooGenerator(int x);

...

void DoStuff()
{
    YourDelegateConsumer(x => new Foo(x));
}

This isn't doing strictly what you asked for (since you're passing a delegate to an anonymous method that returns a new instance, rather than a direct delegate to the constructor), but I don't think what you're asking for is strictly possible.
This is, of course, assuming you're using 3.5+

A: I'm assuming you would normally do something like this as part of a factory implementation, where the actual types aren't known at compile-time...
First, note that an easier approach may be a post-create init step, then you can use generics:
static T Create<T>({args}) where T : class, ISomeInitInterface, new() {
    T t = new T();
    t.Init(args);
    return t;
}

You can then use MakeGenericMethod and/or CreateDelegate.

Otherwise; you can do this with on the fly with Expression (3.5) or DynamicMethod (2.0).
The Expression approach is easier to code:
    var param = Expression.Parameter(typeof(int), "val");
    var ctor = typeof(Foo).GetConstructor(new[] { typeof(int) });
    var lambda = Expression.Lambda<Func<int, Foo>>(
        Expression.New(ctor, param), param);
    var func = lambda.Compile();
    Foo foo = func(123);
    string s = foo.ToString(); // proof

or (using DynamicMethod):
    ConstructorInfo ctor = typeof(Foo).GetConstructor(new[] { typeof(int) });
    DynamicMethod dm = new DynamicMethod("Create", typeof(Foo),
            new Type[] { typeof(int) }, typeof(Foo), true);
    ILGenerator il = dm.GetILGenerator();
    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Newobj, ctor);
    il.Emit(OpCodes.Ret);
    Converter<int, Foo> func = (Converter<int, Foo>)
        dm.CreateDelegate(typeof(Converter<int, Foo>));
    Foo foo = func(123);
    string s = foo.ToString(); // proof

A: It sounds like you probably want to be using the class factory pattern.
Factory Method Pattern

A: Nope, the CLR does not allow binding delegates to ConstructorInfo.
You can however just create your own:
static T Make<T>(Action<T> init) where T : new()
{
  var t = new T();
  init(t);
  return t;
}

Usage
var t = Make<Foo>( x => { x.Bar = "bar"; x.Baz = 1; });

A: Unfortunately not, constructors are not quite the same things as methods and as such you cannot create a delegate that points to them.  This is an interesting idea though, perhaps with more information we could devise some sort of workaround that would be syntactically similar.

A: Marc Gravell's answer inspired me to the following very simple solution:
static void Main()
{
    Pet a = _MakeObject(typeof(Dog));
    Pet b = _MakeObject(typeof(Cat));
}

private static Pet _MakeObject(Type type)
{
    ConstructorInfo info = type.GetConstructor(new Type[0]);
    return (Pet)info?.Invoke(null);
}

Almost the same thing if your constructor has params (in this example: 1 param of type int):
static void Main()
{
    Pet a = _MakeObject(typeof(Dog), 5);
    Pet b = _MakeObject(typeof(Cat), 7);
}

private static Pet _MakeObject(Type type, int age)
{
    ConstructorInfo info = type.GetConstructor(new [] { typeof(int) });
    return (Pet)info?.Invoke(new object[] { age });
}

A: Another option would be to use the Activator class, like so:
Using Generic Types
public delegate Foo FooGeneratorDelegate<T>(int x);

public T FooGeneratorFunction<T>(int x)
{
    return (T)Activator.CreateInstance(typeof(T), x);
}

// implementation example
FooGeneratorDelegate<Foo> del = FooGeneratorFunction<Foo>;
Foo foo = del(someIntValue);

Passing Your Type Foo as a Parameter
public delegate object FooGeneratorDelegate(Type t, int x);

public object FooGeneratorFunction(Type t, int x)
{
    return Activator.CreateInstance(t, x);
}

// implementation example
FooGeneratorDelegate del = FooGeneratorFunction;
Foo foo = (Foo)del(typeof(Foo), someIntValue);

If the Type will Always be of Type Foo
public delegate Foo FooGeneratorDelegate(int x);

public Foo FooGeneratorFunction(int x)
{
    return (Foo)Activator.CreateInstance(typeof(Foo), x);
}

// implementation example
FooGeneratorDelegate del = FooGeneratorFunction;
Foo foo = del(someIntValue);

A: While other answers only support parameter-less constructor. Here is the version support parameters. Hope it can help someone who want to turn with-parameters ConsturctorInfo to Delegate.
public Delegate CreateDelegate(ConstructorInfo constructorInfo)
{
    var ctorParameters = constructorInfo.GetParameters();
    var lambdaParameters =
        ctorParameters.Select(x => Expression.Parameter(x.ParameterType, x.Name)).ToArray();
    var argsExp =
        ctorParameters.Select((p, i) => Expression.Convert(lambdaParameters[i], p.ParameterType));
    var newExp = Expression.New(constructorInfo, argsExp);
    var lambda = Expression.Lambda(newExp, lambdaParameters);
    return lambda.Compile();
}

Usage:
CreateDelegate(/* ConstructorInfo */).DynamicInvoke(args);

A: My guess is that it isn't possible since you would pass a method of an object that has not been created yet.


text:
Q: Second GPU does not show up in `lspci` I switched the second GPU in one of our servers (Ubuntu 12.04.1 LTS). But now lspci only gives one entry:
$lspci | grep -i nvidia
04:00.0 VGA compatible controller: NVIDIA Corporation G94 [Quadro FX 1800] (rev a1)

I already executed sudo update-pciids and re-installed the nvidia dev driver. What other steps can I do?

A: Could be a hardware issue: The card isn't fully seated, you didn't plug in a cable (power, etc.), the card is defective, the slot is defective, there is some dust in the slot.

A: (I know the issue did not exist in 2012, but people searching for it may find it)
For me it turned out that once you plug a M.2 SSD, my board disables the second x16 slot (AsRock AB350 Pro4). From the manual:

So make sure, you also check this.


text:
Q: Is it possible to customize a shortcut in Spotlight search which would lead me to a specific folder? It'd be great if I could enter some name in Spotlight, for instance myproject, and then open a folder with the Finder.
Is that possible?

I have added too many folders to "Favorites". So, a shortcut > folder binding would be very helpful for me.
Thanks for any kind of tips!
Update:
OS: 12.5.1 (21G83)
1. mdutil -avs results:
/:
    Indexing enabled.
    Scan base time: 2022-09-07 12:53:28 +0000 (1111482 seconds ago), reasoning: '(null)'
/System/Volumes/Data:
    Indexing enabled.
    Scan base time: 2023-02-04 15:32:31 +0000 (-11858061 seconds ago), reasoning: '(null)'
/Volumes/Untitled:
    Indexing enabled.
    Scan base time: 2022-09-19 09:20:06 +0000 (87484 seconds ago), reasoning: '(null)'

2. Spotlight preference

And the privacy list was empty.
I realized that Folder was not selected. Just wondering, if I check this, will the Spotlight indexing every folder on my computer? Is it possible to let it only index a few? Because I have thousands of folders on my Mac and but I only need to search part of them. In other words, It'd be great to convert the Privacy tab to a Whitelist tab.

A: Spotlight can search for folders. Just write down the exact folder name in the Spotlight search window and, by using the arrow keys, move over to the item matching your search term with the keyword "Folder" next to it and press ↵. Then, the folder will be opened in the Finder.
If you'd rather open the folder containing the one you are searching for, press Command ⌘+R or Command ⌘+↵ instead.
If the folder you are searching for does not show up in the first few Spotlight search results, press Command ⌘+↓ until you end up in the "Folders" category which would display the search results that are folders.

Addition as of September 21, 2022
Thx for updating your OP by including the settings I have asked for in a comment to this answer. However, I don't know how to directly provide Spotlight a list of folders it should include in its results, i.e. a whitelist. I am not sure if this is possible at all. However, I think I may have a solution that works for you:

*

*Create a folder somewhere that you can remember easily later on such as under your home or the Documents directory.

*Create a shortcut (alias) for each folder you wish to be able to search via Spotlight and move the aliases to the new folder you just created. (See the "Create and remove aliases on Mac" Apple support webpage if you are not familiar with aliases in macOS.)

*Select the Other category in the System Preferences > Spotlight > Search Results window.

If you do these, you should be able to search for those aliases through Spotlight by typing in their names and still have only a small part (most possibly) of the files on your computer, and none of the folders themselves, show up in Spotlight given your settings. Aliases are indexed for searching by macOS because they are files themselves.
When Spotlight displays one of the aliases you created in a search result, it will just open it in the Finder when you press return after moving over the alias's name. However, it won't be showing the folders themselves pointed by the aliases, or the files or folders inside, assuming they do not belong to one of the categories selected in the System Preferences > Spotlight > Search Results window.
If including the Other category causes Spotlight to show too many files for your taste, you might be able to alleviate that by excluding one or more high level folders from Spotlight using the System Preferences > Spotlight > Privacy window such as the Documents folder under your home directory. Then, of course, the folder containing the aliases should not be placed in the Documents folder.


text:
Q: How do I combine multiple grep commands? I have a command like this:
| grep -v @param | grep -v @return | grep -v @Test | grep -v @throws

And it's getting bigger. Is there a way to make this neater?

A: Alternatively, you can place all your patterns in a file, one pattern per line, and use
... | grep -v -f matches.txt

Would make things easier if you use the patterns regularly

A: Another option:
... | grep -v -e @param -e @return -e @Test -e @throws

A: You can use:
... | grep -v "\(@param\|@return\|@Test\|@throws\)"

or you can use the -E flag to enable extended regular expressions, which will allow you to avoid escaping the parentheses and pipe characters:
... | grep -Ev '(@param|@return|@Test|@throws)'


text:
Q: error unclosed string literal st = con.prepareStatement("SELECT venta.`Codigo_V` AS venta_Codigo_V, venta.`Total` AS venta_Total,
     venta.`Fecha` AS venta_Fecha, detalle_venta.`Codigo_V` AS detalle_venta_Codigo_V,
     detalle_venta.`Codigo_P` AS detalle_venta_Codigo_P, detalle_venta.`Precio` AS detalle_venta_Precio,
     detalle_venta.`Cantidad` AS detalle_venta_Cantidad, detalle_venta.`Descuento` AS detalle_venta_Descuento,
     detalle_venta.`SubTotal` AS detalle_venta_SubTotal, producto.`Codigo_P` AS producto_Codigo_P,
     producto.`Descripcion_P` AS producto_Descripcion_P, producto.`Precio_P` AS producto_Precio_P
     FROM `venta` venta INNER JOIN `detalle_venta` detalle_venta ON venta.`Codigo_V` = detalle_venta.`Codigo_V`
     INNER JOIN `producto` producto ON detalle_venta.`Codigo_P` = producto.`Codigo_P`");

tengo este error y no se como arreglarlo


text:
Q: How to determine the size of a non-installed python package? I don't have much space left, and I am tempted to install python libraries.
I would like to know how big a python library is before installing is (just to know how much extra space to request if I don't have enough).
Is there a way to do that, e.g. using pip?

A: This is not possible using pip as far as I know. But if the package is hosted on PyPI you can append /json to the URL to view more details, including file size.
For example, visit https://pypi.python.org/pypi/pip/json and have a look at the entries in the releases key. The size of each release tells you how big the download would be.
Note that this tells you the download size, not the size after installing (as a package may request additional dependencies for installation, after decompressing the archives, and so on). So your question may be difficult to answer, prior to installation.

A: If you have a requirements.txt file use this script:
#!/bin/bash
# by rubo77: https://stackoverflow.com/a/68278901/1069083

mkdir -p /tmp/pip-size
for i in $(pip-sync -n requirements.txt|tail -n +2); do
  echo -ne "$i:\t"
  wget --quiet -O /tmp/pip-size/$i https://pypi.org/pypi/$i/json
  cat /tmp/pip-size/$i | jq 'last(.releases[])'[].size | paste -sd+ | bc > /tmp/pip-size/$i.size
  cat /tmp/pip-size/$i.size | awk '{$1=$1/1024/1024; print $1,"MB";}'
done
echo -e "--------\ntotal:"
cat /tmp/pip-size/*.size  | paste -sd+ | bc | awk '{$1=$1/1024/1024; print $1,"MB";}';

output example:
ninja:  1.4366 MB
numpy:  120.735 MB
opencv-python:  724.788 MB
pillow: 137.695 MB
scikit-image:   7.46707 MB
torch:  4772.73 MB
torchvision:    153.842 MB
--------
total:
5918.69 MB

A: This is my script i'm currently using
(based off the excellent package walking code from How to see pip package sizes installed?)
Steps :

*

*create a python script to check all currently installed pip packages

*create a shell script to create a brand new python environment and install package to test

*run shell script

*profit :)

Step 1
create a python script called tool-size.py
#!/usr/bin/env python

import os
import pkg_resources

def calc_container(path):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size

def calc_installed_sizes():
    dists = [d for d in pkg_resources.working_set]

    total_size = 0
    print (f"Size of Dependencies")
    print("-"*40)
    for dist in dists:
        # ignore pre-installed pip and setuptools
        if dist.project_name in ["pip", "setuptools"]:
            continue
        try:
            path = os.path.join(dist.location, dist.project_name)
            size = calc_container(path)
            total_size += size
            if size/1000 > 1.0:
                print (f"{dist}: {size/1000} KB")
                print("-"*40)
        except OSError:
            '{} no longer exists'.format(dist.project_name)

    print (f"Total Size (including dependencies): {total_size/1000} KB")

if __name__ == "__main__":
    calc_installed_sizes()

Step 2
create a bash script called tool-size.sh
#!/usr/bin/env bash

# uncomment to to debug
# set -x

rm -rf ~/.virtualenvs/tool-size-tester
python -m venv ~/.virtualenvs/tool-size-tester
source ~/.virtualenvs/tool-size-tester/Scripts/activate
pip install -q $1
python tool-size.py
deactivate

Step 3
run script with package you want to get the size of
tool-size.sh xxx
say for truffleHog3
$ ./tool-size.sh truffleHog3

Size of Dependencies
----------------------------------------
truffleHog3 2.0.6: 56.46 KB
----------------------------------------
smmap 4.0.0: 108.808 KB
----------------------------------------
MarkupSafe 2.0.1: 40.911 KB
----------------------------------------
Jinja2 3.0.1: 917.551 KB
----------------------------------------
gitdb 4.0.7: 320.08 KB
----------------------------------------
Total Size (including dependencies): 1443.81 KB


text:
Q: RTL paragraph in LTR footnote results in odd margins In an English text, I have some Arabic passages. Now I have the special case that there is an Arabic paragraph in a (English) footnote. I have tried two variants, but neither produce satisfying results:
When marking the text using \textarabic{}, the second line of the paragraph is left aligned, which is unnatural for Arabic text.
When using \begin{Arabic}\end{Arabic}, the text direction is changed to RTL, which makes the text flow correctly, but the margins are now odd: The text reaches into the left margin which is reserved to the footnote, while there is an additional margin on the right.

A minimal example is below.
Is there a variant that sets the Arabic paragraph correctly as RTL (i.e., starting the second line on the right), while respecting the overall margins of the footnote?
\documentclass[english, a4paper]{scrartcl}
\usepackage{unicode-math}
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\setmainfont[]{Charis SIL}
\setsansfont[]{Charis SIL Compact}
%% languages/scripts
\newfontfamily\arabicfont[Script=Arabic]{Scheherazade}
\usepackage{polyglossia}
\setmainlanguage[]{english}
\setotherlanguage[]{arabic}
\usepackage{bidi}

\begin{document}
%% No additional space between sentences
\frenchspacing

Christians are
compared to \emph{goim} and are also accused of heresy (\emph{herejía}),
mainly because of their inability to understand revelation. They are
compared to donkeys (\emph{ḥimār}): an ``asno ke lieba libros''
(``donkey that carries books'').\footnote{Cardaillac (1972, 2:41),
  Madrid, National Library of Spain, Aljamiado 4944, f.~45f. Algiers,
  National Library of Algeria, Ar. 1557, p.~57, lines 7--8.

  \textarabic{فسجن الله ما اعمى ابصارهم بيدهم الانجيل يقرونه ولا يفهموه انما مثلهم
  كمثل الحمار يحمل اسفارا اصدق الله العظيم ورسول الكريم}

  The expression ``ka-mathal al-ḥimār yaḥmilu asfāran'' is well known by
  Muslims, as it is found in Qur. 62:5 and used by Arabic grammarians as
  an illustrative case study.} but the basic idea is the same in the Arabic
original and the Aljamiado adaptation.

Christians are
compared to \emph{goim} and are also accused of heresy (\emph{herejía}),
mainly because of their inability to understand revelation. They are
compared to donkeys (\emph{ḥimār}): an ``asno ke lieba libros''
(``donkey that carries books'').\footnote{Cardaillac (1972, 2:41),
  Madrid, National Library of Spain, Aljamiado 4944, f.~45f. Algiers,
  National Library of Algeria, Ar. 1557, p.~57, lines 7--8.

  \begin{Arabic}

  فسجن الله ما اعمى ابصارهم بيدهم الانجيل يقرونه ولا يفهموه انما مثلهم
  كمثل الحمار يحمل اسفارا اصدق الله العظيم ورسول الكريم

  \end{Arabic}

  The expression ``ka-mathal al-ḥimār yaḥmilu asfāran'' is well known by
  Muslims, as it is found in Qur. 62:5 and used by Arabic grammarians as
  an illustrative case study.} but the basic idea is the same in the Arabic
original and the Aljamiado adaptation.

\end{document}

A: You could use the extrafootnotefeatures option of the bidi package. One possibly undesirable side effect is that this makes the footnote rule full width. Presumably this could be redefined.
\documentclass[a4paper]{scrartcl}
\usepackage{fontspec}
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\setmainfont{Noto Serif}
\setsansfont{Noto Sans}
\newfontfamily\arabicfont[Script=Arabic]{Amiri}
\PassOptionsToPackage{extrafootnotefeatures}{bidi}
\usepackage{polyglossia}
\setmainlanguage{english}
\setotherlanguage{arabic}
\begin{document}
\null\vfill
Christians are compared to \emph{goim} and are also accused of heresy
(\emph{herejía}), mainly because of their inability to understand revelation.
They are compared to donkeys (\emph{ḥimār}): an ``asno ke lieba libros''
(``donkey that carries books'').\footnote{Cardaillac (1972, 2:41), Madrid,
  National Library of Spain, Aljamiado 4944, f.~45f. Algiers, National Library
  of Algeria, Ar. 1557, p.~57, lines 7--8.

  \textarabic{فسجن الله ما اعمى ابصارهم بيدهم الانجيل يقرونه ولا يفهموه انما
  مثلهم كمثل الحمار يحمل اسفارا اصدق الله العظيم ورسول الكريم}

  The expression ``ka-mathal al-ḥimār yaḥmilu asfāran'' is well known by
  Muslims, as it is found in Qur. 62:5 and used by Arabic grammarians as an
illustrative case study.} but the basic idea is the same in the Arabic
original and the Aljamiado adaptation.

Christians are compared to \emph{goim} and are also accused of heresy
(\emph{herejía}), mainly because of their inability to understand revelation.
They are compared to donkeys (\emph{ḥimār}): an ``asno ke lieba libros''
(``donkey that carries books'').\footnote{Cardaillac (1972, 2:41), Madrid,
  National Library of Spain, Aljamiado 4944, f.~45f. Algiers, National Library
  of Algeria, Ar. 1557, p.~57, lines 7--8.

  \begin{Arabic}
  فسجن الله ما اعمى ابصارهم بيدهم الانجيل يقرونه ولا يفهموه انما مثلهم كمثل
  الحمار يحمل اسفارا اصدق الله العظيم ورسول الكريم
  \end{Arabic}

  The expression ``ka-mathal al-ḥimār yaḥmilu asfāran'' is well known by
  Muslims, as it is found in Qur. 62:5 and used by Arabic grammarians as an
illustrative case study.} but the basic idea is the same in the Arabic
original and the Aljamiado adaptation.
\end{document}


text:
Q: TP-Link WiFi router I'm trying to install a TP-Link wireless router. I am using a modem and have a PPPoE connection. I connected the router to the computer and the modem, but in the last step of the Easy Setup it says:

Failed to verify router settings. 1. Please check the WAN connection type and parameters. 2. Please check your connectivity and retry.

The Internet works fine if I connect the modem directly to the computer. When I connect the computer to the router, the wireless network is detected by other devices, but cannot be accessed.
I accessed the router settings, and everything seems normal, except that it just says "Connecting...". It never manages to connect to the Internet. I tried restarting the router and several walkthroughs on the web, but I couldn't get it to work.

A: You seem to have made an error in how you connect the router to the modem. Either by its settings or by how the cables are connected.
Verify the following:

*

*The modem goes from its LAN port to the router's WAN port

*If you have not configured anything on your pc, use 2a, otherwise 2b.

*

*2a. In the configuration for internet, you set the IP to get one through DHCP, not static.

*2b. In the configuration for internet, you set the IP to static, and fill it in the same way as on your pc.

*Make sure you set the connection type to PPPoE.


text:
Q: nx.hits shows OverflowError: Python int too large to convert to C long Please see code below
   #HITS
nx.hits(G, max_iter=9999999999)

# Finding Hubs & Authorities. Outputs in a dictionary format
hubs, authorities = nx.hits(G, normalized=False)
# removed the default normalization because it normalizes hubs from a range of 1 to 5 only.

A: scipy is a collection of algorithms for interacting with numpy arrays. Under the hood, a lot of numpy's implementation is written in C, and therefore it is somewhat limited by the capabilities of C. In this case, it is trying to convert a Python int into a C int, which unlike Python's int type have a limited range (up to 2^31 - 1 = 2147483647). Your value for max_iter is greater than the maximum value that C supports, and therefore it fails to call the function you require since it can't perform the conversion.


text:
Q: Setting SDL_BLENDMODE_BLEND on a texture breaks rendering quality I'm trying to create a texture A, make it transparent, and then render a texture B to the texture A. The problem is that to make the texture A transparent I have to first set SDL_BLENDMODE_BLEND on the texture A, which, sadly, breaks the way the texture B is being rendered. I want to render multiple textures to the texture A, when I resolve the issue.
The texture B contains a white "New Game" text. The blue background is rendered separately.
Here is an image of the correct result, rendering texture B directly

Here is an image of what I get rendering texture A without setting SDL_BLENDMODE_BLEND.

Here is an image of what I get rendering texture A  with setting SDL_BLENDMODE_BLEND.

I noticed that when using SDL_SetRenderDrawColor(r, 255, 255, 255, 0); the texture B renders correctly, if the text is white, but it renders incorrectly when the text is black.
    texA = SDL_CreateTexture(r, SDL_PIXELFORMAT_RGBA8888,
                             SDL_TEXTUREACCESS_TARGET,
                             mWidth, mHeight);

    SDL_SetRenderTarget(r, texA);

    // breaks texB rendering, necessary to make texture transparent
    SDL_SetTextureBlendMode(texA, SDL_BLENDMODE_BLEND);

    SDL_SetRenderDrawBlendMode(r, SDL_BLENDMODE_NONE);
    SDL_SetRenderDrawColor(r, 0, 0, 0, 0);
    SDL_RenderFillRect(r, NULL);

    SDL_RenderCopy(r, texB, NULL, NULL);

    SDL_SetRenderTarget(r, nullptr);

A: The solution was to create a custom blend mode. Figured that out by accident, so I'm not sure why that works.
texA = SDL_CreateTexture(r, SDL_PIXELFORMAT_RGBA8888,
                         SDL_TEXTUREACCESS_TARGET,
                         mWidth, mHeight);

SDL_SetRenderTarget(r, texA);

const auto bm = SDL_ComposeCustomBlendMode(
                        SDL_BLENDFACTOR_ONE,
                        SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA,
                        SDL_BLENDOPERATION_ADD,

                        SDL_BLENDFACTOR_ONE,
                        SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA,
                        SDL_BLENDOPERATION_ADD);
SDL_SetTextureBlendMode(texA, bm);

SDL_SetRenderDrawBlendMode(r, SDL_BLENDMODE_NONE);
SDL_SetRenderDrawColor(r, 0, 0, 0, 0);
SDL_RenderFillRect(r, NULL);

SDL_RenderCopy(r, texB, NULL, NULL);

SDL_SetRenderTarget(r, nullptr);


text:
Q: How to make that when you click on the text it was copied telegram bot api node.js I am writing a telegram to the bot. I ran into such a problem. I need the bot to send a message (text) when clicked on which it was copied (as a token from @BotFather)
I use node.js


text:
Q: Opencv C++ Thresholding not working after absdiff, Barcode Detection I am trying to detect barcode from an image using OpenCv,
I am using the gradient method: http://www.pyimagesearch.com/2014/11/24/detecting-barcodes-images-python-opencv/
With help from the following question: How to find the location of red region in an image using MATLAB?
Code:
Mat imgco,img,imgx,imgy,thresh;
imgco = imread("/Users/a/Desktop/barcode_01.jpg");

//### Convert image to grayscale ###
cvtColor(imgco,img,CV_BGR2GRAY);
imshow("img", img);
waitKey(0);

//### Finding horizontal and vertical gradient ###

Sobel(img,imgx,CV_16S,1,0,-1,50,0,BORDER_DEFAULT);
imgx = abs(imgx);
imshow("img", imgx);
waitKey(0);

Sobel(img,imgy,CV_16S,0,1,-1,50,0,BORDER_DEFAULT);
imgy = abs(imgy);
imshow("img", imgy);
waitKey(0);

absdiff(imgx, imgy, img);
imshow("img", img);
waitKey(0);

//### Low pass filtering ###
GaussianBlur(img, img, Size(9,9), 0);
imshow("img", img);
waitKey(0);

//### Applying Threshold ###
threshold(img,thresh,225,255,CV_THRESH_BINARY);
imshow("img", thresh);
waitKey(0);

Now the program works correctly upto gaussian blur, Somehow trying to threshold the image gives a blank output. Can anyone suggest what could be the issue?

Thank You.
UPDATE: Applying the threshold operation before AbsDiff, Results in thresholding correctly. Hence there is something related to using AbsDiff, that is messing up with thresholding. Any help?
UPDATE 2: Comparing my output with the following: http://www.pyimagesearch.com/wp-content/uploads/2014/11/barcode_gradient_and_detection.jpg I realize that I am getting a grey image while the author is getting a crisp black bacground? Even when we are performing the same operations. Thank you.

A: Okay the solution:
1) No need to use scaling in the gradient operations.
2) Use of convertScaleAbs method to convert the image to 8bit is necessary.
img.convertTo(img, CV_8U, 0.00390625);

Does not work. Solves the problem! :) Helped by the author of pyimage!


text:
Q: Finding extrema of a tri-variable function under a constraint We need to find extremum of $$f(x,y,z) = yz$$ under the constraint $$g(x,y,z) = 2x^2 + 3y^2 + z^2 - 12xy + 14xz - 35$$
Using the technique of Lagrange Multipliers, leads to four simultaneous equations which are quite tedious to solve esp. in an exam-setup under limited duration of time.
Entirely alternate solutions and/or techniques that efficiently solves the above system of equations are welcome.


text:
Q: Getting a error when installing TRUFFLE on windows I have tried installing truffle on windows powershell with Execution Policy set to "ByPass".
And installing a older version but noting has worked any help is appreciated.
I have node v16.13.0. And have not had any problems before with installing packages.
As well I have the latest version of Virtual studio code.
 npm ERR! code 1
    npm ERR! path C:\Users\boxin\AppData\Roaming\npm\node_modules\truffle\node_modules\ganache\node_modules\secp256k1
    npm ERR! command failed
    npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp rebuild
    npm ERR! gyp info it worked if it ends with ok
    npm ERR! gyp info using node-gyp@8.2.0
    npm ERR! gyp info using node@16.13.0 | win32 | x64
    npm ERR! gyp info find Python using Python version 3.10.0 found at "C:\Users\boxin\AppData\Local\Programs\Python\Python310\python.exe"
    npm ERR! gyp ERR! find VS
    npm ERR! gyp ERR! find VS msvs_version not set from command line or npm config
    npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
    npm ERR! gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details
    npm ERR! gyp ERR! find VS looking for Visual Studio 2015
    npm ERR! gyp ERR! find VS - not found
    npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
    npm ERR! gyp ERR! find VS
    npm ERR! gyp ERR! find VS **************************************************************
    npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio
    npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload.
    npm ERR! gyp ERR! find VS For more information consult the documentation at:
    npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
    npm ERR! gyp ERR! find VS **************************************************************
    npm ERR! gyp ERR! find VS
    npm ERR! gyp ERR! configure error
    npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
    npm ERR! gyp ERR! stack     at VisualStudioFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:121:47)
    npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:74:16
    npm ERR! gyp ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
    npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:70:14
    npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:372:16
    npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
    npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
    npm ERR! gyp ERR! stack     at ChildProcess.exithandler (node:child_process:404:5)
    npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
    npm ERR! gyp ERR! stack     at maybeClose (node:internal/child_process:1064:16)
    npm ERR! gyp ERR! System Windows_NT 10.0.22000
    npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
    npm ERR! gyp ERR! cwd C:\Users\boxin\AppData\Roaming\npm\node_modules\truffle\node_modules\ganache\node_modules\secp256k1
    npm ERR! gyp ERR! node -v v16.13.0
    npm ERR! gyp ERR! node-gyp -v v8.2.0
    npm ERR! gyp ERR! not ok

    npm ERR! A complete log of this run can be found in:

A: Hello did u try npm install --g --production windows-build-tools
Similar problem -> node-gyp configure got "gyp ERR! find VS"
Lot of ppl had similiar issue and this command helped
If nothing will help i can recommend u https://remix.ethereum.org/ its online IDE that simulate everything. (I have good experience with it on Ether and solidity)

A: I fix the problem by uninstalling node.js and reinstall in it. And when i installed node, I checked the box that shows up that installs extra build tools.


text:
Q: Multiplying two one-dimensional arrays A quick question that bugs me (both from a mathematical perspective and implementation-wise). How do you multiply two one-dimensional arrays?
If we have:
int[] a = {1,2,3};
int[] b = {4,5,6};

And we wanna put the result into a variable c, how do you do the math and the implementation? Should c also be one-dimensional or two-dimensional?
Thank you in advance!
EDIT:
To everyone asking what I want. I'm trying to solve a math problem that literally tells me:
a = {1,2,3};
b = {4,5,6};

c = a * b; //what is c?

I found nothing on the internet on how to do it mathematically and I am equally puzzled on how to do it in a programming language.

A: I'm not sure if you are trying to find the sum if everything, or trying to create a matrix with the multiplication.
For sum refer to duffymo's answer.
For a new array, the end product will be:
int[][] c= {{4, 8, 12}, {5, 10, 15}, {6, 12, 18}};
Idea: You can just loop through both of them and multiply each index. Then store the products in int[][] c. You can also just have them in a list depending on your implementation like so: c = {4, 8, 12, 5, 10, 15, 6, 12, 18}.
int[][] c = new int[a.length][b.length];
// int[] c = new int[a.length * b.length];
for(int i = 0; i < a.length; i++){
    for(int j = 0; j < b.length; b++){
        c[i][j] = a[i] * b[j];
        // c[i * a.length + j] = a[i] * b[j]; if you want to store it in a 1D array
        // Try a few examples to see why this will work for 1D array
    }
}


text:
Q: Create index on table with multi columns I'm new to sql, if i use this query frequently:
SELECT * FROM student WHERE key1=? AND key2=?

I want to create index on student, what is the main difference between these two below?
CREATE INDEX idx_key1 on student (key1);
CREATE INDEX idx_key2 on student (key2);

and
CREATE INDEX idx_keys on student (key1, key2);

Thanks!

A: The second one (CREATE INDEX idx_keys on student (key1, key2)) will return all the rows you need in a single index seek (to find the rows) + key lookups to get the columns.
If you create 2 single-column indexes, only one of them can be used for index seek. Then for every returned row you need a key lookup to get the other key and filter the results. Or the DB engine will simply decide it's faster to just do a table scan and filter.
So the 2nd one is much better for your query.


text:
Q: How can i pass values from querystring to javascript? Now that i learned how to pass values to an SWF object via flashvars, could you please guide me how can i pass values from a querystring to javascript?
What do i mean? In the following example i hard-code the xml file to load in the SWF object.
<script type="text/javascript">
    var so = new SWFObject("preview.swf", "", "100%", "100%", "9", "#ffffff");
    so.addParam("allowFullScreen", "true");
    so.addParam("scale", "noscale");
    so.addParam("menu", "false");
    so.addVariable("xmlPath", "xml/exampleData.xml");
    so.write("flashcontent");
</script>

Since the Xml file is created dynamic, the xml should be loaded from the value of a query-string. (I guess).
Supposing my url is http://www.example.com/load.aspx?XmlFile=SomeData
How can i pass it to the javascript side? Like..
  so.addVariable("xmlPath", "xml/<% SomeData %>.xml");

or whatever it needs to make it work.
UPDATE: Besides the above example, is there any way of creating the JavaScript, in server-side?

A: Try something like:
function GetQueryString(param)
{
 var url = window.location.search.substring(1);
    var params = url.split("&");
    for (i=0;i<params.length;i++)
    {
        var p = params[i].split("=");
        if (p[0] == param)
        {
            return p[1];
        }
    }
}

And use it like:
so.addVariable("xmlPath", "xml/" + GetQueryString("XmlFile") + ".xml");

A: window.location.href contains the querystring of the current page, this should work:
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

A: function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}

return vars;

}


text:
Q: Which formats are available for Keys Enum? I have a next problem. I need to represent a pressed keys combination in a text form. I got pressed keys from KeyEventArgs e...
And when I try to use following code
e.KeyData.ToString(); I got something like this: N, Control .... But I want to get Ctrl+N string.
I think that must be present specific format for String.Format because when i bind property with type Keys to the DataGridView I saw in the table cell string Ctrl+N. It's mean that DataGridView can do this, and i think this is not done manually...
Thanks a lot!!

A: The Keys values are probably displayed using the TypeConverter belonging it.
If you want to emulate the behavior of the DataGridView, you should use
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Keys));
string displayName = converter.ConvertToString(e.KeyData);

The Keys type is tagged with [TypeConverter(typeof(KeysConverter))], which is what GetConverter should return.

A: According to MSDN, there is nothing built-in to do this. I suspect the grid is just substituing ", " for "+".