text:
Q: Do these properties characterize differentiation? Let $L: C^\infty(\mathbb{R}) \to  C^\infty(\mathbb{R})$ be a linear operator which satisfies:
$L(1) = 0$
$L(x) = 1$
$L(f \cdot g) = f \cdot L(g) + g \cdot L(f)$
Is $L$ necessarily the derivative?  Maybe if I throw in some kind of continuity assumption on $L$?  If it helps you can throw the "chain rule" into the list of properties.
I can see that $L$ must send any polynomial function to it's derivative.  I want to say "just approximate any function by polynomials, and pass to a limit", but I see two complications:  First $\mathbb{R}$ is not compact, so such an approximation scheme is not likely to fly. Maybe convolution with smooth cutoff functions could help me here.  Even if I could rig up something I am concerned that if polynomials $p_n$ converge to $f$, I may not have $p_n'$ converging to $f'$.  My Analysis skills are really not too hot so I would like some help.
I am interested in this question because it is a slight variant of a characterization given here:
Why do we teach calculus students the derivative as a limit?
I am not sure whether or not those properties characterize the derivative, and they are closely related to mine.
If these properties do not characterize the derivative operator, I would like to see another operator which satisfies these properties.  Can you really write one down or do you need the axiom of choice?  I feel that any counterexample would have to be very weird.

