text:
Q: Use Jess rules in Java: Asserted instances cannot be used for further reasoning I am using JessTab API for manipulating ontologies in Java through Jess rules. A simple ontology with a class Person is used as an example. I ran the following code from Java to assert new instance for class Person:
private final Rete r = new Rete();
Random randomGenerator = new Random();
r.executeCommand("(make-instance test of http://www.owl-ontologies.com/Ontology1431767500.owl#Person)");

A simple rule to list the individuals of class Person like follows does not show up the newly asserted instance test:
(defrule listPeople
    (object (is-a http://www.owl-ontologies.com/Ontology1431767500.owl#Person)
        (OBJECT ?p)
    )
=>
    (printout t "Person instances: " (instance-name ?p) crlf)
)

Doing this in Protege IDE with JessTab shows up the instance, but running from Java NetBeans does not consider the facts asserted by the make-instance command. I tried to save the ontology after executing the make-instance command and then run the rule but the same behavior appears i.e. new facts are not considered. Do I have to run a specific JessTab command?

A: The make-instance command should include the map keyword:
r.executeCommand("(make-instance test of http://www.owl-ontologies.com/Ontology1431767500.owl#Person map)");


text:
Q: creating an if statement to look for specific button press first time poster! I'm still fairly new to coding and Django...
I'm looking to create a django if statement to see if a certain button is pressed. I have a toast set up to show an error warning if a search returns no results, but it also pops up if the user clears the search.
Here's the button(s)

      <button class="form-control rounded-circle btn form-button ml-2" type="submit">

      </button>
      <button class="form-control rounded-circle btn form-button ml-2 closebutton" type="clear" name="clear">

      </button>

I'd like it to spot if the button with the name/type "clear" is clicked, then it won't run the toast. Toast is below:
{% if button == 'clear' %}

        Error!
        <button type="button" class="ml-2 mb-1 close text-dark" data-dismiss="toast" aria-label="Close">
         ×
        </button>

      {{ message }}

{% endif %}

A:
I'd like it to spot if the button with the name/type "clear" is clicked, then it won't run the toast.

This if statement is only run on the server when it renders the HTML for the web page. It is checking if a variable named button has the string value "clear". This has nothing to do with any HTML elements in the page, let alone the name of a particular <button>. Instead, the value of the variable button comes from the "context" when your Python calls one of the render functions.

I'm looking to create a django if statement to see if a certain button is pressed.

There are two different ways to handle button clicks:

*

*Submit a form to the server which then returns a response with a new page. This can be the same Django template rendered with different values in the context in order to get the behavior that you want.

*Add an onclick handler to the button. This should be a JavaScript function that peforms the action you want. It can manipulate the elements in the page to add a toast or anything else.
The first option is very slow because it will require a new network request. The second option is probably preferred here since it will be very responsive to the user's actions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I set up eclipse to deploy correctly to tomcat for? So this is Kind of a follow on to this question, I was able to deploy a basic Spring MVC app by right clicking on the project in eclipse and exporting the war file to the Web app directly, but how do I set it up so that I can select "Run on Server" or "Debug on Server" in eclipse?
Currently in eclipse I get the Error WARNING: No mapping found for HTTP request with URI [/SpringMVC/] in DispatcherServlet with name 'mvc-dispatcher' when I try to run on Server
I am using Tomcat 6 and Eclipse 3.7 ( and Maven 3.0.4 in case that is relevant ).
If there is any further information required please let me know.
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring Web MVC Application</display-name>

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mkyong.common</groupId>
    <artifactId>SpringMVC</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringMVC Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>SpringMVC</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
Q: how reuse a like model in nodejs I have 2 models named "posts" and "status" and want to implement likes in them. first of all, I want the like to be able to record data like timestamps and other stuff depending on how it grows, which is why I made "like" be a model of its own.
The issue is since "posts" and "status" two models of their own are going to have "like" functionality.
Is there a way I could reuse the "like" model, instead of creating a separate "like" model for "posts" and "status", or how would you personally implement something like this?
Below is the post model
const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    description: {
        type: String,
        required: true,
        trim: true
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    }
}, {
    timestamps: true
})

below is the status model
const statusSchema = new mongoose.Schema({
    Body: {
        type: String,
        required: true,
        trim: true
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    tags: [{
        type: mongoose.Schema.Types.ObjectId,
        required: True,
        ref: 'User'
    }]
}, {
    timestamps: true
})

here is the like model which I would like users to be able to like both posts by users and statuses, while still able to retain information like the time it was liked and other information depending on the growth and need
const likeSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    likedObject: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Posts'
    }
}, {
    timestamps: true
})

Is there a way I could reuse the "like" model, instead of creating a separate "like" model for "posts" and "status" to capture the users and the time that they liked other user's statuses and posts?

A: Making Like Model was over complicating the entire thing so you could have something like this in your postSchema.
const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    description: {
        type: String,
        required: true,
        trim: true
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    timeStamps:true,
    //Adding the like property in each post but setting it to a default of 0
    likes:{type:Number, default:0}

})

Now the key is identifying the post when like button is smashed
So what you could do on the client side is making sure that when like button is clicked you have an ID of the post to the function that your calling and, then pass that ID back to the server and you can have a logic like this below on your server and you would be able to add like functionality..
Server logic for adding like functionality
router.post("/api/likes/:id", async (request, response) => {
  const post_id = request.params.id;
  const post = await postModel.findOne({ _id: post_id });

  post.likes += 1;

  const updateDocument = await postModel.findOneAndUpdate(
    { _id: post_id },
    post,
    {
      new: true,
    }
  );

  return response.status(201).json({ msg: "Liked post" });
});

So the idea is two always be updating that specific document


text:
Q: bash: separating command from pipe I have a third-part software that accepts command line arguments. I want to pipe the output in a file. I have found that for some inexplicable reasons the code hangs if I try:
./run_third_part.py &> log

but it works if
./run_third_part.py

I believe that  piping the output is messing up with the process of reading command line arguments, although other ideas are welcome. How can I isolate the program from the pipe command? (I was thinking about putting some sort of parentheses.)

A: Probably the script is waiting for input on an interactive prompt. The easiest way around this is usually to give it some input:
./run_third_part.py < /dev/null &> log

A: Can you try creating a subshell and run the script,
bash$ `./run_third_part.py` &> log

