text:
Q: How to use handwave library for Android studio? I want to get hand gestures for my application.
I googled for this.Some one suggested Hand Wave library full fill this.
I get some sample code of Hand Wave by using the following link.
https://github.com/kritts/HandWave-Sample-Apps
I am trying to import those samples to Android studio.
 It shows error like

*

*Project HandsFreeGallery:C:\Users\Administrator\Desktop\Kiran\HandWave-Sample-Apps-master\Gallery\project.properties:
Library reference ......\Handsfree Interaction\Code\HandsFree-master\sdk\java could not be found
Path is C:\Users\Administrator\Desktop\Kiran\HandWave-Sample-Apps-master\Gallery......\Handsfree Interaction\Code\HandsFree-master\sdk\java which resolves to C:\Users\Administrator\Desktop\Handsfree Interaction\Code\HandsFree-master\sdk\java

I don't know how to resolve this.
If any body know the solution.
Please help me.

A: You can use the Android Studio version. Someone forked the original project, and then made this one that works with AS. However, you will need to download OpenCV, and change the compile path in the AS library to the OpenCV that you downloaded and imported.
https://github.com/Manishearth/HandWave/tree/androidstudio


text:
Q: Process_vm_readv Returning Random Values I am trying to use the process_vm_readv systemcall to read a value from another Linux process. When attempting to read a magic number at a known location, I receive a random value.
I have tried writing two simple programs to see if I can get it working but I have failed. I have checked my return values and they succeed every time, I just left it out to make the code clearer.
Main File (to read from)
const long val = 0xDEADBEEF;

int main(int argc, char** argv) {
    std::cin.get(); // keep process running so I can read from it
}

Reader
int main(int argc, char** argv) {
    pid_t pid = strol(argv[1], NULL, 10);
    constexpr bufferLen = sizeof(long);
    char buffer[bufferLen] { 0 };
    struct iovec local, remote;
    local.iov_base = buffer;
    local.iov_len = bufferLen;
    remote.iov_base = reinterpret_cast<void*>(0x603120);
    remote.iov_len = bufferLen;
    ssize_t bytesRead = process_vm_readv(pid, &local, 1, &remote, 1, 0);
    std::cout << reinterpret_cast<long>(local.iov_base) << std::endl;
}

I have used objdump to find that the correct address of 'val' is 0x603120. I also printed out the address of it and tried the same, just to be sure.
I expect to print out 0xDEADBEEF (well the base 10 version of it) but what happens is that it prints out different values every time 'reader' is called, even when running it against the same 'main' program; the 'main' program shouldn't have anything in .data changing since it is just waiting for input so I am confused what I am doing wrong.

A: With std::cout << reinterpret_cast<long>(local.iov_base) << std::endl;, you actually print out the address of buffer, which is why it looks like random value.
This should solve your problem
std::cout << *reinterpret_cast<long*>(local.iov_base) << std::endl;

redpajama_set_name: RedPajamaStackExchange


text:
Q: .htaccess URL Rewrite Help Needed I need some help to clean my URL.
I have a PHP script that generate URL's like:
http://example.com/index.php?a=profile&u=simon

Currently I have an .htaccess that clean most of it
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^welcome/([^/]+)/?$         index.php?a=welcome&filter=$1   [NC,QSA,L]
RewriteRule ^explore/([^/]+)/?$         index.php?a=explore&filter=$1   [NC,QSA,L]
RewriteRule ^profile/([^/]+)/?$         index.php?a=profile&filter=$1   [NC,QSA,L]
RewriteRule ^page/([^/]+)/?$            index.php?a=page&filter=$1      [NC,QSA,L]
RewriteRule ^(([^/]+)+)(/([^/]{0,32})(/.+)?)?$ index.php?a=$1&q=$3 [L,QSA]

The previous link with these rules looks like:
http://example.com/profile&u=simon

Is there a way to achieve this?
http://example.com/simon

A: You can use the following, place this at the bottom (bellow your existing rules) :
RewriteRule ^(.+)/?$ /index.php?a=profile&u=$1 [NC,L]

This will internally redirect

*

*site/foo

to

*

*site/index.php?a=profile&u=foo


text:
Q: How does a disentangler disentangle a short ranged entangled (SRE) states in multi-scale entanglement renormalization ansatz (MERA) circuit? I encounter a problem in understanding the role of disentanglers in Multi-scale entanglement renormalization ansatz (MERA). I do understand that without disentanglers, some short ranged entangled (SRE) modes will propagate to next RG level which is unwanted, therefore, we apply the "disentangler" to first disentangle the SRE states. However, I don't understand how the disentangler disentangles a SRE modes and how the SRE be removed. From Vidal' paper(p.10), he said that the disentangler can turn an entangled state $ (1/ \sqrt{2}) | 1_r 1_s \rangle + |2_r 2_s \rangle $ to a product state $ | 1_r 1_s \rangle $. Could someone explain how this process actually work and how the entanglement be removed? Is there an explicit form of the disentangler for this problem?

A: Do you know how you can create entanglement between two qubits with a CNOT gate? Invert this and you have the disentangler you talk about.
Specifically, if you apply a CNOT gate to $(\lvert1\rangle+\lvert2\rangle)\otimes\lvert1\rangle$, you get the state $\lvert1,1\rangle+\lvert2,2\rangle$ you talk about. Invert it, and you have disentanged said state.
If you want to end up with $\lvert1,1\rangle$, you still have to do a Hadamard transformation on the first qubit.


text:
Q: Form do not submit even when function is true I made the following code, but it prevents form submission in both cases.

$(document).ready(function() {
  $('#password_result_success').hide();
  $('#password_result_error').hide();
  $('#current_password_blank').hide();
  $('#confirm_new_password').blur(function(event) {
    data = $('#current_password').val();
    var len = data.length;
    if (len < 1) {
      //alert("Password cannot be blank");
      $('#current_password_blank').show();
      // Prevent form submission
      //event.preventDefault();
      $('form#form_change_password').submit(function(e) {
        e.preventDefault();
      });
    } else {
      $('#current_password_blank').hide();
    }

    if ($('#new_password').val() != $('#confirm_new_password').val()) {
      //alert("Password and Confirm Password don't match");
      //$('#password_result').html('');
      $('#password_result_success').hide();
      $('#password_result_error').show();
      // Prevent form submission
      $('form#form_change_password').submit(function(e) {
        e.preventDefault();
      });
    } else {
      $('#password_result_error').hide();
      $('#password_result_success').show();
    }
  });
});

change password

  <form action="post.php" id="form_change_password">

      <input type="password" class="form-control" id="current_password" placeholder="current password">

current password can't be blank

      new password
      <input type="password" class="form-control" id="new_password" placeholder="New Password">

      confirm new password
      <input type="password" class="form-control" id="confirm_new_password" placeholder="Confirm New Password">

 password match

 password do not match

      <button type="submit" id="change_password" class="btn btn-default">Change Password</button>

  </form>

The complete validation I will make in PHP, but I would like to check via jQuery first, before making an AJAX call to PHP validation. The problem is that my script prevents the form submission even when it returns true.

A: You are setting your submit handler inside your blur handler, this means that any time that code is triggered a new handler will be set. It's not conditional execution, it will fire even when calling submit outside that block. You can inspect the bound listeners in your browser to check that once you hit that code, the listener remains after the execution.
You can rely on the visibility of your validation containers to determine if you should prevent submission or not. You could also use other techniques, like adding a has-error class to your form or data-* attributes, but the idea remains the same.

$(document).ready(function() {
  // Cache selectors to make them a bit shorter and more performant
  $pwd_success = $('#password_result_success').hide();
  $pwd_error = $('#password_result_error').hide();
  $pwd_blank = $('#current_password_blank').hide();

  $('#confirm_new_password').blur(function(event) {
    data = $('#current_password').val();
    var len = data.length;
    if (len < 1) {
      //alert("Password cannot be blank");
      $pwd_blank.show();
    } else {
      $pwd_blank.hide();
    }
    if ($('#new_password').val() != $('#confirm_new_password').val()) {
      $pwd_success.hide();
      $pwd_error.show();
    } else {
      $pwd_error.hide();
      $pwd_success.show();
    }
  });

  // Attach listener globally (and only once)
  $('form#form_change_password').submit(function(e) {
    if ($pwd_blank.is(':visible') || $pwd_error.is(':visible')) {
      // Prevent submission if there's an error
      e.preventDefault();
    }
  });
});

change password

  <form action="post.php" id="form_change_password">

      <input type="password" class="form-control" id="current_password" placeholder="current password">

current password can't be blank

      new password
      <input type="password" class="form-control" id="new_password" placeholder="New Password">

      confirm new password
      <input type="password" class="form-control" id="confirm_new_password" placeholder="Confirm New Password">

 password match

 password do not match

      <button type="submit" id="change_password" class="btn btn-default">Change Password</button>

  </form>


text:
Q: Play! Framework app on EC2 I want to deploy and run my Play! Framework app on EC2.
I have installed the Play! Framework on one instance, now I don't want to copy my source code over but instead I want to "build" my app into libraries/jar/wars and copy the binary over and have play run against the binaries. Does Play! support that?

A: You can deploy your play application as standalone java application without installing play framework on EC2. You will need to generate distribution file of your play application by following step

*

*Navigate to project folder

*type play

*type dist
This will generate project snapshot zip file in dist folder of your play application.
Upload that zip file to EC2 instance and extract in some folder. There you will find a start shell script file. Just execute that script file
Note: To make file executable type: chmod 777 start
./start
This will publish application and opens port to receive http request on default port 9000. If you want to change port when executing file,
./start -Dhttp.port=8080
This will publish application on port 8080

A: Well, the Play documentation mention it clearly that you can.
play war myapp -o myapp.war

Take a look on Play documentation, its very clear.

A: No, there is no native single-file format for play apps.
But, yes you can use any archive format for your purpose. Instead of running :
play command myfile

you'll do something like this :
unzip myfile; play command file;

Plus, you could always try using wars and rune those across multiple tomcats, but it would be a waste of ressources as native play server is better.

A: If you are using activator you can exploit its stage command which prepares all dependent libraries and compiles your code.
In my blog, I have tried to explain the whole deployment scenario of an Play application to an EC2 instance. Here is the link for more detail:
http://www.javacirecep.com/cloud/deploy-play-scala-applications-on-amazon-ec2/


text:
Q: How to display af pdf image in the markdown on github I have been looking on other questions and answers especially this one:
Display pdf image in markdown
But i still do not get it.
I have a link to a pdf from dropbox (i have also tried google drive) Links (same picture): https://www.dropbox.com/s/a1hdh6vlcoknwsb/software_achitecture.pdf
https://drive.google.com/open?id=1SFAAmHxWcK9QbVybjVY4_jMYTsLnWHn1
Code
<object data="https://www.dropbox.com/s/a1hdh6vlcoknwsb/software_achitecture.pdf?dl=0" type="application/pdf" width="700px" height="700px">
    <embed src="https://www.dropbox.com/s/a1hdh6vlcoknwsb/software_achitecture.pdf?dl=0">

