text:
Q: Magento 2 : Swatches not display when use plugin around I used around plugin to call custom phtml in category list page. It's working proper. But, In configurable product it's hide to display swatches.
I upload here my files code. Which function should I need to use in plugin to working perfectly ?
di.xml :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Block\Product\ListProduct">
        <plugin name="custom-module-category" type="Vendor\Module\Plugin\File" sortOrder="16"/>
    </type>
    <virtualType name="Magento\CatalogSearch\Block\SearchResult\ListProduct">
        <plugin name="custom-module-search" type="Vendor\Module\Plugin\File" sortOrder="17"  />
    </virtualType>
</config>

File.php :
public function aroundGetProductDetailsHtml(
    \Magento\Catalog\Block\Product\ListProduct $subject,
    \Closure $proceed,
    \Magento\Catalog\Model\Product $product
    ) {
    $data = $this->_productDocFactory->create()->load($product->getId(), 'product_id');
    if(count($data->getData())){
    return $this->layout->createBlock('Vendor\Module\Block\File')->setProduct($data_id)->setTemplate('Vendor_Module::file.phtml')->toHtml();
    } else {
    return '';
    }
    }

A: You didn't anything in else condition. So, it was display blank. Use this below code :
 public function aroundGetProductDetailsHtml(
    \Magento\Catalog\Block\Product\ListProduct $subject,
    \Closure $proceed,
    \Magento\Catalog\Model\Product $product
) {
    $data = $this->_producyFactory->create()->load($product->getId(), 'product_id');
    if (count($data->getData())) {
        return $this->layout->createBlock('Vendor\Module\Block\File')->setProduct($data)->setTemplate('Vendor_Module::file.phtml')->toHtml();
    } else {
        $result = $proceed($product);
        return $result;
    }
}


text:
Q: setTimeout in loop in react native I am trying to implement logic for smart search. I am using below code in onChangeText on TextInput
 clearTimeout(this.timeout);
        this.timeout = 0
        this.timeout = this.timer(text);

Here i am clearing last timeOut and setting new one in timer method
timer = (searchText) => {
        const { selectedFilter } = this.state

        setTimeout(function () {
            //Hit Api
            console.log("new instance" + selectedFilter)

        }, 2000);
    }

Above code is working fine but there is one issue, previous listener is not getting cleared. so i am getting console multiple time. Please suggest me what i am doing wrong.
Thanks in advance.

A: You just need to return the value returned by the setTimeout call, like this:
timer = (searchText) => {
    const { selectedFilter } = this.state

    return setTimeout(function () {
        //Hit Api
        console.log("new instance" + selectedFilter)
    }, 2000);
}

Also, you don't need to do this.timeout = 0 just before this.timeout = this.timer(text);

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does "Has been cloaked" mean? I'm working on moving some types to a matching file refactoring in a VB.NET application written years ago by someone whose no longer with us. He tended to put lots of classes in a file. For example, he'd put a dozen classes into a BaseClases.vb file. It has become hard to find those classes, so I started performing this refactoring to help me as I support the app.
However, every time I'd refactor a type into a separate class file, VS 2019 would generate a message that reads like this:
"The item SomeClass.vb has been cloaked. See output tool window for information on any other errors."
I'd look at the Errors window but didn't see anything obvious. Although there's lots of other errors unrelated to this, so it might be there, and I've missed it in the crowd of errors.
I've searched SO for the phrase "has been cloaked". It only brought up 2 posts, neither of which addressed the situation I'm in.
So, what does it mean to have a new class cloaked? From what is it being cloaked?


text:
Q: Radian measure in sin in R? I want to calculate the following in R:
sin(52.517°)
and this should be equal to 0.79353. But when I code
sin(52.517)

I get
0.777119

So how can I get the 0.79353. I am not good in math, but I know something is not working with degrees and the radian measure here in R.

A: it works
1 degree =0.0174532925 radians
sin(52.517*0.0174532925)
[1] 0.7935339

EDIT
refered from here
 degrees.to.radians<-function(degrees=45,minutes=30)
{
if(!is.numeric(minutes)) stop("Please enter a numeric value for minutes!\n")
if(!is.numeric(degrees)) stop("Please enter a numeric value for degrees!\n")
decimal<-minutes/60
c.num<-degrees+decimal
radians<-c.num*pi/180
radians
}
sin(degrees.to.radians(52.517,0))
[1] 0.7935339

A: well, let's just function things up
coss <- function(a){
  a=cos(a*pi/180)
  return(a)
}
sinn <- function(a){
  a= sin(a*pi/180)
  return(a)
}
tann <- function(a){
  a= tan(a*pi/180)
  return(a)
}

A: From the help page on sin which you can read by typing in ?sin in the R console:

Angles are in radians, not degrees (i.e., a right angle is π/2).

So by default, the trigonometric functions take radians as input and not degrees. To get the sin(52.517) you need to convert those degrees to a radian measure first:
52.517 degrees = 52.517 * (pi/180) = sin(52.517*(pi/180)) = 0.916...

If you do:
sin(52.517*(pi/180))

you get the wanted 0.7935339.


text:
Q: Topological sorting of C++ data structures Before I start, I first have to mention that with the term "graph" I'll refer to an image displaying a structure. Due to my visual impairment, I can neither imagine nor draw them. I can look at them and understand - but I have a difficult time making them up myself.
I am working on a build tool that uses a scripting language to generate targets, which are processed and split into tasks. A task is represented as a data structure: https://github.com/IngwiePhoenix/IceTea/blob/master/src/main.cpp#L98
As you can see, the Task class takes note of it is a master (the actual result of the process) and stores a reference - note, one reference only, not an array - to its child and parent - if any.
So far I am able to fill the task queue with all required tasks and send it into the executor void Run(void*): https://github.com/IngwiePhoenix/IceTea/blob/master/src/main.cpp#L1107
But here come the problems:

*

*The tasks are not properly sorted, and the build will become a mess if a previous build is canceled and then started again. If you have a.cpp and b.cpp and your last build terminated at either of the two while the other is not build, it will result in the parent task being ran twice. A proper sorting mechanism - a topological one - would very likely solve this. For now, I have classified this as a non-existent dependency tracking.

*When one target depends on another, then the target depending on the other may end up being in the queue before the one it depends on. Imagine that you have libfoo.a and bar.exe. It can happen, that the task to compile bar.exe is before the one that creates libfoo.a. That means, that we'd run into a linking error.
Currently, the program is structured with a thread pool that pulls tasks from the queue and runs them. But after I have investigated more into the Ninja tool, this logic might change; there will be a thread pool that only executes commands generated from the scripting language. However, this has to wait, for now. Therefore, I am making the tool run on a single thread only, to simulate the behavior that I actually want; one command running after another.
The problem that I am mainly facing though, stays to be the sorting mechanism. From my studies on build tools, they tend to use what's called a DAG and topological sorting. Now, neither could I find a good explanation on how to write a topological sorting algorithm nor did I figure out how it works at all. I know that there are the constants u and v. But I am unable to find a way to implement it.
So far, I have understood that it is a linear graph. Let's assume the following structure:
myApp.exe
    - main.o
    - util.o
    | libfoo.a
        - foo_a.o
        - foo_b.o

This is very straight forward. There is one result, and one dependency. But what if we have two results depending on the same libfoo?
myApp.exe       libbar.so
    - main.o        - barlib.o
    - util.o
-------------------------
            | libfoo.a
                - foo_a.o
                - foo_b.o

And that is where I am already stuck at.
Can you maybe explain to me how to implement a topological algorithm, and what a DAG actually is? It would be really helpful, because I am very honestly hitting a barrier here that is hard to overcome. Thank you in advance!
A side-note: I want to keep the tool as small as I can, therefore I can not add stuff like Boost.Graph, which I have seen as a search result.

A: Okay, first things first: A DAG is a Directed Acyclic Graph.

*

*A graph is a data structure that has nodes which are connected in
some way. For instance, a map is a graph, where the intersections are
the nodes and the roads are the edges.

*A directed graph is a graph with some sort of direction on the edges;
for instance, many roads are undirected (please stay on the correct
side of the road), but some are one-way.

*An acyclic graph is a graph without any cycles; that means that once
you leave a node, you can't get back to it.
You can't sort a cyclic graph; which part of the cycle would come first? But you can sort an acyclic graph, and the result is a 'topological sort.' As you pointed out (maybe accidentally) in your second example, multiple topological sortings may be valid for the same graph.
In order to handle the dependencies in your problem, you will have to use a graph. However, since you know that it will be that it will be acyclic, you can write your own, very concise graph class.
struct node {
  string name;
  vector<node*> out_neighbors;
  vector<node*> in_neighbors;
}