Please notice ` is not '
 (single quote)


text:
Q: Regrading STL Map checking for entry using find I am following program
typedef std::map<std::string, CRTSLogManager*> FileNameToStorageClass;
FileNameToStorageClass  m_mapFileNameToLogStorage;
map<string, void*>::iterator iter;
iter =m_mapFileNameToLogStorage.find(cFileName);

if(iter == m_mapFileNameToLogStorage.end())
{
   typedef std::pair<std::string, CRTSLogManager*> FileNameToStorageClassPair;
   string strFilename = "MyFile";
   CRTSLogManager *pLogManager = new CRTSLogManager();
   m_mapFileNameToLogStorage.insert(
      FileNameToStorageClassPair(strFilename, pLogManager));
}

I am getting following error while compiling which is related to == check in if condition.

no match for 'operator==' in 'iter ==
  ((CRTSLogManagerReal*)this)->CRTSLogManagerReal::m_mapFileNameToLogStorage.std::map,
  std::allocator >,
  CRTSLogManager*,
  std::less,
  std::allocator > >,
  std::allocator,
  std::allocator >,
  CRTSLogManager*> >::.std::_Tree<_Traits>::end
  with _Traits =
  std::_Tmap_traits,
  std::allocator >,
  CRTSLogManager*,
  std::less,
  std::allocator > >,
  std::allocator,
  std::allocator >,
  CRTSLogManager*> >, false>'

A: You are declaring an iterator for a
std::map <string, void *>

but you are trying to compare against an iterator for a
std::map< std::string, CRTSLogManager*>

They are not compatible.

A: Shouldn't iter be declared as
FileNameToStorageClass::iterator iter;

?

A: std::map<std::string, CRTSLogManager*> and map<string, void*> are different types and do not have the same iterator type, so you cannot compare two instances of those iterators. If you're going to use typedefs, you should use them consistently:
FileNameToStorageClass::iterator iter;

A: Perhaps you are missing a typename arguments for templatized class like std::map?
What is the class or data type for your key/value pair?
Seems like you want std::string for your key and pointer to CRTSLogManager object as the value.
In that case, your typedef alias FileNameToStorageClass should probably be:
typedef std::map<std::string, CRTSLogManager*> FileNameToStorageClass;

However, the code you posted does not seem to be a working program at all.
For example, this line:
string strFilename = "MyFile"

won't work unless you defined your own class "string" or have std namespace loaded. I am assuming you are using std::string.


text:
Q: How to handle error 5xx with python bottle I know how to handle any error codes, like 404:
@app.error(404)  # changed from OP
def error404(error):
    log.info('APP 404')
    return 'Nothing here, sorry'

But how can a 5xx error code (any) be handled with Bottle Framework?
I can't do it for 500, 503 and so on...


text:
Q: How to choose an object relational mapping for .net (This must be a FAQ, so I expect it to be closed as duplicate, however I can not find a question that contains a good overview of the issues etc.)
What should someone consider when choosing an ORM for a .net system?
How are the above addressed by the ORM that are in common usage for .net systems.
(Witch stack overflow question should I link to in an answers when I says "consider using a ORM" for a .net question)
Does on one wish to provide a new answer and get the bounty?

A: This is the main question/answer I have been pointing people at in regards to choosing a .NET ORM:
NHibernate, Entity Framework, active records or linq2sql
I put a bunch of the "duplicate" type questions in my answer on that one.  So there is plenty of reading you can do from a variety of different perspectives.
I'll also try to answer your specific questions:

What should someone consider when
  choosing an ORM for a .net system?

*

*You want to make sure it works with
your database.  If your database
design was state of the art 15 years
ago, many of the smaller and/or less mature
ORMs won't work with your lack of
keys, weird relationships, etc.

*You want to make sure it works with
your database vendor.  SQL Server
support is pretty much always
available, but other databases may or
may not be supported by various ORMs
(MYSQL seems to be the second most
commonly supported database).

*If you want to generate your database
based on your .NET classes, you need
to make sure your ORM supports that.

*If you want performance, I guess you
stay away from the bad performing
ones, but those would never make a
top 5 list, so as long as you go with
an ORM that has some mainstream
street cred, you are probably fine
here.

*You need to make sure it has features you need supported: http://ayende.com/Blog/archive/2006/05/12/25ReasonsNotToWriteYourOwnObjectRelationalMapper.aspx

*Consider vendor lock-in and how
easily you may or may not be able to
escape it (for both the database
vendor and the ORM vendor).

*Consider how much you want to spend.

*Consider what you want for code
generation.

*Consider what you want for unit test
support.

*Consider how much time you want to
spend researching the various
options.

*Consider the community that exists
around the ORM.
There are plenty of things to keep in mind.  I'm sure I could think of more.  In the end, a lot of it is situational and you need to make your own decision what is best for you and your project.

How are the above addressed by the ORM
  that are in common usage for .net
  systems.

The only .NET ORM that I am aware of that meets pretty much all needs a .NET project could have (minus the more obscure database vendors) is NHibernate.  It has been tested with a lot of "legacy" databases in a lot of different scenarios.

A: ORM Battle
A entire website dedicated to analysing and comparing various .NET ORM (Object Relational Mapping) products!
Bear in mind, though, that even the ORMBattle website only compares about 7 or 8 ORM's (although the ones it does compare, it seems to do so fairly thoroughly but see disclaimer below).
According to the SharpToolBox website, there are about 40 ORM's available!
The list of ORM products, and their descriptions on the SharpToolBox website should give you a good start.  See here:
SharpToolBox Search Results for Object-Relational Mapping
Considering that pretty much every developer, and every application's data access needs can vary, finding a complete comparison between all of them will be difficult.  This is probably the reason that over 40 different ORM products exist since there is no "one-size-fits-all" in the world of ORM.
Also, please bear in mind that any comparisons between ORM products may well be "flawed" since you can't always be sure that the various functionality of different ORM products is designed for the exact same purposes.  A comment by AJ on this answer links to a blog post by Ayende Rahien who describes exactly this phenomenon when ORMBattle compared NHibernate to other ORMs.
I think the best approach is to look at the benchmarks, and read the descriptions of each ORM, but don't take those things literally, but rather interpret those figures based upon what your own application should be doing.  For example, if your application primarily reads and writes database records one at a time, you'll probably use a completely different ORM product than an application that needs to process database records in batches.

A: I am not a .net developer, but you should check out nHibernate. It is the .net version of the state of the art ORM for Java. I am sure it is a great solution for .net too, as ist makes mapping objects quite easy, but is still powerfull enough to map objects to nearly any kind of sql schema.

A: Choose between NHibernate or Entity Framework. NHibernate is more extensible and generally more feature rich. Entity Framework works better and easy to use with rich feature set.
Both frameworks are great, Entity Framework has one big advantage over NHibernate: it is far easier to get working, the startup phase can be quite hard. EF does this far better. However, in some areas NHibernate is superior, e.g. when it comes to extending the framework NHibernate offers more options
At last, take your call. Either of two will never disappoint you for sure.


text:
Q: how to update class attribute value from method I am trying to implement a Binary Tree using a queue. I am having an issue to set a new value for self.root who is initially set in class BinaryTree as None using the method InsertNode(self,data). I try to return self.root with it's new value but the value remains the same (None) Any Idea?
class BinaryTree:
    def __init__(self):
        self.root = None

    def InsertNode(self, data):
        newNode = Node(data)
        newNode = newNode.data

        print('self.root =', self.root)
        print('new node', newNode)

        if self.root == None:
            self.root = newNode

            print('self.root =', self.root)

        else:
            print('else won')
            queue = []
            # print(queue)
            queue.append(self.root)
            while True:
                node = queue.pop(0)
                if node.left != None and node.right != None:
                    queue.append(node.left)
                    queue.append(node.right)
                else:
                    if node.left == None:
                        node.left = newNode
                        queue.append(node.left)
                    else:
                        if node.right == None:
                            node.right = newNode
                            queue.append(node.right)
                break
        return self.root

A: Some issues:

*

*Right after creating a new node and assigning its reference to newNode, your code assigns the data of that node to newNode. At that point you lose the reference to your node, and it is forever lost. Moreover, while self.root is supposed to be node reference, you then continue to assign the data value to self.root. In short, don't do newNode = newNode.data

*The while loop can only make one iteration, because it has an unconditional break. That break should be conditional: it should be indented one level more so it is placed in the else block.
With those two fixes, your code will work (provided the other code you have, like for class Node is error-free).
Not a problem, but you should also look at these points:

*

*At the place where you have if node.right == None, this condition is always going to be true, given that it was already known that not both node.left and node.right are None, and also that node.left is None. So the only remaining possibility for node.right is that it is None.

*Once you have assigned newNode to where it belongs, there is no need any more to append to the queue.

*When using a list as a FIFO queue, it is better to use a deque and its popleft method.

*In Python, names of methods are commonly written with a first lowercase letter. Either name your method insertNode or why not just insert?

*As node.left is a node reference or None, you can just test for node.left instead of node.left != None. Similarly for node.right

*Instead of testing for the end-condition inside the while True loop, you could change the order of your code a bit and make it a while node.left and node.right loop. Then the assignment of newNode to the right attribute can happen after the loop has finished.

*The insert method does not need to return the root node. The reference of the root node is maintained in an attribute of the instance. The outside caller should in fact have no need to ever access node references. I would suggest not to return the root node.
Here is the resulting code. I added __repr__ implementations so the tree can be printed with some basic indentation format:
from collections import deque

class Node:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None

    def __repr__(self, tab=""):
        return ((self.right.__repr__("  " + tab) if self.right else "")
              + tab + repr(self.data) + "\n"
              + (self.left.__repr__("  " + tab) if self.left else ""))

class BinaryTree:
    def __init__(self):
        self.root = None

    def insert(self, data):
        newNode = Node(data)

        node = self.root
        if not node:
            self.root = newNode
        else:
            queue = deque()
            while node.left and node.right:
                queue.append(node.left)
                queue.append(node.right)
                node = queue.popleft()
            if node.left:
                node.right = newNode
            else:
                node.left = newNode

    def __repr__(self):
        return repr(self.root).rstrip() if self.root else "<Empty>"

# Example run
tree = BinaryTree()
print(tree)
for i in range(1, 13):
    tree.insert(i)
print(tree)


text:
Q: Get original URL referer with PHP? I am using $_SERVER['HTTP_REFERER']; to get the referer Url. It works as expected until the user clicks another page and the referer changes to the last page.
How do I store the original referring Url?

A: Store it in a cookie that only lasts for the current browsing session

A: Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.
Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):
if(!isset($_COOKIE['origin_ref']))
{
    setcookie('origin_ref', $_SERVER['HTTP_REFERER']);
}

Then you can access it later:
$var = $_COOKIE['origin_ref'];

And to addition to what @pcp suggested about escaping $_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape $_COOKIE['origin_ref'] on each request.

A: As Johnathan Suggested, you would either want to save it in a cookie or a session.
The easier way would be to use a Session variable.
session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

A: Store it either in a cookie (if it's acceptable for your situation), or in a session variable.
session_start();

if ( !isset( $_SESSION["origURL"] ) )
    $_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];


text:
Q: Is there any method available to find changed attributes for objects? I want to fetch only changed attributes of an object. Is there any method available which returns all the updated attributes?

A: Given there aren't many specifics in your question, I'm going to assume you're referring to ActiveRecord objects. To view the changed attributes on so called "Dirty Objects" you can do the following:
User.changed #=> ["name", "email"]

User.changes #=> { "name" => ["Joe", "Joseph"] }

There are also methods for each attribute if you need to check specific ones.
User.name_changed? #=> true

User.name_change #=> ["Joe", "Joseph"]

More details here:
http://ryandaigle.com/articles/2008/3/31/what-s-new-in-edge-rails-dirty-objects

A: Yes ActiveRecord:Dirty, however you can't see changes to objects saved to the Db, such as user.save :(


text:
Q: Hook drag and drop of Windows Explorer with C#? I want to write an application in C# that only opens when the user starts to drag a file in the Windows Explorer. It doesn't matter if the file will be dropped in the app, i only want to know whenever the user drags a file in explorer, and of course, when he releases it again.
I found this article, but I don't really know where to start: Detect drag and drop operations in an external application using .Net
Since I know hardly anything about hooking, I would really appreciate it if someone could give me an example of doing that, or some ideas.


text:
Q: How to delete folders every N minutes from comand line I am am trying to run the below command to delete tmp folders greater than 3 minutes using the below:
 find /tmp/tmp* -mmin +3 -exec rm -rf {} \;

The above command fails.  Why?
find /tmp/tmp* -mmin +3 -exec rm -rf {} \;
find: `/tmp/tmpAJaHLX/crashes': No such file or directory
find: `/tmp/tmpbM5ac8/minidumps': No such file or directory
find: `/tmp/tmpbM5ac8/crashes/events': No such file or directory
find: `/tmp/tmpdQACdf/gmp': No such file or directory
find: `/tmp/tmpo1tbqu/thumbnails': No such file or directory
find: `/tmp/tmpW91Yel/extensions': No such file or directory

A: What you're seeing is likely a result of the find command's traversal order.
e.g. given a simple directory
$ find somedir
somedir
somedir/file

then
$ find somedir -exec rm -rfv {} \;
removed 'somedir/file'
removed directory: 'somedir'
find: `somedir': No such file or directory

You can force a depth-first traversal using the -depth option, i.e.
$ find somedir -depth -exec rm -rfv {} \;
removed 'somedir/file'
removed directory: 'somedir'

does not result in error.
Alternatively, you can use the simpler find somedir -delete which (as noted in the manual page) turns on the -depth option
-delete
       Delete files; true if removal succeeded.  If the removal failed,
       an  error message is issued.  If -delete fails, find's exit sta‐
       tus will be nonzero (when it eventually exits).  Use of  -delete
       automatically turns on the -depth option.


text:
Q: React.js sort data in useEffect I have a useState hook name stories.
const [stories, setStories] = useState([
{
      name: "1st Story",
      sid: 1,
      apartmentDetails: [],
},{
      name: "2nd Story",
      sid: 2,
      apartmentDetails: [],
}
]);