A: Yeah, these force it to be ordinary differentiation. We have to show that for each fixed $x_0 \in \mathbb{R}$, the composite
$$C^\infty(\mathbb{R}) \stackrel{L}{\to} C^\infty(\mathbb{R}) \stackrel{ev_{x_0}}{\to} \mathbb{R}$$
is just the derivative at $x_0$. For each $f \in C^\infty(\mathbb{R})$, there is a $C^\infty$ function $g$ such that
$$f(x) = f(x_0) + f'(x_0)(x - x_0) + (x - x_0)^2g(x)$$
and so $(ev_{x_0} L)(f) = ev_{x_0}(f'(x_0) + 2(x - x_0)g(x) + (x - x_0)^2 L(g)(x))$ by the properties you listed. Of course evaluation at $x_0$ kills the last two terms and one is left with $f'(x_0)$, as desired.

A: Here is a slightly more general take on this question. First notice that your condition $L(1) = 0$ is redundant. That is because if you take $f = g = 1$ in your third condition, you get $L(1) = L(1) + L(1)$. It is a theorem that goes back as far as I know to Chevalley (see around page 76 in his Theory of Lie Groups) that if $M$ is a $C^\infty$ manifold, then any linear map $L$ of $C^\infty(M)$ to itself that satisfies the derivation condition (your third condition) is a smooth vector field. This means that in local coordinate $(x_1,\ldots,x_n)$ it has the form $L(f) = \sum_i h_i {\partial f\over \partial x_i}$ where the $h_i$ are smooth functions. Moreover, if we compute $L(x_j)$ using this formula we see that $h_j$ is just $L(x_j)$. So in particular if a linear map $L$ of $C^\infty (R^n)$ to itself satisfies the derivation condition and $L(x_i) = \delta_{ij}$, then $L = {\partial \over \partial x_j}$.

A: I remember thinking the same thing as Richard is saying and thinking about defining $L$ simply by using the third property. I believe only using this property you can prove change rule (but maybe I'm wrong, and my notes are far away).
The caveat is that if you don't use $L(x)=1$, then you can think of (with suitable restrictions on domains) the following:
$$L(f)(x)=\frac{f(x)}{x}$$
which, by the way, satisfies the chain rule. :)


text:
Q: count number of user comments with a specific comment meta value I am using the code below to count the number of comments by a certain user:
global $wpdb;

        $count = $wpdb->get_var(
          'SELECT COUNT( comment_id ) FROM '. $wpdb->comments .'
          WHERE user_id = '.$user->ID.'
          AND comment_approved = "1"
          AND comment_type NOT IN ("pingback", "trackback" )'
        );

I am in addition, using a comment meta field ('consider') which takes 0 or 1 as values. To get its value I use:
get_comment_meta($comment_id, 'consider',true);

How can I merge these two operations so that I get the number of comments submitted by the user and which have the meta value 'consider' equal to 1? I am not an SQL user and it seems that I need to use inside my SQL query the table wp_commentmeta?
Your help is always appreciated.

A: Your basic question is a pure SQL question.
$count = $wpdb->get_var(
  'SELECT COUNT( comments.comment_ID ) FROM '. $wpdb->comments .' as comments
  LEFT JOIN '.$wpdb->commentmeta.' AS cmeta ON comments.comment_ID = cmeta.comment_id
  WHERE user_id = 1
  AND comment_approved = "1"
  AND comment_type NOT IN ("pingback", "trackback" )
  AND cmeta.meta_key = "rating"
  AND cmeta.meta_value = 5'
);

I cleaned that up a bit to be more readable.
What you are doing with that SQL is pretty close, possibly identical to, what you'd get with ....
$args = array(
  'type' => '',
  'user_id' => '1',
  'count' => true,
  'meta_key' => 'rating',
  'meta_value' => '5',
);
$count = get_comments($args);

You aren't explicitly excluding trackbacks and pingbacks with that but I am pretty sure that trackbacks and pingbacks will never have an associated user ID, so you are excluding them by that mechanism.

A: Try this  :
SELECT
    COUNT(*) AS RESULT
FROM
    wp_commentmeta a,
    wp_comments b
WHERE
    a.comment_id = b.comment_ID
AND a.meta_value = 1
AND user_id = 2

Hope it helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to tune parameters of Bagging in R? I was wondering when we use the Bagging to do the classification, what parameters can be tuned and can we use the cross-validation to tune it?
In the Bagging function in R, it says we can use the nbagg to change the number of bootstrap replications. And use rpart.control.
Here's my code
bagging(income ~., data = training3, coob= T)

A: When to use bagging in classification?
Bagging is essentially taking repeated samples from the single training set in order to generate x number of different bootstrapped training data sets. We then train our method on these training sets and average all the predictions in case of regression, we use voting in case of classification. Bagging helps in reducing the variance of an outcome so in cases where your you have a very high variance in your results you often choose bagging, often bagging techniques are outperformed by random forest and boosting.
What parameters can be tuned and can we use the cross-validation to tune it ?
nbagg: The nbagg parameter is used to control the number of decision trees voting
in the ensemble (with a default value of 25). Depending on the difficulty of the learning task and the amount of training data, increasing this number may improve the model's performance but it rquires additional
computational expense.
cp: cp is the complexity parameter when tuned properly gives a pruned tree, The complexity parameter (cp) is used to control the size of the decision tree and to select the optimal tree size. In cases where the cost of adding another variable to the decision tree from the current node is above the value of cp, then tree building does not continue, you can hit and trial to plot it and see what fits for you.
Can we use cross validation?
Yes you can, you should use however caret package to do it(just to make your life simple)
library(caret)
set.seed(1729)
cntrl <- trainControl(method = "cv", number = 10)
train(dependent_variable ~ ., data = mydata, method = "treebag",
        trControl = cntrl)


text:
Q: effeciently updating relationships between hibernate entities I have an m2m relationship between two hibernate entities, let's call them Movies and Actors, which I've setup with bidirectional links.  Obviously this is modeled as a movies table, and actors table, and a join table of foreign keys between the two in the db.
The UI lets you update relationships between Actors and Movies.  Internally, the UI tracks your onscreen updates using the ids of the movies and actors involved, then sends the movie id with a list of actor ids to the controller when you hit "save".
Now my question: suppose I update a Movie by adding four Actors to it in the db.  I have the list of actor ids to add, but I don't have the actual Actor objects, because I've only received their ids from the UI.
To make this update, do I need to populate four full-blown Actor objects just to add them to my Movie object so that I can store it back to the db?  In other words, do I need to first select from my db just to then do the update?  It seems inefficient to make that extra select call since all that will really be updated is adding some rows to the join table, and I already have all the information required to do that.
Does hibernate therefore provide a handy way to directly add keys to the join table itself (without writing a custom raw sql query)?

A: Session.load does what you want. It returns a proxy of Actor containing only the ID of the actor, and assumes you know that the actor exists in the database. If it doesn't, your transaction will of course rollback after the update because of a broken foreign key constraint.
If the actor is already present in the session, it's returned. If the transaction finally needs to call a method on one of the actors, no probem: it's a proxy, and the state of the actor will be loaded if needed.
The equivalent method with a JPA EntityManager is getReference.


text:
Q: login script "you came here by mistake, didn't you?" doesn't show up
Possible Duplicate:
Login script problem

If I enter the URL of loginchk.php I'm supposed to get  "you came here by mistake, didn't you?" But I get "you didn't fill in the required fields". Please help:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>Login | JM Today </title>
    <link href="Mainstyles.css" type="text/css" rel="stylesheet" />

    <?php include("header.php"); ?>
    <?php include("navbar.php"); ?>
    <?php include("cleanquery.php") ?>

       <?php
       ini_set('display_errors', 'On');
        error_reporting(E_ALL | E_STRICT);

        $conn=mysql_connect("localhost", "***", "***") or die(mysql_error());
        mysql_select_db('jmtdy', $conn) or die(mysql_error());

        if(( strlen($_POST['user']) >0) && (strlen($_POST['pass']) >0) && isset($_POST['sublogin'])) {

            checklogin($_POST['user'], $_POST['pass']);

        }
        elseif(( strlen($_POST['user']) == 0) || (strlen($_POST['pass']) == 0) && isset($_POST['sublogin'])){

            echo '
You didn\'t fill in the required fields.

<input type="button" value="Retry" onClick="location.href='."'login.php'\">";
            return;
        }
        else{

            echo '
You came here by mistake, didn\'t you?

<input type="button" value="Retry" onClick="location.href='."'login.php'\">";
            return;

        }

      function checklogin($username, $password){

        $username=mysql_real_escape_string($username);
        $password=mysql_real_escape_string($password);

            $result=mysql_query("select * from users where username = '$username'");
            if($result != false){

                $dbArray=mysql_fetch_array($result);
                $dbArray['password']=mysql_real_escape_string($dbArray['password']);
                $dbArray['username']=mysql_real_escape_string($dbArray['username']);

                if(($dbArray['password'] != $password ) || ($dbArray['username'] != $username)){
                    echo '
The username or password you entered is incorrect. Please try again.

<input type="button" value="Retry" onClick="location.href='."'login.php'\">";
                    return;
                }
                $_SESSION['username']=$username;
                $_SESSION['password']=$password;

                if(isset($_POST['remember'])){
                    setcookie("jmuser",$_SESSION['username'],time()+60*60*24*356);
                    setcookie("jmpass",$_SESSION['username'],time()+60*60*24*356);
                }
            }

            else{
                echo'
  The username or password you entered is incorrect. Please try again.

input type="button" value="Retry" onClick="location.href='."'login.php'\">";
                return;
            }
        }

      ?>

<?php include("footer.php") ?>

A: strlen($_POST['user']) == 0

evaluates to true when $_POST is not set, you should replace it with
isset($_POST['user']) && empty($_POST['user'])

A: Check your paranthesis on this line:
elseif(( strlen($_POST['user']) == 0) || (strlen($_POST['pass']) == 0) && isset($_POST['sublogin'])){

AND (&&) is evaluated before OR (||), therefore the expression evaluates to true. Check http://php.net/manual/en/language.operators.precedence.php for reference.
What you actually need is another set of parenthesis around the user/pass part:
elseif(( ( strlen($_POST['user']) == 0) || (strlen($_POST['pass']) == 0) ) && isset($_POST['sublogin'])){

Or why not check if $_POST['sublogin'] is set before even looking at user/pass data?


text:
Q: Boost asio concurrent timer cancelation problem with strand I am writing a program with the following function:

*

*A server starts up and run trans2C, trans2C will set a candidate_timer_ and call itself every 300ms. Let's say after calling the first trans2C the server's term is 0, then the handler calls the second trans2C the term is 1, and so on.

*During every term, the server will start RV, and RV will set a retry_timer_ to repeatedly call itself every 10ms. When setting retry_timer_, RV will check the retry_timer_'s handler number, if it's not 0, throw an exception.

*I used the boost::asio::strand and there is only one thread.

*Every time the trans2C runs, it cancels candidate_timer_ and retry_timer_.

Let's say in a timepoint in term 8, the RV set retry_timer_ to call itself after 10ms. But after 5ms, the candidate_timer_ expires and calls the trans2C to enter the term 9 and cancels both the timers. In the normal situations the retry_timer_ will be canceled so every time RV is called, there is no handler on retry_timer_ and the program will loop forever. However it is not.
What's wrong with my program?
Reproducible code:
#define BOOST_ASIO_ENABLE_HANDLER_TRACKING

#include <iostream>
#include <vector>
#include <string>
#include <boost/asio.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>

namespace logging = boost::log;
namespace keywords = boost::log::keywords;
namespace attrs = boost::log::attributes;

using namespace boost::asio;
using namespace std;
using boost::asio::ip::tcp;

std::tuple<string, int> another_server("127.0.0.1", 7777);

class instance {
public:
    instance(io_service &loop, const string &_ip, int _port) :
            server_(_ip, _port),
            ioContext(loop),
            candidate_timer_(loop),
            strand_(boost::asio::make_strand(loop)),
            retry_timer_(loop) {
    }

    void run() {
        trans2C();
        ioContext.run();
    }

private:
    void trans2C() {
        BOOST_LOG_TRIVIAL(error) << "trans to candidate";
        cancel_all_timers();
        int waiting_count = candidate_timer_.expires_from_now(boost::posix_time::milliseconds(300));
        if (waiting_count == 0) {
        } else {
            throw std::logic_error("trans2C只能是timer_candidate_expire自然到期触发,所以不可能有waiting_count不为0的情况,否则就是未考虑的情况");
        }
        candidate_timer_.async_wait(boost::asio::bind_executor(strand_, [this](const boost::system::error_code &error) {
            if (error == boost::asio::error::operation_aborted) {
            } else {
                trans2C();
            }
        }));
        RV(another_server);
    }

    void RV(const tuple<string, int> &server) {
        BOOST_LOG_TRIVIAL(trace) << " send rpc_rv to server ";

        int waiting_counts = retry_timer_.expires_from_now(boost::posix_time::milliseconds(10));
        if (waiting_counts != 0) {
            std::ostringstream oss;
            oss << "rv retry timer is set and hooks is not zero, it should be ";
            string s = oss.str();
            throw logic_error(s);
        } else {
            retry_timer_.async_wait(boost::asio::bind_executor(strand_, [this, server](const boost::system::error_code &error) {
                BOOST_LOG_TRIVIAL(trace) << "rv retry_timers expires";
                if (error == boost::asio::error::operation_aborted) {
                    BOOST_LOG_TRIVIAL(error) << "rv retry callback error: " << error.message();
                } else {
                    RV(server);
                }
            }));
        }
    }

private:
    void cancel_all_timers() {
        BOOST_LOG_TRIVIAL(trace) << " all timer canceled";
        candidate_timer_.cancel();
        int retry_handlers_canceled_number = retry_timer_.cancel();
        BOOST_LOG_TRIVIAL(trace) << retry_handlers_canceled_number << " retry_timer is canceled by cancell_all_timers";

    }

    io_context &ioContext;
    std::tuple<string, int> server_;
    deadline_timer candidate_timer_;
    deadline_timer retry_timer_;
    boost::asio::strand<boost::asio::io_context::executor_type> strand_;
};

int main() {
    try {
        boost::asio::io_service io;
        int _port = 8888;
        instance raft_instance(io, "127.0.0.1", _port);
        raft_instance.run();
    } catch (std::exception &exception) {
        BOOST_LOG_TRIVIAL(error) << " exception: " << exception.what();
    }
    return 0;
}

CmakeList:
cmake_minimum_required(VERSION 3.14)
project(raft)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS " -DBOOST_LOG_DYN_LINK")

set(BOOST_ROOT /Users/ynx/boost/build)
#include(FindProtobuf)
#find_package(protobuf REQUIRED)

#if (protobuf_VERBOSE)
#    message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
#endif ()

find_package(Boost COMPONENTS log log_setup serialization REQUIED)
include_directories(${Boost_INCLUDE_DIRS})

add_executable(test_boost_timer_bug tests/boost_timer_bug.cpp
        )
target_link_libraries(test_boost_timer_bug
        ${Boost_LOG_LIBRARY}
        ${Boost_LOG_SETUP_LIBRARY}
        ${Boost_SERIALIZATION_LIBRARY}
        ${Boost_WSERIALIZATION_LIBRARY}
        ${Boost_FILE_SYSTEM_LIBRARY}
        ${Boost_THREAD_LIBRARY}
        ${Boost_SYSTEM_LIBRARY})

Handler tracking log can show something strange (I can't paste it here for that will exceed StackOverflow's 30000 text limit. But it is easy to reproduce it, just run the code), the last cancelation before crash show that it cancels 0 handlers while the "normal" cancelations return 1.

A: According to this How to avoid firing already destroyed boost::asio::deadline_timer and boost timer reference. A timer expired can not be canceled. I think I need to re-designed my program to fit asio::timer's behavior.
And here is the solution: Cancelling boost asio deadline timer safely


text:
Q: xmlstartlet shell script to add attribute and elements under an attribute I am trying to add attribute under an existing attribute in an XML file. I have been using xmlstarted for edit but never used it for update. Would be helpful is someone tell how to add a new attr and an element under that new attrb -
Here is the snippet of my xml file -
Here is what i usually does to edit the sub elements with the hel;p of xmlstarlet-
xmlstarlet edit  --inplace -u "/allocations/queue[@name='root']/queue[@name='paas_api_q1']/queue[@name='child1_sq1']/minResources" --value "$value" myfile.xml

Before -
<?xml version="1.0"?>
<allocations>
  <queue name="root">
    <aclSubmitApps> bddbagrp,mapr</aclSubmitApps>
    <aclAdministerApps> bddbagrp,root,mapr,trmte_id</aclAdministerApps>
    <schedulingPolicy>drf</schedulingPolicy>
    <defaultMinSharePreemptionTimeout>60</defaultMinSharePreemptionTimeout>
    <fairSharePreemptionTimeout>60</fairSharePreemptionTimeout>
    <queue name="paas_api_q1">
      <minResources>90000 mb,15 vcores,2 disks</minResources>
      <maxResources>135000 mb,22 vcores,3 disks</maxResources>
      <queue name="child1_sq1">
        <minResources>66000 mb,11 vcores,2 disks</minResources>
        <maxResources>264000 mb,44 vcores,8 disks</maxResources>
        <aclSubmitApps> paas_opsauto_admin_unix</aclSubmitApps>
        <aclAdministerApps> paas_opsauto_admin_unix</aclAdministerApps>
        allnodes||balanced
      </queue>
    </queue>
  </queue>
  <queuePlacementPolicy>
    <rule create="false" name="specified"/>
    <rule name="reject"/>
  </queuePlacementPolicy>
</allocations>

After it should look like this.. Here i am adding a new attribute under an existing attr - pass_api_q1 .

<?xml version="1.0"?>
<allocations>
  <queue name="root">
    <aclSubmitApps> bddbagrp,mapr</aclSubmitApps>
    <aclAdministerApps> bddbagrp,root,mapr,trmte_id</aclAdministerApps>
    <schedulingPolicy>drf</schedulingPolicy>
    <defaultMinSharePreemptionTimeout>60</defaultMinSharePreemptionTimeout>
    <fairSharePreemptionTimeout>60</fairSharePreemptionTimeout>
    <queue name="paas_api_q1">
      <minResources>90000 mb,15 vcores,2 disks</minResources>
      <maxResources>135000 mb,22 vcores,3 disks</maxResources>
      <queue name="child1_sq1">
        <minResources>66000 mb,11 vcores,2 disks</minResources>
        <maxResources>264000 mb,44 vcores,8 disks</maxResources>
        <aclSubmitApps> paas_opsauto_admin_unix</aclSubmitApps>
        <aclAdministerApps> paas_opsauto_admin_unix</aclAdministerApps>
        allnodes||balanced
      </queue>
      <queue name="child2_sq1">
        <minResources>66000 mb,11 vcores,2 disks</minResources>
        <maxResources>132000 mb,22 vcores,4 disks</maxResources>
        <aclSubmitApps> paas_opsauto_admin_unix</aclSubmitApps>
        <aclAdministerApps> paas_opsauto_admin_unix</aclAdministerApps>
        allnodes||balanced
      </queue>
    </queue>
  </queue>
  <queuePlacementPolicy>
    <rule create="false" name="specified"/>
    <rule name="reject"/>
  </queuePlacementPolicy>
</allocations>

Any help/direction would be appreciated.

A: You could use a bunch of -i/-a/-s to add the new elements (see here), but I think it would be easier to use XSLT with tr. You could put your elements in another file and pass it in as a parameter.
Example...
XML fragment to add (fragment.xml)
<?xml version="1.0"?>
<queue name="child2_sq1">
    <minResources>66000 mb,11 vcores,2 disks</minResources>
    <maxResources>132000 mb,22 vcores,4 disks</maxResources>
    <aclSubmitApps> paas_opsauto_admin_unix</aclSubmitApps>
    <aclAdministerApps> paas_opsauto_admin_unix</aclAdministerApps>
    allnodes||balanced
</queue>

XSLT (test.xsl)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="frag"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="queue[@name='paas_api_q1']" name="target">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <xsl:copy-of select="$frag"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

xmlstarlet command line
xmlstarlet tr test.xsl -p frag='document("fragment.xml")/*' input.xml

Output
<?xml version="1.0"?>
<allocations>
  <queue name="root">
    <aclSubmitApps> bddbagrp,mapr</aclSubmitApps>
    <aclAdministerApps> bddbagrp,root,mapr,trmte_id</aclAdministerApps>
    <schedulingPolicy>drf</schedulingPolicy>
    <defaultMinSharePreemptionTimeout>60</defaultMinSharePreemptionTimeout>
    <fairSharePreemptionTimeout>60</fairSharePreemptionTimeout>
    <queue name="paas_api_q1">
      <minResources>90000 mb,15 vcores,2 disks</minResources>
      <maxResources>135000 mb,22 vcores,3 disks</maxResources>
      <queue name="child1_sq1">
        <minResources>66000 mb,11 vcores,2 disks</minResources>
        <maxResources>264000 mb,44 vcores,8 disks</maxResources>
        <aclSubmitApps> paas_opsauto_admin_unix</aclSubmitApps>
        <aclAdministerApps> paas_opsauto_admin_unix</aclAdministerApps>
        allnodes||balanced
      </queue>
      <queue name="child2_sq1">
        <minResources>66000 mb,11 vcores,2 disks</minResources>
        <maxResources>132000 mb,22 vcores,4 disks</maxResources>
        <aclSubmitApps> paas_opsauto_admin_unix</aclSubmitApps>
        <aclAdministerApps> paas_opsauto_admin_unix</aclAdministerApps>
        allnodes||balanced
      </queue>
    </queue>
  </queue>
  <queuePlacementPolicy>
    <rule create="false" name="specified"/>
    <rule name="reject"/>
  </queuePlacementPolicy>
</allocations>

A: As Daniel Haley points out, using xmlstarlet exclusively can be tedious because it doesn't have a copy/paste functionality which would have made the task much simpler. As an exercise, I tried the code below which seems to work:
xmlstarlet ed
     -a "//queue/queue[@name='paas_api_q1']/queue"
     -t elem -n queue -v "$(xmlstarlet sel  -t -m //queue/queue[@name]/*/* -c . myfile.xml)"
     -i "//queue[@name='paas_api_q1']//queue[not(@name)]" --type attr --name "name" -v "child2_sq1" \
   myfile.xml | xmlstarlet unesc

Basically, it creates a new node in the appropriate place, creates a copy of the original node (using a variable), inserts the copy into the value of new node, adding an attribute and a value to the new node and, finally, unescaping the tags from the copy of the original node.
As I said, just an exercise...
While I haven't tried it, I would guess that this task could also be performed using, instead of xmlstarlet, xidel and its support for xquery.


text:
Q: Proving $\int_0^\infty e^{-ax}x^n\,dx = \frac{1}{a^{n+1}} \Gamma(n+1)$
Prove that $$
\int_{0}^{\infty} \ e^ {-ax} x^{n} dx
=   \frac{1}{a^{n+1}}  \Gamma(n+1)
\qquad (n>-1, \, a>0).
$$

My try:
Let $dv = e^{-ax}$ and $u = x^n$.
Then $v = -\frac{1}{a}e^{-ax}$ and $du = nx^{n-1}$.
So the integral is $ -\frac{1}{a}e^{-ax} x^n |_{\infty}^0  + \int_{\infty}^0 [ -\frac{1}{a}e^{-ax}\cdot nx^{n-1}]$. I'm stuck here.

A: Use substitution $y=ax$, so that the integral becomes
$$\int_0^\infty e^{-y}\left(\frac{y}{a}\right)^n\ \left(\frac{dy}{a}\right)=\frac{1}{a^{n+1}}\int_0^\infty e^{-y}y^{(n+1)-1}\ dy=\frac{1}{a^{n+1}}\Gamma(n+1)$$


text:
Q: Can you define optional docker-compose services? Is there a way to define a Docker Compose service such that it is only brought up when you explicitly request it?
That is to say:
docker-compose up

would not start it, but
docker-compose up optional_service

would.

A: Docker compose now supports profiles, which allow you to a) disable one or more services by default, and b) enable them when docker compose is ran with the corresponding --profile argument.
This is done by adding a profiles key to your service in the docker-compose.yml file. Services that have don't have this key are always started by docker-compose (for all profiles).
For example, with the following docker-compose.yml file
version: '3.9'
services
  app_service:
    # ...
  test_service:
    profiles:
      - testing
    # ...

