text:
Q: What JS scope is used by
A: The script tag is just that...An HTML tag. As such, it doesn't have a scope because it's not JavaScript, it's HTML. What the script element does for your is allows the HTML parser to "stand down" and have the JavaScript interpreter take over. The JS within the script tag will execute according to standard JS rules. That means that references will be evaluated via the normal scope chain process.
In essence, everything in JS is global unless you code it to be otherwise.
Keep in mind that window is not part of JavaScript. It's an API provided by browsers, so when we talk about "global", we are not always talking about window. In node.js, for example, there is no window or document, but there still is a global scope. So, in JS, you can have globals, but that doesn't mean that they are automatically attached as properties of the window object.

*

*Globals in JS are accessible by simply stating their reference name.

*Any HTML element with an ID attribute will become a property of the
window object.

*Any JS property explicitly created as part of the window object
will be available via the window object.

*Any HTML element that is part of the page that is loaded will be
accessible via a DOM API (i.e., document.querySelector,
document.getElementById).

This is another answer from a while back that talks about the "scope chain" and how it works.
As @Teemu points out in the comments below, when you have a script type="module", things work a bit differently. See this link for more details.


text:
Q: Lorenz Gauge Condition in Helmholtz equation I do not understand why we can apply the Lorenz Gauge Condition in Helmholtz equation. What is its physical meaning? Any help is appreciated.

$\nabla\cdot \vec{A} + \mu_0\varepsilon_0\frac{∂\phi}{∂t} = 0$

SOLUTION:
We can describe electromagnetic fields as a function of the electromagnetic potentials through the following equations (delayed potential equations):

$\vec{B}=\nabla × \vec{A}$
$\vec{E}=-\nabla \phi - \frac{∂\vec{A}}{∂t}$

We can transform these electromagnetic potentials so that they continue
fulfilling the previous equations. Making the following changes we will obtain the same electromagnetic fields but the potentials will lose their physical meaning. These transformations will allow us to solve simpler statements, like Helmholtz's equation.
Then we can rewrite the new potentials like:

$\vec{A'}=\vec{A}+\vec{\alpha}$
$\phi'=\phi+\beta$

As I mentioned before, these transformations will have to satisfy the delayed potential equations so:

$\vec{B}=\nabla × \vec{A'}=\nabla × (\vec{A}+\vec{\alpha})$
$\vec{E}=-\nabla \phi' - \frac{∂\vec{A'}}{∂t}=-\nabla (\phi+\beta)- \frac{∂(\vec{A}+\vec{\alpha})}{∂t}$

If we continue simplifying the following equations we obtain:
$\nabla ×\vec{\alpha}=0$;
$\vec{\alpha}=\nabla\lambda$;
$\beta=\frac{∂\lambda}{∂t}$
So finally we get:

$\vec{A'}=\vec{A}+\nabla\lambda$
$\phi'=\phi+\frac{∂\lambda}{∂t}$

Conclusion: we can find any electromagnetic potential that satisfies Maxwell's equations. So we will try to find potentials that ease the calculations. It is important to note that these transformations will lead to a loss of potencial's physical meaning. But we do not have to worry about the electromagnetic fields because they will remain the same.

A: The Maxwell equations are gauge invariant. If you choose the Lorenz gauge, instead of the free Maxwell equations you get an equation saying that the d'Alembertian of the potential vanishes. If then you choose a complex solution with temporal dependence $\exp(j\omega t)$ (I am not sure about the sign of the phase though), you get the Helmholtz equation.

A: Assuming $A$ is the vector potential and $\phi=\partial_{t}V$ is the scalar potential, the potentials are calculation aids. The physical fields are the $E$ and $B$ fields. Choosing the Lorenz gauge allows one to solve the coupled partial $2$-nd order differential equation for $A$ and $V$ by uncoupling $A$ and $V$ into two independent partial $2$-nd order differential equations.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Report is being generated runs forever in IE8.0 but works with firefox I have made a report and a simple web program in C# that is calling for that report. When I run the program it works perfect with Firefox but not in IE 8.0. In IE it´s run forever until you got this error message:The underlying connection was closed: An unexpected error occurred on a receive.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
An existing connection was forcibly closed by the remote host.
Anybody ever had this problem before and have a solution for this.
Thanks in advance for all who reply!
The code that generate the report:
           ReportViewer1.ProcessingMode = ProcessingMode.Remote;
        ServerReport serverReport = ReportViewer1.ServerReport;
        // Set the report server URL and report path
        serverReport.ReportServerUrl =
            new Uri("http://localhost/Reportserver");
        serverReport.ReportPath =
            "/WinLife.Accounting.Report/Report_Accountingvoucher";
        // Create the sales order number report parameter
        List<ReportParameter> paramList = new List<ReportParameter>();
        paramList.Add(new ReportParameter("Workplace", Session["WorkPlace"].ToString()));
        paramList.Add(new ReportParameter("BookkeepingYear", Session["BookkeepingYear"].ToString()));
        paramList.Add(new ReportParameter("SerialNo", Session["SerialNo"].ToString()));
        paramList.Add(new ReportParameter("DocumentType", Session["DocumentType"].ToString()));
        paramList.Add(new ReportParameter("IndentDate", Session["IndentDate"].ToString()));
        paramList.Add(new ReportParameter("AccountingVoucherCode", Session["AccountingVoucherCode"].ToString()));
        paramList.Add(new ReportParameter("UserId", Session["UserId"].ToString()));
        paramList.Add(new ReportParameter("Password", Session["Password"].ToString()));

        ReportViewer1.ServerReport.SetParameters(paramList);
        ReportViewer1.ServerReport.Refresh();

If I run the reportviewer in IE8 its looks OK. The reportserver, sql-server is installed on my machine. I run the program in Debug mode from VS2008 and I have Windows 7 installed.
I tried to set the localhost in the trusted site but it didn´t change anything. It seems that it being stoped before it does anything in the SQL-Server. This works in Firefox.

A: Have you tried to add the site to the trusted zone ? I had some similar issues and that's the way I fixed it.

A: maybe your returned data for report is very great. you can set time out value for report processing. please see the below link:
Setting Time-out Values for Report Processing

A: i was experiencing EXACTLY the same thing (including the fact that it works with FF)...
The solution is to set the "Browser Mode" to IE7...to do that follow:
1. Tools -> Developer Tools.
2. Browser Mode: -> Internet Explorer 7
btw - Microsoft sucks...


text:
Q: Change width of dropdown according to screen resolution I am trying to use a dropdown menu in react application. Everything seems to works fine, but one thing is bugging me when I try to try to change browser resolution from console.
// index.js:
<select
    id="project_type"
    name="project_type"
    className="dropdown_menu"}
>
    <option value="Yes">
        Yes
    </option>
    <option value="No">
        No
    </option>
</select>

css file:
.dropdown_menu {
    position: absolute;
    width: 590px;
    height: 48px;
    background: rgba(0, 50, 160, 0.1);
    margin-top: 270px;
    border-radius: 5px;
    border: 1px solid rgba(46, 81, 158, 0.6);
    padding-left: 23.33px;
    padding-top: 0;
}

This happens when I try to change resolution:

How can I make the dropdown menu of equal width of its dropdown option instead of overflowing when changing resolutions.
Note: I have used 'width: inherit' but it doesn't work.

A: Just use content-box

input,
select {
  -moz-box-sizing: content-box;
  box-sizing: content-box;
}
<select id="project_type" name="project_type" className="dropdown_menu" }>
  <option value="Yes">
    Yes
  </option>
  <option value="No">
    No
  </option>
</select>