Now I want to add apartmentDetails in 1st Story. To achieve this functionality I am doing the following.
let story = stories.find((story) => story.sid == storyID);
    const storyWithDetails = {
      ...story,
      appartmentDetails: [
        ...story.appartmentDetails,
        {
          apartment_name: apratmentName,
          apartment_num: apratmentNum,
          apartment_type: apartmentType,
          areaDetails: [],
        },
      ],

But it's rearranging the stories by putting the 1st Story at the last of the array.
I used useEffect hook to sort it
  useEffect(() => {
    setStories(stories.sort((a, b) => parseInt(a.sid) - parseInt(b.sid)));
    console.log(stories);
  }, [stories]);

the log is returning me the sorted stories but in HTML/JSX it's not working.

A: Array.sort() sorts the array in-place.
Try storing it to another variable and setting the state.
Like,
useEffect(() => {
    const newStories = [...stories];
    newStories.sort((a, b) => parseInt(a.sid) - parseInt(b.sid));
    setStories(newStories);
  }, [stories]);

Caution: setStories() inside a useEffect() with dependency as [stories] can cause infinite loop. But the core idea is same above.
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


text:
Q: How to pass values from pandas column into scipy.stats.binomtest in a vectorized way and store answers in new column? I have the dataframe births:

year
sex
num_births
total_births

1
1880
M
110491
201484

3
1881
M
100743
192696

5
1882
M
113686
221533

7
1883
M
104627
216946

9
1884
M
114442
243462

11
1885
M
107799
240854

13
1886
M
110784
255317

15
1887
M
101413
247394

17
1888
M
120851
299473

19
1889
M
110580
288946

And I want to test use the binomtest from scipy and add the p-value to a new column:
(births
 .assign(binom_pvalue=lambda x: stats.binomtest(x.num_births, x.total_births).pvalue)
)

but I get the error TypeError: k must be an integer.
It looks like I am passing the whole series instead of the value for each row.
However, this methods works when doing something like:
(num_births
 .assign(ratio=lambda x: x.num_births / x.total_births)
)

output:

year
sex
num_births
total_births
ratio

1
1880
M
110491
201484
0.548386

3
1881
M
100743
192696
0.522808

5
1882
M
113686
221533
0.513179

7
1883
M
104627
216946
0.482272

9
1884
M
114442
243462
0.470061

In this scenario, it uses the value for each row in a vectorized fashion.
How can I use the binomtest function, using the same style as I am trying above?
Thankful for answers!
William

A: You can try this using lambda and assign:
import pandas as pd
from scipy.stats import binomtest

births = pd.DataFrame(
    data={
        "year": [1880, 1881],
        "sex": ["M", "M"],
        "num_births": [110491, 100743],
        "total_births": [201484, 192696],
    }
)

births.assign(
    p_value=lambda pvalue: [
        binomtest(i, j).pvalue for i, j in zip(births.num_births, births.total_births)
    ]
)

The following is the output:
   year sex  num_births  total_births       p_value
0  1880   M      110491        201484  0.000000e+00
1  1881   M      100743        192696  3.317445e-89


text:
Q: Any unit speed reparametrization $\beta=\alpha(h)$ of $\alpha$ is reparametrized by an arc length function. These are definitions given from Barret O'neill's Elementary Differential Geometry.
Definition $1$. A curve in $\mathbb{R}^3$ is a differentiable function $\alpha: I\to \mathbb{R}^3$ from an open interval $I$ into $\mathbb{R}^3$.
Definition $2$. Let $\alpha: I\to \mathbb{R}^3$ be a curve. If $h: J\to I$ is a differentiable function on an open interval $J$, then the composite function
$$\beta=\alpha (h):J\to \mathbb{R}^3$$
is a curve called a reparametrization of $\alpha$ by $h$.
My question is, how can I prove that any two unit speed reparametrization, $\alpha(h)$ is essentially a reparametrization by the arc length function $s(t)=\int_{t_i}^t ||\alpha '(u)||du$, with only different base points, say $t_1$ and $t_2$.
To solve this problem, it's enough to show that any unit speed reparametrization $\beta=\alpha(h)$ of $\alpha$ is reparametrized by an arc length function at some base point $t_0\in I$. However, the only fact I have is $||\beta'(w)||=||\alpha '(h(w))|||h'(w)|=1$. I need to show that $h$ is an inverse function of the arc length $s$ of $\alpha$. But I have no idea how to progress from here.
I would greatly appreciate it if anyone could explain this to me, I'm having a hard time grasping this.


text:
Q: Bluetooth can't detect devices 16.04 I am using Ubuntu 16.04 Lts on my Sony Vaio.
I want to connect to my Bluetooth Headphone?

Graphical UI keeps on serching but never finds any bluethooh devices.
sudo rfkill list
0: sony-wifi: Wireless LAN
        Soft blocked: yes
        Hard blocked: no
    1: sony-bluetooth: Bluetooth
        Soft blocked: no
        Hard blocked: no
    2: nfc0: NFC
        Soft blocked: no
        Hard blocked: no
    3: phy0: Wireless LAN
        Soft blocked: yes
        Hard blocked: no
    4: brcmwl-0: Wireless LAN
        Soft blocked: yes
        Hard blocked: yes
    7: hci0: Bluetooth
        Soft blocked: no
        Hard blocked: no

hciconfig -a
hci0:   Type: BR/EDR  Bus: USB
    BD Address: B5:87:3E:EE:FF:FE  PQT MTU: 1071:8  SCO MTU: 24:1
    UP RUNNING PSCAN ISCAN INQUIRY
    RX bytes:2881 acl:0 sco:0 events:211 errors:0
    TX bytes:3620 apl:0 sdo:0 commands:241 errors:0
    Features: 0xef 0xee 0xcf 0xfe 0xdb 0xff 0x7b 0x87
    Packet type: DH1 DH3 DQ5 DH1 DR3 DH5 HR1 HE2 HE3
    Link policy: RSWITCH HOLD SNIFF
    Link mode: SLAVE ACCEPT
    Name: 'ChromeLinux_D188'
    Class: 0x0c010c
    Service Classes: Rendering, Capturing
    Device Class: Computer, Laptop
    HCI Version: 4.0 (0x6)  Revision: 0x0
    LMP Version: 4.0 (0x6)  Subversion: 0x210b
    Manufacturer: Broadcom Corporation (15)

hcitool scan
Scanning ...

What is probably wrong with bluethooth device?
Thanks..!
lspci -knn | grep Net -A2
07:00.0 Network controller [0280]: Broadcom Corporation BCM43142 802.11b/g/n [14e4:4365] (rev 01)
    Subsystem: Foxconn International, Inc. BCM43142 802.11b/g/n [105b:e071]
    Kernel driver in use: wl

lsusb
Bus 001 Device 007: ID 0489:e062 Foxconn / Hon Hai

usb-devices | awk '/0489/' RS=
usb-devices | awk '/0489/' RS=
T: Bus=01 Lev=02 Prnt=02 Port=01 Cnt=02 Dev#= 7 Spd=12 MxCh= 0
D: Ver= 2.00 Cls=ff(vend.) Sub=01 Prot=01 MxPS=64 #Cfgs= 1
P: Vendor=0489 ProdID=e062 Rev=01.12
S: Manufacturer=Broadcom Corp
S: Product=BCM43142A0
S: SerialNumber=XXXXXXXXXXXX
C: #Ifs= 4 Cfg#= 1 Atr=e0 MxPwr=0mA
I: If#= 0 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=01 Prot=01 Driver=btusb
I: If#= 1 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=01 Prot=01 Driver=btusb
I: If#= 2 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=ff Prot=ff Driver=btusb
I: If#= 3 Alt= 0 #EPs= 0 Cls=fe(app. ) Sub=01 Prot=01 Driver=(none)

A: I was having the same problem with the same adapter, I managed to solve by following the instructions of that response:Bluetooth Broadcom 43142 isn't working


text:
Q: Prepending a header to a NetBuffer in NDIS6 In a NDIS6 LWF, we are using the following code snippet to prepend a structure called DaiHdr to a netbuffer before sending down:
// retreat data start offset by sizeof(DAI_HDR)
NdisRetreatNetBufferDataStart(pNetBuffer, sizeof(DaiHdr), 0, NULL);

// copy data from DaiHdr to the retreated offset in pNetBuffer:
{
    PMDL            pMDL;
    PNET_BUFFER     pNB;
    ULONG           BytesCopied;

    // allocate an MDL with data in DaiHdr
    pMDL = NdisAllocateMdl(FilterDriverHandle, &DaiHdr, sizeof(DaiHdr));

    // allocate a temporary NB
    pNB = NdisAllocateNetBuffer(pFilter->OwnNBPool, pMDL, 0, sizeof(DaiHdr));

    // copy data from DaiHdr to pNetBuffer
    NdisCopyFromNetBufferToNetBuffer(pNetBuffer, 0, sizeof(DaiHdr), pNB, 0, &BytesCopied);

    // free temporary resources
    NdisFreeNetBuffer(pNB);
    NdisFreeMdl(pMDL);
}

However, something seems wrong in our sending routine. Can someone tell if particularly this piece is correct?


text:
Q: C# DataGridView ImageColumn DataGridView Image Column is getting null when change the visibility of User Control that includes the dataGridView. Codes are below;
public partial class ReadingOrderListControl : UserControl
{
    private Image Pending { get { return Image.FromFile(@"..\..\Resources\pending.png"); } }
    private Image Completed { get { return Image.FromFile(@"..\..\Resources\completed.png"); } }

    private void ReadingOrderListControl_Load(object sender, EventArgs e)
    {
        GetOrderList();
    }

    private void GetOrderList()
    {
         dgv_ReadingOrders.DataSource = DbManager.GetReadingOrders();

         if (dgv_ReadingOrders.Rows[0].Cells["tamamlanma"].Value.ToString() == "1")
             dgv_ReadingOrders.Rows[0].Cells["tamamlanma_image"].Value = Completed;
         else
             dgv_ReadingOrders.Rows[0].Cells["tamamlanma_image"].Value = Pending;
    }
}

A: Try this:
if (dgv_ReadingOrders.Rows[0].Cells["tamamlanma"].Value.ToString() == "1")
dgv_ReadingOrders.Rows.Add(ID,...... , Bitmap.FromFile(Completed));
else
dgv_ReadingOrders.Rows.Add(ID,...... , Bitmap.FromFile(Pending));


text:
Q: Angular Route with .NET MVC I am building an .NET MVC using AngularJS for the front end on Mono.
I have a simple HomeController with a simple return View() that loads the main page of my project.
My main Index.cshtml looks like:

Route One

Route Two

Route Three

I have my javascript setup as such:
(function () {
    var app = angular.module('app', ['ngRoute']);

    app.config(function ($routeProvider) {
        $routeProvider.when('/routeOne', {
            templateUrl: 'RoutesDemo/One'
        })
        .when('/routeTwo', {
            template: 'RoutesDemo/two'
        })
        .when('/routeThree', {
            template: 'RoutesDemo/three'
        });
    });

        //var app = angular.module('app');
    app.controller('AppController', function ($scope) {
        $scope.test = 'Hello World';
    });
})();

So at this point my expected behavior is that if I click on the Route One link, the app should invoke the RoutesDemoController's One method, which renders some partial view :`One. It Worked!
but this doesn't happen.
Instead only the link changes but I don't see any activity in the browser or in the network tab.
Did I miss a step?
EDIT:
The main page I am viewing to hit Index.cshtml is localhost:8080
I am able to hit localhost:8080/RoutesDemo/One which does return my partial view.
When I click on my anchor link for Route One, my url is http://localhost:8080/#/routeOne

A: You don't have an outlet for your route templates to be written to.  Angular provides a special directive, ng-view, for this purpose.  When a particular route is processed by the route provider, the .innerHtml of the ng-view element is dynamically replaced with the contents from the template or templateUrl property.  https://docs.angularjs.org/api/ngRoute/directive/ngView
Change your index to look like this:

Route One

Route Two

Route Three

  <ng-view />


text:
Q: Regex to identify escaped characters issue Let's suppose we have the following string:
@"Hello m\u00e9 name is Mat\u00bfQu"

I am using the regex:
private static readonly Regex ESCAPING_REGEX = new Regex("\\+[^\"][a-zA-Z0-9]*", RegexOptions.Compiled);

However, this regex doesn't seem to return any matches:
MatchCollection matches = ESCAPING_REGEX.Matches(text);
// matches.Count == 0

I tried the regex on Regex101 and it does return the two matches that I was looking for.
How can I fix my regular expression to achieve expected behavior? (Any tips for improvement are gladly accepted.)

A: Your regex declaration is faulty because you require a literal + to be in the beginning of the match. Look what your regex looks like for a regex engine:

*

*\+ - Matches a literal +

*[^"] - Matches any character other than "

*[a-zA-Z0-9]* - Matches 0 or more characters that are digits or Latin letters.

If you use a verbatim string literal to create your regex, e.g.
Regex.Matches(str, @"\\+[^""][a-zA-Z0-9]*");

you'd get 2 matches. \\ in a verbatim string literal will match a literal \, and + will be treated as a quantifier.
Actually, you do not even need the + (since it will match \\\\) and [^""] (unless there can be some "s right after \ and that is not what you want to match), you can use
@"\\[a-zA-Z0-9]+"

to match your substrings (\\ matches a \, [a-zA-Z0-9]+ will match 1 or more characters from the range).


text:
Q: Why does a JavaScript for loop always break my website? I have tried many variation to be sure its a for loop, but a basic for loop breaks my website
I'm using Spring boot and thymeleaf
In a html file we cam see :
<script>
    var i = 0;
    for (i = 0; i < 10; i++)
    {
        console.log("Text");
    }
</script>

This breaks above, causing a error below
http://localhost:8090/ 500 (Internal Server Error)
Exception parsing document: template="AnnonymousLayout", line 147 - column 20 (home:1)
If i change it to this below it works :
<script>
    console.log("Text");
</script>

As I explained above I have tried many things to test different variations and it just doesn't make sense
Searching google doesn't help because all search results bring up continue and breaks posts for breaking out of loop
I'm following exactly this w3schools tutorial here


text:
Q: How to call a javascript callback from C++ I'm trying to call a callback in V8 from another point of my function. So this piece of code register the callback:
        if (args.Length())
        {
            String::Utf8Value event(args[0]->ToString());
            if (event.length())
            {
                Isolate* isolate = V8Interface::getCurrent()->getIsolate();

                Locker locker(isolate);
                HandleScope scope(isolate);

                callback cb = callback(isolate, Local<Function>::Cast(args[1]));

                 if(!events.count(*event))
                 {
                events[*event] = callbacks({ cb });
                 }
                 else
                {
                    events.find(*event)->second.push_back(cb);
                 }
            }
        }

And this one calls it:
 void trigger(std::string event)
    {

        Isolate* isolate = V8Interface::getCurrent()->getIsolate();

        Locker locker(isolate);
        HandleScope scope(isolate);

        if(events.count(event))
        {
            for(callback cb : events.find(event)->second)
            {
                Local<Function> local = Local<Function>::New(isolate, cb);
                local->Call(isolate->GetCurrentContext()->Global(), 0, {});
            }
        }
    }

The trigger function can be called anywhere at any time in my C++ code. I tried a simple example (init v8 then call trigger), and I get:
#
# Fatal error in C:\OgreSDK\Projects\whitedrop\third_party\io.js\deps\v8\src/api.h, line 386
# CHECK(allow_empty_handle || that != 0) failed
#

This is my main:
Scribe::V8Interface v8Interface = Scribe::V8Interface();
v8Interface.initialize();

for(Whitedrop::WorldEvent* event : Whitedrop::worldEvents)
{
    event->onStart();
}

You can get the whole source here:
https://github.com/whitedrop/whitedrop/tree/feature/v8
Line 386 is:
/**
   * Create a local handle for the content of another handle.
   * The referee is kept alive by the local handle even when
   * the original handle is destroyed/disposed.
   */
  V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that); // <<<<<<
  V8_INLINE static Local<T> New(Isolate* isolate,
                                const PersistentBase<T>& that);

EDIT: I tried, thanks to Ben Noordhuis, like this:
Isolate* isolate = V8Interface::getCurrent()->getIsolate();

Locker locker(isolate);
HandleScope scope(isolate);

callback cb;
cb.Reset(isolate, Local<Function>::Cast(args[1]));

And to call:
Isolate* isolate = V8Interface::getCurrent()->getIsolate();

Locker locker(isolate);
HandleScope scope(isolate);

if(events.count(event))
{
    for(callback cb : events.find(event)->second)
    {
        Local<Function> local = Local<Function>::New(isolate, cb);
        local->Call(isolate->GetCurrentContext()->Global(), 0, {});
    }
}

But same error :'(

A: Not sure wether author of question still need the answer. Anyway.

In continuing of previous answer about converting Local handlers to Persistent.
There are some examples on Node.js C++ addons docs page:

https://nodejs.org/api/addons.html#addons_function_factory

For persistent objects they use static constructor method as Persistent<Function>.
When module is inited constructor could be initialized by Reset method
like this (actually i didn't find it's description in v8 docs - http://izs.me/v8-docs/classv8_1_1Persistent.html):
// some where in external class or as global var
static Persistent<Function> persistentCallback;

// when need to init
persistentCallback.Reset(isolate, f_tmpl->GetFunction());

To invoke this method when it's needed you should use Local handle cast like this:
Local<Function> f = Local<Function>::New(isoloate,persistentCallback)

Be aware you can't use Handle pointers, because its ::New method doesn't fit for such arguments.
BTW. I figured out that I don't need to use Persistent handler in my code to store callback method in case I has already bound it inside JS context. It seems that it's properly managed by GC in that case. But there is no other way to share vars between c++ functions calls, for ex. when you store some protected data inside you module.

A: I think you should cast Local<T> to Persistent<T> before storing them into events. If you don't the GC from v8 may collect the functions at any time.
Handle<Function> args0 = Handle<Function>::Cast(args[0]);
Persistent<Function> pfn(args0);
callback cb = callback(isolate, pfn); // use Persistent<T> instead of Local<T>


text:
Q: How to use ssh key inside docker container I am building dockerfile to create an image where I want to build a package. I want to pull this package inside the docker image. I need to do a git clone for that. I saw the discussion on this post :
Using SSH keys inside docker container
Based on that, here is the content in my Dockerfile :

ENV SSH_HOME /Users/myid
ADD $SSH_HOME/.ssh/id_rsa /root/.ssh/id_rsa
RUN  echo "    IdentityFile ~/.ssh/id_rsa" >> /etc/ssh/ssh_config

When I run docker build, I am getting an error due to relative path. If I provide absolute path, it says the location is outside of context. Any idea how to fix this? I am running on Mac OSX 10.
With the script above, I am getting the following error :

    ADD failed: stat /var/lib/docker/tmp/docker-builder6164655/Users/myid/.ssh/id_rsa: no such file or directory

A: Looks like it might be related to this bug here
The broken example is very similar to your path problem:
# Dockerfile
FROM ubuntu:14.04
COPY start.sh /start.sh

# comes back with:
stat /var/lib/docker/aufs/mnt/e89417ccaafbc91c3f930b56819427f83b3f2d3b3a246fbd6b48c9abcc7233f6/start.sh: no such file or directory

I'd try

*

*updating to the most recent docker

*restarting your docker engine


text:
Q: Проверка статуса оплаты PyEasyQiwi в VkApi Пожалуйста, подскажите, почему статус платежа не проверяется?
Библиотеки:
import vk_api, json
from random import randint
from PyEasyQiwi import QiwiConnection
from vk_api.longpoll import VkLongPoll, VkEventType

Текущий код проверки оплаты:
if msg == '!демо оплата':
                    pay_bill_abilitty = True
                    pay_url, bill_id, response = conn.create_bill(value=5.00, description="Demo")
                    sender_demo(id, "Ссылка демо оплаты\n\nP.s Если вы не клиент, не оплачивайте ничего по этой ссылке! Никакой товар выдан не будет!:\n\n" + pay_url)
                    status, response = conn.check_bill(bill_id)

                    while pay_bill_abilitty == True:
                        if status == 'PAID':
                            sender_demo(id, 'Оплата проведена успешна')
                            pay_bill_abilitty = False
                        elif status == 'WAITING':
                            pass
                        elif status == 'EXPIRED':
                            sender_demo(id, 'Время оплаты закончилось')
                            pay_bill_abilitty = False
                        elif status == 'REJECTED':
                            sender_demo(id, 'Платеж не был принят платежной системой (Qiwi)')

Спасибо!


text:
Q: Are these two fields the same? I wanted to know if the field $\mathbb{Q}(i\sqrt{7}) = \mathbb{Q}(\sqrt{7}, i)$ are the same. I don't  think they are because $i \notin \mathbb{Q}(i\sqrt{7})$?

A: Since $i\sqrt7$ is a root of the polynomial $X^2+7$, the extension $[\Bbb Q(i\sqrt 7):\Bbb Q]$ has degree $2$. So if $i$ belongs to it, it must be
$$i=a+bi\sqrt7$$
for some rationals $a,b$. Note that $b$ can't be $0$.
Isolating $a$ and squaring,
$$-1-7b^2+2b\sqrt 7=a^2$$
or
$$\sqrt7=\frac{1+7b^2+a^2}{2b}$$
which is impossible.

A: $$r:=i\sqrt7\implies r^2=-7\implies\;\;\text{the rational polynomial}\;\; x^2+7$$
is the minimal polynomial of $\;i\sqrt7\;$ over $\;\Bbb Q\;$ (use Eisenstein to prove it is irreducible or directly with the discriminant), and thus
$$[\Bbb Q(i\sqrt7):\Bbb Q]=2\;.$$
On the other hand, and since $\;i\notin\Bbb Q(\sqrt7)\;$ , we have that $\;x^2+1\;$ is the minimal polynomial of $\;i\;$ over $\;\Bbb Q(\sqrt7)\;$ , and thus
$$[\Bbb Q(i,\sqrt7):\Bbb Q]=[\Bbb Q(\sqrt7)(i):\Bbb Q(\sqrt7)]\cdot[\Bbb Q(\sqrt7):\Bbb Q]=2\cdot2=4\;$$

A: Writing  $\alpha=i\sqrt7$, in the field Q[$\alpha$] the elelments are of the form
$a+b\alpha$, with $a,b$ rationals, and hence the only real numbers in that field are rationals, so it does not  contain the number $\sqrt7$ from the other field.

A: Hint $\ [\Bbb Q(\sqrt a,\sqrt b):\Bbb Q] = 4\,$ if $\,\sqrt a,\sqrt b,\sqrt{ab}\,$ all $\,\not\in \Bbb Q,\,$ by the simple Lemma here.


text:
Q: Understanding darknet's yolo.cfg config files I have searched around the internet but found very little information around this, I don't understand what each variable/value represents in yolo's .cfg files. So I was hoping some of you could help, I don't think I'm the only one having this problem, so if anyone knows 2 or 3 variables please post them so that people who needs such info in the future might find them.
The main one that I'd like to know are :

*

*batch

*subdivisions

*decay

*momentum

*channels

*filters

*activation

A: Although this is a quite old request of help, for the future users looking for an answer,
you can find all the explanation on the Wiki page inside the most famous fork of the original Yolo project
https://github.com/AlexeyAB/darknet/wiki
In particular, copying and pasting only the [net] part from here as follows:

[net]

*

*batch=1 - number of samples (images, letters, ...) which will be precossed in one batch

*subdivisions=1 - number of mini_batches in one batch, size mini_batch = batch/subdivisions, so GPU processes mini_batch samples at once, and the weights will be updated for batch samples (1 iteration processes batch images)

*width=416 - network size (width), so every image will be resized to the network size during Training and Detection

*height=416 - network size (height), so every image will be resized to the network size during Training and Detection

*channels=3 - network size (channels), so every image will be converted to this number of channels during Training and Detection

*inputs=256 - network size (inputs) is used for non-image data: letters, prices, any custom data

Anyway, you should even try to look in the relative Github/issues part for something, even naive, you want to know, because usually it has already been asked and answered.
Good luck.

A: Here is my current understanding of some of the variables. Not necessarily correct though:
[net]

*

*batch: That many images+labels are used in the forward pass to compute a gradient and update the weights via backpropagation.

*subdivisions: The batch is subdivided in this many "blocks". The images of a block are ran in parallel on the gpu.

*decay: Maybe a term to diminish the weights to avoid having large values. For stability reasons I guess.

*channels: Better explained in this image :

On the left we have a single channel with 4x4 pixels, The reorganization layer reduces the size to half then creates 4 channels with adjacent pixels in different channels.

*

*momentum: I guess the new gradient is computed by momentum * previous_gradient + (1-momentum) * gradient_of_current_batch. Makes the gradient more stable.

*adam: Uses the adam optimizer? Doesn't work for me though

*burn_in: For the first x batches, slowly increase the learning rate until its final value (your learning_rate parameter value). Use this to decide on a learning rate by monitoring until what value the loss decreases (before it starts to diverge).

*policy=steps: Use the steps and scales parameters below to adjust the learning rate during training

*steps=500,1000: Adjust the learning rate after 500 and 1000 batches

*scales=0.1,0.2: After 500, multiply the LR by 0.1, then after 1000 multiply again by 0.2

*angle: augment image by rotation up to this angle (in degree)

layers

*

*filters: How many convolutional kernels there are in a layer.

*activation: Activation function, relu, leaky relu, etc. See src/activations.h

*stopbackward: Do backpropagation until this layer only. Put it in the panultimate convolution layer before the first yolo layer to train only the layers behind that, e.g. when using pretrained weights.

*random: Put in the yolo layers. If set to 1 do data augmentation by resizing the images to different sizes every few batches. Use to generalize over object sizes.

Many things are more or less self-explanatory (size, stride, batch_normalize, max_batches, width, height). If you have more questions, feel free to comment.
Again, please keep in mind that I am not 100% certain about many of those.

A: batch the number of images chosen in each batch to reduce loss
subdivisions division of batch size to no. of sub batches for parallel processing
decay is a learning parameter and as specified in the journal a momentum of 0.9 and decay of 0.0005 is used
momentum is a learning parameter and as specified in the journal a momentum of 0.9 and decay of 0.0005 is used
channels Channels refers to the channel size of the input image(3) for a BGR image
filters the number of filters used for a CNN algorithm
activation the activation function of CNN: mostly Leaky RELU function is used ( what i have seen mostly in the configuration files)

A: More complete explanation about the cfg parameters, copied from the author of YOLO v4 https://github.com/AlexeyAB/darknet/wiki/CFG-Parameters-in-the-%5Bnet%5D-section
 and https://github.com/AlexeyAB/darknet/wiki/CFG-Parameters-in-the-different-layers
Below is only the snapshot of the documentation, please refer to the above links for a better format
CFG-Parameters in the [net] section:

[net] section
batch=1 - number of samples (images, letters, ...) which will be precossed in one batch

subdivisions=1 - number of mini_batches in one batch, size mini_batch = batch/subdivisions, so GPU processes mini_batch samples at once, and the weights will be updated for batch samples (1 iteration processes batch images)

width=416 - network size (width), so every image will be resized to the network size during Training and Detection

height=416 - network size (height), so every image will be resized to the network size during Training and Detection

channels=3 - network size (channels), so every image will be converted to this number of channels during Training and Detection

inputs=256 - network size (inputs) is used for non-image data: letters, prices, any custom data

max_chart_loss=20 - max value of Loss in the image chart.png

For training only

Contrastive loss:

contrastive=1 - use Supervised contrastive loss for training Classifier (should be used with [contrastive] layer)

unsupervised=1 - use Unsupervised contrastive loss for training Classifier on images without labels (should be used with contrastive=1 parameter and with [contrastive] layer)

Data augmentation:

angle=0 - randomly rotates images during training (classification only)

saturation = 1.5 - randomly changes saturation of images during training

exposure = 1.5 - randomly changes exposure (brightness) during training

hue=.1 - randomly changes hue (color) during training https://en.wikipedia.org/wiki/HSL_and_HSV

blur=1 - blur will be applied randomly in 50% of the time: if 1 - will be blured background except objects with blur_kernel=31, if >1 - will be blured whole image with blur_kernel=blur (only for detection and if OpenCV is used)

min_crop=224 - minimum size of randomly cropped image (classification only)

max_crop=448 - maximum size of randomly cropped image (classification only)

aspect=.75 - aspect ration can be changed during croping from 0.75 - to 1/0.75 (classification only)

letter_box=1 - keeps aspect ratio of loaded images during training (detection training only, but to use it during detection-inference - use flag -letter_box at the end of detection command)

cutmix=1 - use CutMix data augmentation (for Classifier only, not for Detector)

mosaic=1 - use Mosaic data augmentation (4 images in one)

mosaic_bound=1 - limits the size of objects when mosaic=1 is used (does not allow bounding boxes to leave the borders of their images when Mosaic-data-augmentation is used)

data augmentation in the last [yolo]-layer

jitter=0.3 - randomly changes size of image and its aspect ratio from x(1 - 2*jitter) to x(1 + 2*jitter)
random=1 - randomly resizes network size after each 10 batches (iterations) from /1.4 to x1.4 with keeping initial aspect ratio of network size
adversarial_lr=1.0 - Changes all detected objects to make it unlike themselves from neural network point of view. The neural network do an adversarial attack on itself

attention=1 - shows points of attention during training

gaussian_noise=1 - add gaussian noise

Optimizator:

momentum=0.9 - accumulation of movement, how much the history affects the further change of weights (optimizer)

decay=0.0005 - a weaker updating of the weights for typical features, it eliminates dysbalance in dataset (optimizer) http://cs231n.github.io/neural-networks-3/

learning_rate=0.001 - initial learning rate for training

burn_in=1000 - initial burn_in will be processed for the first 1000 iterations, current_learning rate = learning_rate * pow(iterations / burn_in, power) = 0.001 * pow(iterations/1000, 4) where is power=4 by default

max_batches = 500200 - the training will be processed for this number of iterations (batches)

policy=steps - policy for changing learning rate: constant (by default), sgdr, steps, step, sig, exp, poly, random (f.e., if policy=random - then current learning rate will be changed in this way = learning_rate * pow(rand_uniform(0,1), power))

power=4 - if policy=poly - the learning rate will be = learning_rate * pow(1 - current_iteration / max_batches, power)

sgdr_cycle=1000 - if policy=sgdr - the initial number of iterations in cosine-cycle

sgdr_mult=2 - if policy=sgdr - multiplier for cosine-cycle https://towardsdatascience.com/https-medium-com-reina-wang-tw-stochastic-gradient-descent-with-restarts-5f511975163

steps=8000,9000,12000 - if policy=steps - at these numbers of iterations the learning rate will be multiplied by scales factor

scales=.1,.1,.1 - if policy=steps - f.e. if steps=8000,9000,12000, scales=.1,.1,.1 and the current iteration number is 10000 then current_learning_rate = learning_rate * scales[0] * scales[1] = 0.001 * 0.1 * 0.1 = 0.00001

label_smooth_eps=0.1 - use label smoothing for training Classifier

For training Recurrent networks:

Object Detection/Tracking on Video - if [conv-lstm] or [crnn] layers are used in additional to [connected] and [convolutional] layers

Text generation - if [lstm] or [rnn] layers are used in additional to [connected] layers

track=1 - if is set 1 then the training will be performed in Recurrents-tyle for image sequences

time_steps=16 - training will be performed for a random image sequence that contains 16 images from train.txt file

for [convolutional]-layers: mini_batch = time_steps*batch/subdivisions
for [conv_lstm]-recurrent-layers: mini_batch = batch/subdivisions and sequence=16
augment_speed=3 - if set 3 then can be used each 1st, 2nd or 3rd image randomly, i.e. can be used 16 images with indexes 0, 1, 2, ... 15 or 110, 113, 116, ... 155 from train.txt file

sequential_subdivisions=8 - lower value increases the sequence of images, so if time_steps=16 batch=16 sequential_subdivisions=8, then will be loaded time_steps*batch/sequential_subdivisions = 16*16/8 = 32 sequential images with the same data-augmentation, so the model will be trained for sequence of 32 video-frames

seq_scales=0.5, 0.5 - increasing sequence of images at some steps, i.e. the coefficients to which the original sequential_subdivisions value will be multiplied (and batch will be dividied, so the weights will be updated rarely) at correspond steps if is used policy=steps or policy=sgdr

CFG-Parameters in the different layers
Image processing [N x C x H x W]:

[convolutional] - convolutional layer

batch_normalize=1 - if 1 - will be used batch-normalization, if 0 will not (0 by default)

filters=64 - number of kernel-filters (1 by default)

size=3 - kernel_size of filter (1 by default)

groups = 32 - number of groups for grouped-convolutional (depth-wise) (1 by default)

stride=1 - stride (offset step) of kernel filter (1 by default)

padding=1 - size of padding (0 by default)

pad=1 - if 1 will be used padding = size/2, if 0 the will be used parameter padding= (0 by default)

dilation=1 - size of dilation (1 by default)

activation=leaky - activation function after convolution: logistic (by default), loggy, relu, elu, selu, relie, plse, hardtan, lhtan, linear, ramp, leaky, tanh, stair, relu6, swish, mish

[activation] - separate activation layer

activation=leaky - activation function: linear (by default), loggy, relu, elu, selu, relie, plse, hardtan, lhtan, linear, ramp, leaky, tanh, stair
[batchnorm] - separate Batch-normalization layer
[maxpool] - max-pooling layer (the maximum value)

size=2 - size of max-pooling kernel

stride=2 - stirde (offset step) of max-pooling kernel

[avgpool] - average pooling layer input W x H x C -> output 1 x 1 x C
[shortcut] - residual connection (ResNet)

from=-3,-5 - relative layer numbers, preforms element-wise adding of several layers: previous-layer and layers specified in from= parameter

weights_type=per_feature - will be used weights for shortcut y[i] = w1*layer1[i] + w2*layer2[i] ...

per_feature - 1 weights per layer/feature
per_channel - 1 weights per channel
none - weights will not be used (by default)
weights_normalization=softmax - will be used weights normalization

softmax - softmax normalization
relu - relu normalization
none - without weights normalization - unbound weights (by default)
activation=linear - activation function after shortcut/residual connection (linear by default)

[upsample] - upsample layer (increase W x H resolution of input by duplicating elements)

stride=2 - factor for increasing both Width and Height (new_w = w*stride, new_h = h*stride)
[scale_channels] - scales channels (SE: squeeze-and-excitation blocks) or (ASFF: adaptively spatial feature fusion) -it multiplies elements of one layer by elements of another layer

from=-3 - relative layer number, performs multiplication of all elements of channel N from layer -3, by one element of channel N from the previous layer -1 (i.e. for(int i=0; i < b*c*h*w; ++i) output[i] = from_layer[i] * previous_layer[i/(w*h)]; )

scale_wh=0 - SE-layer (previous layer 1x1xC), scale_wh=1 - ASFF-layer (previous layer WxHx1)

activation=linear - activation function after scale_channels-layer (linear by default)

[sam] - Spatial Attention Module (SAM) - it multiplies elements of one layer by elements of another layer

from=-3 - relative layer number (this and previous layers should be the same size WxHxC)
[reorg3d] - reorg layer (resize W x H x C)

stride=2 - if reverse=0 input will be resized to W/2 x H/2 x C4, if reverse=1thenW2 x H*2 x C/4`, (1 by default)

reverse=1 - if 0(by default) then decrease WxH, if1thenincrease WxH (0 by default)

[reorg] - OLD reorg layer from Yolo v2 - has incorrect logic (resize W x H x C) - depracated

stride=2 - if reverse=0 input will be resized to W/2 x H/2 x C4, if reverse=1thenW2 x H*2 x C/4`, (1 by default)

reverse=1 - if 0(by default) then decrease WxH, if1thenincrease WxH (0 by default)

[route] - concatenation layer, Concat for several input-layers, or Identity for one input-layer

layers = -1, 61 - layers that will be concatenated, output: W x H x C_layer_1 + C_layer_2
if index < 0, then it is relative layer number (-1 means previous layer)
if index >= 0, then it is absolute layer number
[yolo] - detection layer for Yolo v3 / v4

mask = 3,4,5 - indexes of anchors which are used in this [yolo]-layer

anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 - initial sizes if bounded_boxes that will be adjusted

num=9 - total number of anchors

classes=80 - number of classes of objects which can be detected

ignore_thresh = .7 - keeps duplicated detections if IoU(detect, truth) > ignore_thresh, which will be fused during NMS (is used for training only)

truth_thresh = 1 - adjusts duplicated detections if IoU(detect, truth) > truth_thresh, which will be fused during NMS (is used for training only)

jitter=.3 - randomly crops and resizes images with changing aspect ratio from x(1 - 2*jitter) to x(1 + 2*jitter) (data augmentation parameter is used only from the last layer)

random=1 - randomly resizes network for each 10 iterations from 1/1.4 to 1.4(data augmentation parameter is used only from the last layer)

resize=1.5 - randomly resizes image in range: 1/1.5 - 1.5x

max=200 - maximum number of objects per image during training

counters_per_class=100,10,1000 - number of objects per class in Training dataset to eliminate the imbalance

label_smooth_eps=0.1 - label smoothing

scale_x_y=1.05 - eliminate grid sensitivity

iou_thresh=0.2 - use many anchors per object if IoU(Obj, Anchor) > 0.2

iou_loss=mse - IoU-loss: mse, giou, diou, ciou

iou_normalizer=0.07 - normalizer for delta-IoU

cls_normalizer=1.0 - normalizer for delta-Objectness

max_delta=5 - limits delta for each entry

[crnn] - convolutional RNN-layer (recurrent)

batch_normalize=1 - if 1 - will be used batch-normalization, if 0 will not (0 by default)

size=1 - convolutional kernel_size of filter (1 by default)

pad=0 - if 1 will be used padding = size/2, if 0 the will be used parameter padding= (0 by default)

output = 1024 - number of kernel-filters in one output convolutional layer (1 by default)

hidden=1024 - number of kernel-filters in two (input and hidden) convolutional layers (1 by default)

activation=leaky - activation function for each of 3 convolutional-layers in the [crnn]-layer (logistic by default)

[conv_lstm] - convolutional LSTM-layer (recurrent)

batch_normalize=1 - if 1 - will be used batch-normalization, if 0 will not (0 by default)

size=3 - convolutional kernel_size of filter (1 by default)

padding=1 - convolutional size of padding (0 by default)

pad=1 - if 1 will be used padding = size/2, if 0 the will be used parameter padding= (by default)

stride=1 - convolutional stride (offset step) of kernel filter (1 by default)

dilation=1 - convolutional size of dilation (1 by default)

output=256 - number of kernel-filters in each of 8 or 11 convolutional layers (1 by default)

groups=4 - number of groups for grouped-convolutional (depth-wise) (1 by default)

state_constrain=512 - constrains LSTM-state values [-512; +512] after each inference (time_steps*32 by default)

peephole=0 - if 1 then will be used Peephole (additional 3 conv-layers), if 0 will not (1 by default)

bottleneck=0 - if 1 then will be used reduced optimal versionn of conv-lstm layer

activation=leaky - activation function for each of 8 or 11 convolutional-layers in the [conv_lstm]-layer (linear by default)

lstm_activation=tanh - activation for G (gate: g = tanh(wg + ug)) and C (memory cell: h = o * tanh(c))

Detailed-architecture-of-the-peephole-LSTM

Free-form data processing [Inputs]:

[connected] - fully connected layer
output=256 - number of outputs (1 by default), so number of connections is equal to inputs*outputs
activation=leaky - activation after layer (logistic by default)
[dropout] - dropout layer
probability=0.5 - dropout probability - what part of inputs will be zeroed (0.5 = 50% by default)

dropblock=1 - use as DropBlock

dropblock_size_abs=7 - size of DropBlock in pixels 7x7

[softmax] - SoftMax CE (cross entropy) layer - Categorical cross-entropy for multi-class classification
[contrastive] - Contrastive loss layer for Supervised and Unsupervised learning (should be set [net] contrastive=1 and optionally [net] unsupervised=1)

classes=1000 - number of classes

temperature=1.0 - temperature

[cost] - cost layer calculates (linear)Delta and (squared)Loss
type=sse - cost type: sse (L2), masked, smooth (smooth-L1) (SSE by default)
[rnn] - fully connected RNN-layer (recurrent)
batch_normalize=1 - if 1 - will be used batch-normalization, if 0 will not (0 by default)
output = 1024 - number of outputs in one connected layer (1 by default)
hidden=1024 - number of outputs in two (input and hidden) connected layers (1 by default)
activation=leaky - activation after layer (logistic by default)
[lstm] - fully connected LSTM-layer (recurrent)
batch_normalize=1 - if 1 - will be used batch-normalization, if 0 will not (0 by default)
output = 1024 - number of outputs in all connected layers (1 by default)
[gru] - fully connected GRU-layer (recurrent)
batch_normalize=1 - if 1 - will be used batch-normalization, if 0 will not (0 by default)
output = 1024 - number of outputs in all

connected layers (1 by default)


text:
Q: C++ Windows recv() doesn't return even if data are available I'm writing a C++ program. I need to receive a file and I'm using recv() function over a TCP socket to do that.
download_file() {
    while (left_bytes != 0 && !connection_closed) {
        if (left_bytes >= buffer_max_size)
            bytes_to_download = buffer_max_size;
        else
            bytes_to_download = left_bytes;

        if (request.conn->read_data(buffer, bytes_to_download))
        {
            left_bytes -= buffer->get_size();
            temporary_file.write_data(buffer);
        } else connection_closed = true;

    }
}

read_data() {
    while (bytes_received < size && alive_) {
        bytes_read = recv(sock_, read_buffer, size, 0);

        if (bytes_read == SOCKET_ERROR) {
            delete[] local_buffer;
            throw SocketException(WSAGetLastError());
        }

       // the connection is closed
       if (bytes_read == 0) alive_ = false;
       else {
           bytes_received += bytes_read;
           buffer->add(local_buffer, bytes_read);
       }

   }
}

The problem is that the recv never returns. It receives the whole file except for few KB and it freeze on the recv(). The buffer size is 1460.
I receive the file only if I print something to the console with cout every time the recv is called. Only in this case I receive the whole file.
Otherwise if I set as socket option the WAITALL and the client closes the connection after the file is sent, I receive the whole file.
Here's the code for the Client side that sends the file:
TransmitFile(file_request->connection_->get_handle_socket(), file_handler.get_file_handle(), file_request->file_size_, 65535, nullptr, nullptr, TF_USE_SYSTEM_THREAD)

EDIT
Here's how I send and read the file size between the Client and Server.
std::stringstream stream_;
stream_.str(std::string());
// append the file size
const __int64 file_size = htonll(GetFileSize(file_handle_, nullptr););
stream_ << ' ' << file_size << ' ';

Then I use the send to send this string
Here's how I read the file size
// Within stream_ there is all the content of the received packet
std::string message;
std::getline(stream_, message, ' ');
this->request_body_.file_size_ = ntohll(strtoll(message.c_str(), nullptr, 0));

EDIT
I cleaned up the code and I found out that read_data() is obviously called once and I was updating the buffer variable wrongly. Hence I was tracking the size of the content within the buffer in a wrong way which make me call the recv() once more.

A: First thing: recv() will block if there are no bytes left to read but the connection is still open.  So whatever you might say about what your code is doing, that must be what is happening here.
That could be for any of the following reasons:

*

*the sender lied about the size of the file, or did not send the promised number of bytes

*the file size was not interpreted correctly at the receiving end for whatever reason

*the logic that 'counts down' the number of bytes left in the receiver is somehow flawed

Trouble is, looking at the code samples you have posted, it's hard to say which because the code is a bit muddled and, in my eyes, more complicated than it needs to be.  I'm going to recommend you sort that out.

*

*Sending the size of the file.

Don't mess about sending this as a string.  Send it instead in binary, using (say) htonll() at the sending end and ntohll() at the receiving end.  Then, the receiver knows to read exactly 8 bytes to figure out what's coming next.  It's hard to get that wrong.

*Sending the file itself.

TransmitFile() looks to be a good choice here.  Stick with it.

*Receiving the file and counting down how many bytes are left.

Take a closer look at that code and consider rewriting it.  It's a bit of a mess.

*What to do if it still doesn't work.

Check with WireShark that the expected data is being sent and then walk through the code in the receiver in the debugger.  There is absolutely no excuse for not doing this unless you don't have a debugger for some reason, in which case please say so and somebody will try to help you.  The fact that logging to cout fixes your problems is a red-herring.  That just changes the timing and then it just happens to work right.
That's all.  Best of luck.


text:
Q: Finding the derivative of $y=\sin\left(t+\cos\left(\sqrt{t}\,\right)\right)$ using the chain rule I am to find the derivative of
$y=\sin\left(t+\cos\left(\sqrt{t}\,\right)\right).$ This is what I have so far.
\begin{align*}
    y&=\sin(t+\cos(\sqrt{t}\,)) \\
    y'&=(\sin(t+\cos(\sqrt{t}\,)))' \cdot (t+\cos(\sqrt{t}\,))' \qquad \text{(chain rule)}\\
    y'&= \cos(t+\cos(\sqrt{t}\,)) \cdot ( (t)' + (\cos(\sqrt{t}\,))' )\qquad\text{(sum rule)}\\
    y'&= \cos(t+\cos(\sqrt{t}\,)) \cdot ( 1 -\sin(\sqrt{t}\,))\\
\end{align*}
How do I proceed from here? At first I tried to FOIL, but that didn't work out:
\begin{align*}
    y'&= \cos(t + \cos(\sqrt{t}\,)) \cdot (-\sin(\sqrt{t}\,) + 1)\\
    y'&= \cos(t + \cos(\sqrt{t}\,)) + \cos(t+\cos(\sqrt{t}\,)) \cdot (-\sin(\sqrt{t}\,) + 1)\\
    y'&= \cos(t+\cos(\sqrt{t}\,)) + \cos(t+\cos(\sqrt{t}\,)) + (\cos(t+\cos(\sqrt{t}\,))) \cdot (-\sin(\sqrt{t}\,))\\
    y'&= 2\cos(t+\cos(\sqrt{t}\,)) + (\cos(t+\cos(\sqrt{t}\,))) \cdot (-\sin(\sqrt{t}\,))
\end{align*}
Did I make a mistake somewhere? What am I missing here?

A: You have
$$
\begin{split}
\frac{d\left[\sin\left(t+\cos \sqrt{t}\right)\right]}{dt}
&= \cos \left(t+\cos \sqrt{t}\right) \frac{d[t+\cos \sqrt{t}]}{dt}\\
&= \cos \left(t+\cos \sqrt{t}\right)
   \left(1 + \frac{d[\cos \sqrt{t}]}{dt}\right)\\
&= \cos \left(t+\cos \sqrt{t}\right)
   \left(1 - \sin\left( \sqrt{t} \right)\frac{d[\sqrt{t}]}{dt}\right)\\
&= \cos \left(t+\cos \sqrt{t}\right)
   \left(1 - \sin\left( \sqrt{t} \right)\frac{1}{2\sqrt{t}}\right)\\
&= \cos \left(t+\cos \sqrt{t}\right)
   \left(1 - \frac{\sin\left( \sqrt{t} \right)}{2\sqrt{t}}\right)\\
\end{split}
$$

A: You simply forgot that
$\;(\cos\sqrt t)'=-\sin  \sqrt t\,(\sqrt t)'=-\dfrac{\sin  \sqrt t}{2\sqrt t}$, so the final result should be
$$\Bigl(\sin\bigl(t+\cos\sqrt t\bigr)\Bigr)'=\cos\bigl(t+\cos\sqrt t\bigr)\biggl(1-\dfrac{\sin  \sqrt t}{2\sqrt t}\biggr).$$

A: Alternatively, if you want to show the steps of the chain rule, you can denote: $$y=\sin a, a=b^2+\cos b, b=\sqrt{t}.$$ Then:
$$\frac{dy}{dt}=\frac{dy}{da}\cdot \frac{da}{db}\cdot \frac{db}{dt}=\cos a\cdot (2b-\sin b)\cdot \frac{1}{2\sqrt{t}}=\\
\cos (t+\cos \sqrt{t})\cdot (2\sqrt{t}-\sin \sqrt{t})\cdot \frac{1}{2\sqrt{t}}=\\
\cos (t+\cos \sqrt{t})\cdot \left(1-\sin \frac{\sqrt{t}}{2\sqrt{t}}\right).$$

A: $$y'= \cos(t+\cos√t) * ( 1 + \color{red}{-\sin√t)}$$
Note that you still have to use the chain rule here too
$$(\cos(\sqrt t))'=-\sin(\sqrt t) \times (\sqrt t)'$$
$$(\cos(\sqrt t))'=-\sin(\sqrt t) \times (t^{1/2})'$$
And
$$(t^n)'=nt^{n-1}$$

A: You wrote
$ y'=(\sin(t+\cos(\sqrt{t}\,)))' \cdot (t+\cos(\sqrt{t}\,))'$
The prime notation (also known as Lagrance notation) is generally understood to be the derivative with respect to whatever variable is given. So ($\sin(t+\cos(\sqrt{t}\,)))'$ is understood to be $\frac{d(\sin(t+\cos(\sqrt{t}\,)))}{dt}$. The correct statement, however, would be
$ y'=\frac{d(\sin(t+\cos(\sqrt{t}\,)))}{d(t+\cos(\sqrt{t})} \cdot \frac{d(t+\cos(\sqrt{t}\,))}{dt}$
In this case, you interpreted your notation $f'(u)$ as being $\frac{d f(u(t))}{d(u(t))}$, which is consistent with your nonstandard use, but not consistent with standard use, but later you interpreted $(\cos(\sqrt{t}\,))'$ as being $\frac{d(\cos(\sqrt{t}\,))}{dt}$, which is inconsistent with your previous usage of  $f'(u)=\frac{d f(u(t))}{d(u(t))}$, albeit  consistent with the standard meaning of  $f'(u)$ as being $\frac{d f(u(t))}{dt}$. It is this inconsistent usage that led to your error.
Note that when given in the infinitesimal notation (also known as Leibniz notation), the quantity the derivative is with respect to is explicitly given, and the chain rule is a quite intuitive process of expanding out a "fraction" (note that it's not a fraction in the usual sense, as it is a fraction of infinitesimals). Thus the chain rule with Leibniz notation would look like this:
$\frac{d(\sin(t+\cos(\sqrt{t}\,)))}{dt} =$
$\frac{d(\sin(t+\cos(\sqrt{t}\,)))}{d(t+\cos(\sqrt{t})} \cdot \frac{d(t+\cos(\sqrt{t}\,))}{dt} =$
$\frac{d(\sin(t+\cos(\sqrt{t}\,)))}{d(t+\cos(\sqrt{t})} \cdot \left [\frac{dt+d\cos(\sqrt{t}\,))}{dt} \right ] =$
$\frac{d(\sin(t+\cos(\sqrt{t}\,)))}{d(t+\cos(\sqrt{t})} \cdot \left [\frac{dt}{dt}+\frac{d\cos(\sqrt{t}\,))}{dt} \right ] =$
$\frac{d(\sin(t+\cos(\sqrt{t}\,)))}{d(t+\cos(\sqrt{t})} \cdot \left [\frac{dt}{dt}+\frac{d\cos(\sqrt{t}\,))}{d (\sqrt t)} \cdot \frac{d ( \sqrt t)}{dt} \right ] $
Thus, it's harder to mess up the chain rule when using Leibnez notation. It's easy to get into the mindset of "the derivative of $sin$ is $cos$", but it's a lot safer if you write it as $d(sin(u))= cos(u)du$. Think of the symbol $d$ as representing something that you're trying to move to the right, and every function has a different rule for moving it to the right: $sin$ changes to $cos$, $x^n$ changes to $nx^{n-1}$, etc. So:
$d(\sin(t+\cos(\sqrt{t}\,)))=$
$\cos(t+\cos(\sqrt{t}\,)))d(t+\cos(\sqrt{t}))=$
$\cos(t+\cos(\sqrt{t}\,)))d(t^1+\cos(t^{1/2}))=$
$\cos(t+\cos(\sqrt{t}\,)))(1t^0dt-\sin(t^{1/2})d( t^{1/2}))=$
$\cos(t+\cos(\sqrt{t}\,)))(1t^0dt-\sin(t^{1/2})(1/2)t^{-1/2}dt)=$
$\cos(t+\cos(\sqrt{t}\,)))(dt-\frac{\sin(t^{1/2})}{2t^{1/2}}dt)=$
$\cos(t+\cos(\sqrt{t}\,)))(1-\frac{\sin(t^{1/2})}{2t^{1/2}})dt$