Running docker-compose up will only start the app_service, and running docker-compose --profile testing up will start both the app_service and the test_service.
Multiple profiles can be specified by passing multiple --profile flags.
More info can be found here: https://docs.docker.com/compose/profiles/
Edit: I had to update to docker engine v20.10.5 for this to work.

A: One way to achieve that is to define your optional service in a different compose file. Then to start the optional service, run:
$ docker-compose -f docker-compose.yml -f optional-service.yaml up

For example, if I have a docker-compose.yml file that looks like:
version: '2.1'
services:
  lb:
    image: nginx:1.13
  db:
    image: redis:3.2.9

I can extend it with an optional-service.yml that looks like:
version: '2.1'
services:
  busy:
    image: busybox

Notice that both compose files must use the same Compose file version.
You can read more about it in the Compose documentation.

A: The extend keyword has been removed in version 3.x.
I faced the same issue and this is what I did:

*

*From Docker's official docs, we can use a COMPOSE_FILE environment variable in a .env file.

*The way this works is: when you do docker-compose up, instead of reading docker-compose.yml, it will read all the compose files specified in COMPOSE_FILE variable.

For example,
COMPOSE_FILE=docker-compose.yml:./optional/docker-compose.prod.yml

*

*the good part is that:

*

*the .env file is auto-read (if located in the same level as docker-compose.yml),  when we invoke docker-compose up.

*no need to specify each file with a -f flag in CLI.

*The one drawback is: need to create separate compose files for each service you wish to make optional.

Note: separate file names with a : in case of linux or ; in case of windows.


text:
Q: How to change MySQL data directory to workspace folder for syncing databace between devices? My problem is that I want to have my MySQL database in my workspace folder. I want to sync my database for all of my workdevices, so that i dont have to export my data every single time a change something.
I tried to create just a softlink to the direktory on every device I use with the mklink /D command in the commandline but I see that this doesn'n work.
Have you any idea how i can configure my database right this?

A: Here is the solution on stackexchange site : change data dir path
Just follow the step by step solution by RolandoMySQLDBA


text:
Q: How to set specific user settings for certain Git remotes? Suppose I have configuration like the following:
[remote "origin"]
        [..]
[branch "main"]
        [..]
[remote "alternative-origin"]
        [..]
        mirror = true
[user]
        name = My Name
        email = my@email.com
        signingkey = mysigningkey
[commit]
        gpgsign = true

How do I set alternative-remote to use another set of user settings?

A: The user settings have nothing to do with your remote: they only affect the identity that is used in your commit messages. By the time git is communicating with a remote server, those commits already exist and have whatever user/email/etc you were using at the time.


text:
Q: Hashing a string into sha256 with openssl So i'm making this program to generate mock data to populate a database and I want my passwords to be in SHA256 for the obvious reasons. Upon looking some stuff up found the openssl/sha.h lib and tried using it - first time using openssl to be honest.
After quite a bit fighting with it I managed to get it running and code the string into sha256, but apparently it's in base64. So far had no luck turning it back into an ASCII string.
Hopefully someone can provide some pointers on how to get this working


text:
Q: Make Sympa authenticate users with another database and tablestructure We would like to integrate Sympa's webinterface with another system using MySQL using the other systems user table.
I've done some searching but since Sympa is poorly documented no results of relevance has shown up.
Is this possible?

A: Sympa authentication is configured by the auth.conf file.  This can contain one or more stanzas defining alternative authentication methods, such as the internal database, LDAP, cas or generic_sso.  Sysmpa identifies users by their email address.
The first two (internal and LDAP) take the user email address and password, and authenticate directly. CAS authentication uses a CAS service.
Generic_sso authentication uses the Web server's own authentication to return a userID, and then obtains the user email address either from metadata or via an LDAP lookup.  One example would be using Shibboleth (via mod_shib) and pulling the email address from the Shibboleth metadata.  However, any web server authentication may be used, so you can easily use mod_mysql or similar to authenticate against an external user database.  In order to get the email address, you can either use an assosciated LDAP lookup, have your web server authentication module return metadata (as an HTTP header), or ensure that the authenticated userID is the same as the email address.
In short; use generic_sso, and then configure the necessary authentication in your web server, making sure to return the email address in the metadata if you cannot map user to email via an LDAP lookup.
The (admittedly poor) documentation on this is here : Sympa authentication
Example:
This auth.conf stanza uses mod_shib to authnticate via Shibboleth; if the mail metadata is returned then it will be used, otherwise an LDAP lookup will be performed to obtain the email address.  In order for the authentication to work, the location /sympa/sso_login/shibboleth is configured in the web server to be protected by Shibboleth using mod_shib.
 generic_sso
   service_name       Shibboleth
   service_id         shibboleth
   http_header_list   mail,displayName,uid,unscoped_affiliation
   netid_http_header  uid
   email_http_header  mail
         ldap_host       ldap.company.com:636
         ldap_timeout    20
         ldap_bind_dn        cn=sympa,o=company
         ldap_bind_password  xxxxxx
         ldap_suffix     ou=users,o=company
         ldap_get_email_by_uid_filter (cn=[uid])
         ldap_email_attribute mail
         ldap_scope      one
         ldap_use_ssl    1

Example:
A similar method can be used to protect a location using a different method, such as mod_auth_mysql or mod_authn_dbd.  If you use mod_authn_dbd, you can return the email address in the same query, from where it will be loaded into the environment. You can then use RequestHeader set in your Apache config to push it into the HTTP headers to be picked up by the email_http_header definition.  See here for the mod_authn_dbd documentation.
 generic_sso
   service_name       MySQL
   service_id         mysql
   email_http_header  x-mail

and in Apache (this is not tested but should be correct):
DBDriver mysql
DBDParams "dbname=apacheauth user=apache password=xxxxxx"
DBDMin  4
DBDKeep 8
DBDMax  20
DBDExptime 300
<Location /sympa/sso_login/mysql>
    AuthType basic
    AuthBasicProvider dbd
    Require valid-user
    AuthDBDUserPWQuery "SELECT password, emailaddr FROM authn WHERE user = %s"
    RequestHeader set x-mail %{AUTHENTICATE_emailaddr}e
</Location>


text:
Q: mp3 extractor for whole album mp3? Some users upload a whole album as a single mp3 file. Is there a tool for Windows which can automatically create separate mp3 files from that file? I don't want to do this manually. I don't care what the mp3 file name is nor if it has missing tags and meta info.

A: There's a whole ton of those out there.  The problem with the 'automatic' ones is that they do 'silence checking' to determine when one song ends and the next begins.
Since lots of songs have 'silent' parts in them, you usually end up needing to manually check everything at the end anyway.
Having said that, the program I use for all my audio editing needs is Audacity. It's free, open source, and cross platform.
It has silence checking in it, as well as other tools to help you split large MP3s into individual tracks.  Here's a link to their Wiki article on the subject.  Plus all you'll need to fix what the 'automatic' things mess up. ;)

A: mp3DirectCut.
If you have a .cue file that goes with the MP3 describing where the split points are, it'll use that. Otherwise you can pick the points by hand, or use 'Pause detection' to guess from where there's silence. (This isn't wholly reliable as there may not be silence between tracks, and there may be silent bits in the middle of a track; check it by manually listening first.)
The point of direct MP3 editors like mp3dc is that they won't re-encode the file. If you load, split and save in a traditional audio editor such as Audacity, you'll be decompressing and recompressing the data; because MP3 is a lossy format that would inevitably result in degraded audio quality.


text:
Q: Django - posts.Post.None I am working on a django project and I have 2 models that look like this:
class Playlist(models.Model):
    user        = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='playlist_user')
    name        = models.CharField(max_length=120)
    image       = models.ImageField(upload_to=upload_image_path)
    genre       = models.CharField(max_length=120,null=True,blank=True)
    track       = models.ManyToManyField('Post',related_name='playlist_track')

class Post(models.Model):
    user        = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    title       = models.CharField(max_length=120)
    slug        = models.SlugField(unique=True)
    image       = models.ImageField(upload_to=upload_image_path)
    audiofile   = models.FileField(upload_to=upload_image_path,null=True)
    genre       = models.CharField(max_length=120,null=True,blank=True)

and this view:
def userprofileview(request):
    own_tracks = Post.objects.filter(user=request.user)
    playlist_ = Playlist.objects.filter(user=request.user)
context = {
    'own_tracks':own_tracks,
    'playlist_':playlist_
}
return render(request,'userprofile.html',context)

but when I try to query the posts from the playlist like this:
{% for object in playlist_ %}
{{ object.track }}
{% endfor %}

I get:
posts.Post.None

Thank you for any suggestions

A: In order to access the related objects, you need to add .all at the end:
{% for object in playlist_ %}
    {% for post in object.track.all %}
        {{ post.title }}
    {% endfor %}
{% endfor %}
To avoid the N+1 problem, you can use .prefetch_related(..) [Django-doc]:
def userprofileview(request):
    own_tracks = Post.objects.filter(user=request.user)
    playlist_ = Playlist.objects.filter(user=request.user).prefetch_related('post')
context = {
    'own_tracks':own_tracks,
    'playlist_':playlist_
}
return render(request,'userprofile.html',context)