text:
Q: Is it possible to intercept Vue Router push and other actions? I am hoping to create some middle ware whenever Vue router is used for example if someone where to do this.$router.push({//insertReq}).
I would like to read the details of what is in the push and either redirect their push or allow it for all Router requests across all components in the website.


text:
Q: Master detail view with subdetail view and bindings I try to make a Master Detail View with an additional Detaildetail View with bindings in the interface builder. The whole application is for Mac OSX.
I have 3 table views. Master-Table, DetailsOfMaster-Table and DetailsOfDetails-Table
For each tableview i have an array controller.
My Data structure is an array filled with Objects like the following one:
@interface Node : NSObject
   @property (strong)NSString* name;
   @property (assign)NSArray* details;
@end

Each node's detail is filled again with other nodes.

*

*The Master-ArrayController's content-array is bound to my array of
nodes.

*The Details-ArrayController's content-array is bound to
Master-ArrayController's Selection.details

*The DetailDetails-ArrayController's content-array is bound to the
Details-ArrayController's Selection.details

Each tabel view's Content is bound to the corresponding array controller with the Key, arrangedObjects and the Tabel Column to arrangedObjects.name
Everything compiles fine.
The Problem is the Detail- and DetailsDetail-Table are not getting updated.

Did I missed some bindings?
I would like to be able to show my data-structure completely with bindings who were set with the interface builder.

A: Bindings are all correct, there mistake was the wrong attribute of the property
    @property (assign)NSArray* details;
needs to be
    @property (retrain)NSArray* details;


text:
Q: Laravel: reverse the result of pagination I am using laravel 5.6 and I want to reverse the result of the pagination query. This is what I am trying to do for now:
$chats = Chats::where('message_id', $message_id)->orderBy('id', 'DESC')->latest()->paginate(5);
if(!empty($chats)) {
    $data['messages'] = $chats->reverse()->values();
    $data['status'] = 200;
    $data['create_user_id'] = Auth::id();
}else{
    $data['error'] = "No chats available";
}

But it removes the pagination from the result.
Lets suppose I have these 10 values in table
1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Now I want 6, 7, 8, 9, 10 in first page result and 1, 2, 3, 4, 5 in second page result, specifically in that order.
Please help.

A: you can reversed the pagination with latest function.

   $chats = Chats::where('message_id', $message_id)->orderBy('id', 'DESC')->latest()->paginate(20);
if(!empty($chats)) {
    $data['messages'] = $chats->values();
    $data['status'] = 200;
    $data['create_user_id'] = Auth::id();
}else{
    $data['error'] = "No chats available";
}

remove reverse()  because the latest() gives reverse().

A: $chats = Chats::where(....)
    ->latest()
    ->simplePaginate();
$chats->setCollection($chats->getCollection()->reverse());
return $chats;

so the oldest message is the last inside the collection (as you want for most chat applications) to render it at the bottom,


text:
Q: Fetching more then 1200 items is not possible in GAE I'm trying to fetch more then 1200 records from a query in GAE but this fails, just keeps loading forever. I can see in the debug that it keeps doing GET requests to Google but I never see any results
This works perfectly:
for lcr in deactivation_list.fetch(1200,offset=0, batch_size=1000):
This keeps loading:
for lcr in deactivation_list.fetch(1201,offset=0, batch_size=1000):
Tried increasing the batchsize, didnt help. I'm using NDB models

A: The only solution I have found is to use cursors, as suggested in the comments earlier. The reason is that the Google Remote API has a 1mb limit, using cursors you can query it multiple times.
recordQuery = model.query()
record, cursor, more = recordQuery.fetch_page(1000)
while more:
    record, cursor, more = recordQuery.fetch_page(1000, start_cursor=cursor)


text:
Q: How to find out the static and dynamic types of customized Exceptions First to the task: I got to print out a certain String which includes the dynamic and the static type of my customized Exceptions.
In a try and catch, I have to do the same thing with different ways of expressing the catch part.
I am a little confused about how to print out the static types and the dynamic types.
Can I also just work with getClass()
so just for a more precise explaination, here is my code so far:
    String s1 = "1 : ";
    String s2 = "Exception : ";
    String s3 = "UpdateTimeBeforeLastUpdateException ";
    String s4 = "UpdateTimeInTheFutureException ";
    try {
        outsourced(ts, cal, 1);
    }
    catch(UpdateTimeBeforeLastUpdateException exc1) {
        System.out.println(s1 + s2 + s3 + exc1);
    }
    catch(UpdateTimeInTheFutureException exc2) {
        System.out.println(s1 + s2 + s4 + exc2);
    }
}

public void testCatch2(TimeStamp ts, Calendar cal, int test) throws Exception {
    String s1 = "2 : ";
    String s2 = "Exception : ";
    String s3 = "UpdateTimeBeforeLastUpdateException ";
    String s4 = "UpdateTimeInTheFutureException ";
    try {
        outsourced(ts, cal, 2);
    }
    catch(UpdateTimeBeforeLastUpdateException | UpdateTimeInTheFutureException exc) {
        System.out.println();
    }
}

private void outsourced(TimeStamp ts, Calendar cal, int n) throws Exception {
    switch (n) {
    case 1:
        ts.updateWithExc1(cal);
        break;
    case 2:
        ts.updateWithExc2(cal);
        break;
    case 3:
        ts.updateWithExc3(cal);
        break;
    case 4:
        ts.updateWithExc4(cal);
        break;
    case 5:
        ts.updateWithExc5(cal);
        break;
    }

there are 3 more methods to come but my main problem is just the catch and outprint part

A: If I got the question right, I assume that this may answer it:
try
{
    … // do something that causes an exception
}
catch( final OneException | TwoException e )
{
    if( e instanceof OneException e1 )
    {
        … // Handle OneException e1
    }
    else if( e instanceof TwoException e2 )
    {
        … // Handle TwoException e2
    }
    else throw new Error( "None of the expected exceptions caught" );
}

That instanceof syntax requires a later version of Java (14, I guess).
With the version 17 of Java (and the preview features enabled) it should be possible to use a switch statement, like this:
try
{
    … // do something that causes an exception
}
catch( final OneException | TwoException e )
{
    switch( e )
    {
        case OneException e1 -> e1.printStackTrace(); // Handle OneException e1
        case TwoException e2 -> System.out.println( e2.getMessage() ); // Handle TwoException e2
        default -> { throw new Error( "None of the expected exceptions caught" ); }
    }
}

Confessed, the in the second sample, the handling of the exceptions is lame … but it works!

A: You can use multi-catch statments. And in the catch block, you can call getClass().getName() on the exception object. Now, you will have a fully qualified name of the exception class. If you just want the class name, not the fully qualified name, you can use String#split() and pass in a dot as a regular expression (\Q.\E, if you don't enclose dot with \Q and \E, it means that we are saying to match any character, not the dot) and get the last element from the returned array.
Here is how you do it:
I am just rewriting your testCatch2()
public void testCatch2(TimeStamp ts, Calendar cal, int test) throws Exception {
    String s1 = "2 : ";
    String s2 = "Exception : ";
    try {
        outsourced(ts, cal, 2);
    } catch(UpdateTimeBeforeLastUpdateException | UpdateTimeInTheFutureException exc) {
        System.out.println(s1 + s2 + exc.getClass().getName());

        // If you don't want the fully qualified name, use the below statements.
        // String[] parts = exc.getClass().getName().split("\\Q.\\E");
        // System.out.println(s1 + s2 + parts[parts.length - 1]);
    }
}


text:
Q: Why is output being duplicated inside hashchange event listener? I've generated the months of the year with a hash of #2019-01 #2019-02 etc.. Every time I click on a link it appends another list of the months.
It's only supposed to display one copy of the month links but output the updated hash. So if I click on February it should output #2019-02.
https://jsfiddle.net/captlid/gkhe4naz/3/
var date = new Date();
location.hash = date.getFullYear();
var p = document.querySelector('p');
p.innerHTML = location.hash;

window.addEventListener('hashchange', function() {

   for (dz = 0; dz < 12; dz++) {
      p.innerHTML += ''+ months[dz] +' ';
   }
   p.innerHTML += location.hash;
});

A: Your code is working properly as it's written. I think you accidentally have your calendar output code inside of your hashchange function. If you move it outside, it should work as you expect. Also, you're building your calendar inside of your p element instead of the calendar element. the code below shows a functioning version

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var calendar = document.querySelector('#calendar');
var date = new Date();
location.hash = date.getFullYear();
var p = document.querySelector('p');
p.innerHTML = location.hash;

for (dz = 0; dz < 12; dz++) {
    calendar.innerHTML += '' + months[dz] + ' ';
  }

window.addEventListener('hashchange', function() {

  p.innerHTML = location.hash;
});


text:
Q: Reading string and numbers from text file in MATLAB My text file format is something like this:
X  Y
1.2 3.2
1.0 4
0.9 10
I want to grab only the numbers in two columns. So far I have tried load, textread, it gives error with first line of the txt file. How can I ignore the first string line and grab only the numbers in file?
Thanks!

A: Try the importdata function.
A = importdata ('textfile.txt', ' ', 1);
data = A.data

The parameters:
'textfile' is the name of the file that contains your data,
' ' is the delimiter,
1 tells the function that there is one header line
With A.colheaders{1} and A.colheaders{2} you even can access the names of you columns.

A: Another option is to use textread, which has the option 'headerlines'.  You'd call it like
[A,B]=textread('textfile,txt','%f %f','headerlines',1); %this ignores the first line


text:
Q: how to link a customer and a project to oneanother? I'm kind of new to PHP/MySQl so I would like some guidelines on how these thing work, hard to google this...
So, im trying to learn php/mysql and I'm about to write a small page with customers and each customer could have a few projects.
so, my db is set up as follows (guess this would need heavy modifications):
- customers (id, name, description)
- projects (id, name, description)
- users (id, name )
<?php

if(isset($_GET['id'])) {

$query = "SELECT * FROM customers WHERE id = '". $_GET['id']."'";
   $results = mysql_query($query);

   while($row = mysql_fetch_array( $results ))
   {

   echo "
" . $row['name'] . "
";
   echo "
";

$query = "SELECT * FROM projects ORDER by name ASC";
   $results = mysql_query($query);

   echo "

";

    while($row = mysql_fetch_array( $results ))
   {
   echo "

  " . $row['name'] . "
  " . $row['description'] . "

";
   }
   echo "

";

}

} else {

$query = "SELECT * FROM customers ORDER by name ASC";
   $results = mysql_query($query);

   echo "

            Customer
            Description

";

while($row = mysql_fetch_array( $results ))
   {
   echo "

  " . $row['name'] . "
  " . $row['description'] . "

";
   }
   echo "

";
}
?>

As you can see it missing some heavy things, for instance, if I choose Customer A or B I receive the same projects, I don't know how to separate the projects and "bind" them to a certain customer. And my intention is to "bind" users to projects and customers as well.
Any hints into the correct direction is appreciated!

A: You need another table which has the key (customers.id,projects.id) In this way you link each customer to their own projects, and you'd need to select the data from that table depending on the id of the customer. Probably you'll need a customer/user table too, to link user id to customer id.
Edit for clarity: The new table should look something like:
CREATE TABLE customer_projects (
    customer_id INT NOT NULL,
    project_id INT NOT NULL,
    PRIMARY KEY (customer_id, project_id));

Then you assign each customer to their projects in this table. To get the details (customer name, project name), you'd need to do a "join" with other tables, something like:
SELECT customers.*, projects.* FROM customer_projects
LEFT JOIN customers ON customers.id = customer_projects.customer_id
LEFT JOIN projects ON projects.id = customer_projects.project_id
WHERE customer_projects.customer_id = '1' // 1 is an example of a customer id.

A: You can have an INNER JOIN in the select query, like so:
"SELECT * FROM customers c INNER JOIN projects p ON p.name = c.name WHERE c.id = '". $_GET['id']."'";

Here, I have considered that you DO HAVE a name column in customer table which is the same as that in project.

A: You would need to add some tables.
First a table that represents the relation from Customers to Projects. This would be like
Customer ID | Project ID
    1       |     1
    2       |     3
....
Same would be needed for Customer and User.
Now you can reference to this table to get your needed information and perform the necessary joins to get your data.


text:
Q: Apex trigger to update field and activate workflow I am new to Salesforce and recently learned I cannot schedule workflows to run on certain dates, but must manually (or programatically) edit the record to activate the workflow.  After some research it looks like an Apex trigger would work better to accomplish this through scheduled Apex.   I am not a programmer, and don't know how to accomplish this.  Here is what I have so far....which isn't working...
trigger WorkflowTrigger on Policy_c (after update) {
    for (Policy_c obj: trigger.new) {
        WF_Apex_Trigger_Date__c = TODAY;
    }
}
WF_Apex_Trigger_Date__c is a field on the Policy object that I want to update with the current date.  The workflow is written to evaluate any time the record is edited, and attach a time-based task at 120, 60, and 30 days.
Can anyone point me in the right direction, or tell me what I'm doing wrong?  Thanks...

A: You wouldn't be able to use  trigger for this either. Just like workflows, triggers only fire when a record is inserted, edited, or deleted. If you have a job that you want to run on a scheduled basis that goes through records and updates them, then you should use scheduled apex.


text:
Q: ImportError: cannot import name 'bytes_type' in flask_oauthlib i try to build a apps with flask_oauthlib and deploy it to heroku, but i get some error
2019-02-10T03:14:55.112096+00:00 app[web.1]:   File "/app/flask_oauthlib/client.py", line 20, in <module>
2019-02-10T03:14:55.112098+00:00 app[web.1]:     from .utils import to_bytes
2019-02-10T03:14:55.112099+00:00 app[web.1]:   File "/app/flask_oauthlib/utils.py", line 5, in <module>
2019-02-10T03:14:55.112102+00:00 app[web.1]:     from oauthlib.common import to_unicode, bytes_type
2019-02-10T03:14:55.112106+00:00 app[web.1]: ImportError: cannot import name 'bytes_type'
2019-02-10T03:14:55.112616+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [11] [INFO] Worker exiting (pid: 11)
2019-02-10T03:14:55.112784+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [10] [INFO] Worker exiting (pid: 10)
2019-02-10T03:14:55.267604+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [4] [INFO] Shutting down: Master
2019-02-10T03:14:55.267763+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [4] [INFO] Reason: Worker failed to boot.
2019-02-10T03:17:31.597353+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=askfess.herokuapp.com request_id=1e14f0da-5bbe-4849-9308-3ecf8a49306f fwd="140.213.38.39" dyno= connect= service= status=503 bytes= protocol=https

any ideas to fix it? the app error only when i try to deploy in heroku, but working fine in localhost

A: Run pip to install requests-oauthlib:
pip install requests-oauthlib==1.1.0

solved the issue for me!!

A: This error comes when trying to run project on python 3.7. Flask oauthlib does not have support for python 3.7
I switched to python 3.5 and it works fine.


text:
Q: Keywords to find good tutorials I want to create multiple winform from a SQL Database with multiple realtionships and can't find a good turotrial. My end goal for this front end application is to have:

*

*read data to 6-7 forms and the forms to be able to insert,update,delete

*1 of the forms will have a tab

*button to go to the next/previous/first/last row that has data from a few different tables with relationships.

*The forms will link to one complaint from tables below

*Buttons will lead data-entry person to get to each of the forms.

*Each form will update, insert, delete, or read from SQL Server with the tables listed below.

I've watched many videos similar to the link below but the problem is that these videos don't show the form reading the data from SQL Server, then it being searchable to find a "Complaint" to update or delete. You have to manually enter in a data for it to be updated or delete for these videos.
https://www.youtube.com/watch?v=P3FpM8f2suI

The only thing with this is that, most videos use datagrids or list boxes. I do not want to use a list box and datagris.  I just want to use a textbox for each field. I've also heard entityframework is the way I should go.
What I have are:

*

*Customer

*Customer Service Rep

*Notes

*Complaints

*Complaint Allegations

All tables are either left joined or joined to the Complaints table by the CompID.
My question is, am I searching for videos with wrong keywords? I am using:
1. Update, Insert, Read, Delete WinForm C# SQL Server
2. C# frontend and SQL Server Backend
3. Winform C# and SQL Server

A: use lazy load better for you load the data in the tab form when ever you need it, but if you need to do it use HashTable<fromName, List<YourDBObject>> load this data in the time of the first form load and then map it to the different form when the user change  the tab


text:
Q: Horizontal Bootstrap 4 columns I'm trying to use the grid system of bootstrap 4, I want 3 columns(each of 4) and I need them in a horizontal manner. But I'm getting it in a vertical manner. Here's my code:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />

  <input type="text" placeholder="Search Here..." / name="search" required="">
  <button type="submit" name=" submit">

  </button>

      Elite Shoppy

A: Here is a rough draft of what I think you are looking for. It still needs work on the scaling side. When you shrink the screen down it won't look pretty. Mess around with it to get it to your liking. Remove class="container" if you dont want the padding.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />

        <input type="text" class="form-control" placeholder="Search Here..." aria-label="Search" aria-describedby="button-addon2">

          <button class="btn btn-outline-secondary" type="button" id="button-addon2"></button>

          Elite Shoppy

      Blank


text:
Q: Why doesn't .NET release unused memory back to OS when physical >95%? We are testing a 4-process WCF IIS application (x3 release versions) for memory stability (leaks) by simply pinging it every ~1s as a Load Balancer might.  It runs fine for >12hours if nothing else is running on the server.
However if we purposely reduce the total available memory (fixing the page, reduce physical memory, launch other apps) and push the physical memory usage to 97% and leave it there for 5 minutes or more, oftentimes Windows will sense the condition and shutdown one of the processes.  Note it also fails if the total memory is pushed to 97% (by using a fixed page file).
However, analyzing the memory footprint of one of the surviving processes using the RedGate tool, shows this:

Since the requests are just a steady ping, there seems to be no practical reason for .NET to hold the 269MB free memory when the server is starved.  About 50% of the IIS Processes appear to be in this state (~1.8GB).
The App is compiled against .NET 4.0, gcServer true.  IIS Gate checking was set to 0% (minFreeMemoryPercentageToActivateService="0") although we would probably set it to 2% in production.
The Server is 2008 R2, ~4GB physical 4GB fixed page, was tested with 4.0 and then 4.5.1 (didn't matter).
There is an answer to a similar question by @atanamir claiming:

".NET will free its heap back to the OS once you're running low on
  physical memory."

Anyone know of any reference for that claim?  Could it be version specific?
Refs:

*

*.NET Free memory usage (how to prevent overallocation / release memory to the OS)

*When is memory, allocated by .NET process, released back to Windows

A: This is not exactly an answer to the question you asked (why) but it should be a way to achieve what you're trying to do.
There is something new with .NET Framework 4.5 - source

Once a site is running, its use of the garbage-collector (GC) heap can be a significant factor in its memory consumption. Like any garbage collector, the .NET Framework GC makes tradeoffs between CPU time (frequency and significance of collections) and memory consumption (extra space that is used for new, freed, or free-able objects). For previous releases, we have provided guidance on how to configure the GC to achieve the right balance.
  For the .NET Framework 4.5, instead of multiple standalone settings, a workload-defined configuration setting is available that enables all of the previously recommended GC settings as well as new tuning that delivers additional performance for the per-site working set. For example, there is no need to set gcServer, gcConcurrent, etc.

Also here they state:

Tuning GC for high-density Web hosting: GC can impact a site's memory consumption, but it can be tuned to enable better performance. You can tune or configure GC for better CPU performance (slow down frequency of collections) or lower memory consumption (that is, more frequent collections to free up memory sooner) […] in order to achieve smaller memory consumption (working set) per site

To enable GC memory tuning, add the following setting to the Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config file and Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config file:
<configuration>
<!-- ... -->
<runtime>
<performanceScenario value="HighDensityWebHosting"  />
<!-- ... -->

Basically, based on the tests I made, I saw that it will consume more CPU, less memory and make the GC to be more aggressive in terms of clean up and memory release process.
We tested this setting within our infrastructure (IIS 7.5, new 4.5 framework) and the results were impressive. High memory usage leading to out of memory exceptions are no more an issue.
Hope it helps.

A: The information given by atanamir can be found on this MSDN page.

Garbage collection occurs when one of the following conditions is true:

The system has low physical memory.
The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.


text:
Q: Can't grab properties from XML response this is the first time I am working with kSoap2 and really building an android app, however I am struggling to get it working, I'm trying to pull each callingPoint from the list however I'm just crashing due to a null pointer as it can't find any properties.
Here is the response I am trying to work with.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
    <GetServiceDetailsResponse
        xmlns="http://thalesgroup.com/RTTI/2014-02-20/ldb/">
        <GetServiceDetailsResult
            xmlns:lt="http://thalesgroup.com/RTTI/2012-01-13/ldb/types"
            xmlns:lt6="http://thalesgroup.com/RTTI/2017-02-02/ldb/types"
            xmlns:lt7="http://thalesgroup.com/RTTI/2017-10-01/ldb/types"
            xmlns:lt4="http://thalesgroup.com/RTTI/2015-11-27/ldb/types"
            xmlns:lt5="http://thalesgroup.com/RTTI/2016-02-16/ldb/types"
            xmlns:lt2="http://thalesgroup.com/RTTI/2014-02-20/ldb/types"
            xmlns:lt3="http://thalesgroup.com/RTTI/2015-05-14/ldb/types">
            <lt2:generatedAt>2018-03-12T01:54:31.6803098+00:00</lt2:generatedAt>
            <lt2:serviceType>train</lt2:serviceType>
            <lt2:locationName>London St Pancras (Intl)</lt2:locationName>
            <lt2:crs>STP</lt2:crs>
            <lt2:operator>Thameslink</lt2:operator>
            <lt2:operatorCode>TL</lt2:operatorCode>
            <lt2:std>02:20</lt2:std>
            <lt2:etd>On time</lt2:etd>
            <lt2:previousCallingPoints />
            <lt2:subsequentCallingPoints>
                <lt2:callingPointList serviceType="train" serviceChangeRequired="false" assocIsCancelled="false">
                    <lt2:callingPoint>
                        <lt:locationName>West Hampstead Thameslink</lt:locationName>
                        <lt:crs>WHP</lt:crs>
                        <lt:st>02:27</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Cricklewood</lt:locationName>
                        <lt:crs>CRI</lt:crs>
                        <lt:st>02:31</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Hendon</lt:locationName>
                        <lt:crs>HEN</lt:crs>
                        <lt:st>02:34</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Mill Hill Broadway</lt:locationName>
                        <lt:crs>MIL</lt:crs>
                        <lt:st>02:38</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Elstree & Borehamwood</lt:locationName>
                        <lt:crs>ELS</lt:crs>
                        <lt:st>02:42</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Radlett</lt:locationName>
                        <lt:crs>RDT</lt:crs>
                        <lt:st>02:47</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>St Albans</lt:locationName>
                        <lt:crs>SAC</lt:crs>
                        <lt:st>02:53</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Harpenden</lt:locationName>
                        <lt:crs>HPD</lt:crs>
                        <lt:st>03:00</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Luton Airport Parkway</lt:locationName>
                        <lt:crs>LTN</lt:crs>
                        <lt:st>03:05</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Luton</lt:locationName>
                        <lt:crs>LUT</lt:crs>
                        <lt:st>03:08</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Leagrave</lt:locationName>
                        <lt:crs>LEA</lt:crs>
                        <lt:st>03:13</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Harlington</lt:locationName>
                        <lt:crs>HLN</lt:crs>
                        <lt:st>03:18</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Flitwick</lt:locationName>
                        <lt:crs>FLT</lt:crs>
                        <lt:st>03:22</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                    <lt2:callingPoint>
                        <lt:locationName>Bedford</lt:locationName>
                        <lt:crs>BDM</lt:crs>
                        <lt:st>03:35</lt:st>
                        <lt:et>On time</lt:et>
                    </lt2:callingPoint>
                </lt2:callingPointList>
            </lt2:subsequentCallingPoints>
        </GetServiceDetailsResult>
    </GetServiceDetailsResponse>
</soap:Body>
</soap:Envelope>

here is the code I am using to try and pull my data from the Soap message
SoapObject trainServices = (SoapObject) response
            .getProperty("callingPoint");
    Log.d("gen", String.valueOf(trainServices.getPropertyCount()));
    for (int i = 0; i < trainServices.getPropertyCount(); i++)
    {
        Log.d("this", "looped2");
        Object property = trainServices.getProperty(i);
        if (property instanceof SoapObject) {
            SoapObject trainService = (SoapObject) property;
            Log.d("this", "looped");
            String std = (trainService.hasProperty("std") ? trainService
                    .getPropertyAsString("std") : null);
            String etd = (trainService.hasProperty("etd") ? trainService
                    .getPropertyAsString("etd") : null);
            String platform = (trainService.hasProperty("platform") ? trainService
                    .getPropertyAsString("platform") : null);
            String operator = (trainService.hasProperty("operator") ? trainService
                    .getPropertyAsString("operator") : null);
            String operatorCode = (trainService.hasProperty("operatorCode") ? trainService
                    .getPropertyAsString("operatorCode") : null);
            String serviceID = (trainService.hasProperty("serviceID") ? trainService
                    .getPropertyAsString("serviceID") : null);
            String sta = (trainService.hasProperty("sta") ? trainService
                    .getPropertyAsString("sta"): null);
            String eta = (trainService.hasProperty("eta") ? trainService
                    .getPropertyAsString("eta") : null);
        }
        //CallingPoints.add(new serviceDetails(locationName,"","","","","","",sta,eta,ata,etd,atd));
    }


text:
Q: How to create tooltip that stay on mouseover in pure css? I have a tooltip code here. And when I move mouse on this tooltip to click button it disappear. How to make it stay? I don't know how.

a.tooltips {
  position: relative;
}
a.tooltips span {
  position: absolute;
  width: 140px;
  color: #FFFFFF;
  background: #000000;
  min-height: 50px;
  line-height: 30px;
  text-align: center;
  visibility: hidden;
  border-radius: 6px;
}
a.tooltips span:after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -8px;
  width: 0;
  height: 0;
  border-top: 8px solid #000000;
  border-right: 8px solid transparent;
  border-left: 8px solid transparent;
}
a:hover.tooltips span {
  visibility: visible;
  opacity: 0.8;
  bottom: 30px;
  left: 50%;
  margin-left: -76px;
  z-index: 999;
}
 CSS Tooltips
                  Tooltip <button  >Open dialog</button>

A: This has changed recently and can now be done with pure CSS:
jsFiddle Example
 .tooltip {
  display: none;
  position: absolute;
  height: 45px;
  background-color: #FCF;
  overflow: hidden;
}

.hasTooltip:hover .tooltip,
.tooltip:hover {
  display: block;
}

A: Unfortunately adding a permanent state on hover can't be accomplished with pure CSS, you will have to add a small bit or javascript of jQuery. Something like:
$('a.tooltips span').on('mouseover',function(){
    $(this).css({
        "visibility": "visible",
        "opacity": "0.8"
        // more styles go here
    });
});

A: Here's an example using pure JavaScript. This is just an example, but you can modify it a lot to match your needs. As mentioned in the comments, you can do it in pure CSS by adding a transition delay on the hover state to something absurd, but using a JS solution will give you a lot of flexibility if you want to add additional functionality.

var tooltips = document.querySelectorAll('.tooltip-group');
var closeTooltips = document.querySelectorAll('[data-tooltip-close]');

for ( var i = 0; i < tooltips.length; i++ ) {
  tooltips[i].addEventListener('mouseover', function( evt ) {

    // Open tooltip when the user interacts with the
    // element. We will just open the tooltip as
    // an example
    document.querySelector('[data-tooltip-id="' + evt.currentTarget.id + '"]').style.display = 'block';

  });
}

for ( var i = 0; i < closeTooltips.length; i++ ) {
  closeTooltips[i].addEventListener('click', function( evt ) {

    // Event for button within tooltip, this could be
    // replaced for anything such as opening a modal
    // or changing another element
    document.querySelector('[data-tooltip-id="' + evt.currentTarget.dataset.tooltipClose + '"]').style.display = 'none';

  });
}
body, html{
  width: 100%;
  height: 100%;
  font-family: 'Arial', sans-serif;
}

.f__container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.tooltip-group {
  position: relative;
  margin: 0 auto;
}

[data-tooltip-id]{
  width: 100%;
  position: absolute;
  display: none;
  background: black;
  color: white;
  top: -60px;
  margin-left: -15px;
  border-radius: 5px;
  padding: 15px;
}

      JS Tooltip, hover over me :D!

        Tooltip!
        <button data-tooltip-close="js-tooltip">Close</button>


text:
Q: How to convert this C code to C++? I have some arrays that are declared like this:
static double covalent_radius[256] = {
    [ 0 ] = 0.85,
    [ 1 ] = 0.37,
    ...
};

C++ doesn't allow this kind of declaration. Is there any way to achieve this?

A: Why don't you do this:
static double covalent_radius[256] = {
    0.85, /* 0: ?,  Unknown    */
    0.37, /* 1: H,  Hydrogen   */
    ...
};

A: You could use a std::vector of a std::tuple of two std::string and a double
#include <iostream>
#include <string>
#include <tuple>
#include <vector>

static auto periodic_table = std::vector<std::tuple<std::string, std::string, double>>
{
    std::make_tuple("?", "Unknown", 0.85),
    std::make_tuple("H", "Hydrogen", 0.37)
};

std::string element_symbol(int neutrons)
{
    return std::get<0>(periodic_table[neutrons]);
}

std::string element_name(int neutrons)
{
    return std::get<1>(periodic_table[neutrons]);
}

double covalent_radius(int neutrons)
{
    return std::get<2>(periodic_table[neutrons]);
}

int main()
{
    std::cout << element_symbol(1) << "\n";
    std::cout << element_name(1) << "\n";
    std::cout << covalent_radius(1) << "\n";
}

Live Example (using C++11 initializer-lists).
Note: I'd make the periodic table std::vector instead of an array because they keep synthesizing new (unstable) elements.

A: static double covalent_radius[256] = {
    0.85, /* ?,  Unknown    */
    0.37, /* H,  Hydrogen   */
    ...
};

It's C89, not C99 so I suppose it should work.


text:
Q: scatter3D() function ValueError: shape mismatch: objects cannot be broadcast to a single shape I am building a 3D graph for a representation.
I used the following code.
ax = plt.axes(projection = '3d')
ax.scatter3D(x_int, y_int, der_int, c=der_int, cmap = 'hsv')

I got the above error. x_int, y_int, der_int are integer lists.
I need a solution for this.


text:
Q: How to allow few different symbols using pattern in HTML I want to allow only Xx, numbers and -+/%^* symbols. How to write RegEx, which allows user to input only these characters?
Thats what I have, but it doesn't work:
<input
                           type="text"
                           pattern="Xx[1-9]\-\+\*\^\/\(\)"
/>

A: This should work:
<input type="text" pattern="[Xx0-9\-\+\/\^\*%]*"/>


text:
Q: How can i bulk create in django rest serializer I used to use allow_add_remove=True which was availabe in django rest 2.0  for writing nestable serializer but its not available in 3.0 and i am having hard time implementing it.
I want to do something like this
class UserSerialzier():
    project = ProjectSerilaizer(many=True, allow_add_remove=True, read_only=False)

class ProjectSerialzier():
    ideas = IdeaSerilaizer(many=True, allow_add_remove=True, read_only=False)
    sources = SourceSerilaizer(many=True, allow_add_remove=True, read_only=False)

class IdeaSerialzier():
    pass

class SourceSerialzier():
    pass

Now i am not able to know how can i implement the allow_add_remove behavior in DRF 3.0
I am confused that do i need to override create and update method of UserSerializer
or i need  to create separate IdeaListSerializer  for every model
class IdeaListSerializer(serializers.ListSerializer):
    def create(self, validated_data):
        ideas = [Idea(**item) for item in validated_data]
        return Ideas.objects.bulk_create(books)

A: Yes you do need to override create and update methods of your UserSerializer.
I've spent a lot of time trying to make nested writable serializers work with DRF 2.x and the more I fixed issues the more issues were risen with corner use cases.
Therefore Tom decided that it should be left up to the developer to handle the creation and updates.
The documentation provides an example for a 1 nesting level creation but it's the same for update and/or with more nesting level


text:
Q: Function to redirect to subdomain when user logs into Wordpress site I'm using the function below to redirect non-admin users to the home page of my site rather than the admin page on login, and I'm wondering if there is any way of adapting the function to point to a subdomain of my site?
I have tried entering the full URL of the subdomain in place site_url(), but this doesn't work. Is there another way of achieving this?  Essentially I want the user to be redirected to our discourse forum on login.
function acme_login_redirect( $redirect_to, $request, $user  ) {
    return ( is_array( $user->roles ) && in_array( 'administrator', $user->roles ) ) ? admin_url() : site_url();
}
add_filter( 'login_redirect', 'acme_login_redirect', 10, 3 );

A: The login_redirect filter calls wp_safe_redirect() if a string (url) is returned in the login_redirect filter function.
Then wp_safe_redirect() checks if the returned string (url) is in the list of allowed hosts or not, if the returned string exists in the allowed hosts then wp_safe_redirect() will redirect a user to that returned string (url) otherwise a user will be redirected to to wp-admin on the siteurl instead.
So before adding the login_redirect filter you should add host  in the whitelist using allowed_redirect_hosts filter.
function my_allowed_redirect_hosts($content){
    $content[] = 'google.com'; // Do not add http://

    return $content;
}
add_filter( 'allowed_redirect_hosts' , 'my_allowed_redirect_hosts' , 10 );

function acme_login_redirect($redirect_to, $requested_redirect_to, $user) {
    if (is_array($user->roles) && in_array('administrator', $user->roles)) {
        return admin_url();
    }
    else
    {
        return 'http://google.com';
    }
}
add_filter( 'login_redirect', 'acme_login_redirect', 10, 3 );

For more info check allowed_redirect_hosts
To know more about how login_redirect works, go to login_redirect and scroll to line 807


text:
Q: Pick out words in a string that are in array I have spent hours, close to 8 hours none stop on this, I am trying to use jQuery/JS to create two arrays, one which is dynamic as it is loading a chat script and will be split by whitespace in to an array, for example:
String: Hello my name is Peter
Converted to (message) array: ['hello','my','name','is','peter'];
I have a set array to look out for specific words, in this example let us use:
(find array) ['hello','peter'] however, this array is going to contain up to 20 elements and I need to ensure it searches the message array efficiently, please help.

A: If I understood well, you're asking to filter an array of string (from an incoming string) given a second array.
In your described case you'll certainly not have to worry about efficiency, really. Unless your incoming message is allowed to be very very big.
Given that, there is a dozen of options, I think this is the most succinct:
const whitelist = [
  'hello',
  'peter'
]
const message = 'hello my name is Peter'.split(' ')

const found =  message.filter(function(word) {
  return whitelist.indexOf(word) > -1
}

You can treat invariant case:
const whitelistLower = whitelist.toLowerCase()
const foundInvariantCase = message.filter(function(word) {
  return whitelist.indexOf(word.toLowerCase()) > -1
}

Or use ESS Set:
const whitelistSet = new Set(whitelist)
const found = message.filter(function(word) {
  return whitelistSet.has(word)
}

A: I can help you with that.
var arrayOfWords = $(".echat-shared-chat-message-body").last().text().split(" ");

That code is actually working! i went to an open chat in this website so I can tested.
So just replace the word REPLACE with your DOM object :)
var arrayOfWords = $("REPLACE").last().text().split(" ");


text:
Q: PHP SQL Check if form input exists in other table, then continue I'm writing a form where I want the code to check if the inserted 'date' on which a participant wants to attend an event matches a 'date' in my events table. For the moment (even though 'date' as on the form input doesn't match any of the dates on the events table) users can register for any date without getting the validation error.
on the html-form "register.html" I have:
    <form action="register.php" method="post">
      <div class="form-group">
        <label for="date"> Date of attendence </label>
        <input type="date" class="form-control" id="date" name="date"/>
      </div>
      <input type="submit" class="btn btn-primary" />
    </form>

on "register.php" I have:
    <?php
        $date = $_POST['date'];

        $conn = new mysqli('localhost','root','','skay');
        if($conn->connect_error){
            echo "$conn->connect_error";
            die("Connection Failed : ". $conn->connect_error);
        } else {

            $date_check_query = "SELECT COUNT * FROM events WHERE date='$date'";
            $number_of_matches = mysqli_query($conn, $date_check_query);

            if ($number_of_matches = 0) {
                array_push($errors, "No planned events on this day");
            } else {
                $stmt = $conn->prepare("INSERT INTO registrations(date) values(?)");
                $stmt->bind_param("sssssi", $date); //there are other 5 other values aswell
                $execval = $stmt->execute();
                echo $execval;
                echo "Registration successfully...";
                $stmt->close();
                $conn->close();
            }
        }
    ?>

Grtz Beau

A: Double check your code, especially here
if ($number_of_matches = 0) {

Should be
if ($number_of_matches == 0) {

It's not into the scope of your questions but it's good ti think about SQL injection attacks and rework the following line of code:
$date_check_query = "SELECT COUNT * FROM events WHERE date='$date'";

A: If you assign an alias to the value returned by count(*) - like count(*) as 'aliasname', you can treat that as you would a regular column in the recordset.
Using a prepared statement to input data is fine but the good work is undone by using potentially malicious data directly in the select query - whereever you take user input you need to take extra precautions, so use prepared statements in all such cases.
<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['date'] ) ){

        $date = $_POST['date'];

        $conn = new mysqli('localhost','root','','skay');

        $sql = "SELECT COUNT(*) as `total` FROM `events` WHERE `date`=?";
        $stmt=$conn->prepare($sql);
        $stmt->bind_param('s',$date);
        $stmt->execute();
        $stmt->bind_result($total);
        $stmt->fetch();
        $stmt->close();

        if( $total==0 ){
            $errors[]="No planned events on this day";
        }else{
            $sql='insert into `registrations`( `date` ) values(?)';
            $stmt=$conn->prepare($sql);
            $stmt->bind_param('s',$date);
            $stmt->execute();

            $stmt->close();
            $conn->close();
            echo "Registration successfully...";
        }
    }
?>


text:
Q: Openbugs too many constants error I'm trying to run the code below in which I used a zero trick for my log-likelihood expression(phi is my log-likelihood):
 model{
for (l in 1:k) {
d.1[l] ~ dbern(p.1)
d.2[l] ~ dbern(p.2)
d.3[l] ~ dbern(p.3)
d.4[l] ~ dbern(p.4)
}
for (l in 1:k) {
zeros[l] <- 0
zeros[l] ~ dpois(phi[l])
u.1[l] <- pow((1 - p.1), (1 - d.1[l]))
u.2[l] <- pow((1 - p.2), (1 - d.2[l]))
u.3[l] <- pow((1 - p.3), (1 - d.3[l]))
u.4[l] <- pow((1 - p.4), (1 - d.4[l]))
f.1[l] <- pow(p.1, d.1[l]) * pow((1 - p.1), (1 - d.1[l]))
f.2[l] <- pow(p.2, d.2[l]) * pow((1 - p.2), (1 - d.2[l]))
f.3[l] <- pow(p.3, d.3[l]) * pow((1 - p.3), (1 - d.3[l]))
f.4[l] <- pow(p.4, d.4[l]) * pow((1 - p.4), (1 - d.4[l]))
a[l] <- pow((pow(u.3[l], -theta.1) + pow(u.4[l], -theta.1) -
    1), (theta.0/theta.1 - 2)) * (-1) * ((theta.0/theta.1) *
    (-1) + pow((theta.0/theta.1), 2))
b[l] <- pow((pow(u.1[l], -theta.2) + pow(u.2[l], -theta.2) -
    1), (theta.0/theta.2 - 2)) * (-1) * ((theta.0/theta.2) *
    (-1) + pow((theta.0/theta.2), 2))
c[l] <- pow(pow((pow(u.3[l], -theta.1) + pow(u.4[l],
    -theta.1) - 1), -(1/theta.1)), -theta.0) + pow(pow((pow(u.2[l],
    -theta.2) + pow(u.1[l], -theta.2) - 1), -(1/theta.2)),
    -theta.0) - 1
d[l] <- pow((pow(u.3[l], -theta.1) + pow(u.4[l], -theta.1) -
    1), (theta.0/theta.1 * 2 - 2)) * pow(theta.0/theta.1,
    2)
e[l] <- pow((pow(u.1[l], -theta.2) + pow(u.2[l], -theta.2) -
    1), (theta.0/theta.2 * 2 - 2)) * pow(theta.0/theta.2,
    2)
phi[l] <- log((a[l] * b[l]) * (1 + theta.0)/pow(c[l],
    -(2 + 1/theta.0)) + (d[l] * b[l] + a[l] * e[l]) *
    ((1 + theta.0) * (1 + 2 * theta.0))/pow(theta.0,
    3) * pow(c[l], -(3 + 1/theta.0)) + (d[l] * e[l]) *
    ((1 + theta.0) * (1 + 2 * theta.0) * (1 + 3 * theta.0))/pow(theta.0,
    4) * pow(c[l], -(4 + 1/theta.0))) + log(pow(theta.1,
    2) * pow((u.3[l] * u.4[l]), -(1 + theta.1)) * pow(theta.2,
    2) * pow((u.1[l] * u.2[l]), -(1 + theta.2)))
 }
 p.1 ~ dunif(0 , 1)
 p.2 ~ dunif(0 , 1)
p.3 ~ dunif(0 , 1)
p.4 ~ dunif(0 , 1)
theta.0 ~ dunif(0 , 2)
theta.1 ~ dunif(0 , 2)
theta.2 ~ dunif(0 , 2)
 }

with data:
 k <- 16
 d.1 <- c(0 , 0, 0 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 1 , 0)
 d.2 <- c(0 , 1, 0 , 0 , 0 , 0 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 0 , 1 , 0)
 d.3 <- c(1 , 0, 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0)
 d.4 <- c(0 , 1, 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0)

The model is syntactically correct and the data is loaded but I got the following error:
logical expression contains too many constants

Can anyone please help me solve that problem?

A: BUGS does not like expressions with too many constants. You need to introduce a sub-step to break them up. See point (c) under 'Some Error Messages' in this page:
http://mathstat.helsinki.fi/openbugs/Manuals/TipsTroubleshooting.html


text:
Q: Upgrading a big database inside a transaction Assuming a big database, where normal upgrade (structural changes and data upgrade) currently takes about 2-3 days (not a issue, is not done during production and about 1-2 times per year.
Currently, a backup is done, and if anything fails, backup is restored and upgrade scripts are checked for reason.
We are looking into the possibility of upgrading the database inside a transaction, rollbacking the changes if anything happens.
Are there any best-practices, reasons, knowledge and/or experience that would say if this is a good idea?
Thank you

A: Reverting to a valid backup is the most common and safest approach. You can reduce risk and likelihood of needing to restore from backup by versioning the changes.
For instance, say your upgrade process involves 50 steps that have some sequence/order requirements. Any step or small group of steps that can survive a reboot after they are applied should safely rev a version number in your DB so you know exactly what the last successful upgrade step was. You can then resume the process instead of having to restart.
Add this to putting each step or collection of steps in transactions will help ensure your upgrade steps comply with ACID requirements and make your upgrade process more robust. We do this with some of our major upgrades and rarely ever have to restore when something breaks in the middle unless there's a bug in the script of one of the upgrade steps.


text: Q: How to run scripts in Database which were stored in particular location through C#? I have a DB SQL script which is stored in location  C://Temp. I need to load it, run in database by using C#. which is best way to do it?. I am using microsoft dapper for db connectivity


text:
Q: Fields of the instance are not displayed in the email template Some fields of the instance does not show up in my email template. See below, the field user_phone is not displayed.
I have view which get or create User:
views.py
    # Get informations for creating the User
    user, created = User.objects.get_or_create(
        username=username,
        email=email,
        first_name=first_name,
        last_name=last_name,
    )
    if created:
        user.groups.add(Group.objects.get(name='Clients'))
        user.profile.phone = telephone
        user.save()
    else:
        user.profile.phone = telephone
        user.save()

I send an email to new user with there infos
models.py
@receiver(post_save, sender=User)
def password_mail(sender, instance, **kwargs):
    if kwargs['created']:
        user_email = instance.email
        first_name = instance.first_name
        user_phone = instance.profile.phone

        subject, from_email, to = 'New account', 'mail@example.com', user_email

        text_content = render_to_string('accounts/mail_welcome.txt', {'first_name': first_name, 'user_phone': user_phone})
        html_content = render_to_string('accounts/mail_welcome.html', {'first_name': first_name, 'user_phone': user_phone})

        # create the email, and attach the HTML version as well.
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()

And finally, this the email template:
mail_welcome.txt
{% autoescape off %}
Hello {{ first_name }},

Here is you phone number : {{ user_phone }}

{% endautoescape %}

All the tags are displayed well except the user_phone.
Is this because the way this field is saved in my view?
Help appreciated :)


text:
Q: Array in Rails 4 strong parameters (not nested) I want to create several objects at a time, from my index view, so I have inputs: post[][title] and post[][parent_id], in my post_controller.rb i have:
def post_params
  params.require(:post).permit(:title => [], :parent_id => [])
end

But I'm getting the error on submit: undefined method 'permit' for [{"title"=>"Title", "parent_id"=>"133"}]:Array
I read this post, but if I try params.permit(:title => [], :parent_id => []), then post_params just returns empty hash.
params:
{"utf8"=>"✓",
"authenticity_token"=>"oJwfzxbn+LJ/pD1hKo27gckZg6P4Gd8wyNY9NSFS4BA=",
"post"=>{"title"=>["1",
"2"],
"parent_id"=>["",
""]},
"locale"=>"ru"}

A: The problem was in Cancancan strong params, despite the following article I could not get cancancan gem to use my post_params function (i have load_and_authorize_resource call in ApplicationController), so the fix was to use skip_load_resource :only => :create in my PostController.
Note: due to this issue writing skip_load_resource :only => :create in ApplicationController won't work.


text:
Q: Type checking in arrays I have a class
class Clazz{constructor(public foo: string, public bar: string)}
and then I am creating an array like this:
var cls: Clazz[] = [{foo: 'Foo', bar: 'Bar'}, {foo:'Missing bar'}]

The type checker does not complain about the item with missing bar. Is this by design? If yes, what is the motivation behind this behaviour?

A:
The type checker does not complain about the item with missing bar

It does:

See the sample in the playground.
Note that your code also had a syntax error (which was also reported ... the constructor body was missing).

A: You can leave out arguments and they will be initialized with their default value. This usually is done if you don't know the desired value yet or you are fine with the default value being set. Additionally, if you have a class with a lot of properties, you might not want to set them all in the constructor call.


text:
Q: Xcode 8.3.3: Unable to push to repo using ssh key I have my github repo setup with ssh key to access it: pull/push.
With command-line git commands it does flawlessly.
But I can't push with Xcode.

I don't have any passphrase with my private key.
Whenever I press [OK], I'm getting the same window again and again. No error or something.


text:
Q: How can I grab this website content without losing javascript content I want to download this website
Abd i tried idm and httrack but didn't work for javascript content
http://websdr.uk:8074/
Anyone can help me to download this frequency streaming content,
Thank you

A: In order to capture the javascript actions, you'll need Selenium. It's a browser automation tool, used for Automated testing and data parsing from webpages.
https://www.selenium.dev/
Downloading an entire site is possible only if the website has static pages (HTML, CSS, Img). But Javascript-based content is loaded dynamically, which would be difficult to download.


text:
Q: Finding a subgroup of the Galois group of $E/(\mathbb{Z}/(p))$ where $E = (\mathbb{Z}/(p))(t)$, $t$ transcendental. As the title states, the setup is
Let $E = (\mathbb{Z}/(p))(t)$, and we are looking at it over $\mathbb{Z}/(p)$ and $t$ is transcendental.
Let $G$ be a group of automorphisms of $E$ generated by $\sigma: t \to t+1$. Determine $F = Inv \, G$, and $[E:F]$.
Adjoining a transcendental element to a finite field is one of my weakest aspects of Galois theory, so I don't really know where to start. So $\sigma^p = id$, so $|G| = p$?

A: As you have noticed, $\sigma^p=\operatorname{id}$, and clearly $\sigma$ is not identity, so $G$ has order $p$.
To calculate $[E:F]$ recall that the extension degree from the fixed field of the Galois group is always equal to the order of the group.
Finding $F$ shouldn't be too hard. Can you find a single nonconstant polynomial $P(t)$ such that $\sigma(P(t))=P(t)$?


text:
Q: Setting up openId in tornado python Hey all... I have been reading the tornado doc and came across open id mixin so I thought to myself "Wicked no horrid password system on my side" then I looked into how to implement it, the only example I came across was this
class GoogleHandler(tornado.web.RequestHandler, tornado.auth.GoogleMixin):
    @tornado.web.asynchronous
    def get(self):
        if self.get_argument("openid.mode", None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return
        self.authenticate_redirect()

    def _on_auth(self, user):
        if not user:
            raise tornado.web.HTTPError(500, "Google auth failed")

Which doesn't show the bigger picture, like routes, appsettings etc etc
            # Save the user with, e.g., set_secure_cookie()
So my question is. How does this fit into the bigger picture that is a tornado site.

A: This handler does not depend on other parts of application, you just set it on something like '/login/google' in url conf and place a link to this url somewhere on your website.
User clicks on it and gets redirected to google auth page (if it's logged out of google) or to a page asking to grant permission to acces his/her basic info. If user accepts - browser gets redirected back on this url handler and control comes to _on_auth method, where the user object, if present, contains a dict with user's email, name, location settings and a bunch of other stuff (just dump this variable to logs to see all of it).
At this point you can do whatever you want with this data, but in general it can look something like this:

*

*check whether you have user with this email in database

*if you have: you retrieve it's id and set it to his (secure) cookies

*if it is not present: you create it with provided data, save to database, optionally send email with autogenerated password and also set the cookie

*redirect somewhere else in your application: to his profile, home page or whatever you need

*now your user has cookie available in all other handlers, usually you will use it while overriding RequestHandler.get_current_user method


text:
Q: Can I use present perfect tense here? Suppose, I've been fasting for a few hours. Can I say "I have not eaten since breakfast"?
Or should I say "I have not been eating since breakfast"?
Which one is grammatically correct?

A: They're both grammatically correct, but the important things are "What is your context?" and "What do you want to express?"

*

*I have not eaten since breakfast.

Imply that maybe someone asks you to have some meal right now and you want to. You suppose to terminate the activity(state) "not eaten" now.

*I have not been eating since breakfast.

Imply that you will keep "not eating."


text:
Q: JS change style/className of past dates as string values I have a list of dates in format dd/mm/yyyy as text
I'm trying to make these dates change style or class according to today's date
today is february 9th 2016  or 09/02/2016
obviously, there's something wrong, because i want the "if" statements to mark the className as .past
if  the year is before 2016
        OR
if the month is before today's month (february)
        AND
before today's day of the month (9)
13/01/2016 is marked as future- and i don't know why
what am i doing wrong?

var today=new Date();
    var yr = today.getFullYear();
    var da = today.getDate();
    if (da<10){da= "0"+today.getDate()} else {da=today.getDate()};
    var mo = (today.getMonth()+1);
    if (mo<10){mo= "0"+mo} else {mo=mo};

    var cnl = document.getElementsByClassName("lesson");
    var cnd = document.getElementsByClassName("date");
    var cd = document.querySelectorAll('.date');
    for (var i=0;i<cnd.length;i)
    {
      var cd = document.querySelectorAll('.date')[i].innerHTML;

    if (
        ( cd.substring(6,10)<yr )

          ||

   (
     (
     cd.substring(3,5) <= (mo)
      )

          &&

     (
       (
     cd.substring(0,2) < (da)
        )
     )

   )
    )
     {
     cnd[i].className = "past";
  }
  else
  {
       cnd[i].className = "future";
     }

}
    .date {font-size:15px;}
    .past
    {
    font-family:arial;
    font-size:15px;
    direction:rtl;
    text-align:right;
    font-weight:300;
    color:#f11;
    }
    .future
 {
       font-size:15px;
       direction:rtl;
        text-align:right;
        font-weight:300;
        color:#1f1;
    }

18/11/2015

02/12/2015

16/12/2015

30/12/2015

13/01/2016

03/02/2016

17/02/2016

02/03/2016

16/03/2016

30/03/2016

04/05/2016

13/04/2016

04/05/2016

18/05/2016

08/06/2016

jsfiddle

A: The best way of doing this is to parse the string as a date and check it against the current date. Here's a simple function to convert your DMY date into a Date instance:
function dmyToDate(dmy) {
    var parts = dmy.split('/');
    parts[1] -= 1; // Months are 0-indexed
    return new Date(parts[2], parts[1], parts[0]);
}

Now you can loop through each of your elements and compare their date against the current date, adding a class if necessary.
var i = 0;
var il = cnd.length;

while (i < il) {

    if (dmyToDate(cnd[i].textContent) < today) {
        cnd[i].className = 'past';
    } else {
        cnd[i].className = 'future';
    }

    i += 1;

}

Edit
In order to test for today, you need to reduce the timestamp for today down to the nearest day. This can be done with a couple of basic utility functions.
// You can just write
// var day = 86400000
// but I find that spelling it out like this is easier to understand.
var day = 1000 * 60 * 60 * 24;

function numberToNearest(number, nearest, method) {

    var prop = 'round';

    if (typeof method === 'string' && typeof Math[method] === 'function') {
        prop = method;
    }

    return Math[prop](number / nearest) * nearest;

}

function getDayStart(date) {

    if (typeof date !== 'number' || !(date instanceof Date)) {
        date = Date.now();
    }

    return numberToNearest(date, day, 'floor');

}

var today = getDayStart();

Now the loop just needs an extra clause.
var i = 0;
var il = cnd.length;
var cndElem;
var cndDate;

while (i < il) {

    cndElem = cnd[i];
    cndDate = dmyToDate(cndElem.textContent);

    if (cndDate < today) {
        cndElem.className = 'past';
    } else if (cndDate > today) {
        cndElem.className = 'future';
    } else {
        cndElem.className = 'present';
    }

    i += 1;

}

Edit 2
See my JSFiddle example for a working version.


text:
Q: What does SELECT Function is SQL actually produce? Does it produce a new table by default? I am struggling to understand what the output of SELECT is meant to be in SQL (I am using MS ACCESS), and what sort of criteria this output needs to specify, if any. As a result, I don't understand why some queries work and others don't. So I know it retrieves data from a table, does calculations with it and displays it. But I don't understand the "inner" working of SELECT function. For instance, what is the name of data structure  / entity it displays? Is it a  "new" table?
And for example, suppose I have a table called "table_name", with 5 columns. One of the columns called "column_3", and there are 20 records.
SELECT  column_3, COUNT(*) AS Count
FROM table_name;

Why does this query fail to run? By logic, I would expect it to display two columns: first column will be "column_3", containing 20 rows with relevant data, and second column will be "Count", containing just one non-empty row (displaying 20), and other 19 rows will be empty (or NULL maybe)?
Is it because SELECT is meant to produce equal number of rows for each column?

A: Your questions involve a basic understanding of SQL. SELECT statements do not create tables, but instead return virtual result sets. Nothing is persisted unless you change it to an INSERT.
In your example question, you will need to "tell" the SQL engine what you want a count "of". Because you added column_3, you need to write:
SELECT column_3, COUNT(*) AS Count
FROM table_name
GROUP BY column_3

If you wanted a count of all the rows, simply:
SELECT COUNT(*) FROM table_name


text:
Q: How to enable and disable GUI as need for each boot it to save RAM resources? For an old PC Desktop with 4GB of RAM based on 64bits. For experimental purposes - I want install Ubuntu Desktop - mostly for two purposes:

*

*Server purpose.

*Use the DVD reader/writer to do backup anytime (it is the reason to use the Desktop environment)

Note
This PC is going to be accessed mostly through SSH and only in person when a backup through the DVD writer is need it.
Goal
Therefore to save resources mostly of RAM - I want load Ubuntu by default as server environment - thus without GUI - until the GUI be need it to use it, it to work with Brasero.
I read the following tutorial and seems viable

*

*How to disable/enable GUI on boot in Ubuntu 20.04 Focal Fossa Linux Desktop
I am OK, if is need it do a reboot to change the type of environment from non-GUI to GUI and vice versa. It has sense to reflect the new settings.
My concern and
Question

*

*Is it the best approach to accomplish my goal? The use of the systemctl command?

I am assuming that when Ubuntu is loaded without GUI - as server - therefore at least 1GB to 1.5GB is not consumed because the GUI environment was not loaded from the beginning. Am I correct?
I did do this assumption because through VirtualBox for many VM I did do realize through htop command that Ubuntu Server saves 1/1.5GB of RAM against Ubuntu Desktop - but because here Ubuntu Desktop is used from the beginning and only by enable/disable the GUI - the expected behavior would be different


text:
Q: Simulando hora, fecha y alarma, escogida por el usuario Muy buenas noches, estoy trabajando en este formulario, el cual estoy simulando el cambio de hora, fecha y alarma, ya que con javascript hasta donde se no se puede modificar la hora y fecha, por eso estoy intentando hacerlo de esta manera,el cual el usuario selecciona la hora, la alarma y fecha, la cual se guarda en una variable y se imprime.
creo que se puede simplificar mas el codigo, solo que no tengo tanta experiencia.
la alarma no he podido adaptarla a la hora seleccionada, me podrían ayudar a correjirme los errores que tengo en el código lo dejo aquí
jsfiddle.


text:
Q: Cannot terminate a shell command with Ctrl+c Would someone please tell me why below bash statement cannot be terminated by Ctrl+c properly?
$( { ( tail -fn0 /tmp/a.txt & )| while read line; do echo $line; done } 3>&1 )

I run this statement, then two bash processes and one tail process are launched(got from ps auxf), then input Ctrl+c, and it won't quit to the bash prompt, at this moment, I see the two bash processes stopped, while the tail is still running, then I input something into /tmp/a.txt, then we could get into bash prompt.
What I want is, input Ctrl+c, then just quit into bash prompt without any relevant process left.
It will be more appreciative that someone explains the exact process of this statement, like a pipe causes the bash fork, something redirect to somewhere, etc.
Updated at Oct 9 2014:
Here provide some update in case it's useful to you.
My adopt solution is alike with 2 factors:

*

*use a tmp pid file
( tail -Fn0 ${monitor_file} & echo "$!" >${tail_pid} ) | \
while IFS= read -r line; do
    xxxx
done

*use trap like: trap "rm ${tail_pid} 2>/dev/null; kill 0 2>/dev/null; exit;" INT TERM to kill relevant processes and remove remain files.
Please note, this kill 0 2 is bash specific, and 0 means all processes in the current process group.
This solution used a tmp pid file, while I still expect other solution without tmp pid file.

A: It works to trap the INT signal (sent by Ctrl-C) to kill the tail process.
$( r=$RANDOM; trap '{ kill $(cat /tmp/pid$r.pid);rm /tmp/pid$r.pid;exit; }' SIGINT EXIT; { ( tail -fn0 /tmp/a.txt & echo $! > /tmp/pid$r.pid  )| while read line; do echo $line; done } 3>&1 )

(I use a random value on the PID file name to at least mostly allow multiple instances to run)


text:
Q: Test if all elements are equal with C++17 fold-expression I have a function taking a variadic parameter pack and at the beginning I want to check that all elements compare equal. Can I somehow use the new C++17 fold-expressions to write that succinctly as a one-liner? I was thinking
template<typename... Args>
void func (Args... args)
{
    ASSERT ((args == ...));

    // more code here...
}

but this doesn't work, as it compiles to code that first properly compares the last two arguments, but then compares the third-last argument to the result of the first comparison, which is a bool. What use-case could this type of fold expression possibly have (similar for args < ...)? Is there any chance I can avoid writing a dedicated recursive template to do this?

A: As suggested by Piotr Skotnicki, a simple solution is separate the first argument from the followings and check it with using && as fold operator
By example, the following function that return true if all arguments are equals
template <typename A0, typename ... Args>
bool foo (A0 const & a0, Args const & ... args)
 { return ( (args == a0) && ... && true ); }

Unfortunately this can't work with an empty list of arguments
std::cout << foo(1, 1, 1, 1) << std::endl; // print 1
std::cout << foo(1, 1, 2, 1) << std::endl; // print 0
std::cout << foo() << std::endl;           // compilation error

but you can add the special empty argument foo()
bool foo ()
 { return true; }

If, for some reason, you can't split the args in a a0 and the following args?
Well... you can obviously use the preceding foo() function (with special empty version)
template<typename... Args>
void func (Args... args)
{
    ASSERT (foo(args));

    // more code here...
}

or you can use the C++17 fold expression with comma operator and assignment as in the following bar()
template <typename ... Args>
bool bar (Args const & ... args)
 {
   auto a0 = ( (0, ..., args) );
   return ( (args == a0) && ... && true );
 }

Observe the initial zero in a0 assignment that permit the use of this solution also with an empty list of arguments.
Unfortunately, from the preceding auto a0 assignment I get a lot of warnings ("expression result unused", from clang++, and "left operand of comma operator has no effect", from g++) that I don't know how to avoid.
The following is a full working example
#include <iostream>

template <typename A0, typename ... Args>
bool foo (A0 const & a0, Args const & ... args)
 { return ( (args == a0) && ... && true ); }

bool foo ()
 { return true; }

template <typename ... Args>
bool bar (Args const & ... args)
 {
   auto a0 = ( (0, ..., args) );
   return ( (args == a0) && ... && true );
 }

int main ()
 {
   std::cout << foo(1, 1, 1, 1) << std::endl; // print 1
   std::cout << foo(1, 1, 2, 1) << std::endl; // print 0
   std::cout << foo() << std::endl;           // print 1 (compilation error
                                              //          witout no argument
                                              //          version)

   std::cout << bar(1, 1, 1, 1) << std::endl; // print 1
   std::cout << bar(1, 1, 2, 1) << std::endl; // print 0
   std::cout << bar() << std::endl;           // print 1 (no special version)
 }

-- EDIT --
As pointed by dfri (thanks!), for and empty args... pack, the values for the following folded expressions
( (args == a0) && ... )

( (args == a0) || ... )

are, respectively, true and false.
So return instruction of foo() and bar() can be indifferently written
 return ( (args == a0) && ... && true );

or
 return ( (args == a0) && ... );

and this is true also in case sizeof...(args) == 0U.
But I tend to forget this sort of details and prefer to explicit (with the final && true) the empty-case value.

A: The reason that doesn't work, unfortunately, is due to the fact that boolean operators don't chain in C++ like they do in other languages. So the expression:
a == (b == c)

(what your fold-expression would expand to) would compare a to either true or false, nothing to do with what b or c actually are. I was hoping the operator<=> would add chaining but apparently that part was dropped.
The fixes are that you have to break up the comparisons:
(a == b) && (b == c)

Of course that doesn't lend itself to folding very well, but you could instead compare everything to the first element:
(a == b) && (a == c)

Which is to say:
((a0 == args) && ... )

At that point, we just need to be able to pull out the first element. No problem, that's obviously what lambdas are for:
template <class... Args>
constexpr bool all_equal(Args const&... args) {
    if constexpr (sizeof...(Args) == 0) {
        return true;
    } else {
        return [](auto const& a0, auto const&... rest){
            return ((a0 == rest) && ...);
        }(args...);
    }
}

A: Here is how I do it in gcl library :
template <auto ... values>
constexpr static auto equal_v = []() consteval {
    static_assert(sizeof...(values) > 0, "gcl::mp::value_traits::equal_v : no arguments");
    constexpr auto first_value = std::get<0>(std::tuple{values...});
    static_assert(
            (std::equality_comparable_with<decltype(values), decltype(first_value)> && ...),
            "gcl::mp::value_traits::equal_v : cannot compare values");
    return ((values == first_value) && ...);
}();

or replacing static_assert by concept requirement :
template <typename ... Ts>
concept are_equality_comparable = requires(Ts ... values)
{
    {
        std::conditional_t<(std::equality_comparable_with<decltype(std::get<0>(std::tuple{values...})), decltype(values)> && ...), std::true_type, std::false_type>{}
    } -> std::same_as<std::true_type>;
};

template <auto ... values>
    requires(are_equality_comparable<decltype(values)...>)
constexpr static auto equal_v = []() consteval {
    static_assert(sizeof...(values) > 0, "gcl::mp::value_traits::equal_v : no arguments");
    constexpr auto first_value = std::get<0>(std::tuple{values...});

    return ((values == first_value) && ...);
}();


text: Q: How do I know when I've eaten too much Royal Jelly? Will the side-effect stay for a long time if i do? I understand consuming "too much" of Royal Jelly will cause you side effects. How much Royal Jelly is "too much"? Will that effect go away (after consuming golden elixir or sleeping)? Or will it stay with the character?


text:
Q: How to perform match on sum of two fields I have a query in MySQL that contains the following condition:
WHERE START_TIME < ? AND START_TIME+DURATION >= ?

How should I migrate this to MongoDB using Java driver and aggregation framework?
The first condition will become:
DBObject match = new BasicDBObject("$match", new BasicDBObject("start_time", "{ $lt : "+timestamp+"}") );

But I'm not sure about the second.
Thanks.
EDIT
I've tried to work with Asya Kamsky answer, this is what I got but it's not working:
BasicDBList dbList = new BasicDBList();
dbList.add("$start_time");
dbList.add("$duration");

DBObject matchLT = new BasicDBObject("$match", new BasicDBObject("start_time", new BasicDBObject("$lt",timestamp)));
DBObject project = new BasicDBObject("$project", new BasicDBObject("end_time", new BasicDBObject("$add", dbList)));
DBObject matchGTE = new BasicDBObject("$match", new BasicDBObject("end_time", new BasicDBObject("$gte",timestamp)));
//GROUP CODE GOES HERE
AggregationOutput output = collection.aggregate(matchLT, project, matchGTE, group);

A: Here's how you do it in Aggregation Framework, I'm sure you can translate this to Java:
db.collection.aggregate([ {$match: {start_time:{$lt:ISODate("xxxx-xx-xx")}}},
           {$project:{end_time:{$add:["$start_time","$duration"]}}},
           {$match:{end_time:{$gt:ISODate("yyyy-yy-yy")}}}
] );


text:
Q: When typing in editable ComboBox not showing DropDown list I'm working with ComboBox in WPF. ComboBox IsEditable property setted to TrueIsEditable="True". ComboBox has several items. When I'm typing it is showing item in ComboBox text, but not showing DropDown list.
XAML code:
 <ComboBox Name="uiComboBox" IsEditable="True">
        <ComboBoxItem>One1</ComboBoxItem>
        <ComboBoxItem>One2</ComboBoxItem>
        <ComboBoxItem>One3</ComboBoxItem>
        <ComboBoxItem>One4</ComboBoxItem>
        <ComboBoxItem>Two</ComboBoxItem>
        <ComboBoxItem>Three</ComboBoxItem>
    </ComboBox>

When I typing  "o" showing first item that starts with "o", in this case it is "One1"

When I  type "o" it should show me DropDown list with items that starts with "o" in this case 4 items, you can see in picture in below.
After researching I found:
 private void ComboBox_KeyUp(object sender, KeyEventArgs e)
    {
        uiComboBox.IsDropDownOpen = true;
    }

It is showing all not items that starts with letter i typed.
Any ideas to do that or maybe another control to use for this case?

A: Have you heard the term called "Roll your own"? That's what you will need to do or I am sure some one out there wants the same thing and there should be tons of information about this on the web.
Take a look at these:
Filter ComboBox items based on TextBox text
Dynamic filter of WPF combobox based on text input
I hope that helps!


text:
Q: How to Retrieve Knowledge Validation Status Picklist custom values? Validation Status is a standard picklist available in Lightning Knowledge (Knowledge_kav), however the field metadata is not available in Knowledge Settings or Knowledge Object. I even tried Standard value Set and its not available there as well.
I want to retrieve this field with Picklist values and deploy to another org via metadata. Please let me know if you have any solution for this issue?

A: Oddly enough if you create one in a scratch org it will be tracked as a StandardValueSet, but does not work with a metadata retrieve from a standard sandbox.
=== Source Status
STATE       FULL NAME                     TYPE              PROJECT PATH
──────────  ────────────────────────────  ────────────────  ────────────
Remote Add  KnowledgeValidationStatus     StandardValueSet

So I assume that this is not yet supported, but potentially a part of the ExpandedSourceTracking beta specific to scratch orgs.


text:
Q: How to decode an Opaque data which has obtained by pysnmp? I'm going to read data from an SNMP device by its OID via pysnmp library. However, I'm dealing with an error from Opaque type:
from pysnmp import hlapi

def construct_object_types(list_of_oids):
    object_types = []
    for oid in list_of_oids:
        object_types.append(hlapi.ObjectType(hlapi.ObjectIdentity(oid)))
    return object_types

def get(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(),
        context=hlapi.ContextData()):
    handler = hlapi.getCmd(
        engine,
        credentials,
        hlapi.UdpTransportTarget((target, port)),
        context,
        *construct_object_types(oids)
    )
    return fetch(handler, 1)[0]

def cast(value):
    try:
        return int(value)
    except (ValueError, TypeError):
        try:
            return float(value)
        except (ValueError, TypeError):
            try:
                return str(value)
            except (ValueError, TypeError) as exc:
                print(exc)
    return value

def fetch(handler, count):
    result = []
    for i in range(count):
        (error_indication, error_status,
         error_index, var_binds) = next(handler)
        if not error_indication and not error_status:
            items = {}
            print(var_binds)
            for var_bind in var_binds:
                items[str(var_bind[0])] = cast(var_bind[1])
            result.append(items)
        else:
            raise RuntimeError(f'SNMP error: {error_indication}')
    return result

print(get("192.168.100.112", [".1.3.6.1.4.1.9839.1.2.532.0",
                              '.1.3.6.1.4.1.9839.1.2.513.0'],
          hlapi.CommunityData('public')))

Out:
[ObjectType(ObjectIdentity(<ObjectName value object, tagSet <TagSet object, tags 0:0:6>, payload [1.3.6.1.4.1.9839.1.2.532.0]>), <Opaque value object, tagSet <TagSet object, tags 64:0:4>, encoding iso-8859-1, payload [0x9f780441ccb646]>), ObjectType(ObjectIdentity(<ObjectName value object, tagSet <TagSet object, tags 0:0:6>, payload [1.3.6.1.4.1.9839.1.2.513.0]>), <Integer value object, tagSet <TagSet object, tags 0:0:2>, subtypeSpec <ConstraintsIntersection object, consts <ValueRangeConstraint object, consts -2147483648, 2147483647>>, payload [10]>)]
{'1.3.6.1.4.1.9839.1.2.532.0': '\x9fx\x04A̶F', '1.3.6.1.4.1.9839.1.2.513.0': 10}

The first OID (.1.3.6.1.4.1.9839.1.2.532.0) returns an Opaque value (\x9fx\x04A̶F) and I don't know how I can convert it to a float value. I should add that, that is a temperature value of 25.5°C.

In other words, how can I reach the following values by each other?

*

*25.5

*encoding iso-8859-1, payload [0x9f780441ccb646]

*'\x9fx\x04A̶F'

A: Your value 0x9f780441ccb646 can be

*

*split into two floats, of which one is 25.589001, the other part is something else, or

*the middle is the representation of the pysnmp object (__repr__) without a known interpretation (probably MIB missing), or

*converted to a byte representation (with iso-8859-1 encoding) which is your string '\x9fx\x04A̶F'.

So the data is there, it just needs to be extracted from the SNMP packet. The proper way would be to give the corresponding MIB entry to pysnmp.
Alternatively (answering your second question), the manual way of decoding the bytes can be done with the Python's struct module.
import struct

data = 0x9f780441ccb646         # this is what you got from pysnmp
thebytes = struct.pack("l", data)
print(thebytes.decode('latin1'))
print(thebytes)
print(struct.unpack("ff", thebytes))

gives
F¶ÌAx
b'F\xb6\xccA\x04x\x9f\x00'
(25.589000701904297, 1.4644897383138518e-38)

instead of unpacking to two floats, the MIB will tell you how the other data should be interpreted, so instead of unpack("ff",… you might want something else, check out the available format specifiers, for example "fhh" would give (25.589000701904297, 30724, 159).
EDIT:
TL;DR:
data = '\0\x9fx\x04A̶F'
print("temperature: %f°C" % struct.unpack('>ff', data.encode('latin1'))[1])

temperature: 25.589001°C

To elaborate on the string representation: The bytes you see 'A̶F' are in a reversed order than the ones in my print statement 'F¶ÌA' because of the different endianess. The byte order is already corrected in the int-converted data 0x9f780441ccb646 that you give in your output and I used in the conversion example. If you want to start from the encoded string, you first need to convert it back to the correct memory representation:
data = '\0\x9fx\x04A̶F'       # (initial '\0' is for filling the 8-bytes in correct alignment)
thebytes =  data.encode('latin1')

But that's only half of the trick, because now the endianess is still wrong. Fortunately struct has the flags to correct for that. You can unpack in both byte-orders and choose the right one
print("unpacked little-endian: ", struct.unpack("<ff", thebytes))
print("unpacked big-endian:    ", struct.unpack(">ff", thebytes))
unknown, temperature = struct.unpack(">ff", thebytes)
print("temperature: %f°C" % temperature)

giving
unpacked little-endian:  (2.9225269119838333e-36, 23398.126953125)
unpacked big-endian:     (1.4644897383138518e-38, 25.589000701904297)
temperature: 25.589001°C

The correct endianess of the opaque packet is either part of SNMP standard (then probably "network-byte order" '!' is the correct one), or should also be given in the MIB together with the correct field types which need to be given as format specifiers. If your packets are always 7-byte long, you might try a combination that adds to 7 bytes instead of 8 (ff = 4+4), then you can also omit adding the \0 padding byte.

A: According to the TerhorstD's asnwer plus some changes and knowing that the Opaque frame consists of 7 bytes in which the 3 bytes of those are constant (\x9fx\x04 or 159\120\4 in decimal), I wrote the following code snippet to deal with that problem:
...

handler = get("192.168.100.112", [".1.3.6.1.4.1.9839.1.2.532.0",
                                  '.1.3.6.1.4.1.9839.1.2.513.0'],
              hlapi.CommunityData('public'))

for key, value in handler.items():
    try:
        if len(value) == 7 and value[0].encode('latin1')[0] == 159\
                and value[1].encode('latin1')[0] == 120\
                and value[2].encode('latin1')[0] == 4:

            data = value[3:]
            print(struct.unpack('>f', data.encode('latin1'))[0])
        else:
            print(value)
    except AttributeError:
        print(value)

Out:
25.589001
10

[NOTE]:

*

*Opaque is a little-endian format (> in struct).

[UPDATE]:
More wisely:
for key, value in handler.items():
    try:
        unpacked = struct.unpack('>BBBf', value.encode('latin1'))
        if unpacked[:3] == (159,120,4):
            '''Checking if data Opaque or not.'''

            print(unpacked[-1])
        else:
            print(value)
    except AttributeError:
        print(value)


text:
Q: Can I generate validation rules by @ORM annotations? consider this doctrine entity
class Product
{
     /**
      * @ORM\Column(type="string", length=24, nullable=false)
      */
     private $title;
}

Can I somehow generate @Asserts annotations by @ORM annotations.
So after this generation I would have this class.
class Product
{
     /**
      * @Assert\NotBlank()
      * @Assert\Length(max="24")
      *
      * @ORM\Column(type="string", length=24, nullable=false)
      */
     private $title;
}

A: You can't do it automatically. But possible to create custom generator for it.
Alternatively, you can create custom validator which validate entity based on ORM mapping;


text:
Q: Workflow automation: Makefile vs. Ant Whenever I notice that something in my workflow is a repeating task, I try to automate it.
For example the steps necessary to deploy something on a server. It's often a build, followed by a scp and finally some remote setup scripts:

*

*mvn package

*scp target/foobar.jar  server:

*ssh server install-foobar

*ssh server './bin/foobar restart'

I tend to write a small Makefile in such cases, which could look like
  deploy:
      mvn package
      scp target/foobar.jar server:
      ssh server install-foobar
      ssh server './bin/foobar restart'

How do you automate your workflows?
Is Ant the tool of choice? What are the Pros/Cons?

A: For Java development, I'd say Ant is the default choice.
Pro:
*

*good documentation,

*good IDE integration

*Lots of third-party extensions and tools
Con:
*

*Somewhat verbose (well, it's yet anothr XML format)

*Some things that should be simple aren't (e.g. any kind of looping)
I don't really have any experience using makefiles, so I can't say how they compare. Maybe you should simply use what your developers are more experienced with.

A: SCons is another good one.  And Capistrano seems to be well regarded although I haven't tried it.

A: I use shell and perl scripts

A: consider GAnt (http://gant.codehaus.org/). using Groovy's builder, it is much less verbose than an Ant build script

A: For python I tend to use fabric  for the deployment steps and setuptools for any building that is needed (not that usual for me :-)
Fabric understands how to copy files to servers, runing commands on the remote server (both as the standard user and as root).

A: one of the reasons most build systems are so complex is that folks try and do to much in them. sometimes complementing a build system with a driver-script that takes care of non compilation/linking tasks is a good way to go. There is no single way. Its hard to answer the question without see the project source code structure and all the tasks that need to be done. But you might want to take a look at Rake as it would complement Make, Ant, and Maven

A: Rake is my choice.

A: I find Ant and its XML configuration syntax a bit unwieldy and there are some things that should be trivial but are very hard to get in Ant. I prefer for that kind of automation SCons.
There is another tool precisely made to deploy stuff that I used for a bit and was pretty cool, but I forgot its name, maybe somebody else remembers it :).

A: I use scripts (shell, perl, python) or makefiles. I do not like Ant and SCons


text:
Q: Use a personal program in Firebreath I'm building a plugin using Firebreath. I made a personal method in ABCPluginAPI.cpp called exe_program() and I would like to call another program using popen called my_program. All the files are into firebreath/projects/ABCPlugin/.
My method is:
string ABCPluginAPI::exe_program()
{
    FILE * pPipe;
    fd_set readfd;
    char buff[1024];
    char command[128];
    int ret;

    strcpy(command, "my_program");

    if (!(pPipe = popen(command, "r"))) {
         // Problem to execute the command
       return "failed";
    }
    while(fgets(buff, sizeof(buff), pPipe)!=NULL){
        cout << buff;
        return buff;
    }
}

The problem I have is that the plugin is not running my_program, actually if I execute the pwd command, it shows my $HOME directory. pwd works because is a general command but I don't want to put my program into $PATH variable because this plugin must be portable.
Probably Firebreath use a special directory to refer to this kind of files or something similar.

A: You probably need to specify a full path and filename of the application you want to run; the current working directory is not garanteed to always be the same value.
From the Tips and Tricks page of firebreath.org there is code you can add to your PluginCore-derived object that will give you the full path and filename of your plugin file:
// From inside your Plugin class (that extends PluginCore)
std::string MyPlugin::getFilesystemPath()
{
    return m_filesystemPath;
}

You can take that path, strip off the last part, and change it to your executable filename; as long as you place the executable in the same directory as your plugin that should work fine.  Alternately you could install it in some other well-known location.
Note that to call a method on your main Plugin object from your JSAPI object there should be a helper method getPlugin() on your JSAPI object (if you used fbgen to generate it):
std::string pluginPath = getPlugin()->getFilesystemPath();

Hope that helps


text:
Q: Not showing next/previous button using IQKeyboardManagerSwift I am using IQKeyboardManagerSwift in my application. I can not see next/previous button to toolbar. I attached screen shots of my aliments.
IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.enableAutoToolbar = true
IQKeyboardManager.shared.toolbarPreviousNextAllowedClasses = [UIView.self, UIStackView.self]

Please help me.

A: IQKeyboardManager's Next/Previous button doesn't work on input fields if they are inside multiple subviews.
Assign self.view of IQPreviousNextView class from storyboard. It will start working.


text:
Q: JQL Date and Hours I am taking my first steps in Jira automations and I had the following query:
Can I define actions to be executed at a specific time of a day of the week?
I have created the following rule, which I would like for example to be executed on Saturdays. Is it possible to define range of hours and dates?
Thank you very much![enter image description here][1]
JQL: updated >= startOfDay(8h) AND updated <= startOfDay(11h)