You would store all the nodes in a single array, graph, and the nodes keep a list of the nodes that come after them in out_neighbors (this is called an "adjacency list" format).
Now how do you sort them? Well, you want them sorted so that nodes do not depend on nodes that come later. First, you want to find all the nodes that have no incoming edges (i.e., don't depend on anything).
queue<node*> free;
for(int i=0; i<n; ++i)
  if(graph[i].in_neighbors.size() == 0)
    free.push(&graph[i]);

Next, you are going to use these to find other nodes.
queue<node*> topsort;         //this is going to be the sorted nodes
while(free.size() > 0) {
  node* top = free.front();   //remove the first element from the graph
  topsort.push(top);
  free.pop();

  for(int i=0; i<top->out_neighbors.size(); ++i) {
    node* neighbor = top->out_neighbors[i];
    neighbor->in_neighbors.erase(
      find(neighbor->in_neighbors.begin(), neighbor->in_neighbors.end(), top)
    );
    if(neighbor->in_neighbors.size() == 0)
      free.push(neighbor);
  }
}

At the end of this, topsort will be a list of the node pointers in a sorted topological order. However, all of your incoming edges have been removed from the graph, as well (this can easily be rebuilt using the outgoing edges).

Some suggestions:
First, your Tasks are already like the simple structure I described here, except that they only have one parent and child pointer; why not have a list of parents (incoming) and children (outgoing)? Then you can sort the Task objects themselves.
Second, once it is sorted topologically, you can run things in threads; so long as all of my incoming edges have been compiled, I'm free to go, too.


text:
Q: Ignore space without deleting space in a string while inserting into SQL database I am reading data from a text file into a SQL database using C++ and embedded SQL.
Here is the text file "employee.txt":
1000 Smith Joe 35000.00

Where empId=100, empName= "Smith Joe" and empSal = 35000.00.
The statements I've tried so far do not work properly with the space between the first and last name in the employee.txt file. It is reading the space between "Smith" and "Joe" to mean that Smith and Joe are two separate items rather than a string with a space. Here is my code:
inFile >> empId;

while (!inFile.eof())
{
    inFile >> empName;
    inFile >> empSal;

    string sql;
    sql = "insert into Employee values (\'"+ empID + "\', \' "+empName+ " \', \'"
           +empSal+ "\')";

    mysql_query(connect, sql.c_str());
    inFile >> empSal;

}

If I remove the space from the text file ("SmithJoe" rather than "Smith Joe"), the database populates properly.
I would like to ignore the white-space while reading into the file, without deleting the white-space, in order to put the entire string "Smith Joe" into one cell of the database.
Is there a way to ignore the white space between the two names without deleting the space so that the entire string "Smith Joe" can be read into one cell of the database?
Thankyou

A: *

*Read in the whole line. "1000 Smith Joe 35000.00"

*Find the first space. Split at that space. "1000", "Smith Joe 35000.00"

*Find the last space in the remainder of the line. Split at that space. "1000", "Smith Joe", "35000.00"

A: You can try by reading the empName into two variables like empFirstName and empLastName, then concat them while inserting into database.


text:
Q: is there a method to trigger paste (ctrl+v) event to any application? I have a code that triggers PASTING to any 3rd party application   by sending ctrl+v (see below),  but this does not seem to work with CITRIX. is there any other method to trigger ctrl+v than keyb simulation?
keybd_event(VK_CONTROL, Lo(MapVirtualKey(VK_CONTROL,0)), 0,0);
keybd_event(86, Lo(MapVirtualKey(86,0)), 0,0);
keybd_event(86, Lo(MapVirtualKey(86,0)), KEYEVENTF_KEYUP,0);

A: Maybe, you can send a WM_PASTE message to the application?

A: Ah, the nice problems with Citrix!

*

*I would 1st check on the receiving application side that you actually have something in the clipboard. Try to paste manually there. If it's empty, it's not an automation/keyboard hook problem.

*If the clipboard content is indeed available, I would then try different ways to communicate with the receiving application: sending windows messages (WM_PASTE, but also others in case of failure to see if any can go through), but also look if you can do DDE.

A: You can try PostKeyEx32
I Wrote a article in Portuguese, but you can read the code, it is simple.
http://www.cesarromero.com.br/simulando-keypress-com-postkeyex32/
You can send CTRL + Vm like this:
PostKeyEx32(Ord('V'), [ssCtrl], False);

A: I think the critical statement here is -- with CITRIX.
My experience with inter-communication with citrix applications is that many things which work fine on a normal desktop, fail when run in a citrix environment.  I would first try to send a WM_PASTE message as Gamecat suggested, and if that fails you might want to make sure that your clients are running your application thru a citrix desktop, NOT by running the applications directly from a shortcut on their desktop.  When a citrix application is launched from an external shortcut, it gets a different session than when it is launched from an internal shortcut on the citrix desktop.


text:
Q: Recover my database structure from from files It was my habit to uninstall easyphp without losing my database...But this time, I've uninstalled my easyphp and re-installed it again, but when I tried to view my database, I see that all tables have been lost.
Actually, my tables are all empty, because I've just finished the database conception and I did not yet begun the project online.
But the tables are about 40 table, and I don't want to recreate them again.
so I've viewed my mysql directory, and I see that *.frm files with the names of my tables.
How can I recover my tables structure (not data) from those *.frm files?

A: I have tried and tried to do this after reading lots of suggestions on the Internet, but the answer is no.
Either find an earlier backup or, as I had to do, redo all your tables.  This is taking me about 2 hours, but I'm going to back up my files a lot more often now :)
Use this as a learning experience.


text:
Q: imagemagick not responding After installing of imageMagick on a Debian Machine (debian_version 6.0.2)
Running this command:
/usr/bin/convert -scale "90x>" -quality 80 -strip "/right/path/source.jpg" "/right/path/destination.jpg"

doesn't save the destination image in /right/path/
and returns no errors.
"convert" is found into /usr/bin/ so that's where the command should be launched from...but nothing happens...
permissions are set "775" for each folders i'm saving the file in.
writing:
echo exec("whoami");

works and returns "www-data" wich has any kind of permissions
Any clue why/what to do?
Thanks.


text:
Q: Using regular expression? I have two data testing12334 which can be written as
testing[0-9]*$

in regular expression then I have testing33ab_1abckd which I can write as
testing[0-9][a-z][_][0-9][a-z].

I am trying to make one reg exp that works for both. Struggling any insight?
UPDATE: in shell(.ksh)

A: You can use:
\btesting\w+\b

RegEx Demo
Or in shell you can use equivalent:
grep -E '\btesting[[:alnum:]_]+\b'

A: Make the suffix part optional
testing[0-9]*([a-z][_][0-9][a-z]+)?$

In basic regular expressions (e.g. traditional grep and sed), you need to backslash the metacharacters. For extended regular expression syntax (basically grep -E and most everything newer than that, save for Emacs) this should work as-is.


text:
Q: How to filter case-insensitive in a JTable i try to filter my JTable with this code:
String eingabe = eingabeF.getText();
RowFilter.regexFilter(".*" + eingabe + ".*", 1)

it works very well. BUT i want to filter it case-insensitive. All the values in my Column "1" have upper-cases at the beginning.
I tried this:
String eingabe = eingabeF.getText();
setRowFilter(RowFilter.regexFilter(("?i") + Pattern.quote(".*" + eingabe + ".*"), 1));

but i always get the following Error-message:
Exception in thread "AWT-EventQueue-3" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
?i\Q.*f.*\E

A: First of all, the embedded case insensitive flag is "(?i)", rather than ("?i"). Secondly, you do not need to put ".*" around your string. The matcher will find it anywhere within the field as long as you do not surround it with "^" and "$". It is much simpler to initialize the filter as follows:
RowFilter.regexFilter("(?i)" + eingabe, 1);


text:
Q: Should multiple return values be used for Try...() style functions? This is a code style question so I am really after opinions.
Now that C# has multiple return values, should the bool TrySomething(..., out T result) pattern that is familiar to .NET developers be updated to (bool, T) TrySomething(...)?  I can't make up my mind.


text:
Q: MvxListView and scrolling down I'm using an MvxListView that is bound to an observablecollection to display chat messages. I found a way that the listview always scrolls down to the bottom with these 2 attributes:
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"

This works great when I add a message to the observablecollection via a command (when I send a message myself), but when I receive a message (via signalr) via the viewmodel and then add the message exactly the same way to the observablecollection, the ListView is updated but it doesn't scroll down. When I scroll down manually the message is there, it just doesn't scroll down automatically. I'm thinking this might have something to do with the message arriving via signalr, because it's an async callback.
I tried to manually force the listview to scroll down in an MvxAdapter like this:
   public override void NotifyDataSetChanged()
    {
        base.NotifyDataSetChanged();
        ((FragmentActivity)_context).RunOnUiThread(() =>
        {
            _list.SetSelection(this.Count-1);
        });
    }

and then call that explicitly when a message arrives but that doesn't do anything either.
Help?

A: Just saw this answer from Slodge:
Advice on where and when to use ObservableCollection in MvvmCross
The UI updates must be done synchronously. And thinking about it, it makes sense indeed. The answer for me was to use:
MvxMainThreadDispatcher.Instance.RequestMainThreadAction(() => {
    // fill your collection in the viewmodel and do a propertychanged
});


text:
Q: React.js pass parameters with Router not in URL Hi I want to move from one page to another and pass paramters search and type. Can I achieve this with react router without these parameters in the URL ?
I am looking at this https://github.com/rackt/react-router/blob/master/docs/guides/overview.md#dynamic-segments and the solutions using <RouteHandler {...this.props}/> but it is not working until I pass params to the url.
Is there any solution for that ?
EDIT 1. Routes:
<Route name="app" path="/" handler={App}>
    <Route name="realestates" handler={RealEstatesPage}/>
    <Route name="realestatesPrefiltered" path="realestatesPrefiltered/:search/:type" handler=RealEstatesPage}/>
    <Route name="realestate" handler={RealEstateDetails}/>
    <DefaultRoute handler={MainPage}/>
</Route>

A: The link you mentioned outlines the two different strategies. First, dynamic segments are just parameterized URLs, where parameters are sent as part of the URL path instead of in the query string. So these would need to be publicly visible.
Second, you can use props. This is the only supported option for passing things down "behind the scenes." In addition, it's the preferred method in React. The question is, where can this happen?
One option is to pass the values in at the top-level, from within Router.run(). This is outlined in the link above, with each nested handler passing the props down, either explicitly, like <RouteHandler search={this.props.search} />, or wholesale using spread attributes like <RouteHandler {...props} />.
Since you only want it to happen for a subset of pages, you could use nested routes, wherein the parent route handler owns the properties in question as part of its state. It would then just pass them to every child as normal props in the same way as the above case.
For example, your route map might look like this:
<Route name="app" path="/" handler={App}>
    <Route name="realestates" handler={RealEstatesPage}/>
    <Route name="realestatesPrefiltered" handler={RealEstatePrefiltered}>
       <Route name="homes" handler={RealEstateHouseDetails}/>
       <Route name="apartments" handler={RealEstateHouseDetails}/>
       <Route name="land" handler={RealEstateLandDetails}/>
    </Route>
    <Route name="realestate" handler={RealEstateDetails}/>
    <DefaultRoute handler={MainPage}/>
</Route>

Then your RealEstatePrefiltered component might look like this:
RealEstatePrefiltered = React.createClass({
    getInitialState: function () {
        return { search: '', type: '' }; // Update from store or event.
    },
    render: function() {
        return <div>
            <RouteHandler search={this.state.search} type={this.state.type} />
        </div>;
    }
});

The only question left is, how do you change the state on this component? You could use a Flux store for this, or you could just set up a global event and have this component watch for changes.

A: you can use state in history, like this
history.push({
  pathname: '/about',
  search: '?the=search',
  state: { some: 'state' }
})

A: In your first component, you can trigger this onCick of a link or button
browserHistory.push({
    pathname: `/about`,
    search : 'search'
    state: {
        type: 'type'
    }
});

In your other component, you can now grab them like:
constructor(props) {
    super(props);
    this.state = {
        search: props.location.search,
        type: props.location.state.type
    }
}


text:
Q: MVC State - Object is null I'm sure this has a simple answer. Forgive my ignorance; after 15 years of ASPNET WebForms this newfangled web v2.0 stuff is kicking my rear.
I'm trying to understand why my WebUser object is null on HttpPost.
So I have this controller action:
[HttpGet]
public ViewResult PrivateKey()
{
  var pk = new PrivateKey { WebUser = GetWebUserFromSession() };
  return View(pk);
}

This works fine and my razor view can access the members of PrivateKey.WebUser without issue.
The problem arises on the HttpPost action:
[HttpPost]
public ActionResult PrivateKey(PrivateKey pkey)
{
  if (string.IsNullOrEmpty(pkey.Value))
    return View(pkey);

  // pkey.WebUser is always null :(
  // TestKeyAgainstMockCipher(pkey.Value, pkey.WebUser);

  InsertSecuredMasterKeyIntoSession(pkey.Value);
  return RedirectToAction("Index", "Home");
}

So for a reason that I'm sure is totally legitimate, my PrivateKey object comes through the HttpPost okay but the referenced WebUser property contained within the PrivateKey object is always null.
I'm not sure if MVC requires a [Serializable] attribute be placed on the WebUser property or if I'm using the HttpPost incorrectly or even if its just accepted practice in MVC to continually run back to the I/O datastore to constantly fetch data rather than maintaining a standard object oriented data structure in memory to be passed around.
If it would help, here's the view I'm trying to get working:
@model KeePassWeb.Domain.Models.PrivateKey

@{
  ViewBag.Title = "PrivateKey";
  Layout = "~/Views/Shared/_MasterPage.cshtml";
}

@using (Html.BeginForm())
{

                @Html.PasswordFor(x =>x.Value, new { @class = "form-control", id="txtMasterPass", style = "width:65%", placeHolder = "Password" })
            <input Id="btnMasterPass" type="submit" value="Submit" class="submit" />

            @if (string.IsNullOrEmpty(@Model.WebUser.Padding)) {
                @:This is your first login. Please create a private key passphrase.
            }
            else {
                @:Please enter your private key to access your wallet.
            }

}