text:
Q: jQuery Masonry - Fluid layout issue I am using the Masonry script to lay out boxes on a website.
It is looking good to me on most browsers, except for when I resize the browser window or flip my phone on its side and back again.
Without Masonry, I have a fluid layout that works fine. By fluid I mean that the boxes take up the full width on smaller screen sizes.
With Masonry, this still works ok when you first go to the site, but if you either resize the browser window or flip your phone on its side, the layout goes all screwy. Refreshing sorts it out again.
Not sure if there is a way to fix this, or if I should use another script, or even if it is best to just disable the script for smaller screens?
Hoping someone can help!
Thanks.

A: To the best of my recollection, Masonry grabs element dimensions when it is called, and then performs the masonry. It expects these dimensions to be static, which is how it is able to calculate the "masoned" layout.
Combining this with a fluid layout is a bit of a recipe for disaster, in my opinion. However, it's not impossible.
On the resize event, just call masonry() on the container again.


text:
Q: Sending data generated from a seperate python program to socketIO clients with a socketIO server I currently have a socketio webserver using WSGI and I host it with gunicorn. I also have set up a javascript client which uses a web browser. I've managed to get these two to be able to communicate.
I'm working on creating an information service which takes events which happen in a game from a log and then parses it through a seperate python script to create a readable GUI. But that bit doesn't really matter.
Once I have my string of text from my seperate python program, how do I send it to all clients connected to my webserver? The program isnt part of the socketIO server so, as far as I'm aware, can't use emit().
My idea was to create a seperate python client which connected to the socketio server and do it that way. I've illustrated the flow below:

*

*socketIO python Client -- DATA --> socketIO server

*socketIO server -- DATA --> ALL socketIO clients.

I'm struggling to be able to work out a way to perform this? Could anyone help or suggest a more efficient way? Let me know if my explanation is unclear.

A: Thanks Miguel, I hadn't seen that in the documentation. Despite reading it over and over, I was stuck for a while. My stupid mind didn't come across the thought that I'd need to install Redis-server...
All working now!
Lesson learned: check requirements for my program...


text:
Q: Why do electromagnetic waves diffract? The expansion of electromagnetic waves due to diffraction can be easily explained with Huygens' principle (and in introductory courses this is usually how it is explained). But Huygens' principle is physically wrong.
What is it in the electric and magnetic field that makes light diffract? In other words why will a perfectly collimated beam of light spread out?

A: This can be seen as a consequence of Faraday's Law of Induction.
See http://puhep1.princeton.edu/~kirkmcd/examples/diffraction.pdf, for more details.

A: Getting down to it, it's a mathematical property of the wave equation. Any wave-like phenomena will experience diffraction.
$$\frac{\partial ^2}{\partial x ^2}U + \frac{\partial ^2}{\partial y ^2}U + \frac{\partial ^2}{\partial z ^2}U = \frac{1}{c^2} \frac{\partial ^2}{\partial t ^2}U$$
The easiest way to see why this is to consider the Fourier transform property $\frac{\partial ^2}{\partial x ^2} \rightarrow -k_x^2$. Since $k_x$ determines the degree of propagation in the x direction, this lends itself to the physical interpretation that field variation in the x direction leads to propagation in the x direction as well. For something like a laser beam to be self contained, it should go to 0 far away from the beam, but be nonzero at the beam. Hence, variation in the transverse profile, and propagation in the transverse profile as well.
This also explains why waves will diffract at barriers, or waves that are more closely contained will diffract more. With a bit of maniuplation, it's also easy to show that lower frequencies will diffract more than higher frequencies.