This browser does not support PDFs. Please download the PDF to view it: Download PDF.

    </embed>
</object>

what do i do wrong?


text:
Q: Kerberos SSO authorization from React I have a React app that makes requests to our REST API server using axios.
On the REST server we use Kerberos for authorization. When I simply make a request to that server using chrome (through address bar like "https://example.com/api/v1/sso_auth"), the authorization works fine (chrome passes the correct header with kerberos's ticket data), but when the React App makes the request, the ticket isn't added to the request (stuck on www-authenticate: negotiate phase).
How can I access (or maybe intercept) the Kerberos ticket and send it via the react app using axios?


text:
Q: Generate url in MVC Api Controller I am using both Api and routing controller in my web app. My api controller is used to retrieve the link to the page that shows the information about an item. The page is rendered using the traditional mvc controller.
In the api controller, how do I generate the link to the page? Of course I could generate the link by hardcoding the routing path but I'd like to take advantage of the routing capability in mvc.
People have suggested to use UrlHelper.Action, but looks like it cannot be used in Api controller, or am I missing something

A: Use Url.Link, that will work fine. Check out Using the asp.net web api urlhelper for more info


text:
Q: Among all permutations $f$ of $\{1, 2, 3, 4, 5\}$, how many have $f(1)$ odd? $f(2)$ odd? Both odd? Among all permutations $f$ of $\{1, 2, 3, 4, 5\}$, how many have $f(1)$ odd? $f(2)$ odd? Both odd?
I do not understand how to use the $f(1)$ or $f(2)$.  I get that a permutation is odd or even according to the number of transpositions that is made, but I do not get how to apply the $f(1)$ part.

A: If we need $f(1)$ to be odd, we have $(3)(4)(3)(2)(1)$ ways to create a permutation, because we are guaranteeing $f(1)$ to be $1$, $3$, or $5$. We then have $\boxed{72}$ permutations.
If we need $f(2)$ to be odd, we have $(3)(4)(3)(2)(1)$ ways, where we guarantee $f(2)$ to be $1$, $3$, or $5$, then build the rest of the permutation off of that. We also have $\boxed{72}$ permutations.
If we need both $f(1)$ and $f(2)$ to be odd, we have $(3)(2)(3)(2)(1)$ ways to create the permutation, because we guarantee $f(1)$ to be $1$, $3$, or $5$, and $f(2)$ to be one of the odds that isn't $f(1)$. We have $\boxed{36}$ permutations.

A: Among all the $5!$ permutations, $\dfrac 35$ of them have an odd number in the first position, hence $72$. Same answer for the second position.
Among these, $\dfrac{3-1}{5-1}=\dfrac24$ of them have an odd number in the other position, hence $36$.

More explicitly:
The permutations that fulfill the first condition are
$$1\times\times\times\times,\\ 3\times\times\times\times,\\ 5\times\times\times\times$$ where the crosses denote the $24$ permutations of the remaining digits.
The permutations that fulfill the second condition are
$$\times\,1\times\times\times,\\ \times\,3\times\times\times,\\ \times\,5\times\times\times$$ also $3\times 24$.
The permutations that fulfill the third condition are
$$1\,3\,\times\times\times,\\1\,5\,\times\times\times,\\3\,1\,\times\times\times,\\3\,5\,\times\times\times,\\5\,1\,\times\times\times,\\5\,3\,\times\times\times$$
$6\times6$ of them.


text:
Q: Error Type mismatch error in Akka scaladsl in Akka-Http code Im new to Akka framework and i get the below error message when im trying to run my code.
The method which is called through the api code returns a
Future[List[HashMap[String,Object]]]
The api code(akka-http route) which calls this method:
@GET
  @Path("getList/{name}")
  @Authorization("basicAuth")
  @Operation(summary = "Get list", description = "Returns a list",
    parameters = Array(new Parameter(name = "name", in = ParameterIn.PATH, description = "name", required=true)),
    security = Array(new SecurityRequirement(name="basicAuth")),
  )
    def getList: Route = {
      path("getList" / Segment) { name =>
        get {
          complete(getListService(name))
        }
      }
    }

I get the below error message
type mismatch;
 found   : scala.concurrent.Future[List[scala.collection.immutable.HashMap[String,Object]]]
 required: akka.http.scaladsl.marshalling.ToResponseMarshallable
          complete(getList(param))

returning a future should not be giving this error, i'm a bit confused as im not able to pinpoint where the mistake is.
Any suggestions would greatly help.Kindly let me know if any more info is required.

A: It requires an entity that it can serialize to JSON. HashMap[String, Object] isn't something that Akka is able to serialize out of the box. You have to either change the return type to something other than Object or define a custom marshaller. I doubt that you need an Object serializer, you probably want to have some class here instead. Here you have examples of serialization using spray: https://doc.akka.io/docs/akka-http/current/common/json-support.html


text:
Q: Local linearization / calculus The question is :
Local linearization gives values too small for the function x2 and too large for the function . Draw pictures to explain why.
See vvv that is the question only. No additional things are given.

What I want is:
I need a explanation and How to draw a linearization ?

What I know about linearization is:
I know how to find the local linearzation, but there aren't any given x values and its not stated which is the function and which is the tangent function.

A: Let $f(x) = x^2$.  The "local linearization" of $f$ at $x_0 \in \mathbb R$ is the function
$h(x) = f(x_0) + f'(x_0)(x - x_0)$.  The graph of $h$ is a line which is tangent to the graph of $f$ at the point $(x_0,f(x_0))$.
Just graph $f$ then pick some $x_0 \in \mathbb R$ and graph $h$.  The picture will show that the graph of $h$ lies below the graph of $f$.  In other words, if $x_0 \in \mathbb R$, then
$f(x) \geq f(x_0) + f'(x_0)(x - x_0)$ for all $x$.


text:
Q: SQl error with timeout I have been having trouble with timeout on SQL program , I have narrowed it down to this function , i can pass parameters and it words , but in this instance I send a couple hundered . When it runs I get a timeout and maybe 6 or so get through into the database and then timeout occurs in about 2minutes. when run locally everything works fine and operations complete in a few seconds.!! any ideas? .
I know its getting the information it needs and gettting into the list and it can connect and send data to SQL. I have read maybe creating too many connections and the like but nothing seems to fix it. Any ideas or simple problems you have come accross?. also tried disabling debuggers etc as per
public void ConnectToSQl(String word, int count, String HashTag = " ")
{
    checkExcludeList();
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source = dev\\SQLEXPRESS ;" +
                            "Initial Catalog=sml;" +
                            "User id=**** ;" +
                            "Password =******;" +
                            "Trusted_Connection=No";
    try {
        conn.Open();
        SqlCommand Command = new SqlCommand("INSERT INTO word_list (word , count)" +
                                            "VALUES (@word , @count)", conn);
        //add parameters for insert
        Command.Parameters.AddWithValue("@word", word);
        Command.Parameters.AddWithValue("@count", count);
        Command.ExecuteNonQuery();
    } catch (Exception e) {
        Box.Text = "SQL error" + e;
    } finally {
       conn.Close();
    }
}

A: Try passing in your open connection.  Opening a sql connection is very expensive.
public void ConnectToSQl(SqlConnection conn, String word, int count, String HashTag = " ")
{
    if (conn.State != ConnectionState.Open)
        throw new SqlExecutionException("Sqlconnection is not open");

    checkExcludeList();

    SqlCommand Command = new SqlCommand(
        "INSERT INTO word_list (word , count)" +
        "VALUES (@word , @count)", conn);

    //add parameters for insert
    Command.Parameters.AddWithValue("@word", word);
    Command.Parameters.AddWithValue("@count", count);

    Command.ExecuteNonQuery();

}


text:
Q: Empty slice returned Fairly new at go.
I am trying to basically read all the files in directory and subdirectory, populate in a slice and then process further.
Here is the code (Main functions to look are Main and expandDirectory
package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

const dirname string = "MyDirectory"

func check(e error) {
    if e != nil {
        panic(e)
    }

}

func expandDirectory(currentDirectory string, allFiles []os.FileInfo) []os.FileInfo {
    files, e := ioutil.ReadDir(currentDirectory)
    check(e)
    for _, internalDir := range files {
        switch mode := internalDir.Mode(); {
        case mode.IsDir():
            var filepath = currentDirectory + internalDir.Name() + "\\"
            expandDirectory(filepath, allFiles)
        case mode.IsRegular():
            allFiles = append(allFiles, internalDir)
        }
    }
    return allFiles
}

func main() {
    allFiles := expandDirectory(dirname, make([]os.FileInfo, 5))
    fmt.Printf("%v", cap(allFiles))
}

The final print will print 5 which is the initial value.
Just FYI, the expandDirectory function is just recursive function in case of directories and adding the file reference in case of a file.
Thanks for the help
Where am I going wrong
FINAL CODE (changes Only)
func main() {
  allFiles := expandDirectory(dirname)
}

func expandDirectory(currentDirectory string) []os.FileInfo {
    allFiles := make([]os.FileInfo, 0, 5)
    ....
        case mode.IsDir():
    ....
            allFiles = append(allFiles, expandDirectory(filepath)...)
    ....
    return allFiles
}

A: You need to append the result to it:
allFiles = append(allFiles, expandDirectory(filepath, allFiles)...)

Also
 allFiles := expandDirectory(dirname, make([]os.FileInfo, 5))

should be:
 allFiles := expandDirectory(dirname, make([]os.FileInfo, 0, 5))

Otherwise you will be appending to allFiles and the first 5 items will be empty.


text:
Q: Can't commit several files from Visual Studio project to subversion Since a few weeks, I have some problems with Subversion. When I try to commit files from a Visual Studio 2017 project there are some files which I can't commit to my Visual SVN Server. To be precise all files in the project folder like *.cs, *.config, *.csproj, *.resx, ...
My setup:
Client: TortoiseSVN 1.9.7 on Windows10
Server: VisualSVN behind a IIS-ReverseProxy running on Windows Server 2012r2
The error I get when I try to commit for example a *.cs file:
Commit
D:\Test\branches\ScaraControl\ScaraControl\Form1.cs
D:\Test\branches\ScaraControl\ScaraControl\Form1.cs
Commit failed (details follow):
File 'D:\Test\branches\ScaraControl\ScaraControl\Form1.cs' is out of date
'/svn/Test/!svn/txr/5-9/branches/ScaraControl/ScaraControl/Form1.cs' path not found
You have to update your working copy first.

Updating the working copy is finishing successfully but doesn't fix the problem.
You can see my project in the picture below. For testing, I created a completely new and empty repository. As you can see the .vs, bin and obj folders are ignored with all the files inside of them, all other folders are committed to the server (without the files inside of them). In the second picture you can see that I can commit the *.sln file but no other file in the project folder.

For testing, I created an empty text file and renamed it to text.cs. Even this empty file cannot be committed to the Server with the same error message.
Due to the fact that this is happening to all Clients, it is more likely to be a problem on the Server side I guess but I have no idea what could cause this error. Unfortunately, the VisualSVN Server has no error logging or at least not the free version I'm using.
I would be very grateful for any tip I can get to solve this annoying problem.
Edit1: Problem is caused by the IIS Reverse-Proxy
After connecting via port 8443 directly to the VisualSVN server (bypassing the reverse proxy) everything is working again. So there must be a problem with the configuration of the URL Rewrite module. To be honest it took me quiet a long time to get it working somehow because my knowledge about all the settings is very limited.
This my Web.config with the settings for the URL Rewrite module. Maybe there is something not configured as it should be. If you need further information just ask.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <outboundRules>
                <rule name="ReverseProxyOutboundRule1" preCondition="ResponseIsHtml1" enabled="true">
                    <match filterByTags="A, Form, Img" pattern="^http(s)?://svn.example.org:8443/(.*)" />
                    <action type="Rewrite" value="http{R:1}://svn.example.org/{R:2}" />
                </rule>
                <preConditions>
                    <preCondition name="ResponseIsHtml1">
                        <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
                    </preCondition>
                </preConditions>
            </outboundRules>
            <rules>
                <rule name="ReverseProxyInboundRule1" enabled="true" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{CACHE_URL}" pattern="^(https?)://" />
                    </conditions>
                    <action type="Rewrite" url="{C:1}://svn.example.org:8443/{R:1}" />
                </rule>
            </rules>
        </rewrite>
        <security>
            <authorization>
                <remove users="*" roles="" verbs="" />
                <add accessType="Allow" users="" roles="Users" />
                <add accessType="Allow" users="*" />
                <add accessType="Allow" users="?" />
            </authorization>
        </security>
        <urlCompression doStaticCompression="false" doDynamicCompression="false" />
        <httpRedirect enabled="false" destination="https://svn.example.org" exactDestination="true" childOnly="true" />
        <directoryBrowse enabled="false" />
    </system.webServer>
</configuration>

A: I had the same issue.
The fails because IIS prohibits URL suffixes like .cs and .config
You can work around this by adding this to the web.config of the IIS proxy
<system.webServer>
  <security>
    <requestFiltering>
      <fileExtensions allowUnlisted="true" applyToWebDAV="true">
        <clear />
      </fileExtensions>
      <verbs allowUnlisted="true" applyToWebDAV="true" />
      <hiddenSegments applyToWebDAV="true">
        <clear />
      </hiddenSegments>
    </requestFiltering>
  </security>
</system.webServer>

Credits to this post IIS7 and ARR as reverse proxy for Subversion

A: I came across the same problem and am running a reverse proxy through IIS, so believe that has something to do with it.
VisualSVN is served up locally on https://localhost:8443 and I was attempting to use the reverse proxy to route from https://svn.mysite.com. This appears to work fine. You can even checkout a fresh copy of the repo and all files are downloaded. It's when you try and commit that you have problems - as you've identified, certain files fail to be found on the repo.
The only work around I have found (thanks to your question narrowing down the likely causes) was to add the port to the URL: https://svn.mysite.com:8443. This shouldn't be necessary as the reverse proxy should handle, so I'm guessing it's an issue with VisualSVN which may be fixed in a future update.


text:
Q: Границы муниципальных образований России yandex api я ищу границы МО России.
Есть ли подобное для муниципальных образований целиком и по отдельности по регионам и муниципалитетам?
Хочу построить такую карту
Это для регионов из этого примера
ymaps.borders.load('RU', {
        lang: 'ru',
        quality: 2
    })

Для этого пример у меня дополнительный вопрос есть: как сделать так, чтобы эта карта в окне появилась полностью (или другими словами как сделать персональные лимиты для zoom out)? В этом примере не вся Россия попадает сразу на окне: либо Калининград или Камчатка не видны. Приходится left-click-and-drag, чтобы увидеть остальную часть.

A: В API Яндекс.Карт не получится получить границы уровня меньше, чем регионы.
Скачать контуры интересующих вас границ можно на сторонних сервисах, например http://data.esosedi.org


text:
Q: Getting rid of duplicate array Array is like this:
Array
(
    [0] => 2011/10/05
)
Array
(
    [0] => 2011/10/05
)

How can I get rid of the duplicate array?

A: php has a function
array_unique
http://php.net/manual/en/function.array-unique.php
EDIT
  Option 1
      <?php
           $array1 = array("2011/10/05");
           $array2 = array("2011/10/05");
           $merged = $array1;

           foreach($array2 as $v) array_push($merged,$v);
           $unique = array_unique($merged);
      ?>

You could use array_merge, but the problem with array_merge is that it joins the same keys together which you probably don't want. The above code will add elements from array2 to array1 and then do array_unique (adding elements of array2 to array1 can also be done differently).

A: First merge and then unique
$a = array('2011/10/05');
$b = array('2011/10/05');

$c = array_merge($a,$b);

$d = array_unique($c);


text:
Q: Convex optimization: interpretation of the dual variable Let us consider the convex optimization problem
$$
\tag{P}
  \underset{x\in\mathbb R^n}{\sf minimize}
~~
  f(x) ~+~ g({\bf L}x)
$$
where ${\bf L}\in\mathbb R^{m\times n}$. Using the convex conjugate, the corresponding dual problem can be written as
$$
\tag{D}
  \underset{y\in\mathbb R^m}{\sf minimize}
~~
  f^\star(-{\bf L}^{\!\sf T}y) ~+~ g^\star(y)
$$
The quantity ${\bf L}x$ can be somehow interpreted as a feasibility residual (I am thinking of the case $g=\delta_{\{b\}}$ so that it embodies the linear equality constraints ${\bf L}x=b$), but what is the meaning of the quantity ${\bf L}^{\!\sf T}y$, and what is the information that it gives in terms of optimality/feasiblity?
I know that if $(x^\star,y^\star)$ is a primal-dual pair, then it satisfies the optimality conditions

*

*$-{\bf L}^{\!\sf T}y^\star \in \partial f(x^\star)$

*$y^\star \in \partial g({\bf L}x^\star)$

but I still don't get the role of ${\bf L}^{\!\sf T}y$.
Thanks for your help.

A: Technically, D is not the dual of P. P has no constraints, so its true dual is
$$\begin{array}{ll}
\text{maximize} & p^*
\end{array}$$
where $p^*\triangleq \inf_x f(x)+g(Lx)$ is a (possibly infinite) constant. That's right: the dual has no variables. Needless to say it's somewhat useless.
D is actually the dual of
$$\begin{array}{ll}
\text{minimize}_{x,w} & f(x) + g(w) \\ \text{subject to} & L x = w
\end{array}$$
The role of $y$, then, is to serve as the Lagrange multiplier of $Lx=w$. I'm not sure if there's a good alternative interpretation that doesn't involve the equality constraints.


text:
Q: Still not getting proper resolution landscape, portrait images back from the API i follow the steps
Login to into your client application settings on https://instagram.com/developer/
Click Manage Clients on top nav menu.
Locate your API Client, and click Edit.
Click the Migrations Tab for your API Client application, and check the box that says "Non square media".
Click Update Client.
and enabled the Non Square media and uploaded couple of landscape and portriot photos, still i am getting square photos only;please find the example response for still showing 640 * 640 ;please help;
{ caption: "", commentCount: 0, comments: null, createdTime: "Oct 15, 2015", deleted: null, height: 640, id: null, providerImageId: null, thumbnailInfo: { caption: null, commentCount: 0, comments: null, createdTime: null, deleted: null, height: 150, id: null, providerImageId: null, thumbnailInfo: null, type: null, url: "https://scontent.cdninstagram.com/hphotos-xfa1/t51.2885-15/s150x150/e35/12144260_893144404097052_1454548341_n.jpg", username: null, width: 150 }, type: null, url: "https://scontent.cdninstagram.com/hphotos-xfa1/t51.2885-15/s640x640/sh0.08/e35/12144260_893144404097052_1454548341_n.jpg", username: "anilk", width: 640 },

A: Are you trying to upload images from the iOS Hook? From what I can tell with my own tests, landscape and portrait images in Instagram only work when selecting an image from the gallery within the Instagram app. When passing an image via the hook it just crops it.

A: Try this link: https://api.instagram.com/v1/tags/nonsquare/media/recent/?client_id=[CLIENT-ID] or https://instagram.com/explore/tags/nonsquare/. There are many non-square images.
When you upload picture in Instagram, application use square as default. To upload non-square image, just click small gray button in left-down corner of image before filter's selection.


text:
Q: Error when including Windows.h with TCC What I really wanted to do was to include Ws2tcpip, so I followed the instructions in the answers from this thread, copied MinGW's include files to \tcc\include\winapi\ and created a library from wsock2.dll. But the problem I get now is when I include Windows.h.
....\tcc\include\winapi\winnt.h|3819|error: declaration list expected|

which is
typedef __AW(OSVERSIONINFO) OSVERSIONINFO,*POSVERSIONINFO,*LPOSVERSIONINFO;

So how do I get the winapi to work with tcc?
Thanks


text:
Q: Adding max values label to plotly scatter plot I have been trying all day to add max value annotation to a plotly plot. I figured out how to do it manually but I am more interested in a more automatic solution. I added my code in but omitted anything unrelated.
Is there a way to add a label to the max points of my plotly scatterplot?
P.S. Please be nice this is my first posting here.
The relevant part of the code:
import plotly.express as px
import pandas as pd

m = df['values'].max()

day_order = ['Monday',
             'Tuesday',
             'Wednesday',
             'Thursday',
             'Friday',
             'Saturday',
             'Sunday']

fig = px.scatter(df,
                 x='day-of-week',
                 y ='values',
                 category_orders = {
                     'day-of-week': day_order})

fig.add_annotation(x='Sunday',
                   y=m,
                   text=m)

A: I generate a data sample for you.
Data
import plotly.express as px
import pandas as pd
import numpy as np

n = 14
df = pd.DataFrame(
    {"date": pd.date_range(
        start=pd.Timestamp.today().date(),
        periods=n),
     "values": np.arange(n)})

# date to day-of-week
df["day-of-week"] = df["date"].dt.day_name()

day_order = ['Monday',
             'Tuesday',
             'Wednesday',
             'Thursday',
             'Friday',
             'Saturday',
             'Sunday']

m = df["values"].max()

Plot
fig = px.scatter(df,
                 x='day-of-week',
                 y ='values',
                 category_orders = {
                     'day-of-week': day_order})

fig.add_annotation(x=df.iloc[df["values"].idxmax()]["day-of-week"],
                   y=m,
                   text=str(m))

In the last part is important that text is a str

A: Used data

Code: find max value and day(s) with max value and add their annotations
max_value = df['values'].max()
max_days = df[df['values'] == max_value]['day-of-week'].values

day_order = ['Monday',
             'Tuesday',
             'Wednesday',
             'Thursday',
             'Friday',
             'Saturday',
             'Sunday']

fig = px.scatter(df,
                 x='day-of-week',
                 y ='values',
                 category_orders = {
                     'day-of-week': day_order})

for day in max_days:
  fig.add_annotation(x=day,
                    y=max_value,
                    text=max_value)

fig.show()


text:
Q: Excel VBA userform texbox input error I am trying to create a macro that will input whatever is written in the userform textbox onto the active cell. However, whenever I try to run that portion of the code, i get an error 438. Here is a sample of the part there shows up on the debug.
With Selection.Font
.Bold = True
End With
ActiveCell.Value = UserForm2.Controls("TextBox" & i).Caption
ActiveCell.Offset(1, 0).Select

A: Error 438 means the Object doesn't support the property or method.
Textbox.Caption doesn't exist. For a full list of methods / properties see MSDN TextBox Properties
As on how to fix your code:
ActiveCell.Value = UserForm2.Controls("TextBox" & i).Value
or
ActiveCell.Value = UserForm2.Controls("TextBox" & i).Text


text:
Q: OpenLayers 3.7 projection I've been trying to get some GeoJSON features into OpenLayers. 3.7 changed the geojson source format, and I've made the changes. But I don't know how to reproject in the new format from 4326 to 3857.
Here is the link to fiddle.net (https://jsfiddle.net/aborrell/h2yv6moy/) :
As it shows, the features are near 0,0, but actually they should be in Mexico.


text:
Q: Setting UISearchBar to minimal with translucency Is it possible to make a UISearchBar translucent with a background color and search field color that can be changed separately?
This is what I'm currently getting with a search style of minimal and a background of light blue. If I want the search field to be white, I have to not use minimal for the search style, but then my search bar isn't translucent.
What can I do?


text:
Q: how can I take values out of many strings I have a data like below
df<-structure(list(X__1 = c("Q6NVC0 [197-213]", "A0A0A8UAS1 [48-64]",
"A0A0F0XK65 [8-17]", "A0A0G2JMX7 [481-491]; P20406-6 [106-116]; Q6UIN5 [7-17]; P20406-3 [70-80]; P20406-8 [164-174]",
"A0A0G2JMX7 [481-497]; P20406-6 [106-122]; Q6UIN5 [7-23]; P20406-3 [70-86]; P20406-8 [164-180]",
"P20406-6 [106-132]; Q6UIN5 [7-33]; P20406-3 [70-96]; P20406-8 [164-190]",
"H6VRG2 [603-616]", "P13645 [41-59]", "P35527 [488-513]", "P35908 [525-544]; H2R1Z0 [512-531]",
"H6VRG2 [550-588]", "A0A024RBS2 [150-162]", "A0A023L3M5 [83-110]",
"P10809 [143-156]", "V9HW22 [470-493]", "P20406-8 [379-392]",
"P19338 [524-537]", "A0A024L4P7 [46-57]", "G7YYH5 [45-55]", "Q86YZ3 [973-991]; [1443-1461]; [1913-1931]; [2383-2401]",
"P35527 [375-390]", "P35527 [375-391]", "D2TTS3 [41-50]")), .Names = "X__1", class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -23L))

I am trying to make an output like this
At first I try to get the value next to one two IDs P20406-8 and A0A024RBS2. If they dont exist in a row, we take the first two values of any other ID. if they exist together, we take the value next to the first one and if one of the ID is there, we take its value.
So at the end I want a two column of values like below
197 213
48  64
8   17
164 174
164 180
164 190
603 616
41  59
488 513
525 544
550 588
150 162
83  110
143 156
470 493
379 392
524 537
46  57
45  55
973 991
375 390
375 391
41  50

A: this code works just fine for me:
df_new <- df2$X__1
primary_ID <- "P20406-8"
secondary_ID <- "A0A024RBS2"

ID_Primary <- grepl(pattern = primary_ID, df_new)
ID_Secondary <- grepl(pattern = secondary_ID, df_new)

df_new[ID_Primary] <- substr(df_new[ID_Primary],
                              start = regexpr(primary_ID, df_new[ID_Primary]),
                              stop = 2000)

df_new[ID_Secondary & !ID_Primary] <- substr(df_new[ID_Secondary],
                                               start = regexpr(secondary_ID, df_new[ID_Secondary]),
                                               stop = 2000)

start <- regexpr(pattern = "\\[", text = df_new)  # find opening square bracket
end <- regexpr(pattern = "\\]", text = df_new)  # find closing square bracket
temp <- substr(df_new, start+1, end-1)  # only take values between opening and closing
temp <- strsplit(temp, "-")  # split values in two

result <- t(data.frame(temp))
rownames(result) <- NULL

I hope this helps!

A: One approach:
library(splitstackshape)
# separate multi observation lines into multiple columns
df2 <- cSplit(df, splitCols='X__1', sep=';')
# put in a long format for easier processing
df3 <- na.omit(data.frame(melt(as.data.frame(df2),measure=names(df2))))

# extractions
# account id
df3$id <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\1'))
# start range
df3$begin <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\2'))
# end range
df3$end <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\3'))
# accounts with multiple:
df3$mult_id <- as.numeric(with(df3,gsub(x=variable,pattern="^X__1_(.*)$",replacement='\\1')))

# apparently you only want those with one obs:
df.final <- df3[which(df4$mult_id==1),]


text:
Q: Regex Parse In any order at most once I'm working on a Date parser (Tenor parser exactly) where I have to extract dates set as a sum of number of days, weeks, months and years.
This would look like 1d1y or 100m2w or 1y1d1m1w.
I've built a custom parser but I'm looking for a cleaner solution using Regex. I have to check that it contains at most once of each date characters (d, w, m and y) and separated with an integer.
^(?<ValueDay>[0-9]+(d))?(?<ValueWeek>[0-9]+(w))?(?<ValueMonth>[0-9]+(m))?(?<ValueYear>[0-9]+(y))?$

The problem I have is that it could happen in any order (1d1w works as well as 1w1d). I tried to use the positive lookahead (?=) as follow but it doesn't match all the criterias.
^(?=.*(?<ValueDay>[0-9]+(d)))?(?=.*(?<ValueWeek>[0-9]+(w)))?(?=.*(?<ValueMonth>[0-9]+(m)))?(?=.*(?<ValueYear>[0-9]+(y)))?.*$

How could I do this?

A: If each group must occur zero or one time, you can use the following:
^
 (
  (?(y)(?!)|(?<y>\d+)y)
  |
  (?(m)(?!)|(?<m>\d+)m)
  |
  (?(w)(?!)|(?<w>\d+)w)
  |
  (?(d)(?!)|(?<d>\d+)d)
 )+
$

For each letter, it checks whether the group with that letter as a name has a match already. If so, it fails and moves onto the next letter. If not, it tries to capture digits followed by that letter, into the group with that letter as the name.

Previous answer - everything-happens-exactly-once version:
^((?<y>\d+)y|(?<m>\d+)m|(?<w>\d+)w|(?<d>\d+)d){4}$(?<-y>)(?<-m>)(?<-w>)(?<-d>)

This checks for:

*

*start of input

*one of y, m, w or d

*

*four times (= number of groups)

*end of input

*that at least one y was matched

*that at least one m was matched

*that at least one w was matched

*that at least one d was matched

A: Regex r = new Regex(@"^(\d+)([wydm])(?!.*\2)"
                + @"(?:(\d+)([wydm])(?!.*\4))?"
                + @"(?:(\d+)([wydm])(?!.*\6))?"
                + @"(?:(\d+)([wydm]))?$");

This should work. It matches \d+[wydm] at least once and at most four times. Above that, when a character [wydm] is matched, it looks ahead and the same character shall not occur in the text the second time. Now you can get the values from groups:
int GetValue(Match m)
{
    int GetGroupValue(Group numberGroup, Group characterGroup)
    {
        if (!numberGroup.Success) { return 0; }
        int number = int.Parse(numberGroup.Value);
        switch (characterGroup.Value)
        {
            case "d": return number;
            case "w": return 7 * number;
            case "m": return 31 * number;
            case "y": return 365 * number;
            default: throw new NotSupportedException(characterGroup.Value + " is not supported");
        }
    }

    return GetGroupValue(m.Groups[1], m.Groups[2])
         + GetGroupValue(m.Groups[3], m.Groups[4])
         + GetGroupValue(m.Groups[5], m.Groups[6])
         + GetGroupValue(m.Groups[7], m.Groups[8]);
}

Here are some tests to verify the corectness:
var tests = new (string s, bool isOk, int desiredValue)[] {
    ("15y", true, 15*365),
    ("1000w", true, 1000*7),
    ("10000d", true, 10000),
    ("100000m", true, 100000*31),
    ("15y8y", false, 0),
    ("", false, 0),
    ("7y9w12m2d", true, 7*365 + 9*7 + 12*31 + 2),
    ("7d9m12w2y", true, 7 + 9*31 + 12*7 + 2*365),
    ("7y9w12m2dd", false, 0),
    ("7y9w12m2y", false, 0),
    ("7y9w12m2x", false, 0),
    ("-5y", false, 0),
    ("1", false, 0),
    ("y2", false, 0),
    ("yd", false, 0),
    ("7y1", false, 0),
    ("m5d", false, 0)
    };

foreach (var test in tests)
{
    Match m = r.Match(test.s);
    if (m.Success != test.isOk)
    {
        throw new Exception("Test failed for " + test.Item1);
    }
    if (GetValue(m) != test.desiredValue)
    {
        throw new Exception("Test failed for " + test.Item1);
    }
}

MessageBox.Show("All " + tests.Count() + " tests passed");


text:
Q: Есть строка data как определить содержит она "found" или "not found" Смысл такой, хочу написать не большой скрип, который будет ходить на удалённый сервер и пинговать большое кол-во устройств, пинговать он будете не через обычный ping, а через запуск скрипта на удалённом сервере, т.е. мой скрип заходит на сервак и запускает blablabla.sh 192.168.1.1, но это не важно. Суть в том, что при выполнении пинга через скрип на сервере, мне не возвращается ошибка, если устройство доступно скрипт отвечает:
Looking for OpenVPN client with MAC CCCCCCCCCCC... found!
если устройство не доступно то:
Looking for OpenVPN client with MAC CCCCCCCCCCC... not found!
Так вот вопрос заключается в следующем, можно ли как то проверить print на его вывод, если там будет found! или not found! То соответственно скрип пишет работает или не работает.
Устройств будет много больше 100 шт.
import paramiko
import re
import time

host = 'IP'
user = 'LOGIN'
port = PORT
ssh = 'PATH'

a = 'NAME1'
a1 = 'NAME2'
a2 = 'NAME3'

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, username=user, port=port, key_filename=ssh)

stdin, stdout, stderr = client.exec_command('sudo ping_sens.sh CCCCCCCCCC')
data = stdout.read() + stderr.read()
print(data)

вывод: Looking for OpenVPN client with MAC CCCCCCCCCC... found!


text:
Q: Mysterious disappearing reference I have what seems to be a very strange problem with a windows forms application.  I am a web developer and I have limited experience of developing windows forms application.  I am working on an ecommerce web site which stores product images in the database as blobs.  In order to make it easier to bulk import images I am writing a small windows forms utility that uses the existing website bll library.  I am using Visual studio 2010 c# and .net 4.  I created a new windows forms project in my solution and added a reference to the bll project.  I started coding and added using statements to my code, everything was working as expected intelisense worked corectly with my bll classes etc.  Then i built the project and it failed, it complained about every line of code that refered to anything from the bll project including the using statements, and intelisense no longer worked for anything from the bll project.  Basically what you would expect if there were no reference to the bll project. If i remove the reference and then re add it, or add ar reference to another projecct in the solution, intelisense comes back and all of the compiler errors disapear.  Then if i build again they all reappear and intelisense no longer works.
What am i missing, what the hell might be going on here.

A: Your library possibly has dependencies on other .NET libraries such as System.Web that you need to reference in your Forms app. That can create this sort of behaviour.

A: I just recently had an issue like this one, and wanted to include my solution for future reference in case it comes up again. There's a warning (not an error) message that pops up when the build fails, which I missed originally because I had my error list set to filter warnings out. In my particular case I needed to change away from using the client version of .NET, and the warning message contained the information I needed to debug the problem.

Warning 44 The referenced assembly [...] could not be resolved because it has a
      dependency on [...] which is not in the currently targeted framework [...]. Please
      remove references to assemblies not in the targeted framework or consider retargeting
      your project. [...]"


text:
Q: How to test await block logic in Svelte with Jest This is my first attempt at writing unit tests for a Svelte app. The below example is based on the standard Svelte template with an additional  element added. In this element I conditionally render some text with await block logic.

Hello {name}!

    Visit the Svelte tutorial to learn
    how to build Svelte apps.

    {#await isReady}Awaiting...{:then value}Resolved to: {value}{/await}

The function asyncthing returns a Promise<boolean> that resolves after 5 seconds with true.
export const asyncthing = async () => {
  console.log("asyncthing() called");
  return new Promise<boolean>((resolve) => {
    setTimeout(() => {
      console.log("timeout expired");
      resolve(true);
    }, 5000);
  });
};

Opening the app in a browser works as expected, but the test below fails.
import App from "./App.svelte";
import { render } from "@testing-library/svelte";
import { tick } from "svelte";
import * as asyncthings from "./asyncthing";

test("messing with async", async () => {
  jest.setTimeout(20000);
  jest.useFakeTimers();
  jest.spyOn(global, "setTimeout");
  const asyncthingMock = jest.spyOn(asyncthings, "asyncthing");
  const app = render(App, { name: "Everybody" });
  expect(app.getByTestId("greeting")).toBeInTheDocument();
  expect(app.getByTestId("greeting")).toHaveTextContent("Hello Everybody!");
  expect(app.getByTestId("async")).toBeInTheDocument();
  expect(app.getByTestId("async")).toHaveTextContent("Awaiting...");
  expect(setTimeout).toHaveBeenCalledTimes(1);
  expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 5000);
  jest.runAllTimers();
  await tick();
  expect(app.getByTestId("async")).toHaveTextContent("Resolved to: true");
});

The log statements are printed, so the promise does seem to resolve. However, according to Jest the text is not updated. I'm sure I must be doing something wrong, so please, somebody set me straight.


text:
Q: Shared counter in quarto for exercises, examples, etc I'm using quarto to write an online book and need to mimic the environments and counters of a published book. The latter employs five custom framed environments (examples, exercises, remarks, theorems, definitions) with a joined counter (within the chapter).
In quarto there is very nice infrastructure for creating such cross references for theorems and proofs but they have separate counters. Is it possible to configure/force them to use a joint consecutive counter?
As an example, the following code
The first example is @exm-1.

::: {#exm-1}
This should be Example 1.1.
:::

It is followed by the first exercise, @exr-1

::: {#exr-1}
This should be Exercise 1.2.
:::

is rendered as

The first example is Example 1.1.
Example 1.1
This should be Example 1.1.
It is followed by the first exercise, Exercise 1.1
Exercise 1.1
This should be Exercise 1.2.

Note that the first exercise should receive the number 1.2 (instead of 1.1) because it is the second environment in that chapter.
(Remark: I've also tried to do this via callout blocks as provided through quarto, see Is it possible in quarto to create custom cross-references to callout blocks?.)

A: Assuming that, you are trying to do this for an HTML book (since you have said online book), we can hack a way to do this using javascript.
At first, we use the example environment #exm in the case of exercises too and also add an additional class name, say .custom like this,
intro.qmd

# Introduction

The first example is @exm-1.

::: {#exm-1}
This should be Example 1.1.
:::

It is followed by the first exercise, [Exercise @exm-2]

::: {#exm-2 .custom}
This should be Exercise 1.2.
:::

It is followed by the first exercise, [Exercise @exm-3]

::: {#exm-3 .custom}
This should be Exercise 1.3.
:::

Note Two things here,

*

*I have used custom reference syntax [Exercise @exm-2] to refer to those exercises, so that they will render as Exercise 1.2 instead of Example 1.2.

*Added a class .custom to those example environments which I want to render as Exercise but with the consecutive (shared) counter.
Now since we have used example environments for those with .custom class too, quarto will render those as Example 1.2, Example 1.3, but we need them as Exercise 1.2, Exercise 1.3. So to get them Exercise, we will use javascript on the elements of .custom to simply replace the word Example with Exercise and the counter will remain consecutive since under the hood they are actually example environments.
Therefore, we create an HTML file, say custom.html, and put the necessary javascript code wrapped with script tag into that file,
custom.html

<script>
var custom_title = document.querySelectorAll('.custom .theorem-title');

for (let i = 0; i < custom_title.length; i++ ) {
   var mod_name = custom_title[i].innerHTML;
   custom_title[i].innerHTML = mod_name.replace("Example", "Exercise");
};
</script>

Then simply add this html file with include-after-body option in _quarto.yaml
_quarto.yaml

project:
  type: book

book:
  title: "test_book"
  author: "Jane Doe"
  date: "8/7/2022"
  chapters:
    - index.qmd
    - intro.qmd

format:
  html:
    include-after-body: custom.html
    theme: cosmo

Then if we render the book, this rendered output will look like this,


text:
Q: Angular ng serve working fine on localhost but code built using ng build runs slow We have an Angular app that runs fine when running on localhost. We use the following command -
ng serve  --disable-host-check --port 8000 --deploy-url /console/ --base-href /console/

Even on adding the --prod flag it works fine.
But when the same app is built using
ng build --prod  --deploy-url /console/

and deployed to a prod server, we are observing some delay while the user is typing something. This is a memory leak issue, probably because we are incorrectly using RxJs/subscription at some place. But the thing I am confused with is why are we not seeing this same issue on localhost. Because of this, it is taking a long time to debug the issue. Every time I need to build the code and deploy to a server to test the performance.
angular.json
{
  "projects": {
    "ClappiaUI": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "style": "sass"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ClappiaUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [

            ],
            "styles": [
              "..."
            ],
            "scripts": [
              "..."
            ],
            "es5BrowserSupport": true
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true

            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ClappiaUI:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ClappiaUI:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ClappiaUI:build"
          }
        }
      }
    }
  }
}

tsconfig.json
{
    "compileOnSave": false,
    "compilerOptions": {
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "module": "es2015",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "importHelpers": true,
        "target": "es5",
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2018", "dom"],
        "skipLibCheck": true
    }
}

A: Use the command like this:
ng build --source-map=false

Source map is intended only for debugging. Hope it would help!


text: Q: How can I clear just enabled fields from FormPanel? I have a form panel (GXT from Sencha) with 3 fields. One of them is disabled. I want to implement clear button which will clear just enabled fields and will leave the value of disabled field. How can I do this?


text:
Q: Sorting JSON data in Ruby I have following JSON structure:
 {
  "name": "MessageEnvelope",
  "type": "record",
  "fields": [
   {
      "name": "message",
      "type":
        {
          "name": "Message",
          "type": "record",
           "fields": [
             ....
            ]
        }
   },
   {
      "name": "pipeline_system",
      "type": {
                 "type": "enum",
                 "name": "PipelineSystem",
                 "symbols": [ "enterprise", "backscoring", "compliance" ]
              }
    },
    {
      "name": "batch_id",
      "type": [ "null", "string" ]
    }
 ]
}

I am looking to sort the above JSON file as best as it could be. For example:
fields : [
  {
      "name": "batch_id",
      "type": [ "null", "string" ]
    },
  ...
  ...
  {
      "name": "pipeline_system",
      "type": {
                 "type": "enum",
                 "name": "PipelineSystem",
                 "symbols": [ "backscoring",  "compliance", "enterprise" ]
              }
    }

Like it sorts the internal arrays as well as hashes. I am trying to write following:
def sort(collection)
   if collection.is_a?(Hash)
    puts "Hash Object...."
    if(collection["type"]=="record")
      puts "record found...     Type = #{collection["fields"].class}";
      if collection["fields"].is_a?(Array)
        puts "fields type is array...."           #we can sort fields arrays on the basis of name
        collection["fields"].sort_by{|arrayCollectionElement| arrayCollectionElement["name"] }
        arrayCollection = collection["fields"]    #this is array of hash...we can sort them on the basis of name..done above in sort by...
        puts "class  = #{arrayCollection.class}"
        puts "sorted fields:  #{arrayCollection}"
      end
    end   #else it is again a hash
  end
  collection
end

but it is not sorting the fields array on the basis of names.
Appreciate any possible help!

A: If I properly understood the requirements:
json = '...'

require 'json'
hash = JSON.parse json

# ⇓ let's sort the array of fields inplace
hash['fields'].sort_by! { |o| o['name'] }

hash
#⇒ {
#  "fields" => [
#    [0] {
#      "name" => "batch_id",
#      "type" => [ "null", "string" ]
#    },
#    [1] {
#      "name" => "message",
#      "type" => {
#        "fields" => [],
#          "name" => "Message",
#          "type" => "record"
#      }
#    },
#    [2] {
#      "name" => "pipeline_system",
#      "type" => {
#           "name" => "PipelineSystem",
#        "symbols" => [ "enterprise", "backscoring", "compliance" ],
#           "type" => "enum"
#      }
#    }
#  ],
#    "name" => "MessageEnvelope",
#    "type" => "record"
# }

To sort all arrays inside, one might introduce a recursive function:
def sort_arrays hash
  hash.each do |_, v|
    case v
    when Array then v.sort!
    when Hash then sort_arrays v
    end
  end
end

and call it on the topmost hash.


text:
Q: calculating time difference from database i have a table hsave_work_duration
`id_login`   `id_agent`   `agent_name`   `sys_time`              `status`

28               2         hsaveadmin     2014-05-26 12:13:12     Login

28               2         hsaveadmin     2014-05-26 12:19:12     Logout

i want to calculate the timedifference between a login and logout of a user?

A: You can do it with an INNER JOIN on the same table in combination with the TIMESTAMPDIFF function.
SELECT TIMESTAMPDIFF(MINUTE,s1.sys_time,s2.sys_time) AS timediff
FROM hsave_work_duration AS s1
INNER JOIN hsave_work_duration AS s2
ON
    s1.id_login = s2.id_login AND
    s1.id_agent = s2.id_agent
WHERE agent_name = 'hsaveadmin';

If you have more than these 2 status, than add the following to the WHERE clause:
AND s1.status = 'Login'
AND s2.status = 'Logout'

If you want the timediff not in minutes have a look at this section in the MySQL Reference and change the first parameter in the TIMESTAMPDIFF function.
This can be executed with PHP (i.e. with the mysqli connector):
$mysqli = new mysqli("localhost", "user", "password", "database");
$query = <the sql stmt>;
if ($result = $mysqli->query($query)) {
    $row = $result->fetch_assoc();
    print($row["timediff"]);
}

For further information about the SQL have a look at: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff


text:
Q: How do I get an ethernet connection with Automotive Grade Linux (Halibut 8.0.0)? I'm trying to get a basic ethernet connection with Halibut 8.0.0
sa8155:~# ifconfig eth0 up
sa8155:~# udhcpc
udhcpc: started, v1.29.3
udhcpc: sending discover
udhcpc: sending select for 10.0.0.112
udhcpc: lease of 10.0.0.112 obtained, lease time 604800
/etc/udhcpc.d/50default: Adding DNS 75.75.75.75
/etc/udhcpc.d/50default: Adding DNS 75.75.76.76

It seems to get an ip address assigned via DHCP,
and the DNS address is comcast so it does appear to be hitting my comcast router
sa8155:~# ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:50:b6:e9:de:7a
          inet addr:10.0.0.112  Bcast:10.0.0.255  Mask:255.255.255.0
          inet6 addr: 2601:647:4201:a2b0:250:b6ff:fee9:de7a/64 Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:128 errors:0 dropped:0 overruns:0 frame:0
          TX packets:140 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:22180 (21.6 KiB)  TX bytes:25954 (25.3 KiB)

but I cannot ping other computers on my network
sa8155:~# ping 10.0.0.196
PING 10.0.0.196 (10.0.0.196): 56 data bytes
ping: sendto: Network is unreachable
sa8155:~#

nor can other computers on my network ping 10.0.0.112
    >ping 10.0.0.112
PING 10.0.0.112 (10.0.0.112): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
Request timeout for icmp_seq 3
Request timeout for icmp_seq 4

and my router has no record of device sa8155, so I'm skeptical that DHCP is actually working.
Here's what I see in /etc/resolv.conf:
sa8155:~# cat /etc/resolv.conf
# Generated by Connection Manager
sa8155:~#

It seems that the Connection Manager, known as connman, is controlled via connmanctl.
According to the AGL documentation https://wiki.automotivelinux.org/connman:

But "connmanctl services" returns an empty list for me:
sa8155:~# connmanctl services

sa8155:~# connmanctl technologies
/net/connman/technology/ethernet
  Name = Wired
  Type = ethernet
  Powered = True
  Connected = False
  Tethering = False
sa8155:~#

According to this cheatsheet, the list should look something like this:

I'm not sure how to resolve this.

A: In a default installation, ConnMan will connect to a wired ethernet connection without any additional setup or interaction. It monitors kernel network interface events and brings the interface up automatically, including setting a default gateway and default routes. It also has built into it a dhcp client and dns forwarder. Having said that, it all depends on how AGL Halibut has compiled/configured it. Unfortunately, I am not familiar with that distribution.
For your reference, typically, an installation of ConnMan includes a symlink from /etc/resolv.conf to /var/run/connman/resolv.conf. The contents of the file is
# Generated by Connection Manager
nameserver 127.0.0.1

You can find the status of your network interfaces using the ip address command.
It may also be useful to look in the logs generated by ConnMan. You may want to stop connman (depends on the init system, or just kill the connmand process). Then run it from the command line to see what is happening.


text: Q: How to message and not push notify to a specific user with expo react native??I want to tell user that he is verified by not notifying but update app? I have a react native code which generates a device token and forwards it to server and the server then pushes notification to specific user. But rather than using push notification I just want to update user in the app by simple message containing data.


text:
Q: iOS: How to get pngs with transparency when read from disk I am saving png image to disk as NSData (for caching), when read gives Black color in place of transparent pixels. How to fix that??
this what I am using for saving to disk:
-(void)cacheImage:(UIImage *)image forURL:(NSURL *)url {
NSURL *cacheFileURL = [[self asyncableCachesDirectory] URLByAppendingPathComponent:[[url absoluteString] MD5]];

NSData *imageData = nil;

switch ([self imageTypeForJTDynamicImageURL:url]) {
    case AsyncableImageTypeJPEG:
        imageData = UIImageJPEGRepresentation(image, 1);
        break;
    case AsyncableImageTypePNG:
        imageData = UIImagePNGRepresentation(image);
        break;
    default:
        break;
}

NSError *error = nil;

[imageData writeToURL:cacheFileURL options:0 error:&error];

}
and this is what I am using for reading image:
-(UIImage *)imageFromCacheForURL:(NSURL *)url {
UIImage *image;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *urlHash;
NSURL *cacheFileURL;

image = [self.images objectForKey:[url absoluteString]];

// if we already have the full size image in memory just return it.
if (image) {
    debug(@"---Asyncable returning full size image from memory for url: %@", url);
    return image;
}

// check disk for full size image
urlHash = [[url absoluteString] MD5];
cacheFileURL = [[self asyncableCachesDirectory] URLByAppendingPathComponent:urlHash];

image = [UIImage imageWithData:[fileManager contentsAtPath:[cacheFileURL path]]];

if (image) {
    [self.images setObject:images forKey:url];
    debug(@"---Asyncable returning full size image from disk for url: %@", url);

    return image;
}

}

A: imageData = UIImagePNGRepresentation(image);

If used in both the cases what happens?


text:
Q: How to efficiently insert ENUM value into table? Consider the following schema:
CREATE TABLE IF NOT EXISTS snippet_types (
  id INTEGER NOT NULL PRIMARY KEY,
  name TEXT NOT NULL UNIQUE
);

CREATE TABLE IF NOT EXISTS snippets (
  id INTEGER NOT NULL PRIMARY KEY,
  title TEXT,
  content TEXT,
  type INTEGER NOT NULL,
  FOREIGN KEY(type) REFERENCES snippet_types(id)
);

This schema assumes a one-to-many relationship between tables and allows efficiently maintaining a set of ENUMs in the snippet_types table. Efficiency comes from the fact that we don't need to store the whole string describing snippet type in the snippets table, but this decision also leads us to some inconvenience: upon inserting we need to retrieve snippet id from snippet_types and this leads to one more select and check before inserting:
SELECT id FROM snippet_types WHERE name = "foo";
-- ...check that > 0 rows returned...
INSERT INTO snippets (title, content, type) values ("bar", "buz", id);

We could also combine this insert and select into one select like that:
INSERT INTO snippets (title, content, type)
SELECT ("bar", "buz", id) FROM snippet_types WHERE name = "foo"

However, if "foo" type is missing in snippet_types then 0 rows would have been inserted and no error returned and I don't see a possibility to get a number of rows sqlite actually inserted.
How can I insert ENUM-containing tuple in one query?


text:
Q: How to download multiple numbered images from a website in an easy manner? I'd like to download multiple numbered images from a website.
The images are structured like this:
http://website.com/images/foo1bar.jpg

http://website.com/images/foo2bar.jpg

http://website.com/images/foo3bar.jpg

... And I'd like to download all of the images within a specific interval.
Are there simple browser addons that could do this, or should I use "wget" or the like?
Thank you for your time.

A: Crudely, on Unix-like systems:
#!/bin/sh
for i in {1..3}
do
    wget http://website.com/images/foo"$i"bar.jpg
done

Try googling "bash for loop".
Edit LOL! Indeed, in a haste I omitted the name of the very program that downloads the image files. Also, this goes into a text editor, then you save it with an arbitrary file name, make it executable with the command
chmod u+x the_file_name

and finally you run it with
./the_file_name


text:
Q: generating dynamic Twiml response and save on Nodejs server So i am following a tutorial to create the XML doc for twilio like as a response,
(https://www.twilio.com/blog/2013/03/introducing-the-twilio-module-for-node-js.html)
but rather than sending it as a response, I want to generate the file on my server to access later.
something like -  localhost/files/USERNAME/FILENAME.xml
this is my current code that sends the file as a response.

  var resp = new twilio.TwimlResponse();

  resp.say({voice:'woman'}, 'Thanks for calling!');

  //Render the TwiML document using "toString"
  res.writeHead(200, {
      'Content-Type':'text/xml'
  });

  res.end(resp.toString());

A: You can save the response from Twillio to your localhost by using the fs library built into node.  Specifically:
https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
Once you have your .xml file saving to localhost, you can use an express route with res.sendFile() that sends back the .xml file.
https://expressjs.com/en/api.html#res.sendFile

A: Twilio developer evangelist here.
As tomato points out, you can use the build in fs library from Node. You could do that like below:
var resp = new twilio.TwimlResponse();

resp.say({voice:'woman'}, 'Thanks for calling!');

//Render the TwiML document using "toString"
res.writeHead(200, {
    'Content-Type':'text/xml'
});

// Save the XML to disk, then return the response to Twilio.
fs.writeFile('twilio-response.xml', resp.toString(), function(err) {
  res.end(resp.toString());
});

You may want to generate a unique file name for each response so that they don't get written over.
Just in case this helps, Twilio does save the TwiML responses that you send back and you can retrieve these in your call log.


text:
Q: SQL Percentage Complete with COUNT and Remaining Percentage Quite difficult to explain in the title so here is my scenario:
Let's say I have a value of £10,000, this is going to be paid in random instalments (up to 100%). The cumulative total is stored in a field called PercentageComplete.

Payment 1 is £5,000 (PercentageComplete = 50% of total amount owed)
Payment 2 is £2,500 (PercentageComplete = 75% of total amount owed)

So far the way I'm trying to work this out is by adding (0.5 + 0.75) which gives me a total of 1.25 ... and using the COUNT function I'm dividing this by 2 (which gives the incorrect answer of 0.625).
I'm probably over complicating this issue so thanks for any help.
The code I tried:
select FinanceID, CustomerID sum(PercentageComplete), COUNT(PercentageComplete)
from Finances group by FinanceID, CustomerID

A: I think you just want max():
select FinanceID, CustomerID max(PercentageComplete)
from Finances
group by FinanceID, CustomerID ;


text:
Q: Flutter - list duplicates old and new values I have a method for receiving push from Firebase Cloud Messaging, and within it, the notification is allocated within a list. What happens is that this method is making the old value a duplicate of the new value.

Firebase method:
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
  if (message.notification != null) {

      widget._localNotificationList.title = message.notification.title;
      widget._localNotificationList.body = message.notification.body;

      widget._pushDecode.notifList.add(widget._localNotificationList);

      savePush(); //this method maintains notification on the user's screen, with sharedPreferences
    setState(() {});
  }
});

Page View:
ListView.builder(
              itemCount: widget._pushDecode.notifList.length,
              itemBuilder: (context, i) {
                return Card(
                  margin: EdgeInsets.all(10),
                  elevation: 4,
                  child: ListTile(
                    trailing: IconButton(
                      icon: Icon(Icons.delete),
                      onPressed: () => removePush(i),
                    ),
                    title: Text(
                      widget._pushDecode.notifList.reversed.elementAt(i).title,
                    ),
                    subtitle: Text(
                      widget._pushDecode.notifList.reversed.elementAt(i).body,
                    ),
                  ),
                );
              },
            ),

A: You need to use the key value because it does not know if the widget that was in the position you are adding it for example is different then the previous, but using keys he can always know that two widgets are different when they are the same type like your card.
ListView.builder(
              itemCount: widget._pushDecode.notifList.length,
              itemBuilder: (context, i) {
                return Card(
                  key: UniqueKey(), // you can also use ValueKey('this must be unique for each element in the list.')
                  margin: EdgeInsets.all(10),
                  elevation: 4,
                  child: ListTile(
                    trailing: IconButton(
                      icon: Icon(Icons.delete),
                      onPressed: () => removePush(i),
                    ),
                    title: Text(
                      widget._pushDecode.notifList.reversed.elementAt(i).title,
                    ),
                    subtitle: Text(
                      widget._pushDecode.notifList.reversed.elementAt(i).body,
                    ),
                  ),
                );
              },
            ),


text:
Q: CMake configuration for multiple test files I'm running into following error. Basically I've two test .c files, how can I've them run both independently? Each one having it's own main function?

duplicate symbol _main in:
CMakeFiles/Tests.dir/test.c.o
CMakeFiles/Tests.dir/test2.c.o

Root CMakeLists.txt
cmake_minimum_required(VERSION 3.9)
project(Polymorphism)

set(CMAKE_C_STANDARD 99)

add_subdirectory(src)
add_subdirectory(test)

src/CMakeLists.txt
add_library(Polymorphism person.c employee.c)
target_include_directories(Polymorphism PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

test/CMakeLists.txt
add_executable(Tests test.c test2.c)
target_link_libraries(Tests Polymorphism)

test/test.c
void main() {
    // some tests
}

test/test2.c
void main() {
   // some tests
}

A: This is actually quite simple to solve. CMake allows you to create multiple executables (These can have their own main function) and also contains a function add_test used to bind these to tests.
So, given that you have files test.c and test2.c, each with their own main function:
add_executable(test1 test.c)
add_executable(test2 test2.c)

add_test(NAME t1 COMMAND test1)
add_test(NAME t2 COMMAND test2)

Now, you can run the commands make test or ctest, which will register two separate tests and run them as such.


text:
Q: Laravel Nova 3 - Queued Actions - Can I skip model? I'm using Laravel Nova 3 Queued Actions.
I have over 25K records in my table.
I want to Laravel Nova Action create new job only if model has attribute status == 1.
I tried to use continue in foreach loop but it does'nt work.
<?php

namespace App\Nova\Actions;

use App\Http\Services\UserService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;

class UserSynchronization extends Action implements ShouldQueue
{
   use InteractsWithQueue, Queueable;

   public $name = 'Synchronize User';
   public static $chunkCount = 1;
   public $withoutActionEvents = true;

   public function __construct()
   {
      $this->connection = 'database';
      //$this->queue = 'default';
   }

   /**
    * Perform the action on the given models.
    *
    * @param \Laravel\Nova\Fields\ActionFields $fields
    * @param \Illuminate\Support\Collection $models
    * @return mixed
    */
   public function handle(ActionFields $fields, Collection $models)
   {
      foreach ($models as $model) {
         if (!$model->status !== 1) {
            continue;
         }

         UserService::synchronize($model);
      }

      return Action::message('Users have been successfully synchronized');
   }

   /**
    * Get the fields available on the action.
    *
    * @return array
    */
   public function fields()
   {
      return [];
   }
}

Create record in jobs table only if model->status === 1


text:
Q: How to pass ID from React component to ASP.NET controller? I am building test CRUD application with React, ASP.NET and EF.
Right now I have a problem with sending productID to be deleted by the asp.net  controller from the server..
I want to send projectID from handleDeleteProduct. Right now productID argument in controller is getting no value. I am guessing that there is something wrong in ProductBox
ProductList.js:
import React, { Component } from 'react';
import $ from 'jquery';
import uuid from 'uuid';
import Product from '../components/Product';

class ProductList extends React.Component {
    deleteProduct(productID) {
        this.props.onDelete(productID);
    }
    render() {
        let productNodes;
        if (this.props.data) {
            productNodes = (this.props.data || []).map(product => {
            return (
                <Product onDelete={this.deleteProduct.bind(this)} name={product.name} key={product.productID}>
                    {product.description} ,
                    {product.price}
                </Product>
            );
        });
    }
        return (

                {productNodes}

        );
    }
}
export default ProductList;

My ProductBox.js looks like this:
import React, { Component } from 'react';
import $ from 'jquery';
import uuid from 'uuid';
import ProductList from '../components/ProductList';
import ProductForm from '../components/ProductForm';

class ProductBox extends React.Component {
    constructor(props) {
        super(props);
        this.state = { data: this.props.initialData };
        this.handleProductSubmit = this.handleProductSubmit.bind(this);
        this.handleDeleteProduct = this.handleDeleteProduct.bind(this);
    }
    loadProductsFromServer() {
        const xhr = new XMLHttpRequest();
        xhr.open('get', this.props.url, true);
        xhr.onload = () => {
            const data = JSON.parse(xhr.responseText);
            this.setState({ data: data });
        };
        xhr.send();
    }
    handleProductSubmit(product) {
        const products = this.state.data;
        product.productID = products.length + 1;
        const newProducts = products.concat([product]);
        this.setState({ data: newProducts });

        const data = new FormData();
        data.append('Name', product.Name);
        data.append('Description', product.Description);

        const xhr = new XMLHttpRequest();
        xhr.open('post', this.props.submitUrl, true);
        xhr.onload = () => this.loadProductsFromServer();
        xhr.send(data);
    }
    handleDeleteProduct(projectID) {
        const data = projectID;
        const xhr = new XMLHttpRequest();
        xhr.open('post', this.props.deleteUrl, true);
        xhr.onload = () => this.loadProductsFromServer();
        xhr.send(data);
    }
    componentDidMount() {
        window.setInterval(() => this.loadProductsFromServer(), this.props.pollInterval);
    }
    render() {
        return (

Tutaj React z EF

                <ProductForm onProductSubmit={this.handleProductSubmit} />
                <ProductList onDelete={this.handleDeleteProduct.bind(this)} data={this.state.data} />

        );
    }
}

export default ProductBox;

piece of code from app.js :
<ProductBox url="/comments" submitUrl="/comments/new" deleteUrl="/comments/delete" pollInterval={2000}/>

HomeController.cs
[Route("comments/delete")]
        [HttpPost]
        public ActionResult DeleteComment(int productID)
        {
            var products = _context.Products;
            foreach(var item in products)
            {
                if(item.ProductID == productID)
                {
                    products.Remove(item);
                    _context.SaveChanges();
                }
            }

            return Content("Success :)");
        }

A: You first problem is you are not passing the productId to parent controller. Here is how you need to do it.
<Product onDelete={(e)=>this.deleteProduct(product.productID)}

Second, make sure in parent method handleDeleteProduct you are getting this productId Passed
Third, check for the xhr request is correct. Here is an example of it
handleDeleteProduct(projectID) {

    var xhr = new XMLHttpRequest();
    xhr.open("POST", this.props.deleteUrl, true);

    //Send the proper header information along with the request
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function () {//Call a function when the state changes.
        if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
            // Request finished. Do processing here.
        }
    }
    xhr.send("productID=" + projectID);
}

A: Ok, after a few hours of flatting my butt when trying to figure it out i found a solution. I used Ajax with jQuery:
handleDeleteProject(projectID) {
        $.ajax({
            url: './comments/delete',
            data: { productID: projectID },
            type: 'get',
            cache: true,
            success: function (response) {
                console.log("ok");
            },
        });
    }

I start to think, that XMLHttpRequest is kind a crap.Thank you @Justcode for your time and effort.


text:
Q: Remove line between buttons HTML I'm doing an html project that requires me to have buttons as links, but as I did it, It had this hyperlink line in between. I'm not allowed to use css for this certain project, how do I fix it just by using html?

        <button>First</button>

        <button>Second</button>

        <button>Third</button>

        <button>Fourth</button>

A: You can't change styling with only HTML, but you can add styles with the style attribute:

        <button>First</button>

        <button>Second</button>

        <button>Third</button>

        <button>Fourth</button>

Third button has no underline.

A: You are using button inside anchor tag. This cause an underline below the button (if you have only 1 button, you cannot see it). You should use  inside <button>, like this:
<button>
    First
</button>
...

This may cause text inside button have underline. We can remove this with CSS by text-decoration.


text:
Q: App crashes on devices with removable sd card when it is not inserted my application stores files received from other devices in the external storage. It works fine with devices with non removable sd cards
The issue is on galaxy tab4 when the external sd card is not inserted.
I am using the following line to get file path
String filePath=Environment.getExternalStorageDirectory()+"/BFT/";

What I want to do is if the external sd card is removable and not inserted I want to create the above mentioned directory in the device storage (Like 16 GB is provided in Galaxy s4).

I am confused because in galaxy s4 it is working fine but it is stored in this directory when using Environment.getExternalStorageDirectory()+"/BFT/"
This is where it is stored on S4
How to make it work on tab4 or any other device which may crash when external sd card is removable and not inserted and I used the above line.

I just want a folder to be created on the device no matter what its storage architecture is. Specific code is appreciated or at least what is causing the error(I know directory is not found.But Why?).

A: You need to get the state of the External Storage Directory before using it
getExternalStorageState()
Returns the current state of the primary shared/external storage media.
Returns
one of MEDIA_UNKNOWN, MEDIA_REMOVED, MEDIA_UNMOUNTED, MEDIA_CHECKING, MEDIA_NOFS, MEDIA_MOUNTED, MEDIA_MOUNTED_READ_ONLY, MEDIA_SHARED, MEDIA_BAD_REMOVAL, or MEDIA_UNMOUNTABLE.

Also ExternalStorage doesn't always mean External

Note: don't be confused by the word "external" here. This directory
  can better be thought as media/shared storage. It is a filesystem that
  can hold a relatively large amount of data and that is shared across
  all applications (does not enforce permissions). Traditionally this is
  an SD card, but it may also be implemented as built-in storage in a
  device that is distinct from the protected internal storage and can be
  mounted as a filesystem on a computer.

For more information on External Storage

A: Turns out the Environment.getExternalDirectory() returns removable sd card path on some devices while on others it displays the device storage (Both are external storages not internal).
To display the list of mounted external storage I used getStorageList() of this class and then selecting one external storage which was available.
public class StorageUtils {

private static final String TAG = "StorageUtils";

public static class StorageInfo {

    public final String path;
    public final boolean readonly;
    public final boolean removable;
    public final int number;

    StorageInfo(String path, boolean readonly, boolean removable, int number) {
        this.path = path;
        this.readonly = readonly;
        this.removable = removable;
        this.number = number;
    }

    public String getDisplayName() {
        StringBuilder res = new StringBuilder();
        if (!removable) {
            res.append("Internal SD card");
        } else if (number > 1) {
            res.append("SD card " + number);
        } else {
            res.append("SD card");
        }
        if (readonly) {
            res.append(" (Read only)");
        }
        return res.toString();
    }
}

public static List<StorageInfo> getStorageList() {

    List<StorageInfo> list = new ArrayList<StorageInfo>();
    String def_path = Environment.getExternalStorageDirectory().getPath();
    boolean def_path_removable = Environment.isExternalStorageRemovable();
    String def_path_state = Environment.getExternalStorageState();
    boolean def_path_available = def_path_state.equals(Environment.MEDIA_MOUNTED)
                                || def_path_state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
    boolean def_path_readonly = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);

    HashSet<String> paths = new HashSet<String>();
    int cur_removable_number = 1;

    if (def_path_available) {
        paths.add(def_path);
        list.add(0, new StorageInfo(def_path, def_path_readonly, def_path_removable, def_path_removable ? cur_removable_number++ : -1));
    }

    BufferedReader buf_reader = null;
    try {
        buf_reader = new BufferedReader(new FileReader("/proc/mounts"));
        String line;
        Log.d(TAG, "/proc/mounts");
        while ((line = buf_reader.readLine()) != null) {
            Log.d(TAG, line);
            if (line.contains("vfat") || line.contains("/mnt")) {
                StringTokenizer tokens = new StringTokenizer(line, " ");
                String unused = tokens.nextToken(); //device
                String mount_point = tokens.nextToken(); //mount point
                if (paths.contains(mount_point)) {
                    continue;
                }
                unused = tokens.nextToken(); //file system
                List<String> flags = Arrays.asList(tokens.nextToken().split(",")); //flags
                boolean readonly = flags.contains("ro");

                if (line.contains("/dev/block/vold")) {
                    if (!line.contains("/mnt/secure")
                        && !line.contains("/mnt/asec")
                        && !line.contains("/mnt/obb")
                        && !line.contains("/dev/mapper")
                        && !line.contains("tmpfs")) {
                        paths.add(mount_point);
                        list.add(new StorageInfo(mount_point, readonly, true, cur_removable_number++));
                    }
                }
            }
        }

    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (buf_reader != null) {
            try {
                buf_reader.close();
            } catch (IOException ex) {}
        }
    }
    return list;
}
}

This issue is faced when dealing with newer devices with more than one mount points for external storage like galaxy series of Samsung.


text:
Q: PHP and mySQL getting a image root folder I am using DELIMETER in PHP to call in a row from a table but i need to call in a image from a row in the table and the image folder. How do i do this?
Current code is below. How do i add in the folder location that is holding my images (folder name is image and is in the same folder as this code)
while ($row = fetch_array($query)) {
        $product = <<<DELIMETER


text:
Q: Why does overriding a method and adding const to a parameter type work? Consider the following example:
#include <iostream>
#include <string>

class Base {
public:
    virtual void func(int a) {}
};

class Derived : public Base {
    public:
    void func( const int a) override {
    }
};

int main()
{
    Derived d;
    d.func(1);

    return 1;
}

I override the func method but add const to the parameter, in which case the linker should scream that something is wrong. Either the function is not overridden or the function parameter should not be const.
But to my surprise, this code links and works.
You can find an online example here.
Am I missing something? Why does this code work?
Although similar to Functions with const arguments and Overloading it addresses a different problem. That question was about not being possible to overload a method of the base class, while this question addresses the problem of being able to override a derived method.

A: Because their signatures are the same in fact.

The type of each function parameter in the parameter list is determined according to the following rules:
...
4) Top-level cv-qualifiers are dropped from the parameter type (This adjustment only affects the function type, but doesn't modify the property of the parameter: int f(const int p, decltype(p)*); and int f(int, const int*); declare the same function)

That means, void func(int a) and void func(const int a) are considered as the same function type; then the overriding is valid.


text:
Q: change the background colour of a div based on the text of another using jQuery and CSS I would like to change the background colour of a div based on the text of another div using jQuery and CSS.
my HTML looks like this

Darkpsyde

06/05/14 | Transcendent Tuesdays

Drum and Bass

I would like to change the background-colour of the "livenow-channelcolour" div to a set colour based on the text in the div directly below it called "livenow-channel"
I had someone help me with something similar before and I tried to change the code to achieve this but its not working. The code I am using is the following however happy to use something completely different if it works.
 $(".live-content").each(function() {

    var $el = $(this);
    var color;
    var content = $el.text().toLowerCase();

    if (content.indexOf("drum and bass") !== -1) {
        color = "#39d52d";
    }
    else if (content.indexOf("house") !== -1) {
        color = "#6dc8bf";
    }

    if (color) {
            $el.closest('div')
            .find('.livenow-channelcolour')
            .css("background-colour", color);
        }
});

Any help with this simple but frustrating issue is very much appreciated.
Many thanks.

A: i tried it in fiddle with backgound property of css and its working:
 $el.closest('div')
        .find('.livenow-channelcolour')
        .css("background", color);

Code:
$(".live-content").each(function() {

var $el = $(this);
var color;
var content = $el.text().toLowerCase();

if (content.indexOf("drum and bass") != -1) {
    color = "#39d52d";
}
else if (content.indexOf("house") != -1) {
    color = "#6dc8bf";
}

if (color) {
        console.log("if");
        $el.closest('div')
        .find('.livenow-channelcolour')
        .css("background", color);
    }

});

Fiddle DEMO

A: here is a go at it
http://jsfiddle.net/Icepickle/uJwE6/
$(function() {
    var text = $('.live-content>.livenow-channel').text().toLowerCase(), color;
    switch (text) {
     case 'drum and bass':
        color = '#39d52d';
        break;
     case 'house':
        color = '#6dc8bf';
        break;
     default:
        color = 'transparent';
    }
    $('.live-content>.livenow-channelcolour').css('background', color).text(color);
});


text:
Q: Twilio call hold is not working as expected I am using Twilio to call my customers from my Twilio client and want to put the user on hold whenever is needed. For that i am calling RESTAPI whenever user clicks on the "Hold" Button.
But after calling the method call is getting disconnected for My Twilio client and playing Hold sound for my customer. Can you please suggest something for this. Both the below approaches are not working
   var response = new VoiceResponse();
        var dial = new Dial();
        dial.Conference("Customer Waiting Room", beep: Conference.BeepEnum.False);
        response.Append(dial);
        var call = Twilio.Rest.Api.V2010.Account.CallResource.Read(parentCallSid: callSid).ToList();
        Twilio.Rest.Api.V2010.Account.CallResource.Update(new Twilio.Rest.Api.V2010.Account.UpdateCallOptions(call[0].Sid) { Twiml = response.ToString() });
        return Content(response.ToString(), "application/xml");

Alternative:
 var response = new VoiceResponse();
                response.Say("You have a caller on hold.");
                var call = Twilio.Rest.Api.V2010.Account.CallResource.Read(parentCallSid: callSid).ToList();
                response.Enqueue("admin");
                Twilio.Rest.Api.V2010.Account.CallResource.Update(new Twilio.Rest.Api.V2010.Account.UpdateCallOptions(call[0].ParentCallSid) { Twiml = response.ToString() });

A: Twilio developer evangelist here.
You have a direct call setup between your agent and you customer. When you move your customer call away from that, then your agent call will move on to the next TwiML instruction. If there are no further TwiML instructions available for your agent, then they will get disconnected.
To overcome this, you need to consider what you want your agent to do while your customer is on hold. It might be better, for example, to have your call take place in a conference. That way, when you put your customer on hold, the agent can remain in the conference.
Otherwise, you should provide further TwiML instructions after your agent's <Dial> so that they continue the call after the customer leg goes away.


text:
Q: mongodb group by min I have a table:
id   value   date
1      1     2014-08-10 10:00:00
1      2     2014-08-10 10:05:00
1      1     2014-08-10 12:00:00
1      1     2014-08-11 12:05:00
1      2     2014-08-11 12:06:00
2      2     2014-08-10 10:00:00
2      2     2014-08-11 10:05:00
2      1     2014-08-11 12:00:00
2      1     2014-08-20 12:05:00
2      2     2014-08-20 12:06:00

and i want to get the total number of value for each id for the first day. I can do it in MySQL using the following command:
SELECT test.id, COUNT(CASE WHEN value=1 THEN 1 END) AS 'total_value_1',
                COUNT(CASE WHEN value=2 THEN 1 END) AS 'total_value_2'
FROM test,
(SELECT id, date(min(date)) as firstDay
 FROM test
 GROUP BY id) AS temp
WHERE  test.id = temp.id AND date(test.date) = temp.firstDay
GROUP BY test.id;

Result is:
id total_value_1 total_value_2
1         2           1
2         0           1

How can i do this in MongoDB?

A: This is possible through the aggregation framework where you use a collection of operators to define and manipulate documents in pipeline stages that will give you the desired results. Your first pipeline stage is the $project operator where you would transform your value fields for easier manipulation in the later pipeline stages. The equivalent SQL for this operation is:
SELECT id, date, CASE WHEN value=1 THEN 1 END AS 'value_1',
                 CASE WHEN value=2 THEN 1 END AS 'value_2'
FROM test

The next pipeline stages use $group and $project operators to calculate the minimum day of the month on the date field and the sum aggregates on the transformed value fields:
db.test.aggregate([
    {
        "$project": {
            "id": 1,
            "date": 1,
            "value_1": { "$cond": [{ "$eq": [ "$value", 1 ] }, 1, 0] },
            "value_2": { "$cond": [{ "$eq": [ "$value", 2 ] }, 1, 0] }
        }
    },
    {
        "$group": {
            "_id": {
                "id": "$id",
                "date": "$date"
            },
            "minimumDayofMonth": {
                "$min": { "$dayOfMonth": "$date"}
            },
            "total1" : {
                "$sum": "$value_1"
            },
            "total2" : {
                "$sum": "$value_2"
            }
        }
    },
    {
        "$group": {
            "_id": {
                "id": "$_id.id",
                "day": "$minimumDayofMonth"
            },
            "firstDay": { "$min": "$minimumDayofMonth"  },
            "total_value_1" : {
                "$sum": "$total1"
            },
            "total_value_2" : {
                "$sum": "$total2"
            }
        }
    },
    {
        "$group": {
            "_id": "$_id.id",
            "result": { "$first": "$$ROOT" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "id": "$_id",
            "total_value_1": "$result.total_value_1",
            "total_value_2": "$result.total_value_2"
        }
    }
])

Output:
/* 0 */
{
    "result" : [
        {
            "id" : 2,
            "total_value_1" : 0,
            "total_value_2" : 1
        },
        {
            "id" : 1,
            "total_value_1" : 2,
            "total_value_2" : 1
        }
    ],
    "ok" : 1
}