In short, I'm confused why the httpPost controller action is receiving a valid PrivateKey object from the postback but the objects contained within the PrivateKey object are always null.
Thanks in advance!
--Oldtimer :)

A: Looks like your form is only posting back one of the properties. If you don't need it in your form then just capture it again during the post or change your view model appropriately.

A: Thank you very much everyone for the help. Adding the following code into my PrivateKey view solved the problem (as @Reddy suggested)
@Html.HiddenFor(x => x.WebUser.Padding)
However, @Stephen Muecke and @gabriel make excellent points and I think I'm going to need to re-think the process flow of this application. Its currently a Webforms website and its written in a desktop application style, where objects are serialized and deserialized only when a new session is created/closed and these objects are passed around to all the pages whether those pages actually need all this data or not.
After digging into MVC and getting a better understanding of how Http actually works, I'm thinking this needs to change so only the data that is really needed is fetched and passed through the pipeline.
Thanks again everyone!


text:
Q: Failing AWS Serverless contact form request I'm a newbie to all this so it may be something obvious but I cannot get my contact page to work for a static website hosted on AWS S3, I've set it up via API>Lambda>SES and when I've ran the test on the AWS console side of things it works fine and I receive the test email. I'm testing the HTML and JavaScript in Visual Studio Code, the html seems to be linking to the Jscript i.e. if I don't fill out the contact form correctly such as not enough digits in the phone number the prompt to enter a correct number. But whenever I click submit I just get unsuccessful and no email. The endpoints in the Jscript are definitely correct. Emails in the Lambda code are correct. Could it e anything to do with regions? I've attached the code I've used below. Hope someone can help, it's driving me crazy. Thanks.
HTML

    <form id="contact-form" method="post"></form>

Name:

                                <input type="text" style="height:35px;" id="name-input" placeholder="Enter name here…" class="form-control" style="width:100%;" />

Phone:

                                <input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;"/>

Email:

                                <input type="email" style="height:35px;" id="email-input" placeholder="Enter email here…" class="form-control" style="width:100%;"/>

How can we help you?

                                <textarea id="description-input" rows="3" placeholder="Enter your message…" class="form-control" style="width:100%;"></textarea>

                                <button type="submit" onClick="submitToAPI(event)" class="btn-primary btn-block border-0 py-3";>Get an Appointment2</button>

                            </form>

`
JAVASCRIPT

`

function submitToAPI(e) {

    var URL = "https://123456789.execute-api.eu-west-2.amazonaws.com/test";

         var Namere = /[A-Za-z]{1}[A-Za-z]/;
         if (!Namere.test($("#name-input").val())) {
                      alert ("No no no !Name can not less than 2 char");
             return;
         }
         var mobilere = /[0-9]{10}/;
         if (!mobilere.test($("#phone-input").val())) {
             alert ("Please enter valid mobile number");
             return;
         }
         if ($("#email-input").val()=="") {
             alert ("Please enter your email id");
             return;
         }

         var reeamil = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,6})?$/;
         if (!reeamil.test($("#email-input").val())) {
             alert ("Please enter valid email address");
             return;
         }

    var name = $("#name-input").val();
    var phone = $("#phone-input").val();
    var email = $("#email-input").val();
    var desc = $("#description-input").val();
    var data = {
       name : name,
       phone : phone,
       email : email,
       desc : desc
     };

    $.ajax({
      type: "POST",
      url : "https://123456789.execute-api.eu-west-2.amazonaws.com/Test",
      dataType: "json",
      crossDomain: "true",
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify(data),

      success: function () {
        // clear form and show a success message
        alert("Successfull");
        document.getElementById("contact-form").reset();
    location.reload();
      },
      error: function () {
        // show an error message
        alert("not this time m/c");
      }});

}

`
LAMBDA CODE
`

var AWS = require('aws-sdk');
var ses = new AWS.SES();

var RECEIVER = '\<MYemail\>';
var SENDER = '\<MYemail\>';

var response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json","Access-Control-Allow-Origin": "\*"
},
"isBase64Encoded": false,
"body": "{ "result": "Success"\\n}"
}

exports.handler = async function (event, context) {
console.log('Received event:', event);
sendEmail(event, function (err, data) {
context.done(err, null);
});
return response;
};

function sendEmail (event, done) {
var params = {
Destination: {
ToAddresses: \[
RECEIVER
\]
},
Message: {
Body: {
Text: {
Data: 'name: ' + event.name + '\\nphone: ' + event.phone + '\\nemail: ' + event.email + '\\ndesc: ' + event.desc,
Charset: 'UTF-8'
}
},
Subject: {
Data: 'Website Referral Form: ' + event.name,
Charset: 'UTF-8'
}
},
Source: SENDER
};
ses.sendEmail(params).promise();
}

`

The endpoints in the Jscript are definitely correct. Emails in the Lambda code are correct. I've attached the code I've used below. Hope someone can help, it's driving me crazy. Thanks.


text:
Q: Some translated strings do not take effect With the site update, some translated strings have been "discarded".
We've re-added the new translation, but the changes don't take effect.
Bug report on ja.SO meta

"$count$ questions with new activity"

$minutes$ mins ago

Add a comment

Enter at least $min$ characters

A: I confirmed that this problem has been resolved as of 2022-02-02.


text:
Q: "Access denied" error talking to MySQL I am getting this warning on line 25:

Warning :
Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' >(using password: NO) in C:\xampp\htdocs\shadaab\register.php on line 25
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:\xampp\htdocs\shadaab\register.php on line 25
Access denied for user 'ODBC'@'localhost' (using password: NO)"

I have following SQL query on line 25:
$result=mysql_query("SELECT email FROM user WHERE email='$email'")or die(mysql_error());

A: The error message means:

*

*You have not connected to database (using mysql_connect and mysql_select_db)

*If you have specified mysql_connect, you are not specifying correct username and password to the mysql_connect function.

Here is how you can connect to your db before running your SQL queries:
$con = mysql_connect('server address', 'username', 'password') or die(mysql_error());
mysql_select_db('your db name') or die(mysql_error());

More information on official documentation.

A: It seems that you provide invalid data in mysql_connect. Check user/password.

A: Looks like a connection problem, check that you are calling mysql_connect above that line, and that your settings (password, host name, database name) and permissions are correct. Docs


text:
Q: Optimally cutting a stick at specified locations
You have to cut a stick with length l into several pieces. Cuts have to be made at locations c1, c2, c3, ..., cn, where ci is an integer between 1 and n-1 (inclusive). The cost of a cut is equal to the length of the stick on which it is made. What should be the order of the cuts to minimize the overall cost of the operation?
For example, consider a stick of length 10 and cuts have to be made at locations 2, 4, 7. You could cut the sticks in the order given. The first cut would cost 10, since the stick is of length 10. The second cut would cost 8, since the remaining stick on which the cut is made is of length 10 - 2 = 8. The last cut would cost 6, since the length of the remaining stick is 10 - 4 = 6. The total cost is 10 + 8 + 6 = 24
But if we cut the stick in the order: 4, 2, 7, we get the cost of 10 + 4 + 6 = 20 which is better for us.
Design an algorithm to solve the problem.

I'm pretty sure this is a DP problem. A tantalizing recurrence relation I could see was the fact that if we cut a stick, we get two smaller sticks. If we know the optimum solution for these two sticks, we can easily figure out the optimum solution for the larger stick. But this would be very inefficient.
If you have a recursive function min_cost(stick_length, c_1, c_2, ..., c_n) which returns the minimum cost of cutting a stick of length stick_length at c_1, c_2, ..., c_n, the recurrence relation would look something like this
min_cost(stick_length, c_1, c_2, ..., c_n) =
    stick_length
    + minimum(min_cost(c_1, a_1, a_2, ..., a_i)
    + min_cost (stick_length - c_1,
                a_(i+1), ..., a_(n-1)),
                min_cost(c_2, a_1, a_2, ..., a_i)
    + min_cost(stick_length - c_2,
               a_(i+1), ..., a_(n-1)), ... ,
               min_cost(c_n, a_1, a_2, ..., a_i)
    + min_cost(stick_length - c_n,
                a_(i+1), ..., a_(n-1)))`,

where a_1, a_2, ..., a_n is a permutation of the remaining places to be cut. We will have to pass all possible permutations to the recurrence function not just one as I have written.
This is obviously impractical. How do I solve this?

A: One more DP solution:
Let's COST(a,b) is the best cost of cutting the segment between a-th and b-th cut point. It is clear that COST(a,a) and COST(a,a+1) is zero. We can compute the best value of COST(a,b) as minimum of cuts through all the middle points a+1...b-1 plus own segment length. So we can fill triangle table diagonal by diagonal and find final result as COST(start,end) with O(N^3) time complexity and O(N^2) space
Delphi code (outputs Cost 20  Sequence 4 2 7)
var
  Cuts: TArray<Integer>;
  Cost: array of array of Integer;
  CutSequence: array of array of String;
  N, row, col, leftpos, rightpos, cutpos, Sum: Integer;
begin
  Cuts := TArray<Integer>.Create(0, 2, 4, 7, 10); // start, cuts, end points
  N := Length(Cuts);
  SetLength(Cost, N, N);  //zero-initialized 2D array
  SetLength(CutSequence, N, N);  //zero-initialized 2D array

  for rightpos := 2 to N - 1 do
    for leftpos := rightpos - 2 downto 0 do begin //walk along the diagonals
                                                  //using previously computed results
      //find the best (mincost) cut
      Cost[leftpos, rightpos] := MaxInt; //big value
      for cutpos := leftpos + 1 to rightpos - 1 do begin
        Sum := Cost[leftpos, cutpos] + Cost[cutpos, rightpos];
        if Sum < Cost[leftpos, rightpos] then begin
          Cost[leftpos, rightpos] := Sum;
          //write down best sequence
          CutSequence[leftpos, rightpos] := Format('%d %s %s', [Cuts[CutPos],
            CutSequence[leftpos, cutpos], CutSequence[cutpos, rightpos]]);
        end;
      end;

      //add own length
      Cost[leftpos, rightpos] :=
        Cost[leftpos, rightpos] + Cuts[rightpos] - Cuts[leftpos];
    end;

  //show the best result
  Caption := Format('Cost %d  Sequence %s',[Cost[0, N-1], CutSequence[0, N-1]]);

A: This is actually a problem from the UVa Online Judge. http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=944
In this problem L < 1000 and n < 50.
As I mentioned in the comments, if you notice then for each cut, the possible lengths of stick at which the cut can be made = n.
The total possible remaining lengths shall be finite and for each remaining length the number of sets of cuts remaining shall also be finite. So you can build a DP on the remaining lengths.
Starting from the smallest, for each 'remaining length', you can calculate the minimum cost of cutting it down further.
Something like:
DP[k][SetOfCutsRemaining] = k + Min( DP[m1][SetOfCutsRemaining till c1]
                                 + DP[k-m1][SetOfCutsremaining from c1],
                                 DP[m2][SetOfCutsRemaining till c2]
                                 + DP[k-m2][SetOfCutsremaining from c2],... )
                           where mi are the lengths remaining if we make a cut at ci