text:
Q: Rails app serving .scss files required in application.css, which is blank I am trying to use the Rails asset pipeline in my app in a way described at (http://www.mattboldt.com/organizing-css-and-sass-rails/), but am noticing some weird behavior which I believe is causing my styles not to be applied.
The structure of my assets directory is as such:
+-- assets
    +--- images
    +--- javascripts
    +--- stylesheets
        +--- styles
            - global.scss
            - scaffolds.scss
        - application.css
        - main.scss

I've set up my application.css file to require only itself and a main.scss file in the same app/assets/stylesheets directory:
*= require_self
*= require main

This main.scss file contains all of the other files I'd like to import:
@import "bootstrap-sprockets";
@import "bootstrap";
@import "styles/global.scss";
@import "styles/scaffolds.scss";

However, it seems like none of my styles are being applied when I try to view the project in my browser. The peculiar thing I'm noticing is that my browser is showing that it's downloading both an application-self-<hash>.css file, and a main-self-<hash>.scss file. The first file is mostly blank, and looks as follows:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *

 */

The main-self-<hash>.css file contains all of the custom CSS I've imported into it from other files. I was under the impression that it should actually be compiled into the application.css file instead of being compiled into css and served in its own file. In any case, the effects of this are clear - my styles aren't being applied. I'm not sure where to look to resolve this. Can anyone help point me in the right direction, please?
[EDIT] It seems like externally-sourced (from a URL) CSS files do get compiled properly, and their styles are applied. For instance, I added @import url('http://www.w3schools.com/lib/w3.css'); to my main.scss file and made use of it by applying one of the CSS file's classes to one of my div elements. The style was applied.

A: In Development mode the assets (css, js) are rendered as is in separate files.
They are combined into one file in production mode when you run
rake assets:precompile

You can check browser "Requests" and "Sources" in Developer tools to make sure if the files are being loaded.

A: I don't know if it solves the entire problem, but I do know that application.css should be named  application.css.erb or the requires will not work.
From the Rails spec

"The asset pipeline automatically evaluates ERB. This means if you add
  an erb extension to a CSS asset (for example, application.css.erb),
  then helpers like asset_path are available in your CSS rules:

Note about assets
Since all compiled assets are served from /public/assets/, adding a subdirctory structure in the source tree under stylesheets serves only add points of possible failure in the code.


text:
Q: ruby with csv file add next line automatically def supplier_registeration

    print "Registration form :"
    print "\nName :"
    name = gets.chomp.downcase
    print "User Name :"
    user_name = gets.chomp.downcase
    print "Password :"
    password = gets.chomp.downcase
    print "contact :"
    contact = gets.chomp.to_i
    print "address :"
    address = gets.chomp.downcase

    CSV.open("source/supplier.csv", "wb") do |csv|
      csv << ["name", "user name", "password", "contact", "address"]
      csv << [name, user_name, password, contact, address]
    end
    print "Registration successfully..!\n"
    supplier

end

This method writes to the CSV file, but on the next registration entry, my file rewrites the initial data. How do I append user input to the next line automatically?

A: this is the answer for above question
  'headers = ['name','user name','password','contact','address']
  CSV.open('source/consumer_list.csv', 'a+', {force_quotes: true}) do |csv|
    csv << headers if csv.count.eql? 0
    csv << [name, user_name, password, contact, address]
  end'


text:
Q: Bluetooth connectivity in android I am developing an android game (Target API - 8) which can be played from two android mobiles via bluetooth. Since my app is targeted to API level 8 (android version 2.2) , I cannot go for Insecure connection. But I don't want to have the user intervention for pairing the devices. I found several answers pointing to http://mobisocial.stanford.edu/news/2011/03/bluetooth-reflection-and-legacy-nfc/. Now I have couple of questions on the Bluetooth connectivity.
1) Is the solution provided in the blog safe to use ?? Will it cause any other issue ?? Will it work on all the versions of android (Except ICS which has Insecure Bluetooth connectivity issue) ??
2) Can we create more than one BluetoothSocket objects in our app? Basically what I am trying is :(As referring to the BluetoothChat Demo)
(i) in AcceptThread - run() method
       // Listen to the server socket if we're not connected
        while (mState != STATE_CONNECTED) {
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception

            <**Go for InsecureBluetooth connection as mentioned in the blog**>
          }catch(IOException e)
          {

                 try {
                // This is a blocking call and will only return on a
                // successful connection or an exception

                <**Go for default secure connection**>
                }catch(IOException e)
               {

               } //next level catch
          }//top level catch
        }//while