text:
Q: Does CancellationToken removes file lock? I have following async function:
private async Task<bool> ValidateFtpAsync()
    {
        return await Task.Run(
            () =>
            {
                if(File.Exists("settings.xml"))
                {
                    var xs = new XmlSerializer(typeof(Information));
                    using (var read = new FileStream("settings.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        Information info = (Information)xs.Deserialize(read);

                        try
                        {
                            var DecryptedInfo = FileCryptoDecryptor.ReadEncryptedConfiguration("hakuna.xml.aes", Global_Variables.AppPassword);
                            string DecryptedFTPPass = EncryDecryptor.Decrypt(DecryptedInfo.FtpPassword, "UltraSecretPasswordNotGonnaSayItToYou");
                            return General_Functions.isValidConnection(info.HDSynologyIP, info.FtpUsername, DecryptedFTPPass);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                    return false;
                }
                else
                {
                    MessageBox.Show("Missing settings file.");
                    return false;
                }

            });
    }

You can see it reads data from a file. My question is if i use CancellationToken for async method does it remove file lock when its in using block?

A: No, cancellation token by itself does not do anything (and in particular does not close files). The task's code needs to check state of the token repeatedly and act accordingly to perform cancellation.
It is unclear where do you plan to use a cancellation token in your case as there is no repeated operations... But since code has properly set with using(…){} statements irrespective where you break the operation the file will be correctly closed in finally block of using (var read = new FileStream(....


text:
Q: Spring+Hibernate+JPA: Add dynamic tables/entities An application permits admin users to upload CSV-files and save them as database tables.
The application uses Spring+JPA+Hibernate to access the database. How can I access the dynamically added new tables/entities to the system, without restarting or even recoding the system?


text:
Q: Assembler failed link obj file MASM32 I am a Chinese who interested in computer science.
I am learning assembly language following Assembly Language FOR x86 PROCESSORS Seventh Edition by Kip Irvine.

I download MASM32 and try coding in MASM32 Editor

code below:
.386
.model flat,stdcall
.stack 4096
ExitProcess PROTO,dwExitCode:DWORD

.data
byteVal BYTE 10h
.code
main PROC
    mov esi,OFFSET byteVal
    mov al,[esi]
    INVOKE ExitProcess,0
main ENDP
END main

When I Assemble ASM file it works and generate .obj file. But, when I Run 'Assemble and Link' I got link errors.

xxxx.obj : error LNK2001: unresolved external symbol _ExitProcess@4
xxxx.exe : fatal error LNK1120: 1 unresolved externals

Can anyone help me solve this & explain why?


text:
Q: pbcopy in Python to copy to the clipboard on OSX? I am receiving the following error when trying to use pbcopy to add the output to the clipboard. I tried different variations of the command and still no luck.
Does anyone have any ideas where I may have failed?
Error Screenshot:

#!/usr/bin/env python3
# This script creates a secure password using all available key combinations.

import secrets , string, os

def prRed(skk): print("\033[91m {}\033[00m" .format(skk))

chars = string.ascii_letters+string.punctuation+string.digits # Cleaner way of assigning variable

print()
pwd_length = int(input('Enter the length of the desired password: '))

print()
print('[+] ' + 'Your secure password is:')
print()

for n in range(1):
    output = ""
    for i in range(pwd_length):
        next_index = secrets.SystemRandom().randrange(len(chars))
        output = output + chars[next_index]
    prRed(os.system("echo '%s' | pbcopy" % output))
print()


text:
Q: rails 6 error messages not working with sign in/sign up modal I am using devise to handle registration with username/email and facebook.  Everything is working except error messages.  If I try to login from the modal and enter the wrong email or password, it doesn't do anything, but I can't figoure out how to get the error messages to appear in the modal form.
If I close the modal after an error and reopen it there are no errors and I'm not sure how to refresh the modal. If it is successfulit logs me in and takes me to my profile page, but if it is not succesful it just sits there. I'm not sure how to open it without clicking a link.
If I submit the registragion form with no or missing info it will go back to the regular sign up page and display the errors but I can't figure out how to hvae it reload the modal and display them there.
Here is the _login.html.erb model:

Member Login

        <button type="button" class="close text-right" data-dismiss="modal" aria-label="Close">
          ×
        </button>

                Login

                <%= form_for(resource, :as => resource_name, :url => session_path(resource_name), :remote => true) do |f| %>
                  <%= render "shared/error_messages", resource: resource %>

                      <%= image_tag("layout/login/icon_reg_email.gif") %>

                      <%= f.email_field :email, class: "form-control shadow rounded", placeholder: "Email", :autofocus => true %>

                      <%= image_tag("layout/login/icon_reg_locked.gif") %>

                      <%= f.password_field :password, class: "form-control shadow rounded", placeholder: "Password" %>

                  <% if devise_mapping.rememberable? -%>

                      <%= f.check_box :remember_me %> <%= f.label :remember_me, class: "form_small_text" %>

                  <% end -%>

                      <%= f.submit "Sign in", :class => 'btn reg-submit-btn' %>

                    <%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
                      <%= link_to t(".forgot_your_password"), new_password_path(resource_name), class: "form_small_text" %>

                    <% end -%>

                <% end %>

            <%= image_tag("layout/login/login_divider.gif") %>

                Sign-Up

                <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), id: "form", :remote => true) do |f| %>
                  <%= render "shared/error_messages", resource: resource %>

                      <%= image_tag("layout/login/icon_reg_name_37_33.gif") %>

                      <%= f.text_field :first_name, class: "form-control shadow rounded", placeholder: "First Name" %>

                      <%= f.text_field :last_name, class: "form-control shadow rounded", placeholder: "Last Name" %>

                      <%= image_tag("layout/login/icon_reg_email.gif") %>

                      <%= f.email_field :email, class: "form-control shadow rounded", placeholder: "Email", :autofocus => true %>

                        <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-question-diamond" fill="white" xmlns="http://www.w3.org/2000/svg">
                          <path fill-rule="evenodd" d="M6.95.435c.58-.58 1.52-.58 2.1 0l6.515 6.516c.58.58.58 1.519 0 2.098L9.05 15.565c-.58.58-1.519.58-2.098 0L.435 9.05a1.482 1.482 0 0 1 0-2.098L6.95.435zm1.4.7a.495.495 0 0 0-.7 0L1.134 7.65a.495.495 0 0 0 0 .7l6.516 6.516a.495.495 0 0 0 .7 0l6.516-6.516a.495.495 0 0 0 0-.7L8.35 1.134z"/>
                          <path d="M5.255 5.786a.237.237 0 0 0 .241.247h.825c.138 0 .248-.113.266-.25.09-.656.54-1.134 1.342-1.134.686 0 1.314.343 1.314 1.168 0 .635-.374.927-.965 1.371-.673.489-1.206 1.06-1.168 1.987l.003.217a.25.25 0 0 0 .25.246h.811a.25.25 0 0 0 .25-.25v-.105c0-.718.273-.927 1.01-1.486.609-.463 1.244-.977 1.244-2.056 0-1.511-1.276-2.241-2.673-2.241-1.267 0-2.655.59-2.75 2.286zm1.557 5.763c0 .533.425.927 1.01.927.609 0 1.028-.394 1.028-.927 0-.552-.42-.94-1.029-.94-.584 0-1.009.388-1.009.94z"/>
                        </svg>

                      <%= image_tag("layout/login/icon_reg_name_37_33.gif") %>

                      <%= f.text_field :username, class: "form-control shadow rounded", placeholder: "Username", id: "username" %>

                      <%= image_tag("layout/login/icon_reg_locked.gif") %>

                      <%= f.password_field :password, class: "form-control shadow rounded", placeholder: "Password" %>

                      <%= image_tag("layout/login/icon_reg_locked.gif") %>

                      <%= f.password_field :password_confirmation, class: "form-control shadow rounded", placeholder: "Confirm Password" %>

                      <%= f.submit "Sign up", :class => 'btn reg-submit-btn' %>

                <% end %>

              <%=link_to( image_tag("layout/facebook_login_200_42.gif"), user_facebook_omniauth_authorize_path) %>

This is the applicatin_helpers.rb file:
module ApplicationHelper
  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end
end

Both forms in the modal work. I can sign up with email/password or facebok and I can create an account and log in but I can't get the errors to show up in the modal.


text:
Q: Carrierwave: Encoding::UndefinedConversionError ("\xFF" from ASCII-8BIT to UTF-8) I'm trying to upload multiple files to a record called Post, with a json attribute called images, using Carrierwave. But when I try to save the record, I get this error:
  (0.5ms)  ROLLBACK
Completed 401 Unauthorized in 15ms (ActiveRecord: 0.8ms)
Encoding::UndefinedConversionError ("\xFF" from ASCII-8BIT to UTF-8):

I've used Carrierwave before and I never got this error. I checked if anyone's had this problem, before, and I didn't find much. This question suggested the activesupport-json_encoder gem, but this gem isn't compatible with Rails 5. Also suggested were the force_encoding method and using a "wb" flag when saving the file, but the Carrierwave code has no place to implement those suggestions.
Here's the code I have:
form
<%= form_for @post, :html => {multipart: true}, do |f| %>
  <%= f.file_field :images, multiple: true %>
  <%= f.submit "submit" %>
<% end %>

posts controller
  ...
  private
    def post_params
      params.require(:post).permit({images: []})
    end
end

posts migration
  ...
  create_table :posts do |t|
    t.json :images
    ...

posts uploader
class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :fog

  def fix_exif_rotation
    manipulate! do |img|
      img.tap(&:auto_orient)
    end
  end

  process :fix_exif_rotation
  process :resize_to_fit => [800, 56000]

  version :thumb do
    process resize_to_fit: [300, 56000]
  end
end

A: My guess would be that you need to use :string instead of :json in the ActiveRecord::Migration.
class AddImagesToGallery < ActiveRecord::Migration
  def change
    add_column :galleries, :images, :string, array: true, default: [] # add images column as array
  end
end

You can check following How to: Add more files and remove single file when using default multiple file uploads feature for more.
EDIT - added the reason
The reason why you are getting this error is that the gem activesupport-json_encoder (the one PR is hanging there from 2014) is no longer maintained and is not compatible with rails 5.x.


text:
Q: Failed To Create Agent after Build Game - Unity My game is running normally in the runtime editor. The problem occurs with the build result. seen in the Output Log that the agent (NavMeshAgent) was not created because it did not close enough to navmesh. whereas in the editor the problem did not arise. Next I attach a screenshot of my output log.

Maybe someone knows why this happens? and what is the solution ??


text:
Q: Delphi - Parse TNullable (record) to JSON We are using the Spring4D nullable types (which are records, not objects) in some of our business objects that need to be parsed to JSON.
When the nullable type field has no value, there are 2 options that would be okay in our case:

*

*The field is not present in the JSON

*The field is present in the JSON with value null

I am trying to make this work by using a TJSONInterceptor subclass.
For example for the TNullableInteger:
I want to create an interceptor that will be used when the field has a NullableIntegerAttribute (derived from JsonReflectAttribute), in which case my TNullableIntegerInterceptor will be used.
The problem is that I don't quite know which convertertype and revertertype to use in this case because the nullable types are record types and not object types.
Does anyone have any experience with parsing record types in Delphi?
Or are there other ways to achieve this?
Any guidance would be much appreciated.
UPDATE
In the meantime I have managed to make interceptors for most of the TNullable types that we use.
Example for TNullableInteger:
{ JsonNullableIntegerAttribute }
constructor JsonNullableIntegerAttribute.Create;
begin
  inherited Create(ctObject, rtString, TNullableIntegerInterceptor);
end;

{ TNullableIntegerInterceptor }
constructor TNullableIntegerInterceptor.Create;
begin
  inherited;
  ConverterType := ctObject;
  ReverterType := rtString;
end;

function TNullableIntegerInterceptor.ObjectConverter(Data: TObject; Field: string): TObject;
var
  ctx: TRTTIContext;
  Int: TNullableInteger;
begin
  Int := ctx.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<TNullableInteger>;
  If Int.HasValue
  then begin
    StringProxy.Value := IntToStr(Int.GetValueOrDefault);
    Result := StringProxy;
  end
  else Result := nil;
end;

procedure TNullableIntegerInterceptor.StringReverter(Data: TObject; Field, Arg: string);
var
  ctx: TRTTIContext;
  Value: TValue;
  Int: Integer;
begin
  If TryStrToInt(Arg, Int)
  then begin
    TValue.Make<TNullableInteger>(Int, Value);
    ctx.GetType(Data.ClassType).GetField(Field).SetValue(Data, Value);
  end;
end;

The only type that is still a problem is TNullableBoolean.
For the unmarshalling the procedure TJONUnMarshal.PopulateFields checks if there is a reverter available but then, depending on the revertertype, it only handles TJSONArray, TJSONObject, TJSONString and TJSONNull. Boolean values in JSON are of type TJSONBool and are not handled. Instead I get the error 'JSON object expected for field fieldname in JSON true'
Also, for the serialization, I don't know how I can achieve that my JSON looks like
"FieldName": true
instead of
"FieldName": "true"
Passing a boolean as a string in JSON is not allowed by our backend software. So for now I am using a rather stupid workaround in my ObjectConverter method by returning "BOOLEAN_TRUE_IDENTIFIER" or "BOOLEAN_FALSE_INDENTIFIER" which I replace by true or false in the resulting JSON just before sending it to our backend.
If anyone would have a solution for this, it would make me very happy :-)
In the meantime we will try to avoid using NullableBoolean variables.


text:
Q: GoogleMaps iOS SDK 1.5 won't load So I've started investigating using GoogleMaps iOS SDK.
I followed the instructions:

*

*Enabled the Google Maps SDK for iOS in the console

*Setup an API key and added the Bundle ID (I used the demo Project Google Supplies)

*Updated the constant 'kAPIKey'the the key in my Project

I run the app and I get the following

2013-11-18 11:24:59.155 SDKDemos[7073:c07] ClientParametersRequest failed, 3 attempts remaining (0 vs 5). Error Domain=com.google.HTTPStatus Code=400 "The operation couldn't be completed. (com.google.HTTPStatus error 400.)" UserInfo=0x8c4b0e0 {data={length = 145, capacity = 256, bytes = 0x3c48544d4c3e0a3c484541443e0a3c54 ... 3c2f48544d4c3e0a}}
2013-11-18 11:24:59.233 SDKDemos[7073:6403] Google Maps SDK for iOS version: 1.5.0.5445
  ...
2013-11-18 11:25:11.836 SDKDemos[7073:c07] Google Maps SDK for iOS cannot connect or validate APIKey: Error Domain=com.google.HTTPStatus Code=400 "The operation couldn't be completed. (com.google.HTTPStatus error 400.)" UserInfo=0x8c1a9b0 {data={length = 145, capacity = 256, bytes = 0x3c48544d4c3e0a3c484541443e0a3c54 ... 3c2f48544d4c3e0a}}
2013-11-18 11:25:11.836 SDKDemos[7073:c07] Your key may be invalid for your bundle ID: com.example.SDKDemos

Here is an image from the API Console to show I have bundleID entered correctly

XCode 5.0
iOS SDK 7.0
So it seems I am missing something fairly fundamental here or there is a time I have to wait until my API key is actually activated
Update:
Map is now rendering but the ClientParametersRequest failed errors are still being reported
Update2 :
Added Image showing example

A: Ok so it turns out the Demo Project Supplied by Google didn't follow the proper setup and they skipped step 7

In the Other Linker Flags section, add -ObjC.

A: Can you please raise this as a bug on our issue tracker for Google Maps SDK for iOS?


text:
Q: PsExec command working on cmd doesn't work inside .bat file nor via SQL xp_cmdshell When I execute the following command on machine1's cmd it works fine:
C:\PSTools\psexec64.exe \\machine2 -u domain\user -p pass -i -d -accepteula C:\folder\file.bat

However, if I try to run it via xp_cmdshell (sql server is also on machine1) as bellow it will fail:
exec xp_cmdshell 'C:\PSTools\psexec64.exe \\machine2 -u domain\user -p pass -i -d -accepteula C:\folder\file.bat'

Here is the output:
NULL
PsExec v2.4 - Execute processes remotely
Copyright (C) 2001-2022 Mark Russinovich
Sysinternals - www.sysinternals.com
NULL
Connecting to xx.xxx.xxx.xx...   Starting PSEXESVC service on xx.xxx.xxx.xx...   Could not start PSEXESVC service on xx.xxx.xxx.xx:
Access is denied.
Connecting to xx.xxx.xxx.xx...   Starting PSEXESVC service on xx.xxx.xxx.xx...

I also tried to save the command as a bat file to see if the problem is exclusive to the SQL server, but it won't work either.
Here is the output:
PsExec could not start C:\folder\file.bat on xx.xxx.xxx.xx:
The user name or password is incorrect.

The exact same command works fine on cmd, same machine.


text:
Q: Storing a two-bit binary in char So I'm working on a program that takes a file of characters and turns these into a file of characters of binary numbers. Then I have to be able to read these characters (the binary characters) and turn them back into the denoted characters.
So essentially this is encoding and decoding a file.
So I have a file with the four characters: '@', '/n', ':', ' '. (Last one is space)
So the reason I want to do this is that I have a bunch of ascii pictures that I want to store in smaller files.
I have been told that I can use an unsigned char, set it to 0, then read a file with the characters described above, and use bitwise operators to assign the values read into the unsigned char and then for each four characters read (because each character is 8 bites and these can then be turned into 2 bites each and stored in one character, hence four characters in one char) append (add) each number to the char.
Any help Appreciated!
The code I have now is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *inputFile;
FILE *outputFile;

int encodeBinary[4] = {0x00, 0x01, 0x02, 0x03};
char encodeChars[4] = {':', '@', '\n', ' '};

//reads from a file and creates the encoded file
void encode(const char * inFile, const char * outFile)
{

    inputFile = fopen(inFile, "r");
    outputFile = fopen(outFile, "w");
    char lineBuffer[BUFSIZ];
    int size = 0;
    char temp = 0;

    if(inputFile == NULL)
    {
        perror("Error while opening file.\n");
        exit(EXIT_FAILURE);
    }

    while(fgets(lineBuffer, sizeof(lineBuffer), inputFile))
    {
        for(int i = 0; lineBuffer[i] != 0; i++)
        {

            //adds four different characters to a char before adding the character to the file
            if(size < 4) {
                if(lineBuffer[i] == encodeChars[0])
                {

                }
                else if(lineBuffer[i] == encodeChars[1])
                {

                }
                else if(lineBuffer[i] == encodeChars[2])
                {

                }
                else if(lineBuffer[i] == encodeChars[3])
                {

                }

                size++;
            } else {
                size = 0;
                temp = 0;

            }
        }
    }

    fclose(inputFile);
    fclose(outputFile);

}

Would really appreciate if someone could come up with some examples as how to add the bits read in to the temp char. I have no idea as to how I can add the numbers to the char so that they are moved in such a way and added in such a way as to represent the old numbers and the new. I'm thinking I can bitshift the number 3 times to the left, so that 01 becomes 0100.

A: Instead of using bitfields, you could use << and >> operators and bitwise & and | to manipulate the bits directly,
Encode,
unsigned char accum;

if(size>0) accum = encodeChars[0] << 6
if(size>1) accum |= encodeChars[0] << 4
if(size>2) accum |= encodeChars[0] << 2
if(size>3) accum |= encodeChars[0]
if(lineBuffer[i] accum

Decode,
char array[4];
if(size>0) array[0] = decodeChars[ (accum >> 6) &0x3 ];
if(size>1) array[1] = decodeChars[ (accum >> 4) &0x3 ];
if(size>2) array[2] = decodeChars[ (accum >> 2) &0x3 ];
if(size>3) array[3] = decodeChars[ (accum) &0x3  ];

and read about big-endian vs. little-endian to understand element storage order.

A: Like others have said this needs a little thought. Your character has 8bits which can be divided into 4 2bit fields. So you initially need to set all the bits in the 8bit character to zero. Each character in the file will need to be encoded to a value between 0-3. Once you read a character in, you will need to find its encoding and create a mask of the encoded value. The mask will need to be shifted to an empty 2bit field within the 8bit character and ORed with it.
There are lots of implementation specific stuff left for you to do, but that is the basic idea.

A: let's say you have an input char from file, we call it input_char;
unsigned char input_char;

you define:
typedef union
{
   struct
   {
      unsigned char first  :2;
      unsigned char second :2;
      unsigned char third  :2;
      unsigned char fourth :2;
   } two_bits;

   unsigned char byte;

} UNION_TWO_BITS_STORAGE;

UNION_TWO_BITS_STORAGE storage_char;

and then
storage_char.two_bits.first = (input_char & 0x03);

this is valid if only bits 0 and 1 of input_char are significative.  Otherwise, you need logical shifts right.
Or, you can have
unsigned char temp;

switch(input_char)
{
     case '@':
        temp = 0x00;
        break;

     case '/n':
        temp = 0x01;
        break;
etc...

and
storage_char.two_bits.first = (temp);

and, when you write character back to destiation file, you can just write
 storage_char.byte

Yes, it's a little messy, and you can write it in a more loopable way.  But it was only to show the concept of using a union, here

A: another way to see what ChuckCottril says, using your code, is the following
    #include <stdio.h>
            #include <stdlib.h>
            #include <string.h>

    FILE *inputFile;
    FILE *outputFile;

    int encodeBinary[4] = {0x00, 0x01, 0x02, 0x03};
    char encodeChars[4] = {':', '@', '\n', ' '};

    //reads from a file and creates the encoded file
    void encode(const char * inFile, const char * outFile)
    {

        inputFile = fopen(inFile, "r");
        outputFile = fopen(outFile, "w");
        char lineBuffer[BUFSIZ];
        int size = 0;
        char temp = 0;
        char output_char;

        if(inputFile == NULL)
        {
            perror("Error while opening file.\n");
            exit(EXIT_FAILURE);
        }

        output_char = 0;

        while(fgets(lineBuffer, sizeof(lineBuffer), inputFile))
        {
            for(int i = 0; lineBuffer[i] != 0; i++)
            {

                //adds four different characters to a char before adding the character to the file
                if(size < 4) {
                    if(lineBuffer[i] == encodeChars[0])
                    {
                       temp = encodeBinary[0];
                    }
                    else if(lineBuffer[i] == encodeChars[1])
                    {
                       temp = encodeBinary[1];
                    }
                    else if(lineBuffer[i] == encodeChars[2])
                    {
                       temp = encodeBinary[2];
                    }
                    else if(lineBuffer[i] == encodeChars[3])
                    {
                       temp = encodeBinary[3];
                    }

                    output_char |= temp << (size*2);

                    size++;
                } else {

                    //PRINT TO FILE OUTPUT CHAR, or save to output buffer
                    size = 0;
                    temp = 0;
                    output_char = 0;

                }
            }
        }

        fclose(inputFile);
        fclose(outputFile);

    }

Be aware of one thing: you should always have input file with a multiple of 4 Bytes, otherwise decode can result in a different file!


text:
Q: Is the grammar in this quote correct? This quote from Zig Ziglar doesn't seem right to me. I'm not sure if it's the original quote by him but is it grammatically correct?

One can get anything if he is willing to help enough others get what they want.

I'm wondering about the use of 'one' and 'he' to refer to the same person, and 'help enough others' doesn't seem right to me either.


text:
Q: export React to word - hyperLink to place in the same document I created word files by simple js code,  that convert react to html and download it
let HTMLContent = exportToWord(simulator, options);
const dir = "ltr";
const docTitle = simulator.name;
const header =
  `<html xmlns:o='urn:schemas-microsoft-com:office:office'` +
  ` xmlns:w='urn:schemas-microsoft-com:office:word' ` +
  `xmlns='http://www.w3.org/TR/REC-html40' dir=\"${dir}\"> ` +
  `<head><meta charset='utf-8'><title>${docTitle}</title></head><body>`;
const footer = "";
const sourceHTML = `${header}${HTMLContent}${footer}`;
const source = `data:application/vnd.ms-word;charset=utf-8,${encodeURIComponent(
  sourceHTML
)}`;
const fileDownload = document.createElement("a");
document.body.appendChild(fileDownload);
fileDownload.href = source;
fileDownload.download = `${docTitle}.doc`;
fileDownload.click();
document.body.removeChild(fileDownload);

The files are created and everything works well.
The problem is that I want to create links within the file to another location in the word document
How can I do it?


text:
Q: Form field is required even if not defined so I am using Net 6 with Fluent Validation and I have a form with the field:
  <form method="post" asp-controller="Product" asp-action="Create" asp-antiforgery="true" autocomplete="off">
    Description
    <input asp-for="Description" type="text">

    ...
    <button class="submit" name="button">Create</button>
  </form>

The ProductModel is:
public class ProductModel {

  public String Description { get; set; }

  // ...
}

And the ProductModel Fluent Validator is:
public class ModelValidator : AbstractValidator {
public ModelValidator() {

  RuleFor(x => x.Description)
    .Length(0, 200).WithMessage("Do not exceed 200 characters");

  // ...

}

}
When I submit the form I get an error on description if I let it empty:
The Description field is required.

But my validator is not requiring the description.
This happens to all fields. When not filled I get a similar error.
What am I missing?

A: Did a little bit of digging, this seems to be due to a problem relating to model validation changes; specifically in ASP Net 6. I found a documentation link that can explain it better than me but I'll give a code implementation also: Microsoft docs
builder.Services.AddControllers(
    options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

//Removes the required attribute for non-nullable reference types.

Hope this helps, I've taken this code straight from the MS docs, so if it doesn't fix your issue, there is likely another cause.

A: Here is very detailed explaintion about this issue in the MC document:

Gets or sets a value that determines if the inference of
RequiredAttribute for properties and parameters of non-nullable
reference types is suppressed. If false (the default), then all
non-nullable reference types will behave as-if [Required] has been
applied. If true, this behavior will be suppressed; nullable reference
types and non-nullable reference types will behave the same for the
purposes of validation.

There are two methods to solve this problem, one global and one partial.
You can set:
builder.Services.AddControllersWithViews(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true)

In your Program.cs (.Net6), After using this method, all properties can be null.
Another method is in your model, you can set properties like this:
public class ProductModel {

  public String? Description { get; set; }

  // ...
}

? means this property can be null, in this method, You can specify which properties can be null.


text:
Q: C Using insertion sort to sort array of pointers to structs Im trying to sort, using Insertion Sort, variable-length array of  pointers to struct objects.
The sorting criteria is based on the structs distance_to_neighbor attribute.
The problem is it seems that sorted output is semi-sorted.
Here is my data structure  for a tree node:
typedef struct tree_
    {
        struct tree *left;
        struct tree *right;
        float * info;
        float distance_to_neighbor;
    } tree;

Here is my Insertion Sort implementation, relevant code snippet  (based on https://www.techiedelight.com/insertion-sort-iterative-recursive/):
// perform insertion sort on array of references to structs
void insertion_sort(tree ** arr, int n)
{
    // Start from second element (element at index 0
    // is already sorted)
    tree * pre_value = NULL;
    for (int i = 1; i < n; i++)
    {
        tree * value = *(arr + i);
        int j = i;

        // Find the index j within the sorted subset arr[0..i-1]
        // where element arr[i] belongs
        pre_value = *(arr + j - 1);
        while (j > 0 && pre_value->distance_to_neighbor > value.distance_to_neighbor)
        {
            **(arr + j) = **(arr + j - 1);
            j--;
        }

        // Note that subarray arr[j..i-1] is shifted to
        // the right by one position i.e. arr[j+1..i]
        **(arr + j) = value;
    }
}

Code snippet used  for debugging  before & after sort:
printf ("debug {");
                float * info;
                float distance = 0;
                for (int c = 0; c < k_dimensions; c++)
                {
                    info = (float *) current->info;
                if (NULL != info)
                {

                    printf ("%f,", info[c]);
                }
                else
                {
                    break;
                }

            }//end for
            printf ("} ");
            distance = (float) current->distance_to_neighbor;
            printf ("distance_to_neighbor=%f\n", distance);

Here are the values before sorting (should be sorted based  on distance_to_neighbor) :
debug {-50.000000,-50.000000,-50.000000,} distance_to_neighbor=53.000000
debug {-3.000000,-3.000000,-3.000000,} distance_to_neighbor=6.000000
debug {-2.000000,-2.000000,-2.000000,} distance_to_neighbor=5.000000
debug {-1.000000,-1.000000,-1.000000,} distance_to_neighbor=4.000000
debug {0.000000,0.000000,0.000000,} distance_to_neighbor=3.000000
debug {1.000000,1.000000,1.000000,} distance_to_neighbor=2.000000
debug {2.000000,2.000000,2.000000,} distance_to_neighbor=1.000000
debug {3.000000,3.000000,3.000000,} distance_to_neighbor=0.000000
debug {4.000000,4.000000,4.000000,} distance_to_neighbor=1.000000
debug {5.000000,5.000000,5.000000,} distance_to_neighbor=2.000000
debug {6.000000,6.000000,6.000000,} distance_to_neighbor=3.000000
debug {7.000000,7.000000,7.000000,} distance_to_neighbor=4.000000
debug {8.000000,8.000000,8.000000,} distance_to_neighbor=5.000000
debug {100.000000,100.000000,100.000000,} distance_to_neighbor=97.000000

After sorting (looks sorted descending  order  then suddenly ascending order!. It should only be ascending order):
{8.000000,8.000000,8.000000,} distance_to_neighbor=5.000000
{7.000000,7.000000,7.000000,} distance_to_neighbor=4.000000
{6.000000,6.000000,6.000000,} distance_to_neighbor=3.000000
{5.000000,5.000000,5.000000,} distance_to_neighbor=2.000000
{4.000000,4.000000,4.000000,} distance_to_neighbor=1.000000
{3.000000,3.000000,3.000000,} distance_to_neighbor=0.000000
{2.000000,2.000000,2.000000,} distance_to_neighbor=1.000000
{1.000000,1.000000,1.000000,} distance_to_neighbor=2.000000
{0.000000,0.000000,0.000000,} distance_to_neighbor=3.000000
{-1.000000,-1.000000,-1.000000,} distance_to_neighbor=4.000000
{-2.000000,-2.000000,-2.000000,} distance_to_neighbor=5.000000
{-3.000000,-3.000000,-3.000000,} distance_to_neighbor=6.000000
{-50.000000,-50.000000,-50.000000,} distance_to_neighbor=53.000000
{100.000000,100.000000,100.000000,} distance_to_neighbor=97.000000

I must keep my function signature the same as     void insertion_sort(tree ** arr, int n).  How can I fix this sorting bug?
Thanks

A: You seem to assume that pre-value changes as you change j, but it needs to be re-calculated with each change to j.


text:
Q: connecting Docker to a cloud provider, Amazon AWS Context: I was going though Link to Amazon Web Services to create Swarms, in order to connect to my provider.
The role was created with success.
Then, while creating the policy, to associate to the role, a problem happened.
Problem:
An error occurred: Cannot exceed quota for PolicySize: 5120

As suggested by them, this is what I need to add in policy:
https://docs.docker.com/docker-for-aws/iam-permissions/
Did some research and people seem to like this solution:
https://github.com/docker/machine/issues/1655
How can I create the policy using the best method?
Noticing that the documentation in Docker is wrong - doesn't work in my case - what's the best method?

A: You are looking at the wrong instructions to connect docker-cloud to AWS follow these instructions: https://docs.docker.com/docker-cloud/infrastructure/link-aws/
It's the following 3 steps

*

*Create AWS Policy for docker-cloud

*Create a docker-cloud role and attache the policy from 1

*Attach AWS role/account to docker-cloud

The policy in (1) above is pretty simple. It should be allowed to perform ec2 instances related actions (your screenshot of the policy looks like it doesn't provide ec2 permissions):
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "ec2:*",
        "iam:ListInstanceProfiles"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

The role must have the permissions to implement the policy.
For a detailed post on the deployment via docker-cloud see: https://blog.geografia.com.au/how-we-are-using-docker-cloud-for-automated-testing-and-deployments-of-applications-bb87ec3173e7


text:
Q: Артефакты в коде После сборки выполняемого файла или библиотеки добавляет ли компилятор информацию о себе?

A: Да, обычно добавляет. Не всегда правда явную. Некоторые иструменты (к примеру PeID) могут распознать компилятор (иногда с точностью до билда), ориентируясь на особенности генерации кода.
upd
Microsoft известна тем, что добавляет в exe несколько байт, о значении которых люди долго спорят. Ещё немного.


text:
Q: how to pass url using button click event in angularjs I want passing  URL through button click event into my directive using angularjs.my task is to click on button the new html page will be displayed on browser so for this i am doing following example.
Test.html:
<test1>
    <button  ng-click="click('/sample.html')">Go</button>
</test1>

Test.js:
 app.directive('test1', function() {
        function compile(scope, element, attributes) {
         return{
             post:function(scope, element, iAttrs,location) {
                 scope.click=function(path)
                 {
                 location.path(path );
                 };
             }
         };
        }

        return({
            compile: compile,
            restrict: 'AE',

        });

    });

the path will be getting in click function but i want to display sample.html on browser so please suggest me how to do this.
Thanks.


text:
Q: Triple negation in intuitionistic logic? I'm told that intuitionistic logic is basically classical logic with "law of the excluded middle removed", and that you can't from $\neg \neg A$ infer $A$.
So, if we consider $A$ a state, $\neg A$ a state, and $\neg \neg A$ a state, does this mean that $\neg \neg \neg A$ is a separable state?

A: In addition to the two very nice formal answers, let me give an informal proof that $\neg\neg\neg A \Rightarrow \neg A$.
Recall that, by definition, $\neg B$ is an abbreviation for $B \Rightarrow \bot$.

Assume $\neg\neg\neg A$. We are to show $\neg A$, that is, $A \Rightarrow \bot$.
So assume $A$, we are to show $\bot$.
Since $A$, we have $\neg\neg A$. But we also have $\neg(\neg\neg A)$. Hence $\bot$.

This proof uses the lemma that $A \Rightarrow \neg\neg A$. This lemma can also be proven informally:

Assume $A$. We are to show $\neg\neg A$, that is, $(\neg A) \Rightarrow \bot$.
So assume $\neg A$. We are to show $\bot$.
Since $\neg A$ (which means $A \Rightarrow \bot$) and since $A$, we have $\bot$.

By the way, at no point did we use the principle of explosion (ex falso quodlibet). Hence our proofs are even valid in minimal logic, where $\bot$ doesn't have any special rules attached to it.

A: No, $\neg \neg \neg A$ is equivalent to $\neg A$.
Given $\neg\neg\neg A$:
1. $\neg \neg \neg A$ (premise)
2.1. $A$ (assumption)
2.2.1. $\neg A$ (assumption)
2.2.2. $A$ (reiterate 2)
2.2.3. $\bot$ (contradiction 4 3)
2.3. $\neg\neg A$ ($\neg$intro 2.2.1-2.2.3)
2.4. $\neg\neg\neg A$ (reiterate 1)
2.5. $\bot$ (contradiction 2.3 2.4)
3. $\neg A$ ($\neg$intro 2.1-2.5)
Given $\neg A$:
1. $\neg A$ (premise)
2.1. $\neg \neg A$ (assumption)
2.2. $\neg A$ (reiterate 1)
2.3. $\bot$ (contradiction 2.2 2.1)
3. $\neg\neg\neg A$ ($\neg$intro 2.1-2.3)

A: Triple negation $\neg \neg \neg P $ is a shorthand for $((P \rightarrow \bot) \rightarrow \bot) \rightarrow \bot$. It turns out however that for any pair of propositions $P$ and $Q$, we have that $((P \rightarrow Q) \rightarrow Q) \rightarrow Q$ simplifies to $P \rightarrow Q$, which lets us simplify triple negation to $P \rightarrow \bot$ which is just the definition of $\neg P$.
To prove this, just note that by modus ponens, we have $P \rightarrow ( (P \rightarrow Q) \rightarrow Q)$, for any P, Q. But we note that the RHS of that is equal to the LHS of $((P \rightarrow Q) \rightarrow Q) \rightarrow Q$ , so we can just compose the two implications to get $P \rightarrow Q$. This holds for any logic with modus ponens and transitive implication.

A: It is standard to identify $\lnot A$ with $A \to \bot$ in intuitionistic logic. The $\lambda$-term $\lambda f^{(A\to B)\to B}{\cdot} \lambda a^{A}{\cdot} f(\lambda g^{A \to B}{\cdot} g(a))$ corresponds to a proof of $(((A \to B) \to B) \to B) \to (A \to B)$ under the Curry-Howard Correspondence. Instantiating  $B$ to $\bot$ gives you a proof that $\lnot\lnot\lnot A \to \lnot A$.
The proof of the converse proposition $(A \to B) \to (((A \to B) \to B) \to B)$ is witnessed by $\lambda f^{A\to B}{\cdot}\lambda g^{(A \to B) \to B}{\cdot}g(f)$


text:
Q: SimpleCov 0% coverage I'm working on a small gem and included simplecov to spec_helper.rb two lines:
require 'simplecov'
SimpleCov.start

When I run the rspec test, the simplecov seems started correctly but the report is not:
Finished in 0.00214 seconds
8 examples, 0 failures

Coverage report generated for /home/......
spec to /home/megas/Work/calc/coverage. 0 / 0 LOC (0.0%) covered.

What might be a problem and how to fix it? Thanks

A: Also make sure to enable simplecov (a.k.a. SimpleCov.start) at the very beginning of your file; especially before you require your code.

A: I had the same symptoms. My problem was that in my test file:
#spec/oneclass_spec.rb
require 'oneclass'
require 'spec_helper'

...Rest of the test file

And I needed to change the order of the requires to:
#spec/oneclass_spec.rb
require 'spec_helper'
require 'oneclass'

...Rest of the test file

Hope this helps someone, I was going crazy...

A: I had a similar issue. For some reason, some modules were reported with 0% of coverage. After some investigation, I found that one of the initialisers required a controller, which caused modules to be loaded before Simplecov. What I did I moved Simplecov to initialiser:
# config/initializers/_coverage_rspec.rb

if Rails.env.test?
  require 'simplecov'
  SimpleCov.start 'rails'
end

If you're using spring, remember to turn it off when you run tests with coverage. In another case, the complete application code will be loaded before SimpleCov and report 0% coverage.

A: Just in case the above two answers didn't work (as in my case) a user on simplecov's github issues page suggested this, which worked for me.
Add this after you require simplecov-
module SimpleCov::Configuration
  def clean_filters
    @filters = []
  end
end

SimpleCov.configure do
  clean_filters
  load_adapter 'test_frameworks'
end

A: If one of the above didn't work.
verify that in test.rb:
config.eager_load = false

A: In my case the issue was spring - I had to create a config/spring.rb with the following:
if ENV['RAILS_ENV'] == 'test'
  require 'simplecov'
  SimpleCov.start
end

as documented here.

A: I am running scripts from the command line and I found the solution was simply to put an exit at the end of my script. Doh!
Alternatively, the following also works
SimpleCov.at_exit do
  SimpleCov.result.format!
end


text:
Q: How do I add a button to my list when I'm forced to use simple_list_item_1? I have a list, and I want 'Next' and 'Previous' buttons at the bottom of the list. I've tried to make the ListAdapter for the list something other than simple_list_item_1, but Android won't let me. I keep getting '... can't be resolved'.
Now, simple_list_item_1 is some kind of magical unicorn that is impossible to find, so I can't change it.
How can I put my buttons on the screen?

A: It is not necessary for you to use simple_list_item_1. Can you elaborate the "cant be resolved error". Also post your layout file and the code using those layout components.


text:
Q: Building levmar on Mac Yosemite Hi I want to build levmar (Levenberg Marquardt) C++ library on Mac. It comes with a makefile (http://users.ics.forth.gr/~lourakis/levmar/index.html) but I have some questions about how to use it on Mac (Yosemite)
(1) The gcc I have currently installed on Mac is in fact clang. I can confirm this if I run gcc -v on the terminal. Should I install proper gcc before building levmar?
(2) Levmar recommends using LAPACK (Linear Algebra Library). Again, I have been reading on another stack overflow post (Trying to build the LEVMAR math library on a mac using the Accelerate Framework) that they were using Mac OS Accelerate framework that comes with LAPACK. Does anyone know how do I get that on yosemite? Or should I be building LAPACK standalone on mac first?
Thank you

A: I used the Makefile from Trying to build the LEVMAR math library on a mac using the Accelerate Framework posted by Janos and it works for levmar-2.6 using clang and Accelerate framework.


text:
Q: jCarousellite pauseonhover and mousewheel together not working I m using jCarousellite to scroll slider. But mousewheel scroll does not work when I put pauseonHover:true. Any suggestion?
$('.slider').jCarouselLite({
    btnNext: ".next",
    btnPrev: ".prev",
    vertical: true,
    auto: true,
    timeout: 2800,
    speed: 400,
    easing: 'easeOutQuint',
    pauseOnHover: true,
    start: randNum,
    mouseWheel: true
});

A: Looking at the jCarousel Lite documentation pauseOnHover is not a valid option.
I would recommend using Owl Carousel there's much better documentation and more support through its popularity.


text:
Q: How to verify if an url ends with mp4? Can anyone help me to verify if a certain url ends with mp4 on android?

A: Just take your URL as String and use the function of String as follows:
String str=new String(URL);
if(str.endsWith(".mp4")){
//your stuffs
}

Here is link for VideoView example.

A: I'm pretty sure this is what you are looking for:
http://developer.android.com/reference/java/lang/String.html#endsWith(java.lang.String)
Simply compare the String with the endswith method to see if it ends in .mp4.
Assuming the URL is a String ofcourse, but you haven't said otherwise.


text:
Q: c# passing class argument to constructor The following codes works as is, but I would like to use a reference to the MyProperty class to be passed in the constructor
instead of the strongly typed references in the inline code.
How do I do this, I expected to pass a ref to MyProperty but everything I have tried fails
I would like PropertyClass to be able to handle any MyProperty classes i.e. no references to MyProperty in PropertyClass
Still learning so sorry if I have missed the obvious !
Many Thanks for any help
Sarah
PropertyClass pc = new PropertyClass(!here!);   // Would like to pass MyProperty class here

pc.Settings.Add(new MyProperty("Fred", "Monday"));
pc.SaveXml("MyTest.xml");

public class MyProperty
{
    [XmlAttribute]
    public string MyPropName { get; set; }
    [XmlElement]
    public string MyPropData { get; set; }

    // default constructor needs to be parameterless for serialisation.
    public MyProperty()
    {
    }

    public MyProperty(string Name, string Data)
    {
        MyPropName = Name;
        MyPropData = Data;
    }
}

public class PropertyClass
{
    public List<MyProperty> Settings { get; set; }

    public PropertyClass()              // How to pass the required class here ?
    {                                   // public PropertyClass( ref MyProperty myprop)
        Settings = new List<MyProperty>();
    }

    public void SaveXml(string fileName)
    {
        using (FileStream stream = new FileStream(fileName, FileMode.Create))
        {
            XmlSerializer XML = new XmlSerializer(typeof(List<MyProperty>), new XmlRootAttribute("Settings"));

            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            namespaces.Add(string.Empty, string.Empty);

            XML.Serialize(stream, Settings, namespaces);
        }
    }
}

A: I would change the definition of PropertyClass to
public class PropertyClass<T>
{
    public List<T> Settings { get; set; }

    public PropertyClass()
    {
        Settings = new List<T>();
    }

    public void SaveXml(string fileName)
    {
        using (FileStream stream = new FileStream(fileName, FileMode.Create))
        {
            XmlSerializer XML = new XmlSerializer(typeof(List<T>), new XmlRootAttribute("Settings"));

            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            namespaces.Add(string.Empty, string.Empty);

            XML.Serialize(stream, Settings, namespaces);
        }
    }
}

The type parameter T specifies the type of the items in the List<T>, so that you can instantiate PropertyClass as follows
var pc = new PropertyClass<MyProperty>();

Or when you get tired of MyProperty you can change it to new PropertyClass<foo>() without changing it elsewhere.
Another nice feature that I like about generics is that you can actually place constraints on the type parameter in the line where you declare it like:
public class PropertyClass<T> where T : MyClass, IMyInterface, new()

This means that T has to be derived from MyClass, it has to implement IMyInterface and has to have a parameterless constructor. (Obviously you do not need to add all such constraints, but they can all be useful in certain cases).
I want to rant a little more, but I am sure you can play with it and find some uses for it.

A: I think you need a generic class.
public class PropertyClass<T>
{
  public List<T> Settings { get; set; }

  public PropertyClass()
  {
    Settings = new List<T>();
  }
...
}

PropertyClass<MyProperty> pc = new PropertyClass<MyProperty>();

I must add that your naming is very unclear. PropertyClass should be called something like XmlableList. And MyProperty already exists and is called  NameValuePair<string,string>

A: Possibly you are looking for generics:
public class PropertyClass<TMyProperty>
{
    public List<TMyProperty> Settings { get; set; }

    public PropertyClass()
    {
        Settings = new List<TMyProperty>();
    }
    ..
 }

A: Work on your naming, it wasn't immediately obvious that PropertyClass was actually a collection of properties; perhaps MyPropertyCollection would be better?
What you're looking for is called constructor overloading. Basically you specify the constructor again, but this time with parameters:
public MyPropertyCollection()
{
    Settings = new List<MyProperty>();
}
public MyPropertyCollection(IEnumerable<MyProperty> collection)
{
    Settings = new List<MyProperty>(collection);
}

Or to allow var col = new MyPropertyCollection(new MyProperty(), new MyProperty(), new MyProperty()) you can do:
public MyPropertyCollection(params MyProperty[] collection)
{
    Settings = new List<MyProperty>(collection);
}

Though you should be careful with that, it doesn't feel right and should you later want to introduce additional parameters, well it could end bad.
Also, as you're basically wrapping a list, what you could also consider is the System.Collection.ObjectModel.Collection<T> class as a base:
// The Collection<MyProperty> base class is responsible for maintaining the list
public class MyPropertyCollection : Collection<MyProperty>
{
    public MyPropertyCollection()
    {
        // Default base() constructor is called automatically
    }

    public MyPropertyCollection(IList<MyProperty> properties)
        : base(properties)
    {
         // Overloaded constructor calls base constructor with collection of properties
    }

    public void SaveXml(string fileName)
    {
        using (var stream = new FileStream(fileName, FileMode.Create))
        {
            // Serializer should now target this very class
            var xml = new XmlSerializer(typeof (this), new XmlRootAttribute("Settings"));

            var namespaces = new XmlSerializerNamespaces();
            namespaces.Add(string.Empty, string.Empty);

            xml.Serialize(stream, this, namespaces);
        }
    }
}

A: this is how you call the constructor
PropertyClass pc = new PropertyClass(new MyProperty("Fred", "Monday"));

this is the constructor
Public MyProperty MyProperty { get; set; }
public PropertyClass(MyProperty _myProperty)
{
    MyProperty  = _myProperty
}

A: You need to add a constructor that takes a MyProperty as an argument:
public PropertyClass(MyProperty myprop)
{
    Settings = new List<MyProperty> {myprop};
}

Note that MyProperty is a reference type so ref is unnecessary here (it already is a reference).


text:
Q: ANDROID - Calendar multi date selection on touch (without `DatePicker`) Is it possible to have a CustomCalendarcreated and enable a multi-selection kind of thing (like the photo gallery) to select multiple dates on touch?
What I was thinking is when oppening the Activity, the Calendarwill show and in that phase it allows to choose several days of the current month by touching on the dates...
...is it 'do-able'?
Thanks in advance!


text:
Q: Is there a way to find out which IF condition 'triggered' the entrance into if (){ } block? In this example:
if (object instanceof SomeThing || object instanceof OtherThing) {
    System.out.println("this block was entered because of: " + **____** )
}

Could I check if the true condition was SomeThing or OtherThing?
edit: I'm trying to avoid the separation of conditions.
Thanks.

A: Refactor any common steps in both cases to a function, and then:
if (object instanceof SomeThing) {
    // It's SomeThing
    System.out.println("Got here because it's SomeThing");
    commonStuff();
}
else if (object instanceof OtherThing) {
    // It's OtherThing
    System.out.println("Got here because it's OtherThing");
    commonStuff();
}

Re your edit:

edit: I'm trying to avoid the separation of conditions.

Then you have these options:
if (object instanceof SomeThing || object instanceof OtherThing) {
    System.out.println("Got here because it's " +
        (object instanceof SomeThing) ? "SomeThing" : "OtherThing")
    );
}

Or
boolean isSomeThing:
if ((isSomeThing = object instanceof SomeThing) || object instanceof OtherThing) {
    System.out.println("Got here because it's " +
        isSomeThing ? "SomeThing" : "OtherThing")
    );
}

A: Try
  if (object instanceof SomeThing ) {
        System.out.println("this block was entered because of: " + **SomeThing ____** )
    }
  else if(object instanceof OtherThing){
     System.out.println("this block was entered because of: " + **OtherThing____** )
    }
  else{
     System.out.println("********nothing satisfied)
  }

A: if (object instanceof SomeThing || object instanceof OtherThing) {
     System.out.println(object instanceof SomeThing  );// if this print false then object is type of OtherThing

    System.out.println("this block was entered because of: " + **____** )
}

A: Try using ternary operator:
 if (object instanceof SomeThing || object instanceof OtherThing) {
        System.out.println("this block was entered because of: "
           + (object instanceof SomeThing? "SomeThing" : "OtherThing") );
    }

A: System.out.println("This block was entered because object is instance of SomeThing or OtherThing.");

As an alternative:
System.out.println("This block was entered because object is " + object.getClass().getName());

Or, very unreadable:
boolean other = false;
if (object instanceof SomeThing || (other = true) || ....) {
    System.out.println("because of " + other?"OtherThing":"SomeThing")
}


text:
Q: Need a Regex that contains at least one number, zero or more letters, no spaces, min/max I need a regular expression that will match a string that contains:

*

*at least one number

*zero or more letters

*no other characters such as spaces

The string must also be a minimum of 8 characters and a maximum of 13 characters.
Placement of the numbers and/or letters within the 8-13 character string does not matter.  I haven't figured out how to make sure that the string contains a number, but here are some expressions that don't work because they are picking up spaces in the online tool Regexr. Take a look below:
 - ([\w^/s]){8,13}
 - ([a-zA-Z0-9]){8,13}
 - ([a-zA-Z\d]){8,13}

I am specifically looking to exclude spaces and special characters. The linked and related questions all appear to allow for these characters. This is not for validating passwords, it is for detecting case numbers in natural language processing.  This is different from "Password REGEX with min 6 chars, at least one letter and one number and may contain special characters" because I am looking for at least one number but zero or more letters.  I also do not want to return strings that contain any special characters including spaces.

A: This is a typical password validation with your requirements.
Note that this will also match 8-13 digits as well (but it is requested).
Ten million + 1 (and counting) happy customers ..
^(?=.*\d)[a-zA-Z\d]{8,13}$
Explained
 ^                     # Beginning of string
 (?= .* \d )           # Lookahead for a digit
 [a-zA-Z\d]{8,13}      # Consume 8 to 13 alphanum characters
 $                     # End of string

A: I've seen the answer above (by sln) everywhere over the internet, but as far as I can tell, it is NOT ACCURATE.
If your string contains 8 to 13 characters with no numbers this expression will match it, because it uses the * quantifier on the wildcard character . in the positive lookahead.
In order to match at least 1 digit, 1 A-Z and 1 a-z in a password that's at least 8 characters long, you'll need something like this:
(?=.{1,7}\d)(?=.{1,7}[a-z])(?=.{1,7}[A-Z])[a-zA-Z\d]{8,13}

it uses 3 lookaheads:
(?=.{1,7}\d)
(?=.{1,7}[a-z])
(?=.{1,7}[A-Z])

each time, it looks for the target (eg the first digit) but allows 1 to 7 occurances of any character before it.
Then it will match 8 to 13 alphanumeric characters.
NOTE to Powershell users:
Use a search group to be able to extract a result
$password = [regex]::match($string-to-search,'(?=.{1,7}\d)(?=.{1,7}[a-z])(?=.{1,7}[A-Z])([a-zA-Z\d]{8,13})').Groups[1].Value


text:
Q: Relationship between Frattini subgroup and the first Agemo subgroup of a prime-power order group Let $G$ be a $p$-group for an odd prime $p$. The Frattini subgorup $\Phi(G)$ is defined as the intersection of all maximal subgroups or, equivalently, as the subgroup of non-generating elements, i.e. the elements $x \in G$ such that for every $R \subseteq G$ with $\langle x,R\rangle=G$ we must have that $G=\langle R\rangle$. The Agemo
subgroups $\mho_k(G)$ is the subgroup generated by all $p$-th powers, namely $\mho_k(G)=\langle g^{p^k}|g\in G\rangle$. Finally I call $G'$ the derived subgroup of $G$.
My question is the following:

When is true that $\Phi(G)=G'\mho_1(G)$?

In general is true that $G'\mho_1(G) \le \Phi(G)$.
I found that equation reading the proof of Hall's Theorem for $p$-groups on Huppert's book "Endliche Gruppen I", at page 358.
There $G$ is non cyclic with every abelian characteristic subgroup being cyclic. As it shown in the proof, this hypothesis implies that

*

*$\Phi(G)$ is cyclic

*$G/\Omega_1(G)$ is cyclic

*$G$ is an extraspecial (and then regular?) $p$-group

I don't find out why that equation seems to be kind of general.


text:
Q: what value was present at each 2.5s interval (resampling?) numpy I have a numpy array with a value in the first column, and time in seconds in the second column. Using the timing info in the second column, I need to end up with a vector of the col 1 value at each 2.5s interval. The 2nd column contains onset times, and each trial is 9s long. So the first trial lasts from 0.01s-9.01s. The time values don't perfectly line up with 2.5s intervals, so I want to use the col 1 value only if it's present for more than half of the 2.5s interval. I need to end up with 172 values, from 0 to 430 seconds.
array([[0.00, 0.01],
   [1.91, 9.60],
   [0.00, 19.08],
   [2.05, 28.64],
   [1.04, 38.19],
   [1.89, 47.73],
   [1.69, 57.27],
   [2.24, 66.79],
   [1.89, 76.33],
   [1.86, 85.88],
   [2.37, 95.39],
   [2.29, 104.93],
   [2.03, 114.45],
   [2.16, 123.99],
   [1.34, 133.52],
   [2.40, 143.03],
   [2.17, 152.54],
   [0.00, 162.03],
   [1.61, 171.59],
   [2.31, 181.13],
   [2.15, 190.67],
   [2.22, 200.19],
   [2.16, 209.72],
   [0.00, 219.20],
   [2.65, 228.76],
   [1.74, 238.33],
   [0.00, 247.85],
   [2.33, 257.42],
   [1.85, 266.94],
   [0.00, 276.50],
   [2.27, 286.06],
   [1.67, 295.62],
   [2.41, 305.15],
   [0.00, 314.65],
   [1.32, 324.21],
   [2.39, 333.74],
   [2.19, 343.27],
   [2.51, 352.81],
   [2.41, 362.33],
   [1.79, 371.86],
   [0.00, 381.36],
   [3.07, 390.93],
   [2.30, 400.47],
   [0.00, 409.98],
   [2.41, 419.54],
   [2.22, 0.05],
   [1.75, 9.59],
   [2.18, 19.14],
   [1.99, 28.64],
   [1.80, 38.16],
   [1.45, 47.68],
   [1.57, 57.21],
   [2.24, 66.74],
   [0.00, 76.24],
   [2.31, 85.80],
   [0.00, 95.29],
   [2.39, 104.85],
   [0.00, 114.34],
   [0.95, 123.89],
   [2.35, 133.42],
   [2.43, 142.98],
   [1.66, 152.48],
   [1.08, 162.01],
   [0.00, 171.53],
   [1.20, 181.08],
   [2.43, 190.64],
   [2.42, 200.16],
   [2.59, 209.69],
   [1.98, 219.22],
   [1.75, 228.76],
   [2.28, 238.28],
   [1.98, 247.80],
   [1.08, 257.33],
   [2.08, 266.84],
   [2.30, 276.37],
   [0.00, 285.84],
   [1.38, 295.40],
   [2.19, 304.95],
   [0.00, 314.44],
   [1.54, 324.01],
   [2.19, 333.52],
   [0.00, 343.02],
   [2.13, 352.59],
   [2.31, 362.13],
   [0.00, 371.61],
   [2.36, 381.18],
   [2.02, 390.71],
   [2.68, 400.24],
   [0.00, 409.71],
   [2.19, 419.28]])

I previously tried interpolating using interp1d but that smooths the data a bit and I really want to use the original values. I just need some guidance on how I might do that because it seems really complicated. Thank you!

A: Your data contain 2 consecutive datasets, which don't agree with one another and appear both to be heavily undersampled (huge jumps, very little continuity). Since the time between samples is 9.5 secs on average, I don't think that any kind of resampling at 2.5 sec intervals is going to give any real value. Unless you have a whole lot of phase changes or are sampling something with a built-in modulo operation like a Fresnel lens, I don't think your data are sampled often enough.
import numpy as np

import matplotlib.pyplot as p
%matplotlib inline

data=np.array([[0.00, 0.01],
   [1.91, 9.60],
   ...
   [0.00, 409.71],
   [2.19, 419.28]])

data=data.transpose()
p.figure(figsize=(12,6))
p.subplot(121)
print len(data[0])
dat1=data[:,:45]
dat2=data[:, 45:]
p.plot(dat1[1],dat1[0],'.-')
p.plot(dat2[1],dat2[0]+3,'.-')
p.title ('actual data (half offset for clarity)')

# plot the time steps
p.subplot(122)
p.plot(np.diff(dat1[1]))
p.plot(np.diff(dat2[1]))
p.title('time differences between samples ~ 9.5 secs')