You will then need to do this till DP[L][InitialSetOfCuts].
In the example problem, L = 10, ci = 2, 4, 7
The remaining lengths and their corresponding cuts remaining are as follows. Note that the number of combinations shall be C(n+2,2) = (n+2)(n+1)/2 = 10 in this case
2 {} (2 times, 0-2 and 2-4)
3 {} (2 times, 4-7 and 7-10)
4 {c1}
5 {c2}
6 {c3}
7 {c1, c2}
8 {c2, c3}
10 {c1, c2, c3}

DP[2][{}] = 0 (No cut remaining)
DP[3][{}] = 0 (No cut remaining)
DP[4][{c1}] = 4 (1 cut remaining)
DP[5][{c2}] = 5 (1 cut remaining)
DP[6][{c3}] = 6 (1 cut remaining)
DP[7][{c1,c2}] = 7 + Min( DP[2]{} + DP[5][{c2}], DP[3]{} + DP[4][{c1}] )
               = 7 + Min( 5, 4 ) = 11.
DP[8][{c2,c3}] = 8 + Min( DP[2]{} + DP[6][{c3}], DP[3]{} + DP[5][{c2}] )
               = 8 + Min( 6, 5 ) = 13.
DP[10][{c1,c2,c3}] = 10 + Min( DP[2]{} + DP[8][{c2,c3}], DP[4]{c1} + DP[6][{c3},
                                DP[7][{c1,c2}] + DP[3]{} )
               = 10 + Min( 13, 10, 11 ) = 20.

A: First, assuming we have an ascending-order array of cutting position, so in OP example, it will be
{2,4,7}
At first, we have the stick with length from 0 to n, so we call function
int cal(int start, int end , int [] cuts)

with start = 0 and end = n.
For every cutting point which is greater than start and less than end, we have the formula
int result = 1000000;
for(int i = 0; i < cuts.length; i++){
   if(cuts[i]> start && cuts[i]<end){
         int val = (end - start) + cal(start, cuts[i], cuts) + cal(cuts[i],end , cuts);
         result = min(val, result);
   }
}

and the DP table can be simply
dp[start][end]

So, the whole solution will be:
int cal(int start, int end, int[]cuts){
    if(dp[start][end]!= -1){//Some initializations need to be done
        return dp[start][end];
    }
    int result = 1000000;
    for(int i = 0; i < cuts.length; i++){
       if(cuts[i]> start && cuts[i]<end){
         int val = (end - start + 1) + cal(start, cuts[i], cuts) + cal(cuts[i],end , cuts);
         result = min(val, result);
       }
    }
    return dp[start][end] = result;
}

To further enhance the space using, we can refer each cut position as its index in the array cuts.
Added start and end point to the cut arrays, we have following arrays
{0,2,4,7,10}

By referring to start position as index 0, end as index 4, we can decrease the space of array dp from dp[10][10] to dp[5][5]

A: Sorry, I can buzz like a fridge anytime, but talking in maths is more of a problem. I probably could formalize the algorithm for the life of me, but as long as the karma police leaves me alone, I won't.
Here is my solution (in JavaScript).
It's a pure brute-force approach.
Not a single cut (if I may say so), all branches are taken.
It appears the number of explored cuts for n cuts is equal to 3^^n (I did measure it). I suspect there is a trivial explanation for that, but trying to find it makes my head buzz, so...
I use the format suggested in another comment, i.e. the leftmost and rightmost elements of the array are representing the ends of the current bit of stick.
For instance, [0,2,4,7,10] means "cuts at positions 2, 4 and 7 in a stick ranging from 0 to 10".
function try_cut_raw (list)
{
    // terminal ends
    if (list.length == 2) return 0;
    if (list.length == 3) return list[2]-list[0];

    // left and right split
    var cost_min = 1e6;
    for (var i = 1 ; i != list.length-1 ; i++)
    {
        var cost = try_cut_raw (list.slice (0, i+1))
                 + try_cut_raw (list.slice (i, list.length));
        if (cost < cost_min) cost_min = cost;
    }
    return cost_min+list[list.length-1]-list[0];
}

A more refined one, returning a semi-ordered sequence of the cuts to be applied to achieve the result.
function try_cut (list)
{
    // terminal ends
    if (list.length == 2) return { cost: 0, seq:[] };
    if (list.length == 3) return { cost: list[2]-list[0], seq:[list[1]] };

    // left and right split, retaining best value
    var i_min;
    var cost_min = 1e6;
    var seq_min;
    for (var i = 1 ; i != list.length-1 ; i++)
    {
        var cl = try_cut (list.slice (0, i+1));
        var cr = try_cut (list.slice (i, list.length));

        var cost = cl.cost+cr.cost;
        if (cost < cost_min)
        {
            cost_min = cost;
            // store cut order associated with best result
            seq_min  = [list[i]].concat (cl.seq).concat(cr.seq);
        }
    }
    return { cost: cost_min+list[list.length-1]-list[0], seq: seq_min }
}

A test case with the OP's input and both examples from the initial challenge page
function cut (list)
{
var cut = try_cut (list);
var cut_raw = try_cut_raw (list);
console.log ("["+list+"] -> "+cut.seq+" cost "+cut.cost+"/"+cut_raw);
}

cut ([0,2,4,7,10]);
cut ([0,25,50,75,100]);
cut ([0,4,5,7,8,10]);

output
[0,2,4,7,10] -> 4,2,7 cost 20/20
[0,25,50,75,100] -> 50,25,75 cost 200/200
[0,4,5,7,8,10] -> 4,7,5,8 cost 22/22

A: I respect to all above solution, Here is a my solution for this problem in Java.
This might be helpful for someone.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class CutTheSticks2 {
    public static void main(String s[]) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        short N = Short.parseShort(br.readLine());
        short[] A = new short[N];
        N = 0;
        for (String str : br.readLine().split(" ")) {
            A[N++] = Short.parseShort(str);
        }

        Arrays.sort(A);

        StringBuffer sb = new StringBuffer();
        System.out.println(N);
        for (int i = 1; i < N; i++) {
            if (A[i - 1] != A[i]) {
                sb.append((N - i) + "\n");
            }
        }

        // OUTPUT
        System.out.print(sb);
    }
}


text:
Q: Regex for matching whole words that contain dots In the following sentence:
I woke up in 5 p.m. today
I want to match the 5 p.m..
This pattern works:
5 p\.m\.

But I wanted it to match whole words only (so 5 p.m.us won't be matched).
So I used this pattern:
\b5 p\.m\.\b

But this didn't work because of the dot.
What will be the simplest regex to solve this? Can I define a zero-width match (\b style) that doesn't care if the character is a word character or not, only if it is a space or the end\beginning of the string?

A: You can use positive lookahead and lookbehind, which is a zero-width match, to do it. A regex like (?<=^|\s)5 p\.m\.(?=\s|$) means "Start of the string or a space character, followed by '5 p.m.' followed by anything which is a space character or end of string."

A: Well, for that specific example, a simple one would be:
\b5 p\.m\.\B

But I doubt that would work very well in more complex source texts.
This article on word boundaries may be of help.


text:
Q: Agrupar datos en forma lineal en SQL Buen dia,
el problema es sencillo solo quiero que los datos no se repitan y me muestre un solo registro en el que los datos sean lineales, como lo he agrupado mal por eso sale un dato debajo del otro, quiera su ayuda para poder organizar bien la información y me salgan los datos por un solo producto.
(select t1.ACODIGO,t1.ADESCRI,t1.AUNIDAD,t1.Linea,t1.Linea2,t1.Estado from(
        SELECT
          row_number() over (partition by decodigo,datepart(month,CAFECDOC) order by CAFECDOC desc, CATIPMOV desc ,CACODMOV desc,CAALMA desc,CATD desc,CANUMDOC desc,DEITEM desc)[Fila],
          DECODIGO as ACODIGO,DEDESCRI as ADESCRI,DEUNIDAD as AUNIDAD,
         (case when DATEPART(month, CAFECDOC)=MONTH(GETDATE()) -1  then cast(DEPRECIO as money)  else 0 end) Linea,
         (case when DATEPART(month, CAFECDOC)=MONTH(GETDATE()) then cast(DEPRECIO as money)  else 0 end) Linea2,
        case when (case when DATEPART(month, CAFECDOC)=MONTH(GETDATE()) -1  then cast(DEPRECIO as money) else 0 end) >
        (case when DATEPART(month, CAFECDOC)=MONTH(GETDATE()) then cast(DEPRECIO as money)  else 0 end) then 'Aumento'
         when (case when DATEPART(month, CAFECDOC)=MONTH(GETDATE()) -1  then cast(DEPRECIO as money) else 0 end) <
        (case when DATEPART(month, CAFECDOC)=MONTH(GETDATE()) then cast(DEPRECIO as money)  else 0 end) then 'Disminuye'
        else 'Se mantiene' end Estado
         from
         [025BDCOMUN].DBO.MOVALMCAB AS B INNER JOIN ([025BDCOMUN].DBO.MOVALMDET AS A
                 LEFT JOIN [025BDCOMUN].DBO.MAEART AS M ON A.DECODIGO = M.ACODIGO) ON B.CAALMA = A.DEALMA AND B.CATD = A.DETD AND B.CANUMDOC = A.DENUMDOC
                 WHERE
    /* AFECDOC BETWEEN '01/02/2010' AND '10/02/2010' MONTH(CAFECDOC)= 6  AND*/  YEAR(CAFECDOC) = '2020' AND
   CASITGUI <> 'A' AND
   NOT (CATD = 'GS' AND CACODMOV = 'GF' AND CASITGUI = 'F') AND
   NOT (M.AFSTOCK = 'N' AND M.AFSERIE = 'N' AND M.AFLOTE = 'N')
  AND DECODIGO like '100%' /*(DECODIGO >= '1000000' AND DECODIGO <= '1000000')*/
  AND (DECODIGO <> 'TEXTO')
  AND M.AFAMILIA >= '001' AND M.AFAMILIA <= '027') t1
        where [Fila]=1
        group by [Fila],t1.ACODIGO,t1.ADESCRI,t1.AUNIDAD,t1.Linea,t1.Linea2,t1.Estado)
        order by ACODIGO

Los productos se repiten y los datos que son los costos no se muestran de manera lineal sino uno debajo del otro.

Deberia quedar de la siguiente manera:

A: Básicamente lo que necesitas es agrupar tus líneas para que queden en una sola. Esto lo puedes hacer con la función MAX(), asumiendo que siempre será una sola fila la que contenga el valor deseado.
Con un poco de formato, y moviendo el cálculo de la columna Estado, obtenemos algo como esto. Espero que notes la diferencia al tratar de enteder mi código y el tuyo, y eso te motive a dar un mejor formato al código que escribes.
SELECT  t1.ACODIGO,
        t1.ADESCRI,
        t1.AUNIDAD,
        MAX( t1.Linea ) AS Linea ,
        MAX( t1.Linea2) AS Linea2,
        CASE WHEN MAX( t1.Linea ) < MAX( t1.Linea2 ) THEN 'Aumento'
             WHEN MAX( t1.Linea ) > MAX( t1.Linea2 ) THEN 'Disminuye'
             ELSE 'Se mantiene' END AS Estado
FROM(
     SELECT ROW_NUMBER() OVER (PARTITION BY decodigo, datepart(month,CAFECDOC)
                               ORDER BY CAFECDOC desc, CATIPMOV desc, CACODMOV desc, CAALMA desc, CATD desc, CANUMDOC desc, DEITEM desc)[Fila],
            DECODIGO as ACODIGO,
            DEDESCRI as ADESCRI,
            DEUNIDAD as AUNIDAD,
            (CASE WHEN DATEPART(MONTH, CAFECDOC) = MONTH( GETDATE()) -1  THEN CAST(DEPRECIO AS MONEY)  ELSE 0 END) Linea,
            (CASE WHEN DATEPART(MONTH, CAFECDOC) = MONTH( GETDATE())     THEN CAST(DEPRECIO AS MONEY)  ELSE 0 END) Linea2
     FROM       [025BDCOMUN].DBO.MOVALMCAB AS B
     INNER JOIN ([025BDCOMUN].DBO.MOVALMDET AS A
     LEFT  JOIN [025BDCOMUN].DBO.MAEART AS M ON A.DECODIGO = M.ACODIGO) ON B.CAALMA   = A.DEALMA
                                                                       AND B.CATD     = A.DETD
                                                                       AND B.CANUMDOC = A.DENUMDOC
     WHERE  /* AFECDOC BETWEEN '01/02/2010' AND '10/02/2010' MONTH(CAFECDOC)= 6  AND*/
            YEAR(CAFECDOC) = '2020'
     AND    CASITGUI <> 'A'
     AND    NOT (CATD = 'GS' AND CACODMOV = 'GF' AND CASITGUI = 'F')
     AND    NOT (M.AFSTOCK = 'N' AND M.AFSERIE = 'N' AND M.AFLOTE = 'N')
     AND    DECODIGO like '100%' /*(DECODIGO >= '1000000' AND DECODIGO <= '1000000')*/
     AND    DECODIGO <> 'TEXTO'
     AND    M.AFAMILIA >= '001'
     AND    M.AFAMILIA <= '027') t1
WHERE [Fila]=1
GROUP BY t1.ACODIGO,t1.ADESCRI,t1.AUNIDAD
ORDER BY ACODIGO;


text:
Q: What is the Difference between float "1" and float "1f" in Java? Is there any difference - in Java - between defining float variables like, e.g., this: 1 and this: 1f? Is the JVM doing any casts at run-time when I write 1, or something that could slow down my app?
Regards

A: 1 is implicitly considered as int literal where 1f is considered as float literal
See

*

*Floating point literal

A: Java code
    float f1 = 1;
    float f2 = 1f;

compiles to following bytecode:
     0: fconst_1
     1: fstore_1
     2: fconst_1
     3: fstore_2

As you can see, there's no difference at run-time.

A: float a = 1;
float b = 1f;

It's the same, but if you do something like:
int a = 1f

Will throw "Type mismatch: cannot convert from float to int"
int b = 1d or 1.0

Will throw "Type mismatch: cannot convert from double to int"
float c = 1d or  1.0

Will throw "Type mismatch: cannot convert from double to float"

Note that:
double a = 2.0;
double b = 2d;
double c = 2.0f;
if (a == b) {
    if (c == a) {
        if (c == b) {
            return 1;
        }
    }
}

Will return 1;

Regards.

A: Basically 1 will default to an int. If you write 1f it will be considered a float. If you write 1.0 (no f) it will default to a double.

A floating-point literal is of type float if it is suffixed with an
  ASCII letter F or f; otherwise its type is double and it can
  optionally be suffixed with an ASCII letter D or d.

For more info about java data types.

A: If the case like this the JVM will pass it.
public class Test {

    public static void main(String[] args) {
        float f = 1;
        System.out.println(f);
    }
}

But it will occur exception if you do something like this:
public class Test {

    public static void main(String[] args) {
        float f = 1.5;
    }
}

Exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - possible loss of precision
  required: float
  found:    double
    at package.Test.main(Test.java:17)

What we can analyze for this two example is, for the first example it automatically converted to float, but for the second example if you add some decimal point without the f or F suffix than it will automatically converted to double.

A: Yes, there is a big difference between 1 and 1f. As you can't declare a variable without giving its type in java, Its clear 1 is an int and 1f denotes float at compile time itself. This is nothing related to run time or slow down your app.


text:
Q: Pycharm not showing inherited fields of base class in django 1.10 I am using pycharm for my project, and I have created a core folder such that, it host all the abstract models, such that
class TimeStampedModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

When I try to import this class in other apps, Pycharm gave me an error, such that the base class attributes, such as models are not recoginzed

But this is perfect valid python code. How to fix this.
My project structue is

A: Man you imported TimeStampedModel. But I didn't find your models. Where did you import? if your models inside TimeStampedModel then, import like that,
from ..core.TimeStampedModel import models or
from ..core import TimeStampedModel.models as models
Feel free to write pythonic code :)