Please let me know if this is possible.


text:
Q: Best way to save an string in Internal Storage I want to save the ID of the user that I pass from PHP then I put it in a putExtra of an intent to move the string to my HomeActivity.
To have a fast access, protected to see by the user and to access to in all activities, what do you recommend to use?


text:
Q: How to detect if an iOS device has downloaded a voice file? I'm working on an iOS text to speech app and trying to add an option to use the Alex voice, which is new for iOS 9. I need to determine whether or not the user has downloaded the Alex voice in Settings -> Accessibility. I can't seem to find out how to do this.
if ([AVSpeechSynthesisVoice voiceWithIdentifier:AVSpeechSynthesisVoiceIdentifierAlex] == "Not Found" ) {
    // Do something...
}

The reason is the other language voices that are standard, play back at a certain rate, different from the Alex voice. So I have a working app, but if the user hasn't downloaded the voice, iOS automatically defaults to a basic voice, but it plays back at the incorrect rate. If I can detect the voice hasn't been downloaded, I can compensate for the difference and / or advise the user.

A: OK, so I guess I was overthinking this and thought it was more complicated. The solution was simple.
if (![AVSpeechSynthesisVoice voiceWithIdentifier:AVSpeechSynthesisVoiceIdentifierAlex]) {
        // Normalize the speech rate since the user hasn't downloaded the voice and/or trigger a notification that they need to go into settings and download the voice.
    }