text:
Q: Setup KeePass on Ubuntu 9.04 (Jaunty Jackalope) Has anyone manage to setup KeePass 2.x on Ununtu 9.04? I looked but could not figure out how to install it, plus i didn't find any tutorials on this.
Also if you installed it, how does it work, does it crash a lot ? I saw that a lot of people have been having problems on Ubuntu instalations.

A: I run Ubuntu 9.04 (Jaunty) and KeePass Portable 2.0 works for me. It also appears to work for others from the later responses on this thread: [SOLVED] Mono & KeePass 2. People who initially complained about crashes have reported it to be working for them on the final Jaunty release.
As for installation, get the latest Portable Keepass Professional edition and follow the project instructions on running KeePass under Mono. If you have the mono components required, you should be able to unpack the zip and just run the KeePass executable.
The forum post linked to above mentions that you need the libmono-winforms2.0-cil and libmono-winforms1.0-cil packages in addition to the core mono package. However, I only have libmono-winforms2.0-cil on my system and Keepass 2.0 works fine on it.


text:
Q: how does socket.io client find /socket.io/socket.io.js I have node, socket.io, npm installed on an ubuntu 16.04 aws instance.  I can start a socket.io project and it is running -- says listening on port *3000, but on the client side
<script src="/socket.io/socket.io.js"></script>

cannot find the client file.
What service translates the src path into the real path, and where should npm and node_modules be installed relative to the client.html file?

A: It's automatically served by your http server with
var app = require('http').createServer(handler)
var io = require('socket.io')(app);

Socket.IO also needs an HTTP server for polling, and upgrading connection from HTTP to websocket.


text:
Q: How to differentiate between an atof of a character vs an input of zero atof() returns 0.0 if it its argument cannot be parsed as a valid float.
How do I differentiate that from when it is given an actual 0?


text:
Q: How to add two number and store in array then add the previous number to latest number using javascript

var array=[num1,num2];

function number(){

    var num1 = parseInt(document.getElementById("num1").value);
    var num2 = parseInt(document.getElementById("num2").value);

    for(var i=0;i<=10;i++){

        sum = num1 + num2;
        array.push(sum);
        console.log(array);
    }
}
<input type="text" name="" id="num1">
<input type="text" name="" id="num2">

<button type="submit" onclick="number()">Click</button>

Hello guys, I'm Beginner in javascript how to add number and store in an array. For example, Input 1 is 5 then in Input 2 is 7 so that the answer becomes [5,7,12,19,31,50...]. using javascript. Sorry still learning javascript :)

A: You are really close to the solution.
There are many options, but the simpler would be something like this.
In the for-loop you could access the two last numbers in the array.
var array=[num1,num2];

function number(){

    var num1 = parseInt(document.getElementById("num1").value);
    var num2 = parseInt(document.getElementById("num2").value);

    for(var i=0;i<=10;i++){

        sum = array[array.length - 1] + array[array.length - 2];
        array.push(sum);
        console.log(array);
    }
}

A more complex approach would be using the Array.reduce method. Which I recommend you to learn and understand.
https://www.w3schools.com/jsref/jsref_reduce.asp

A:

const array = []
  ,   eNum1 = document.getElementById('num1')
  ,   eNum2 = document.getElementById('num2')
  ;
function number()
  {
  array[0] = parseInt(eNum1.value);
  array[1] = parseInt(eNum2.value);

  for(var i=1;i<=10;++i)
    {
    array[i+1] = array[i-1] + array[i]
    }
  console.clear()
  console.log(`array = [ ${array.join(', ')} ]`)
  }
<input type="text" name="" id="num1">
<input type="text" name="" id="num2">

<button type="submit" onclick="number()">Click</button>

A: Start from the 3rd index to do your sum like
function number(){

 var num1 = parseInt(document.getElementById("num1").value);
 var num2 = parseInt(document.getElementById("num2").value);

 for(var i=2;i<=10;i++){

    sum = array[i-2] + array[i-1];
    array.push(sum);
    console.log(array);
 }
}

A: You don't need to loop 10 times. One solution for just adding the two numbers and the sum of them would be something like this:

const arr = []

function sum() {

    const firstInputNum = parseInt(document.querySelector('#num1').value)
    const secondInputNum = parseInt(document.querySelector('#num2').value)

    arr.push(firstInputNum, secondInputNum, firstInputNum + secondInputNum)
    console.log(arr)
}
<input type="number" id="num1">
<input type="number" id="num2">

<button onClick="sum()">Add numbers</button>

Notice that i use the querySelector method that must modern browsers support to get DOM elements using CSS selector style instead of the getElementById.


text:
Q: Overlapping Shader Effects in Opengl ES 2.0 Is it possible to overlap shader effects in OpenGL ES 2.0? (not using FBOs)
How to use the result of a shader with another shader without having to do a glReadPixels and push again the processed pixels?
The next pseudo-code is what I'm trying to achieve:
// Push RGBA pixels into the GPU
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, Pixels_To_Render);

// Apply first shader effect
glUseProgram( FIRST_SHADER_HANDLE);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

// Apply the second shader effect sampling from the result of the first shader effect
glUseProgram( SECOND_SHADER_HANDLE );
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

// Get the overall result
glReadPixels(......)

A: I presume you're talking about pixel processing with fragment shaders?
With the OpenGL ES 2.0 core API, you can't get pixels from the destination framebuffer into the fragment shader without reading them back from the GPU.
But if you're on a device/platform that supports a shader framebuffer fetch extension (EXT_shader_framebuffer_fetch on at least iOS, NV_shader_framebuffer_fetch in some other places), you're in luck. With that extension, a fragment shader can read the fragment data from the destination framebuffer for the fragment it's rendering to (and only that fragment). This is great for programmable blending or pixel post-processing effects because you don't have to incur the performance penalty of a glReadPixels operation.
Declare that you're using the extension with #extension GL_EXT_shader_framebuffer_fetch : require, then read fragment data from the gl_LastFragData[0] builtin. (The subscript is for the rendering target index, but you don't have multiple render targets unless you're using OpenGL ES 3.0, so it's always zero.) Process it however you like and write to gl_FragColor or gl_FragData as usual.


text:
Q: Can all of a UIElement RenderTransform effected properties be copied into a new Element? I want to make a copy of the Element that has the new properties based upon the RenderTransform.  For example, a ScaleTransform of an element on one canvas to another canvas.
private void CopyElement(UIElement elem, Canvas src, Canvas dest, Size scale, Vector offset) {
    ScaleTransform resize = new ScaleTransform(scale.Width, scale.Height);
    elem.LayoutTransform = resize;
    UIElement newElem = CopyElement(src, elem);
    Canvas.SetLeft(newElem, Canvas.GetLeft(elem) * scale.Width + offSet.X);
    Canvas.SetTop(newElem, Canvas.GetTop(elem) * scale.Height + offSet.Y);
    dest.Children.Add(newElem);
}