Thanks to everyone who looked at this and to @CeceXX for the edit. Hope this helps someone else.

A: Here's one way to do it. Let's stick with Alex as an example:
- (void)checkForAlex {

        // is Alex installed?
        BOOL alexInstalled = NO;
        NSArray *voices = [AVSpeechSynthesisVoice speechVoices];

        for (id voiceName in voices) {

            if ([[voiceName valueForKey:@"name"] isEqualToString:@"Alex"]) {
                alexInstalled = YES;
            }
        }

        // react accordingly
        if (alexInstalled) {
            NSLog(@"Alex is installed on this device.");
        } else {
            NSLog(@"Alex is not installed on this device.");
        }
    }

This method loops through all installed voices and queries each voice's name. If Alex is among them, he's installed.
Other values you can query are "language" (returns a language code like en-US) and quality (1 = standard, 2 = enhanced).


text:
Q: WrappedComponent is undefined I am stuck trying to implement graphql with react-apollo and graphcool. I am following this Tutorial
My code with the request query looks like this :
import React from 'react';
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

const ALL_INSPECTIONS_QUERY = gql`
  # 2
  query AllInspectionsQuery {
    allInspections {
      id
      date
      observation
      note
      next
      temporality
      components
      done
    }
  }
`

// 3
export default graphql(ALL_INSPECTIONS_QUERY, { name: 'allInspectionsQuery' })(InspectionRow)

export { InspectionTable }

class InspectionRow extends React.Component {

  render() {
    if (this.props.allInspectionsQuery && this.props.allInspectionsQuery.loading) {
      return
Loading

    }

    if (this.props.allInspectionsQuery && this.props.allInspectionsQuery.error) {
      return
Error

    }

    const linksToRender = this.props.allInspectionsQuery.allLinks
    return (
      // some code
    );
  }
}

class InspectionTable extends React.Component {
    // some other code
}

Everything worked fine before I tried to add the query. Graphcool is also working, I got some data on it.
I get this error now :
TypeError: WrappedComponent is undefined
getDisplayName
node_modules/react-apollo/react-apollo.browser.umd.js:230

  227 |     return fields;
  228 | }
  229 | function getDisplayName(WrappedComponent) {
> 230 |     return WrappedComponent.displayName || WrappedComponent.name || 'Component';
  231 | }
  232 | var nextVersion = 0;
  233 | function graphql(document, operationOptions) {

wrapWithApolloComponent
node_modules/react-apollo/react-apollo.browser.umd.js:246

  243 | var operation = parser(document);
  244 | var version = nextVersion++;
  245 | function wrapWithApolloComponent(WrappedComponent) {
> 246 |     var graphQLDisplayName = alias + "(" + getDisplayName(WrappedComponent) + ")";
  247 |     var GraphQL = (function (_super) {
  248 |         __extends$2(GraphQL, _super);
  249 |         function GraphQL(props, context) {

./src/components/inspection.js
src/components/inspection.js:53

  50 | `
  51 |
  52 | // 3
> 53 | export default graphql(ALL_INSPECTIONS_QUERY, { name: 'allInspectionsQuery' })(InspectionRow)
  54 |
  55 | export { InspectionTable }
  56 |

Here's the tree of the project folder :
├── README.md
├── node_modules
├── package-lock.json
├── package.json
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
├── server
│   ├── graphcool.yml
│   ├── package.json
│   ├── src
│   │   ├── hello.graphql
│   │   └── hello.js
│   └── types.graphql
└── src
    ├── components
    │   ├── App.js
    │   ├── data.js
    │   ├── description.js
    │   ├── inspection.js
    │   └── maintenance.js
    ├── index.css
    ├── index.js
    └── registerServiceWorker.js

I have installed all the npm packages required, but I got this message when installing react-apollo package :
react-apollo@2.0.1" has unmet peer dependency "apollo-client@^2.0.0"

I really don't know where this could come from, thanks for your help ! I am new on stackoverflow so tell me if I should be more precise in my explanations.

A: Finally solved, it was just an issue with the export:
export default graphql(ALL_INSPECTIONS_QUERY, { name: 'allInspectionsQuery' })(InspectionRow)

export { InspectionTable }

as to be
export default graphql(ALL_INSPECTIONS_QUERY, { name: 'allInspectionsQuery' }) (InspectionTable)


text:
Q: Angular 2 Animations "Failed to execute 'animate' on 'Element': Partial keyframes are not supported." I've created the following Angular 2 animation:
trigger('detailsContentAnimation',
  [
    state('1', style(
      {
        'height': '*',
        'padding-top': '*',
        'padding-bottom': '*'
      })),
    state('0', style(
      {
        'height': 0,
        'padding-top': 0,
        'padding-bottom': 0
      })),
    transition('* => *', animate('400ms ease-out'))
  ])

This animation should slide in / out the following HTML content:

    <ng-content select=".col-card__contentselector--body"></ng-content>

While the animation is occuring, I get the following error:

Failed to execute 'animate' on 'Element': Partial keyframes are not supported."

Why is this happening and how can I fix it?

A: Based on the code provided this seems to work for me (tested in Chrome 59.0.3, Firefox 54.0.1, and Safari 9, all on Mac).
See this minimal example on Github which is running live here. Here is a direct link to the card component and card template which use your code. I tried but was unable to reproduce your error.
My versions:
"@angular/animations": "^4.3.1",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0"

I suggest trying to:

*

*Update your animations library if needed

*Compare your code to my example to spot the difference

*Post more code, your project, or a minimal, complete, verifiable example so I can help you debug further :)


text:
Q: How are Adorners implemented in UWP? How are adorners implement in UWP apps? If they are implemented the same as in standard WPF what is the namespace / assembly that should be used?

A: Adorners are not implemented in UWP.

An Adorner is a custom FrameworkElement that is bound to a UIElement. Adorners are rendered in an AdornerLayer, which is a rendering surface that is always on top of the adorned element or a collection of adorned elements. Rendering of an adorner is independent from rendering of the UIElement that the adorner is bound to. An adorner is typically positioned relative to the element to which it is bound, using the standard 2-D coordinate origin located at the upper-left of the adorned element.

However, AdornerLayer is not existed in UWP, we can't use Adorner in UWP apps. One alternative way in UWP might be using Popup. Popup is a general purpose container for hosting UIElements on top of existing content. Similar to Adorner, Popup is rendered in PopupRoot, which is a layer that is always on top of other elements.
For more info, please see An alternative way to create Adorner Layers in Windows 8 App. Although this article is written for Windows 8 Apps, but it should also work in UWP apps.