A: You don't need to do this at all.
Just set the element's LayoutTransform property instead of its RenderTransform.


text:
Q: Put marker on the image in OpenCV I'm showing an image using cv::imshow("binary1", binary1);. I want to put a marker on the image to the check the pixel locations. How can I put marker on the image for a particular row and column value?

A: It's difficult to understand what is it that you want to do, but I wrote a code a while back that displays the RGB color of a pixel along with it's coordinates on the title of the window. Move the mouse pointer over the image and you'll see it change.
It uses a Qt window, though. You can check cvImage.


text:
Q: How to scaffold items on Visual Studio for OSX I'm trying to follow a course to create apps using C#, unfortunately I'm using a Mac so I can't follow all the step as the y do it on the videos. I.E. the method to create an empty class is different, Had to manually include the Entity Framework Dependency and create the Models folder.... but now I'm trying to create a Controller by scaffolding it but I can't see how to do it. I don't know if there's a better option than using VS or if I need to install some basic plugins or packages to make it a 'windows-esque' experience.
P.S.: I'm a total noob regarding C#, this is the first time I work on it so it's not as easy as saying "well, you can manually create your controller and the datacontext file" 'cause I'm not really familiar with which files I need to make the project running, that's the reason to stick with VS, since it seems to help you during all the develop process [or at least in Windows].

A: I ran into the same issue going through an older Microsoft tutorial (https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-2.2).
Answer: the scaffolding needs to be done from the command line using dotnet aspnet-codegenerator. The documentation (including the options for scaffolding controllers) can be found here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/tools/dotnet-aspnet-codegenerator?view=aspnetcore-2.2
For the tutorial I linked above the controller scaffolding was done with the following command:
dotnet aspnet-codegenerator controller -name StudentsController -m Student -dc SchoolContext --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries --useAsyncActions

-m is the name of the model.
-dc is the database context.
The aspnet-codegenerator tool has to be installed using the following command:
dotnet tool install -g dotnet-aspnet-codegenerator

I also had to add the Microsoft.VisualStudio.Web.CodeGeneration.Design NuGet package as a project dependency.

A: Visual Studio 2019 for Mac introduces support for scaffolding pages and controllers in a very similar way to what Visual Studio on Windows does. This tooling simplifies the generation of these kinds of items by creating the appropriate code files with basic user interfaces, for pages, and basic methods. You use the new scaffolding feature by right-clicking the project name in the Solution pad and then selecting Add > New Scaffolding. The Add New Scaffolding dialog appears as below.

For more information: https://www.syncfusion.com/ebooks/visual-studio-for-mac-succinctly/creating-net-core-apps

A: File -> New File
Highlight Asp.NET Core on the left, then select MVC Controller Class.


text:
Q: Running two threads in same time ( multithreading?) I'm trying to get two threads to work in same time.
Let me explain with code:
Main Class that runs both threads
public static void main(String[] args) {
    abThread.move(5);
    cdThread.move(5);
}

Thread 1:
static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("a");
            i -= 1;
            continue;
        } else {
            System.out.println("b");
            i -= 1;
            continue;
        }
    }
}

Thread 2:
static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("c");
            i -= 1;
            continue;
        } else {
            System.out.println("d");
            i -= 1;
            continue;
        }
    }
}

Im getting random a/b x 5 and after 5 of them im getting random (c/d) x5
My goal is to get a/b,c/d,a/b,c/d... and so on
Any help or redirection to some way-would greatly appreciate it!
Edit: Notice i tryed with try sleep but it just postpones how long before next a/b after a/b. Only way i could do it a/b,c/b would be
    abThread.move(1);
    cdThread.move(1);
    abThread.move(1);

......
Thanks

A: The work performed by a thread other than the main one is determined by the Runnable with which it was initialized or by the implementation of its run() method if you've overridden that.  One of those places is where you should be placing the invocations of the various move() methods.  Then your main thread should start() both thread instances.
That (probably) achieves the threads running in parallel, subject to thread scheduling and the availability of execution resources.  As @Alexander described, however, it does not necessarily produce perfect alternation between the outputs of the two threads, nor does it even guarantee that any of the output produced by one thread will appear before any of the output produced by the other.
If you need perfect alternation then the two threads need to synchronize with each other to take turns.  There is a large number of ways you could implement that, but if you want it, it needs to be built in to your move() methods.  The low-level, old-school ways revolve around using the wait() and notify() / notifyAll() methods of a shared object.  You might also use a SynchronousQueue for just two threads taking turns, among many other possibilities.

A: If you really want to experiment with threads, not only print characters alternately, you could try something like this:
First of all, implement Runnable that holds code to be run by threads:
class Task implements Runnable {
    //c1 and c2 are characters to print (a,b and c,d for example)
    private final String c1, c2;
    //semaphore guarantees the order of threads execution
    private final Semaphore sync;
    private int i;

    Task(int i, String c1, String c2, Semaphore sync) {
        this.i = i;
        this.c1 = c1;
        this.c2 = c2;
        this.sync = sync;
    }
    @Override
    public void run() {
        try {
            int min = 0;
            int max = 100;
            while (i > 0) {
                sync.acquire();
                int a = ThreadLocalRandom.current().nextInt(min, max + 1);
                if ((a % 2) == 1) {
                    System.out.println(c1);
                    i -= 1;
                } else {
                    System.out.println(c2);
                    i -= 1;
                }
                sync.release();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

Then create Semaphore:
Semaphore sync = new Semaphore(0, true);

Create two threads and run them:
Thread t1 = new Thread(new Task(10, "a", "b", sync));
Thread t2 = new Thread(new Task(10, "c", "d", sync));

t1.start();
t2.start();

And finally release semaphore so that one of the threads waiting on it can proceed:
sync.release();

A: The threads run at their own pace, getting scheduled on and off the CPU as the Operating System desires. You can only expect to get a/b, c/d, a/b, c/d, ... execution if the Operating System uses round-robin scheduling (i.e. every thread gets a turn, in a circle), which it almost certainly doesn't.


text:
Q: how to show up animation at activity launch i have a launcher activity which shows up the blank screen at the start up..i want to show up some animation using an animatd.gif...i initialize my layouts viz home etc when the oncreate of launcher is called, but how do i add some animated image until my first layout is shown..i also doubt whether android supports animated gifs or i have to do a workaround.

A: Animated gifs are not supported  for multiple reasons like "animated .gif are memory hogs", the workaround must be an animation
https://developer.android.com/guide/topics/resources/animation-resource.html


text:
Q: Paperclip looking for file locally for reprocessing when using S3 I am using paperclip to upload files to s3 storage. Once the file is uploaded I am trying to crop it using Jcrop. When the logo.reprocess! runs It tries to look for the file locally rather than on s3 and gives me a No such file or directory error. Here is relevant code
  has_attached_file :logo,
    styles: { thumb: "145x75#", large: "500x500" },
    :storage => :s3,
    :s3_credentials => "#{Rails.root}/config/s3.yml",
    :processors => [:cropper]

  def cropping_logo?
    !logo_crop_x.blank? && !logo_crop_y.blank? && !logo_crop_w.blank? && !logo_crop_h.blank?
  end

  def logo_geometry(style = :original)
    @geometry ||= {}
    path = (logo.options[:storage]==:s3) ? logo.url(style) : logo.path(style)
    @geometry[style] ||= Paperclip::Geometry.from_file(path)
  end

  def reprocess_logo
      logo.reprocess!
  end

module Paperclip
  class Cropper < Thumbnail
    def transformation_command
      if crop_command
        crop_command + super.sub(/ -crop \S+/, '')
      else
        super
      end
    end

    def crop_command
      target = @attachment.instance
      if target.cropping_logo?
      " -crop '#{target.logo_crop_w.to_i}x#{target.logo_crop_h.to_i}+#{target.logo_crop_x.to_i}+#{target.logo_crop_y.to_i}'"
      end
    end
  end
end

Here is some stacktrace for help
/usr/local/ruby/lib/ruby/1.9.1/fileutils.rb:1423:in `stat'
/usr/local/ruby/lib/ruby/1.9.1/fileutils.rb:1423:in `block in fu_each_src_dest'
/usr/local/ruby/lib/ruby/1.9.1/fileutils.rb:1439:in `fu_each_src_dest0'
/usr/local/ruby/lib/ruby/1.9.1/fileutils.rb:1421:in `fu_each_src_dest'
/usr/local/ruby/lib/ruby/1.9.1/fileutils.rb:391:in `cp'
paperclip (3.0.2) lib/paperclip/io_adapters/attachment_adapter.rb:53:in `copy_to_tempfile'
paperclip (3.0.2) lib/paperclip/io_adapters/attachment_adapter.rb:44:in `cache_current_values'
paperclip (3.0.2) lib/paperclip/io_adapters/attachment_adapter.rb:6:in `initialize'
paperclip (3.0.2) lib/paperclip/io_adapters/registry.rb:29:in `new'
paperclip (3.0.2) lib/paperclip/io_adapters/registry.rb:29:in `for'
paperclip (3.0.2) lib/paperclip/attachment.rb:91:in `assign'
paperclip (3.0.2) lib/paperclip/attachment.rb:279:in `reprocess!'

A: I have the same issue. I think it's related to the Paperclip v3 code.
I specified in my Gemfile to use the older version.
# Gemfile
gem "paperclip", "~> 2.7.0"

And cropping works. I'm not sure if that's a good solution for you, but it works for me for the time being.


text:
Q: Use Jquery $.ajax to call a server side function on Flask I want to call a server side function using Ajax.
I have found a straightforward example for PHP in this post. I think the community would improve if we could include this very same example but for Python / Flask MVC framework.
This is the ajax code on the View side, called test.html:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
function create () {
$.ajax({
url:"test1", //the page containing python script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc@gmail.com"},
success:function(result){
console.log(result.abc);
      }
    });
   }
</script>

And this would be the Python code on the Controller:
@app.route('/test', methods=['GET','POST'])
    def test():
        return render_template("test.html", brand = brand)

@app.route('/test1', methods=['GET','POST'])
    def test1():
        if registration == "success":
            return json.dump({"abc":'successfuly registered'});

A: Remove the arguments to the view function. Access posted data with request.form. Return a JSON response using jsonify. The view must return a response from each execution path.
@app.route('/test1', methods=['GET', 'POST'])
def test1():
    if request.form.get('registration') == 'success':
        return jsonify({'abc': 'successfuly registered'})

    return jsonify({'abc': 'registration unsuccessful'})


text:
Q: symfony twig extends: 'only extend if' In twig there is the 'extends' tag, as found here; http://twig.sensiolabs.org/doc/tags/extends.html#conditional-inheritance
Now what I wanna do is something along the lines of the following example from that page:
{% extends standalone ? "minimum.html" : "base.html" %}

But rather than having 2 templates to extend from, I just want to extend from a template if a specific condition is met.
Now I've tried things such as:
{% extends boolean ? "template.html.twig" : "" %}

and:
{% if boolean %}
    {% extends "template.html.twig" %}
{% endif %}

but the former gives an error saying it cannot find a template (since "" obviously isnt a valid path), and the latter just doesn't appear to do anything at all (or rather, it loads for a while and ends up not showing anything)
I've tried some other approaches, but couldn't come up with anything, so figured I'd ask here if I might be missing something.
Thanks in advance for any replies :)
EDIT: To sum up my intent; I am wondering if I can tell my template to only extend if a certain condition is met, and otherwise skip the extend step. (if condition then extend else do nothing)

A: Twig files are generated into PHP classes.
The extends tag should be the first tag in the template, as:

*

*the {% extends %} tag will be converted to the PHP extends so the child template will inherit from the parent template.

*the {% if %} tag is generated as a PHP if, inside a method of the template class, so you can't use {% if %} to extend some class or not.
Anyway, you can extends a variable coming from your context, so you should put your condition in the controller.
if ($boolean) {
  $template = 'hello.twig';
} else {
  $template = 'world.twig';
}
$this->render("MyBundle:MyFeature:child.html.twig", array('template' => $template);

And then in child.html.twig:
{% extends template %}

A: I came with this hack: added empty layout only with content block. Seems to be working :) I can pass variable from controller and page is loaded with or without layout.
<!-- base.html.twig -->
<head>
    ...stuff...
</head>
<body>
    {% block content %}{% endblock %}
</body>

<!-- empty.html.twig -->
{% block content %}{% endblock %}

<!-- some_page.html.twig -->
{% extends boolean ? 'base.html.twig' : 'empty.html.twig' %}
{% block content %}
    Now this is my real content
{% endblock %}

A: In pure twig language, it could be something like this :
{% if app.request.pathinfo starts with '/react' %}
    {% set extendPath = "::react_base.html.twig" %}
{% else %}
    {% set extendPath = "CoreBundle::layout.html.twig" %}
{% endif %}
{% extends extendPath %}


text:
Q: GLM coefficient estimates distribution I'm confused about how the GLM coefficients are distributed. Let $\hat\beta$ be the vector of coefficient estimates and $n$ the number of observations. Are the coefficients distributed like this:
$$
\hat\beta \sim N\bigg(\beta, \frac{1}{n} \bigg(E\Big[-\frac{\partial^2 \mathcal{L}(\beta)}{\partial \beta \partial \beta^T}\Big]\bigg)^{-1}\bigg),
$$
or are they distributed like that:
$$
\hat\beta \sim N\bigg(\beta, \bigg(E\Big[-\frac{\partial^2 \mathcal{L}(\beta)}{\partial \beta \partial \beta^T}\Big]\bigg)^{-1}\bigg)?
$$
Any insight would be very helpful, as I'm having problems with understanding this.

A: Assuming $\hat{\beta}$ is the MLE, we do not know the distribution of $\hat{\beta}$ but we do know the asymptotic distribution of $\sqrt n (\hat{\beta} - \beta)$ to be $N\bigg(0, \bigg(E\Big[-\frac{\partial^2 \mathcal{L}(\beta)}{\partial \beta \partial \beta^T}\Big]\bigg)^{-1}\bigg)$.
Rearranging terms we say $\hat\beta$ is approximately $ N\bigg(\beta, \frac{1}{n} \bigg(E\Big[-\frac{\partial^2 \mathcal{L}(\beta)}{\partial \beta \partial \beta^T}\Big]\bigg)^{-1}\bigg)$. We cannot say this is an asymptotic distribution because as $ n \rightarrow \infty$ the variance will be zero.

A: Your question is, imho, not directly related to GLMs but can be answered using more simple examples that do not require likelihood approaches:
Take $X_i\sim iid (\mu,1)$, i.e., the $X_i$ are independently and identically distributed from a distribution with some mean $\mu$ and a variance of 1 (for simplicity).
Then, by the central limit theorem we know that as $n\to\infty$,
$$\sqrt{n}(\bar{X}-\mu)\to_dN(0,1)$$
Basically, we "magnify" the difference $\bar{X}-\mu$ which itself, by the law of large numbers, vanishes as $n\to\infty$.
We can then approximately say that $\bar{X}\sim N(\mu,1/n)$. The "logic" is as follows:
$$Var(\sqrt{n}(\bar{X}-\mu))=1\Rightarrow nVar(\bar{X}-\mu)=1\Rightarrow Var(\bar{X}-\mu)=1/n\Rightarrow Var(\bar{X})=1/n,$$
where the last implication is because $\mu$ is nonrandom. This is only an approximation because the leftmost statement is the asymptotic variance, i.e., the variance of $\sqrt{n}(\bar{X}-\mu)$ as $n\to\infty$, so that the rightmost statement ought to consequently read $Var(\bar{X})=0$. That, by the LLN, is correct, but the approximation often turns out to be useful nevertheless.


text:
Q: What is the purpose of Tab.TabPanel in this reactJS code? I recently watch a tutorial on YouTube about making Tabs using React and I got these codes.
App.js

import './App.css';
import { Tab } from './components/Tab/Tab';

const tabContent = [
  {
  title: "Chennai",
  content: "Chennai is the capital of the Indian state." },
  {
  title: "Lorem Ipsum",
  content: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem."
  },
  {
  title: "Dolor sit amet",
  content: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Eius, veniam!"
  }];

function App() {
return (
  <>

          <Tab active={1}>
            { tabContent.map((tab, idx) =>
            <Tab.TabPanel key={`Tab-${idx}`} tab={tab.title}>
              {tab.content}
            </Tab.TabPanel>) }
          </Tab>

  </>
  );
}

export default App;

Tab.js

import React, { useState, useEffect } from 'react'
import './Tab.css'

export const Tab = ({children, active=0}) => {
    const [activeTab, setActiveTab] = useState(active);
    const [tabsData, setTabsData] = useState([]);

    useEffect(() => {
        let data = [];
        React.Children.forEach(children, element => {
            if(!React.isValidElement(element)) return; //exit the function

            const {props: {tab, children}} = element;
            data.push({tab, children})
        })

        setTabsData(data);

    }, [children])

    return (

                {
                    tabsData.map(({tab}, idx) => (

                            <a
                            className = {`nav-link ${idx === activeTab ? "active" : ""}`}
                            href = "#"
                            onClick={() => setActiveTab(idx)}
                            >
                                {tab}

                    ))
                }

                {tabsData[activeTab] && tabsData[activeTab].children}

    )
}

const TabPanel = ({children}) => {
    return {children}
}

Tab.TabPanel = TabPanel;

When I look to App.js I see there's a custom element named Tab.TabPanel. I think that is the children of the Tab element. And then I look to Tab.js and I see that there's TabPanel const that runs a function to return it's children.
I wonder, what is the purpose of Tab.TabPanel here? What will he render? And should I make codes like this in the future?

A: It's not the children, it's more of a namespace.  The library author didn't want to export both Tab and TabPanel and decided to attach TabPanel to the function that is exported (for whatever reason).  It's an opinionated choice that makes it harder to tree shake but just understand that Tab.TabPanel is just another React component.
The author could have just as easily done
export Tab = () => {...};
export TabPanel = () => {...};

and you could have consumed it as
import {Tab, TabPanel} from "./Tab.jsx";

const Foo = () => (

    <TabPanel>
      <Tab/>
      <Tab/>
    </TabPanel>

);

or however you wanted to use it.


text:
Q: List devices eligible to use with pmount With pmount one can mount cds, dvds usb partitions (and what not) as a user. I wrote a program (in C) that wants to copy music (and stuff) from a removable device. I want to list these devices and present them to my user. Then I will mount the selected device with pmount, copy the stuff I want and then unmount it with pmount.
But I have no idea about how to list devices that are eligible for such task at a given moment.
I would prefer a pmount based solution if there is any. If there is no such option I would be satisfied with a good enough approximation using other (simlpe user runnable) tools.
I have Debian 7 on i686.

A: First approximation:
AFAIK pmount is just a setuid-wrapper for mount. I'm not sure if there are additional restrictions.
There are various udev-aliases for all block devices in /dev/disk/, e.g. /dev/disk/by-id/. There are also utility programs like lsblk (maybe lsblk -a -l etc.), or lsscsi. Pick the one that comes closest to what you want.
Those include the already mounted devices, though, so you have to remove them with a script.


text:
Q: How to query row with max value in a column in a referencing table? There are popular case, where is needed to select a row with max value (or min or whatever else aggregate function result) from a table. My case is more complex - it adds JOIN into the picture.
Here is an example:
CREATE TABLE spacecraft (
  id   serial PRIMARY KEY,
  name text NOT NULL
);

CREATE TABLE launch (
  id            serial PRIMARY KEY,
  spacecraft_id int REFERENCES spacecraft(id) NOT NULL,
  started       timestamptz NOT NULL,
  success       bool NOT NULL
);

INSERT INTO spacecraft (id, name) VALUES
    (1, 'Bebop'),
    (2, 'Serenity'),
    (3, 'Death Start');

INSERT INTO launch (spacecraft_id, started, success) VALUES
    (1, 'January 8 04:05:06 2999 UTC', true),
    (2, 'December 1 01:00:00 3432 UTC', true),
    (3, 'February 15 00:00:00 4521 UTC', false),
    (3, 'July 10 12:05:00 4525 UTC', true);

http://sqlfiddle.com/#!15/a1921
How to select last launch result (launch.success) for each spacecraft?
UPDATE #1
That's my current solution:
SELECT DISTINCT S.*, last_launch, L2.success FROM spacecraft AS S
LEFT OUTER JOIN (SELECT *, MAX(started) OVER (PARTITION BY spacecraft_id) AS last_launch FROM launch) AS L1
ON L1.spacecraft_id=S.id
LEFT OUTER JOIN launch AS L2
ON L2.started=L1.last_launch;

http://sqlfiddle.com/#!15/45618/38

A: If you want to get only max of success, so you have add a condition to filter only success. and using Window Functions as you did:
select spacecraft.* , max(started) over (partition by spacecraft.id)
from spacecraft
    left outer join
    launch
    on spacecraft.id = spacecraft_id
where success

SQL FIDDLE

A: Here is my solution.
SELECT s.id, s.name, l.last_started
FROM spacecraft AS s
INNER JOIN (SELECT spacecraft_id, MAX(started) AS last_started FROM launch WHERE success GROUP BY spacecraft_id) AS l
ON s.id = l.spacecraft_id

http://sqlfiddle.com/#!15/45618/50

A: Assuming you want all columns from spacecraft in the result, plus the latest launch and the success of the same row.
Faster for few launches per spacecraft:
SELECT s.*, l.last_launch, l.success
FROM   spacecraft s
LEFT   JOIN (
   SELECT DISTINCT ON (spacecraft_id)
          spacecraft_id, started AS last_launch, success
   FROM   launch
   ORDER  BY spacecraft_id, started DESC
   ) l ON l.spacecraft_id = s.id;

Faster for many launches per spacecraft:
SELECT s.*, l.last_launch, l.success
FROM   spacecraft s
LEFT   JOIN LATERAL (
   SELECT started AS last_launch, success
   FROM   launch
   WHERE  spacecraft_id = s.id
   ORDER  BY started DESC
   LIMIT  1
   ) l ON true;

LATERAL requires Postgres 9.3+.
LEFT JOIN to include spacecrafts without any launches. Else use JOIN.
The essential ingredient to make either of these queries fast is a multicolumn index on (spacecraft_id, started). For this particular query it would be beneficial to success to the index to allow index-only scans:
CREATE INDEX launch_foo_idx ON launch (spacecraft_id, started DESC, success);

SQL Fiddle.
Detailed explanation:

*

*Optimize GROUP BY query to retrieve latest record per user

*Select first row in each GROUP BY group?


text:
Q: Cordova application Android compatibility I just published my application on Google play. My config sets min and target Android versions:
<preference name="android-minSdkVersion" value="23" />
<preference name="android-targetSdkVersion" value="31" />

It doesn`t set android-maxSdkVersion as suggested. Alghout this, the application is not available for Android 13 devices. This screenshot comes from Google Play:

What can be wrong?

A: I am not sure what your issue was, but for the record, you do not need to use targetSDK=32, you should be able to build and upload to google play with targetSDK 31 (I have uploaded apps to the store with targetSDK 31 earlier this month).
My guess would be that just having build tools for api-level 33 solved your issue. Also kinda makes sense that you need to have the build tools for the android version you want your app to be available on.

A: So, finally I found the solution - it is necessary to install SDK 33 under Android studio, update Java to version 11 and set target SDK to at least 32. Once I did this, the automatic max version was removed from Google Play.


text:
Q: Difference between Hashlib and System.Security.Cryptography.HashAlgorithm I am trying to understand how hashing algorithms works, specially SHA3-512. To see how it works I searched for codes in Google and came across with Hashlib. The code doesn't work as I don't have the Hashlib library (not sure what it should be called). How can I get that and is it the only way to apply SHA3-512 in C#?
Some basic things that I want to know,

*

*What is Hashlib?

*Is it a  Library?

*Is the output result/work process/function of Hashlib and System.Security.Cryptography.HashAlgorithm same? If not, then what is the difference between them?
Edit: Sorry for removing few questions from the middle. As I feel they don't need to be shown here anymore.

A: Note: Updated 2017.
Hashlib
Hashlib is a library of hash implementations:
https://hashlib.codeplex.com/
It includes implementations of quite a few cryptographic and non-cryptographic hashes - both ones that are already supported by the .NET framework (in System.Security.Cryptography) and ones that aren't. You'll need it - or another external implementation - to support SHA-3.
Note, however, that Hashlib doesn't actually include SHA-3 in its final form - but rather, the way it looked before some adjustments were made to it. That means, its output will not be what you'd expect from SHA-3.
HashLib uses a different architecture than .NET's HashAlgorithm for its hash algorithms - the output is the same (for the same algorithm, e.g. SHA256), the usage isn't. But it has a wrapper/adapter that can make the workflow the same as for HashAlgorithm, for example:
IHash hash = HashFactory.Crypto.SHA3.CreateKeccak512();
HashAlgorithm hashAlgo = HashFactory.Wrappers.HashToHashAlgorithm(hash);
// Now hashAlgo can be used the same as any .NET HashAlgorithm, e.g.:

// Create byte input from string encoded as UTF-8
byte[] input = Encoding.UTF8.GetBytes("Hello Keccak!");

byte[] output = hashAlgo.ComputeHash(bytes);

But again, be aware that Keccak512 is not the same as SHA-3 - it won't give the same hash as an actual 512 bit SHA-3 implementation.
Actual implementations of the final SHA-3 in C# are still (2017) few and far between - the difference to Keccak as implemented in Hashlib is extremely minor, although it has major impact on the output, as would be the case for a hash algorithm - since Wikipedia no longer provides an example of the difference, here's one:
Keccak-512('abc') =
Keccak[1024]('abc', 512) =
    18 58 7d c2 ea 10 6b 9a 15 63 e3 2b 33 12 42 1c
    a1 64 c7 f1 f0 7b c9 22 a9 c8 3d 77 ce a3 a1 e5
    d0 c6 99 10 73 90 25 37 2d c1 4a c9 64 26 29 37
    95 40 c1 7e 2a 65 b1 9d 77 aa 51 1a 9d 00 bb 96

SHA3-512('abc') =
Keccak[1024]('abc' || 01, 512) =
    b7 51 85 0b 1a 57 16 8a 56 93 cd 92 4b 6b 09 6e
    08 f6 21 82 74 44 f7 0d 88 4f 5d 02 40 d2 71 2e
    10 e1 16 e9 19 2a f3 c9 1a 7e c5 76 47 e3 93 40
    57 34 0b 4c f4 08 d5 a5 65 92 f8 27 4e ec 53 f0

Keccak[c](M || s, d) means "Keccak with capacity c, message M, suffix bits s, and output size d."
This (from the Wikipedia article) is the only difference between "standard" Keccak (and Hashlib's implementation) and SHA-3 as it looks in the current spec:

For SHA3-n, an additional two bits 01 are appended to the message before padding.

Implementing it (by e.g. patching the Hashlib code) isn't trivial, though, without knowing how Hashlib works.
So, should you use SHA-3?
It depends on what you want it for - it's no good if you want compatibility with the finalized SHA-3 standard.
The whole Keccak family, independent of SHA-3, is a standard in itself - but NIST's tweaks for SHA-3 are still Keccak - just a specific subset of it (much like AES is a subset of Rijndael). When SHA-3 eventually shows up in - for example - the .NET framework itself, it will likely just be SHA-3 with the parameters NIST picked, rather than a generic Keccak with tweakable parameters.
SHA-512 (answer to a part of the question that has now been removed)
SHA-512 is SHA-2 512 bit - not the same as SHA-3 512. That said, to use it, you simply import System.Security.Cryptography - using in this case imports the namespace - making the classes inside the namespace available to your code.
After that, the workflow is the same as any other HashAlgorithm.
So, should I use SHA-2 or SHA-3 for hashing passwords?
Neither of them. Or at least neither on their own. And while a salt improves matters, that's not optimal security either. See How to securely hash passwords, specifically starting from:

A basic hash function, even if secure as a hash function, is not appropriate for password hashing

A:
What is Hashlib?

Basically it's a library implementing many hashing algorithms.

Is it a Library?

Yes

Is the output result/work process/function of Hashlib and
  System.Security.Cryptography.HashAlgorithm same? If not, then what is
  the difference between them?

Yes.
Hashlib provides the HashLib.HashFactory.Wrappers which can be used to convert the implementation provided by hashlib to System.Security.Cryptography.HashAlgorithm
It can be used this way.
IHash hash = HashFactory.Crypto.CreateSHA256();
System.Security.Cryptography.HashAlgorithm algorith = HashLib.HashFactory.Wrappers.HashToHashAlgorithm(hash);


text:
Q: Deleting every second occurence of a word in a txt file (Python)l I know I have already posted a similar question but this one is different and I have more code. Since the last question was voted down (although the answers were helpful to me) the mods could delete it so as not to clutter the forum.
Anyway, hopefully no one will be irritated by me asking another question trying to achieve my goal.
I am attempting to delete every odd occurrence of a name in a txt file. There are two parts to my question:
a) why do I get AttributeError: 'str' object attribute replace is read-only
b) am I going about this the right way using an accumulator pattern or is there a better way to do this? Someone else has already suggested using the re module but since I am a beginner and I don't know much about it, I am trying to avoid it for the time being.
This is my code so far:
f = open("old_text.txt")
temp = f.read()
f.close

new_file = open("new_text.txt", "w")

counter = 0
name = "Courtney"

for number in range(temp.count(name)):
    counter = +1
    temp.find("Courtney")
    if counter % 2 == 0:
        pass
    else:
        temp.replace = ("Courteny", "")

new_file.write(temp)
new_file.close

So I want to delete the first occurrence of 'Courtney' but not the second and so on until the end of the file. Then write the results to a new file.
Any help is much appreciated,
Fluffy

A: f = open("old_text.txt")
temp = f.read()
f.close

new_file = open("new_text.txt", "w")

counter = 0
name = "Courtney"

for number in range(temp.count(name)):
    counter = +1
    temp.find("Courtney")
    if counter % 2 == 0:
        pass
    else:
        temp = temp.replace("Courteny", "")
#                         ^ No need for = sign here

new_file.write(temp)
new_file.close

str.replace is a function, and takes in two parameters, first the thing you want to replace, and second the thing you want to replace it with. So, you do not need to assign anything here.
This is what your code should look like:
remember = []
with open('old_text.txt', 'r') as old:
    for var in old:
        remember += str(var).split(' ')[::2]
        remember += "\n"

with open('new_text.txt', 'w') as new:
    for var in remember:
        new.write(var + ' ')

print remember

A: This should do it:
import collections
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
  counts = collections.defaultdict(int)
  for line in infile:
    line = line.strip().split()
    for word in line:
      if not counts[word]%2:
        outfile.write(word + " ")
        counts[word] += 1
    outfile.write('\n')


text:
Q: How to update changed on GitHub from PyCharm So I am new to GitHub and decided to add my project there (https://github.com/MiniMinnoww/moviepy-video-editor)
Now I have edited my files a bit in my PyCharm editor, and now I want to update the files on GitHub to match them - how do I do this?

A: So I have figured it out! I have to click 'Git' on the menu bar, then 'current file' then 'commit' and 'commit and push'


text:
Q: How to verify if a compound logical statement is a tautology using substitution I have two examples to figure out, and I've verified the first. The second one is giving me trouble, though. Here is the statement:
$[(p \lor q)\to r] \leftrightarrow  [\lnot r \to \lnot(p \lor  q)]$
All I've done is substitute $(p \lor  q)$ with s, giving me:
$[s\to r] \leftrightarrow  [\lnot r \to \lnot s]$
Since I couldn't figure out a way to simplify further, I made a truth table. When I made up a truth table based on this simplified statement, it doesn't seem to be a tautology. When s and r are the same value ($s = 1$ and $r = 1$, for example) then the biconditional ends up being true, but that's not enough for this to be a tautology, is it?

A: The substitution leading to $(s \to r) \leftrightarrow (\neg r \to \neg s)$ is correct, and this formula is a well-known
tautology. You are right in saying that it's not enough to consider the case $r = s$; maybe there's an error in your truth table somewhere? It should yield true in every row.


text:
Q: Java - Trying to use .setBytes function for SQLite but getting ArrayIndexOutOfBounds 0 error I am trying to insert an image as a blob into the database and first i create the image as a ByteArrayOutsream which I then proceed to use in my prepared statement as a parameter , however I am getting the java.lang.ArrayIndexOutOfBoundsException: 0 error and I have checked that the array length and values are all correct so I don't know what position is trying to access in the array in order to give me this error
Here is my code:
public Boolean insertIntoProducts(String name, String description, String filePath, Double price, int quantity) {
        String url = "jdbc:sqlite:C:/Users/User/Desktop/MyDatabase.db";
        Boolean success = false;
        String sqlSelectID = "SELECT ID FROM Products ORDER BY ID DESC";
        filePath = filePath.replace("\\", "/");
        // Establishing a connection to the database
        String sql = "INSERT INTO Products(ID,Name,Description,Quantity,Price,Image,isAuthorised) "
                            + "VALUES (" + quantity + ",'" + name + "','" + description + "'," + quantity + ",'" + price
                            + "','?','0');";
        try (Connection conn = DriverManager.getConnection(url)) {
            PreparedStatement pstatement = conn.prepareStatement(sql);
            File image = new File(filePath);
            FileInputStream input = new FileInputStream(image);
            ByteArrayOutputStream barray = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            for(int readNum; (readNum = input.read(buffer)) != -1;) {
                barray.write(buffer, 0 , readNum);
            }
            input.close();
            int i = barray.toByteArray().length;
            byte[] array = new byte[i];
            array = barray.toByteArray();
            pstatement.setBytes(1, array);
            pstatement.executeUpdate();
            success = true;
        }catch(Exception e) {
            System.out.println(e.getCause());
        }

        return success;
    }

I am getting the error at line  pstatement.setBytes(1, array);