text:
Q: Toggling on click I have a situation in which I am using Bootstrap collapse to create growing and shrinking content.
I have a class called my-btn which has a background image of a downwards arrow. When I click on this button I want to add a class called open.

    .my-btn{
    background-image:url(../img/template-1/read-more-closed.png);
                background-repeat:no-repeat;
                background-position:center;
                width:50px;
                height:50px;
    margin-bottom:50px;
    }

    .open{
   background-image:url(../img/template-1/read-more-open.png);
                background-repeat:no-repeat;
                background-position:center;
                width:50px;
                height:50px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

 <button class="btn my-btn" type="button" data-toggle="collapse" data-target="#collapse4"
                  aria-expanded="false" aria-controls="collapseExample"> </button>

By adding the open class after my-btn, the arrow is changed... but how can I acheive this using CSS/js?
UPDATE
I have tried
 <script>

$(document).ready(function(){
$('.my-btn').on('click', function(){
    $(this).toggleClass('open');
});
});
          </script>

But on toggle, bootstrap adds the collaPSED CLASS BUT MY CODE IS IGNORED.

A: You can do something like this:

.my-btn{
background-image:url(../img/template-1/read-more-closed.png);
            background-repeat:no-repeat;
            background-position:center;
            width:50px;
            height:50px;
            margin-bottom:50px;
}

.open{
  background-image:url(../img/template-1/read-more-open.png);
            background-repeat:no-repeat;
            background-position:center;
            width:50px;
            height:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<button class="btn my-btn" type="button" data-toggle="collapse" data-target="#collapse4"
              aria-expanded="false" aria-controls="collapseExample" onclick="this.classList.toggle('open')"> </button>

The important part is onclick="this.classList.toggle('open')", this JavaScript code will toggle the "open" class (remove it if it exists or add it if it doesn't).
Keep in mind that the classList.toggle function is not supported by all browser. You may have to use some polyfill if you want to support all browsers.

A: You can quickly and easily achieve this using an on click function combined with a toggle class function for adding/removing classes after your button is clicked.
See below for working code.

$('.btn').on('click', function() {
    $(this).toggleClass('open');
});
.my-btn{
    background-image:url(../img/template-1/read-more-closed.png);
                background-repeat:no-repeat;
                background-position:center;
                width:50px;
                height:50px;
    margin-bottom:50px;
    }

    .open{
   background-image:url(../img/template-1/read-more-open.png);
                background-repeat:no-repeat;
                background-position:center;
                width:50px;
                height:50px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

 <button class="btn my-btn" type="button" data-toggle="collapse" data-target="#collapse4"
                  aria-expanded="false" aria-controls="collapseExample"> </button>

A: You can use the toggleClass() function:
$('.my-btn').on('click', function() {
    $(this).toggleClass('open');
});


text:
Q: What is causing my loop to ignore this "\t" only in the first iteration? For some reason my loop only outputs the "\t" after the first iteration of my for-loop.
Here is my loop's code:
input = -1;
private String[] types = {"none", "vanilla", "hazelnut", "peppermint", "mocha", "caramel"};
while ( (input < 0) || (input > (types.length - 1)) ){ //gets user's latte flavor input
        System.out.println("Enter the number corresponding to the latte type you would like:");
        for ( int i = 0; i < types.length; i++ ){
            if ( i <= (types.length - 2) ){ //prints two options per line
                System.out.println(i + ": " + types[i] + "\t" + (i + 1) + ": " + types[i + 1]);
            }
            else if ( i == (types.length - 1) ){
                System.out.println(i + ": " + types[i]);
            }
            else{ //does nothing on odd indices
            }
            i++;
        }
        input = keyboard.nextInt();
    }

This outputs the following:
Enter the number corresponding to the latte type you would like:
0: none     1: vanilla
2: hazelnut     3: peppermint
4: mocha        5: caramel

As we can see, "1: vanilla" is not spaced in the same way the other rows are. My code for my Tea class, however, works properly:
input = -1;
private String[] types = {"white", "green", "oolong", "black", "pu-erh", "camomille"};
while ( (input < 0) || (input > (types.length - 1)) ){ //gets user's tea flavor input
        System.out.println("Enter the number corresponding to the tea type you would like:");
        for ( int i = 0; i < types.length; i++ ){
            if ( i <= (types.length - 2) ){ //prints two options per line
                System.out.println(i + ": " + types[i] + "\t" + (i + 1) + ": " + types[i + 1]);
            }
            else if ( i == (types.length - 1) ){
                System.out.println(i + ": " + types[i]);
            }
            else{ //does nothing on odd indices
            }
            i++;
        }
        input = keyboard.nextInt();
    }

And this outputs the following:
Enter the number corresponding to the tea type you would like:
0: white    1: green
2: oolong   3: black
4: pu-erh   5: camomille

What causes my Latte loop (my Espresso loop also suffers this spacing issue) to output differently than my Tea loop? Thanks for helping me understand this behavior!

A: Well the TAB is actually there. Note that 0: none is one character shorter than the other examples you have posted. So you tab to an earlier tab stop.

A: Since there is none yet, i'll provide a solution using printf. You could just use a formatter (like System.out.printf() to format the string):
System.out.printf("%d: %-12s%d:%-12s\n", i, types[i], i+1, types[i+1]);

*

*The %d allows you to input an Integer type.

*The %-12s allows you to input a String (minimum length is 12 left aligned)... this replaces your tabs!

A: none is a small word compared to the others. You could pad the words in the types array with spaces in the end to have the same length in order to solve this issue.

A: Tabs are tricky since they are affected by position on line, and tab width.
Better use padding by spaces. A convenient way using Apache Commons:
StringUtils.rightPad(types[i], COLUMN_WIDTH)

(adjust COLUMN_WIDTH based on your longest text)

A: Following is a fix with format
System.out.println(i + ": " + String.format("%-5s\t", types[i]) + (i + 1) + ": " + types[i + 1]);

This will fix the issue.

A: This is caused because of the length of the first String in your array. Try it with "nonee" instead of "none" and see.
If you want to do it properly you should use some sort of padding.

A: The tab exists as mentioned above. As to why things are not aligned. You can refer to this link

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to do an objective-c "toll free bridge" in delphi? How do I do an objective C toll free bridge in Delphi?
e.g. I have a CFDictionaryRef and I want to use it as an NSDictionary, do I just do a wrap to covert it from a CF* instance to an NS* instance?
I can convert from an NS to a CF by
var
  cfvariable CF*;
  nsvariable: NS*;
begin
  ...
  cfvariable :=  (nsvariable as ILocalObject).GetObjectID

But the other way seems to be causing me problems sometimes - i.e. sometimes it works sometimes it crashes. So wondering if I'm doing this the right way or the problem is somewhere else, e.g. for a CFDictionaryRef to an NSDictionary I do
var
  attr : CFDictionaryRef;
  nattr: NSDictionary;
begin
   ...
  attr := CFDictionaryCreate(...);

  nattr := TNSDictionary.Wrap(attr);

Is this the right way to do it?
(Delphi XE6 app on OSX)
Update: It does seem this is the right way to do it, the problem was elsewhere. I'll leave it up here in case any one else needs to know since its not documented well.


text:
Q: Angular - Ngx-mat-datetime-picker and TimeZone Im using angular datetimepicker https://h2qutc.github.io/angular-material-components/datetimepicker
In my application I have a switch to change the current Application TimeZone so every dates in site will be converted (from original UTC format).
For Example selecting America/New_York, every date will be printed like this: 2021-03-10 10:54:12 (-05:00)
DateTimePicker starts with a default Adapter related to Browser TimeZone.
I need a way to set a specific TimeZone after the switch select.
I have the name and the UTC offset.


text:
Q: problems with implementing deque with templates Recently I have tried to implement sequel using templates. Here is result
#pragma once
#include <iostream>
using namespace std;

template<typename Type>
struct Node {
    Node();
    Node<Type>* next = NULL;
    Node<Type>* prev = NULL;
    Type data;
};

template<typename Type>
class deque{
 private:
     Node<Type>* front = NULL;
     Node<Type>* back = NULL;

 public:
     deque(Type key);
     ~deque();
     Node<Type>* back();
     Node<Type>* front();
     int size();
     bool empty();
     void push_front(Type key);
     void push_back(Type key);
     void pop_front();
     void pop_back();
     void print_in_order();
};

 template<typename Type>
  deque<Type>::deque(Type key)
{
     if (front != NULL || back != NULL)
         return
     else
     {
         front = new Node<Type>();
         front->data = key;
         prev = front;
     }
}

 template<typename Type>
  deque<Type>::~deque()
{
     Node<Type>* delPtr;
     while (front->prev != NULL)
    {
         delPtr = front;
         cout << "Deleted " << front->data<<endl;
         front = front->prev;
         delete delPtr;

    }
     back = NULL;
     delete front;
}

 template<typename Type>
  Node<Type>* deque<Type>::back()
{
      if(back!= NULL)
         return back;
     else
          return NULL
}

 template<class Type>
  Node<Type>* deque<Type>::front()
{
     return front;
}

 template<typename Type>
  int deque<Type>::size()
{
     int counter = 0;
     Node<Type>* temp = front;
     while (temp->back != NULL)
    {
         counter++;
         temp = temp->back;
    }
     return counter;
}

 template<typename Type>
  bool deque<Type>::empty()
{
     if (front == NULL && back == NULL)
         return true;
     else
         return false;
}

 template<typename Type>
  void deque<Type>::push_front(Type key)
{
     Node<Type>* temp = new Node<Type>();
     temp->data = key;
     temp->prev = front;
     front->next = temp;
     front = temp;
}

 template<typename Type>
  void deque<Type>::push_back(Type key)
{
     Node<Type>* temp = new Node<Type>();
     temp->data = key;
     temp->next = back;
     back->prev = temp;
     back = temp;
}

 template<typename Type>
 inline void deque<Type>::pop_front()
{
     if (front != NULL) {
         Node<Type>* delPtr = front;
         front = front->prev;
         front->next = NULL;
         delete delPtr;
    }
     else
         cout << "There is no front in empty deque" << endl;
}

 template<typename Type>
  void deque<Type>::pop_back()
{
     if (back != NULL) {
         Node<Type>* delPtr = back;
         back = back->next;
         back->prev = NULL;
         delete delPtr;
    }
     else
         cout << "There is no back in empty deque " << endl;
}

 template<typename Type>
  void deque<Type>::print_in_order()
{
     if (front == NULL)
         return;
     Node<Type> temp = front;
     while (temp->prev != NULL) {
         cout << temp->data << " ";
         temp = temp->prev;
    }
     cout << endl;
}

 template<typename Type>
 inline Node<Type>::Node()
{
}

Then some code to check whether it is working
int main(){
    deque<int> qq(1);
    qq.push_front(2);
    qq.push_front(3);
    qq.print_in_order();
    return 0;
}

This code doesn't want to compile. I have tried looking for similar project or bugs and couldn't find anything useful. Therefore it would be great if someone could explain what is going wrong.
Most of errors are the same. For instance it is not allowed to use back() or front() because they are not functions and not a static members. Or back() and front() as members of template of class can't receive type of function. Hope someone can help.

A: There are a conflict between
Node<Type>* front = NULL;
Node<Type>* back = NULL;

and
Node<Type>* back();
Node<Type>* front();

So first of all change Node<Type>* front = NULL; to Node<Type>* m_front = NULL; and the same to back. There are another errors on your code, for example
Node<Type> temp = front;

have to be
Node<Type>* temp = front;

Finally, you can see the code without compilation errors on ideone
Good Lucky!


text:
Q: Geometric Series to approximate power series expansion I have been stuck working through the following derivation for a while now (for context the problem is a Central Limit Theorem proof in Stochastic Processes: Theory For Applications, specifically the proof of Theorem 1.7.3).
Problem
The specific issue I am having is in going from (1.87) to (1.88) in the following (quoting directly from the text):

Let $\epsilon = \hat{p} - p$ and $q = 1 - p$. Then:
  $$
S = (p + \epsilon)ln(1 + \frac{\epsilon}{p}) + (q - \epsilon)ln(1 - \frac{\epsilon}{q})
$$
$$
S = \frac{\epsilon^2}{2p} - \frac{\epsilon^3}{6p^2} + \dots + \frac{\epsilon^2}{2q} + \frac{\epsilon^3}{6q^2} + \dots \tag{1.85}\label{1.85}
$$
$$
S = \frac{\epsilon^2}{2pq} - \frac{\epsilon^3}{6p^2} + \dots  + \frac{\epsilon^3}{6q^2} + \dots \tag{1.86}\label{1.86}
$$
  In (1.86) we used the fact that $\frac{1}{p}+\frac{1}{q} = \frac{1}{pq}$. Substituting this into an exponential term:
  $$exp(-nS) =
exp\big(-\frac{n\epsilon^2}{2pq} \big)
exp\big( \frac{\epsilon^3}{6p^2} + \dots  - \frac{\epsilon^3}{6q^2} + \dots\big)\tag{1.87}\label{1.87}$$
$$exp(-nS) =
exp\big(-\frac{n\epsilon^2}{2pq} \big)
(1 \pm C_2 n^{-3\alpha + 2})
\tag{1.88}\label{1.88}$$
  Where in (1.88) we used, first, the fact that the neglected terms in (1.87) are decreasing at least geometrically with $\epsilon$, second, the condition in the theorem that $|\epsilon| \leq n^{\alpha -1}$, and third, the expansion $e^x = 1 + x + \frac{x^2}{2}+\dots$

Again, my specific issue is in making the jump from (1.87) to (1.88).
My Attempt
I have tried many routes, the most promising of which utilized the property of a geometric series:
$$a + ar + ar^2 + \dots = \frac{a}{1 - r}$$
Which, applied to (1.87), seems to show that it is decreasing geometrically at least with $\epsilon$, and has an initial term of $\epsilon^3(\frac{1}{6p^2} - \frac{1}{6q^2})$:
$$r = \epsilon$$
$$a = \epsilon^3(\frac{1}{6p^2} - \frac{1}{6q^2})$$
And hence:
$$\frac{a}{1 - r} = \frac{\epsilon^3(\frac{1}{6p^2} - \frac{1}{6q^2})}{1 - \epsilon}$$
Plugging in $n^{\alpha -1}$ for $\epsilon$ I get:
$$ \frac{(n^{\alpha -1})^3(\frac{1}{6p^2} - \frac{1}{6q^2})}{1 - n^{\alpha -1}}$$
And then letting $C_2 = \frac{1}{6p^2} - \frac{1}{6q^2}$, I arrive at:
$$ \frac{(n^{\alpha -1})^3 C_2}{1 - n^{\alpha -1}}$$
But I am not able to make the final jump to (1.88), which leads me to believe I have made a mistake somewhere in this reasoning.
Any insight into how to go from (1.87) to (1.88) is much appreciated!

A: Your solution is correct. A premise of the theorem is that $\alpha$ is a fixed constant such that $1/2 < \alpha < 2/3$. For such $\alpha$ and large $n$ (as required by the theorem), the expression
$$
\frac{c\cdot n^{3\alpha - 2}}{1 - n^{\alpha - 1}}
$$
is a very small number, because both terms $n^{3\alpha-2}$ and $n^{\alpha-1}$ go to zero for large $n$.
Then, as suggested by Gallager, we can use the expansion for $e^x$ for small x.
$$
\exp\left(-\frac{c\cdot n^{3\alpha - 2}}{1 - n^{\alpha - 1}}\right) \approx 1 - \frac{c\cdot n^{3\alpha - 2}}{1 - n^{\alpha - 1}} \approx 1-c\cdot n^{3\alpha-2}
$$
At this point, I believe there are typos in the proof because if $\alpha < 2/3$, terms such as $n^{-3\alpha + 2}$ will blow up for large $n$. Also, the original statement of the theorem uses $n^{3\alpha - 2}$.

A: This is not an answer but rather a long comment.
For this kind of problems which require composition of series, I think that it easier to start from where we want to end (!!). For your case
$$A=e^{-n S} \implies \log(A)=-n S \tag 1$$
$$S=(p+\epsilon ) \log \left(1+\frac{\epsilon }{p}\right)+(q-\epsilon ) \log
   \left(1-\frac{\epsilon }{q}\right)$$
$$S=\frac{ (p+q)}{2 p q}\epsilon ^2+\frac{1}{6}
   \left(\frac{1}{q^2}-\frac{1}{p^2}\right)\epsilon ^3+O\left(\epsilon ^4\right)$$ Now, continuing with Taylor series using $A=e^{\log(A)}$ you will end with
$$A=1-\frac{ n (p+q)}{2 p q}\epsilon ^2+\frac{1}{6} n
   \left(\frac{1}{p^2}-\frac{1}{q^2}\right)\epsilon ^3+O\left(\epsilon ^4\right)$$ which simplify if $p+q=1$ and then write
$$A=1-\frac{ n }{2 p q}\epsilon ^2+\frac{ n(q-p)}{6p^2q^2}\epsilon ^3+O\left(\epsilon ^4\right)$$


text:
Q: Unresolved Unit Test Python Question: When creating Unit Tests, HOW do you instantiate classes from other files?
In my current example: There are two files. The first file contains the class I wish to instantiate, the second is the unitTest.py.
Project.PY has the following
class MyNewClass:
  def __init__(self,mystring):
     pass

My UnitTest.py attempts to instantiate that class
import project
Class MyNewClassTestCase(unit.TestCase):
        def test_something(self):
         MyNewClass("string")

As requested here is the direct traceback
Error:
Traceback
File: 'blahjalalahha', line 6  in test_something
MyNewClass()
Name Error: Global Name MyNewClass is not defined
I am getting a NameError:  MyNewClass is not defined. However, i have used hte IMPORT so I should have that functionality?

A: Your import is incorrect based on how you are instantiating your class:
Doing this:
import project

You would have to call your class as:
project.MyNewClass("string")

So instead do this:
from project import MyNewClass
Class MyNewClassTestCase(unit.TestCase):
        def test_something(self):
         MyNewClass("string")

It would help you greatly to read this very carefully.

A: MyNewClass is part of the project module which is why you are getting a NameError when trying to use it the way you are using it. You either need to reference it from the correct module, project.MyNewClass or you need to import the name into your current module, from project import MyNewClass
import project

class MyNewClassTestCase(unit.TestCase):
    def test_something(self):
        project.MyNewClass("string")


text:
Q: Check all conditions in form using jquery <!DOCTYPE html>

USER REGISTRATION

<form class="for" name="ureg" method="post" action="">
<fieldset style="margin-right: 900px">
<legend>Registration Form</legend>

Name              <input class="name" type="text"></input>

User Name         <input class="uname" type="text"></input>

Password          <input class="pass" type="password" name="pass"></input>

Confirm Password  <input class="cpass" type="password" name="cpass"></input>

Email             <input type="email"></input>

Gender            <input type="radio" name="gender" value="male">Male</input><input type="radio" name="gender" value="female">Female</input>

Country           <select name="country" style="width: 175px;">
                    <option value="india">India</option>
                    <option value="pakistan">Pakistan</option>
                    <option value="sri lanka">Sri Lanka</option>
                    <option value="china">China</option>
                    <option value="china">Japan</option>
                    <option value="china">Bangladesh</option>
                    </select>

Mobile            <input class="mob" type="number"></input>

Age               <input class="age" type="number" name="age"></input>

D.O.B             <input type="date"></input>

Address
<textarea rows="4" cols="50" name="address"></textarea>

Pincode           <input class="pin" type="number"></input>

<input id="submit" type="submit" value="SUBMIT">                <input id="reset" type="submit" value="RESET">

</fieldset>
</form>

this my code for validating the form. Once the SUBMIT is pressed i want to check the values one more time. or alternatively the the submit would work only when all the conditions are true. is there any way to do it?

A: You can target the form and check for the 'submit' event, then return false if the values aren't right. Alternatively, you could preventDefault on the event with e.preventDefault(); and submit the form with AJAX.
EDIT: Here's the short version of what I generally do as a first-pass for form validation. Note that this is the absolute least you should be doing. Users can simply remove the required attribute, and get by your first-pass validation, so you should always check for the absolutely required fields in addition, as well as check on the server-side after sanitizing the input. (As in, remove disallowed chars then check for proper data.)

$('form.validate').on('submit', function(e, el) {
  var inputs = $(this).find('input[required]'),
    empty = $(inputs).map(function(e, el) {
      if (el.value === '') {
        return el;
      }
    });

  if (empty.length > 0) {
    return false;
  }
})


text:
Q: pdf417 barcode reader/decoder in javascript? I would like to read/decode pdf417 barcode from my web app targeted to run only on mobile browsers. I have seen many barcode reader javascript libs online but none of them supporting reading of pdf417 barcode(one of the most popular barcode type) off-course creation of pdf417 was supported by them.
What I am looking for is a javascript based library to read/decode pdf417 barcode, I know how to achieve this with phonegap or native. I am expecting purely js based solution

A: We created a library to do just that, https://github.com/PeculiarVentures/js-zxing-pdf417, unlike the Android-only solution above this is pure Javascript and will work in all browsers.

A: If you're mainly interested in Android, take a look at this fork of the popular barcodescanner plugin, it supports PDF417: https://github.com/Telerik-Verified-Plugins/BarcodeScanner


text:
Q: How do I analyse principal component scores? I have carried out a principal component analysis on 10 emotions I have observed in animals e.g. happy, playful, aggressive etc (5 positive emotions and 5 negative). Each animal is given a score for each emotion from 1 to 100. E.g. an extremely happy animal receives a "happy" score of 100. My PC1 is positively correlated with positive emotions and negatively correlated with negative emotions. Thus, I have labelled the PC "Good welfare". I have component scores for each animal for PC1. I want to assign each animal to a poor or good welfare category based on these PC scores but how do I go about this? The scores range from 3.12673 to -2.23454. Could I take animals with a minus score as having poor welfare and those with a positive score had good welfare? I don't know how to interpret the component scores. Thanks!

A: In this case, higher PCA1 scores will mean "good welfare" as you've labeled it.   But PCA doesn't explicitly provide you with a classification threshold like that.  Zero may be a fine discriminator between the two classes you've named, but that threshold may be better chosen differently.  Plot the component scores to see if there is a natural break between your good and bad welfare animals.
Added detail:
The PCA process reprojects your data along a number of new axes that correspond to the greatest amount of variance in your data, provided that each new axis of rotation is orthogonal to the ones that preceded it.   This means that your PC1 axis is the single axis along which the variance of the data is maximized.   You may be able to cleanly distinguish between clusters or groups of animals along that single axis, or you may need to bring in PC2,3, etc.
In some cases, there will be an explainable relationship to an individual component.  You found that PC1 correlated with the positive emotion scores, so you may find that PC2 corresponds with the negative emotions.   Your implementation of PCA should give you the cumulative variance that is explained by adding more principal components.   Add enough that you are comfortable with the amount of variance you are explaining with these new variables, but not so many that you are adding variance due to noise.


text:
Q: Laravel on shared hosting, post request doesn't work Hi I need some help on installing my laravel project on a shared hosting. I've tried these :
https://laracasts.com/discuss/channels/laravel/how-to-move-laravel-54-application-to-shared-hosting
https://laravel-news.com/subfolder-install
My folder structure is :
laravel/ web/
Where web/ has the contents of my /public/ laravel folder and of course the rest of my laravel project is in the laravel/ folder
Now it does work .. ish .. When I open my public url in my browser, the page is showing. But I also have a backend cms (Angular) project in my web/ folder. When I do a post from my Angular project to Laravel I see something very strange in my browser console.
I see the post request begin moved : [HTTP/1.1 301 Moved Permanently 17ms] and it gets converted to a GET request. And my route doesn't have that defined so I get an error back.
What can cause this behaviour?


text:
Q: Launcher icon not appearing in Action Bar My launcher icon is not appearing in my ActionBar, despite having the android:icon attribute set (and the launcher appearing on my homescreen when I install the app). Note: I am using fragments, and they also contribute action items--but that shouldn't affect the home icon set, correct?
Here is some relevant code from my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns="http://schemas.android.com/apk/res/android"
    package="com.mywebsite.myapp">

    <application
        android:name=".MyApp"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">

        ...etc...

        </activity>
    </application>
</manifest>

And the code from styles.xml:
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>
</resources>

The code from menu_main.xml, for good measure:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <!-- Note: my fragments also contribute action items. -->

    <item
        android:id="@+id/action_about"
        android:orderInCategory="100"
        android:title="@string/menu_item_about"
        app:showAsAction="never" />
</menu>

And some code from MainActivity.java:
package com.mywebsite.myapp;

import android.support.v7.app.ActionBarActivity;
...etc...

public class MainActivity extends ActionBarActivity {

...lots of code; let me know if you need anything...

    // possibly relevant
    @Override public boolean onCreateOptionsMenu(Menu menu) {
        getMeunInflater().inflate(R.menu.menu_main, menu);
    }
}

EDIT: This question is not a duplicate of the question linked to by the moderators. The answer to that question did not solve my problem; the answer I marked as correct below, however, did. To be specific, calling setLogo(int) was not the solution to my problem. Calling actionBar.setDisplayShowHomeEnabled(true);, however, did solve my problem. See? Different questions.

A: Make sure you are displaying it:
actionBar.setDisplayShowHomeEnabled(true);

Then, note that setIcon() and setLogo() will only work if you have set displayOptions accordingly. You can just use:
actionBar.setDisplayOptions(ActionBar.DISPLAY_USE_LOGO);

So your ActionBar will take your AndroidManifest.xml's icon. Or:
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setIcon(R.drawable.ic_launcher);

A: Try this: getActivity().getActionBar().setDisplayShowHomeEnabled(true); in the fragment's onCreate


text:
Q: why is Hashtable not a part of Java Collection framework? I usually work in non multi threaded environment so usually go for HashMap instead of Hashtable. I know the difference between both and I also know Hashtbale was introduced way before Java Collection framework was introduced.
     If we go through the Hashtable source code we can find
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {...

My point is Hashtable was introduced way before Java Collection framework(So way before Map was introduced). Since Hashtable implements Map, Hashtable implementation has been modified.My questions is why is Hashtable not a part of Java Collection Framework when Map is?

A: In the last paragraph of API document of Hashtable

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework.

A: Hashtable was introduced as part of Java 1.0 where it didn't use Map.
In version 1.2, it was changed to implement Map and hence, became part of the Collections framework.
 http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html


text:
Q: Register ASP.NET Core JsonConverter implementations using assembly scan I have lots of json converters, which derive from JsonConverter<T>. They are in various assemblies, not just the executing assembly.
I register them like this:
services
  .AddControllers()
  .AddJsonOptions(o => {
    o.JsonSerializerOptions.Converters.Add(new FooJsonConverter());
    o.JsonSerializerOptions.Converters.Add(new BarJsonConverter());
    o.JsonSerializerOptions.Converters.Add(new BazJsonConverter());
    o.JsonSerializerOptions.Converters.Add(new QuxJsonConverter());
    // lots more...
  });

I'd rather add them dynamically, using an assembly scan - the same way AutoMapper, FluentValidation, Autofac, etc., do it. I looked at their repos for the secret sauce but couldn't find it.
So I tried some basic reflection:
services
  .AddControllers()
  .AddJsonOptions(o => {

    var jsonConverters =
      AppDomain.CurrentDomain
      .GetAssemblies()
      .SelectMany(x => x.ExportedTypes)
      .Where(x => x.BaseType != null && x.IsAssignableFrom(typeof(JsonConverter<>)));

    foreach (var jsonConverter in jsonConverters)
      o.JsonSerializerOptions.Converters.Add(Activator.CreateInstance(jsonConverter) as JsonConverter);

  });

But that fails to start, and throws:

FTL | Microsoft.AspNetCore.Hosting.Diagnostics | Application startup exception
Autofac.Core.DependencyResolutionException: An exception was thrown while activating Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionEndpointDataSourceFactory -> Microsoft.AspNetCore
.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider -> λ:Microsoft.AspNetCore.Mvc.Abstractions.IActionDescriptorProvider[] -> Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerA
ctionDescriptorProvider -> Microsoft.AspNetCore.Mvc.ApplicationModels.ApplicationModelFactory -> λ:Microsoft.AspNetCore.Mvc.ApplicationModels.IApplicationModelProvider[] -> Microsoft.AspNetC
ore.Mvc.ApplicationModels.DefaultApplicationModelProvider -> Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadataProvider -> λ:Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.I
CompositeMetadataDetailsProvider.
---> System.MissingMethodException: Cannot create an abstract class.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& hasNoDefaultCtor
)

Note the Cannot create an abstract class. The base class is abstract, but I'm trying to activate the subclasses.
What is the correct way to do this? Also, is it appropriate to refer to the AppDomain, as I remember reading somewhere that that behavior has changed in aspnet.

A: Just change to:
var jsonConverters =
      AppDomain.CurrentDomain
      .GetAssemblies()
      .SelectMany(x => x.ExportedTypes)
      .Where(x => x.BaseType != null && x.IsAssignableTo(typeof(JsonConverter)));

A: JsonConverter<> fullfills your condition  x => x.BaseType != null && x.IsAssignableFrom(typeof(JsonConverter<>).
It has base type and is assignable. Sorry ;)
U can allways check if type .IsAbstract and then ignore them.
Another solution is to register classes by convention (by name in this case ).I use Autofac but the method will be the same
  builder
                .RegisterAssemblyTypes(serviceAssembly)
                .Where(t => t.Name.EndsWith("Service"))
                .AsSelf();

A: This works for me:
services.AddControllers().AddJsonOptions(o => {

  var jsonConverters =
    AppDomain.CurrentDomain
    .GetAssemblies()
    .Where(x => !x.IsDynamic)
    .SelectMany(x => x.ExportedTypes)
    .Where(x => x.BaseType != null)                           // is not Object, or an interface
    .Where(x => x.BaseType.IsGenericType)                     // must derive from JsonConverter<T>
    .Where(x => x.BaseType.BaseType == typeof(JsonConverter)) // exclude framework types

  foreach (var jsonConverter in jsonConverters) {
    var instance = Activator.CreateInstance(jsonConverter) as JsonConverter;
    o.JsonSerializerOptions.Converters.Add(instance);
  }
});

I'm unsure whether to use AppDomain.CurrentDomain or AssemblyLoadContext.Default, but this way seems to work.


text:
Q: Can Express versions of Visual Studio still use Add-ins I create? Pretty simple question.

A: Unfortunately not.
One of the things not allowed/enabled with the express editions is loading of add-ins.
See here.
And directly from Microsoft.


text:
Q: sequence of pattern in last 3 values in column pandas + python I need help in finding the sequence pattern in the column,
example
colour --- match
blue    no match
orange  no match
orange  no match
blue    no match
orange  no match
orange  no match
orange  **match**

In the above dataframe, we have 2 columns colour and match. I need to find the sequence  in the Column "Color" it should find last 3 value(blue, orange, orange , orange(current cell)) in the column and if it match then need to update the next column match. I am looking this code to work in python code.

A: Use shift for that purpose: df["new_col"] = df.col.eq(df.col.shift(1)) & df.col.eq(df.col.shift(2)) to create a boolean Series of values when one in col equals the 2 preceding ones !
output:
0    False
1    False
2    False
3    False
4    False
5    False
6     True
Name: test, dtype: bool

Edit: if you want to convert back to "mismatched"/"matched" values you can simply add this
df["col"] = np.where(df["col"] == False, "mismatched", "matched")


text:
Q: How to interact with Viewmodel inside recyclerview adapter? I have seen similar question but it did not help me. I would try to be specific about my problem. I have product list in my shopping cart. when I am searching products I want button "Add to cart" disabled for the item which is already present in cart.
Cart item list is inside my view model.
I approached as follows -
When onBindViewHolder is called for a specific position, i need to search if the current item (product) is present in the list of item present in cart, if it is present then disable Button.
Here my problem is that Cart is in Viewmodel and i find myself unable to call viewmodel from OnBindViewholder method.
Is there any better way to do this?
@Override
public void onBindViewHolder(@NonNull ProductAdapter.OurViewHolder viewHolder, int i) {
    Products currentItem = adapterData.get(i);
    viewHolder.productNamesFragmentItemsBinding.setProductName(currentItem);
    if (currentItem.getPhotoUris() != null) {
    Picasso.get().load(currentItem.getPhotoUris().get(0)).into(viewHolder.productNamesFragmentItemsBinding.ivProductImage);

    //  now i want to search if current item is present in cart (cart is in viewModel), if item
        // is present in cart then disable "Add to Cart" button for current position

        //--------------todo : how to do it ??? -----------------------------------
    }
}

A: Initialize with ViewModelProvider. You can do it inside the constructor for one time initialization like this (Sorry for the naming, I had this code written for a project. I just copy-pasted from there:( )
    public class CartChildAdapter extends RecyclerView.Adapter<CartChildAdapter.CartHolder> {

        private ShoppingCartWishListViewModel shoppingCartWishListViewModel;

        public CartChildAdapter(Context context) {
            // this is the line you are looking for. Cast context with FragmentActivity
            this.shoppingCartWishListViewModel = new ViewModelProvider((FragmentActivity)context).get(ShoppingCartWishListViewModel.class);
        }

        @Override
        public void onBindViewHolder(@NonNull CartChildAdapter.CartHolder holder, int position) {
           // call from here
           this.shoppingCartWishListViewModel.getMyProduct(your parameters may be).observe(this,..){
             ......... Your Codes
}
 }


text:
Q: How does integer-float comparison work? The following expression evaluated to true on Ruby 1.9:
31964252037939931209 == 31964252037939933000.0
# => true

but I have no clue how this is happening. Am I missing something here?

A: The explanation is simply that standard methods for representing floating-point (i.e. decimal) numbers on computers are inherently inaccurate and only ever provide an approximate representation. This is not specific to Ruby; errors of the type you show in your question crop up in virtually every language and on every platform and you simply need to be aware they can happen.
Trying to convert the large integer value in your example to floating-point illustrates the problem a little better—you can see the interpreter is unable to provide an exact representation:
irb(main):008:0> 31964252037939931209.to_f
=> 31964252037939933000.0

Wikipedia's article on floating point has a more thorough discussion of accuracy problems with further examples.

A: Ruby used to convert bignums to floats in such comparisons, and in the conversion precision was lost. The issue is solved in more recent versions.

A: Here you can see the source code of the comparer for Ruby:
http://www.ruby-doc.org/core-1.9.3/Comparable.html#method-i-3D-3D
And seems to be using this actual comparer:
https://github.com/p12tic/libsimdpp/blob/master/simdpp/core/cmp_eq.h
The methood seems to be comparing using this:
/** Compares 8-bit values for equality.

@code
r0 = (a0 == b0) ? 0xff : 0x0
...
rN = (aN == bN) ? 0xff : 0x0
@endcode

@par 256-bit version:
@icost{SSE2-AVX, NEON, ALTIVEC, 2}
*/

My guess might be that the value is the same for both numbers.


text:
Q: java - All possible combinations of an array into one method I am looking a way to put the method static void combinationUtil() function into public static void main (String[] args).
I mean to remove the method static void combinationUtil() then the whole class only got one method public static void main (String[] args), or How can I print array data[] in public static void main (String[] args)
class permutation {

    static void combinationUtil(int arr[], int data[], int start, int end, int index, int r){
    if (index == r){
        for (int j=0; j<r; j++){
            System.out.print(data[j]+" ");
        }
        System.out.println("");
        return;
    }

    for (int i=start; i<=end && end-i+1 >= r-index; i++){
        data[index] = arr[i];
        combinationUtil(arr, data, i+1, end, index+1, r);
    }
}

public static void main (String[] args) {
    int arr[] = {1, 2, 3, 4, 5,6,7};
    int r = 5;
    int n = arr.length;
    int data[]=new int[r];
    int start=0,end=n-1,index=0;
    combinationUtil(arr, data, start, end, index, r);
    }
}

A: Like this (just removed the function combinationUtil and put it's content in
main method):
class permutation {

    public static void main (String[] args) {
    int arr[] = {1, 2, 3, 4, 5,6,7};
    int r = 5;
    int n = arr.length;
    int data[]=new int[r];
    int start=0,end=n-1,index=0;

    if (index == r){
        for (int j=0; j<r; j++){
            System.out.print(data[j]+" ");
        }
        System.out.println("");
        return;
    }

    for (int i=start; i<=end && end-i+1 >= r-index; i++){
        data[index] = arr[i];
        combinationUtil(arr, data, i+1, end, index+1, r);
    }
    }
}


text:
Q: Confused myself with matrix and array addition I was doing some practice with lists, arrays and matrices in python and I got confused at something.
if I do:
list1 = [1,2,3,4]
list2 = [2,3,4,5]

print list1 + list2

Output:
I get [1,2,3,4,2,3,4,5]

I think it was like yesterday I was doing something similar but I got
Output2:
[3,5,7,9]

the actual addition of the values of each respective element on both lists. But I was actually expecting it to be the first output, but it added the values.
I haven't done linear algebra or prob&stats in a while. What was the method called for the output I got in output1? and output2? I've confused myself bad.
edit: http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.add.html
If you look at the 2nd example they do a 3x3 array + 1x3 array. I thought if there not the same dimension you can't add them?

A: When using standard lists, addition is defined as concatenation of the two lists
import numpy as np

list1 = [1,2,3,4]
list2 = [2,3,4,5]

print list1 + list2
# [1, 2, 3, 4, 2, 3, 4, 5]

When using numpy types, addition is defined as element-wise addition rather than list concatenation.
array1 = np.array(list1)
array2 = np.array(list2)

print array1 + array2
# [3 5 7 9]

This is often called a vectorized operation. In cases where arrays are large it can be faster than iterating over the structures, since the vectorized operation utilize a highly optimized implementation which is provided by numpy.

A: If you do not understand zip or numpy -
Assuming both lists list1 and list2 have same length, this will do your work
[a[i]+b[i] for i in xrange(len(a))]

PS: simply using list1 + list2 would only concatenate these two lists.
To add each of the element you need to iterate through the lists.

A: You can get "Output2" canonically with sum() and zip():
result = [sum(item) for item in zip(list1, list2)]

If you put each list1, list2, etc. into a container (such as a tuple or another list, e.g. lists = [list1, list2]) you can instead use zip(*lists) and then not have to change that code for any quantity of lists.


text:
Q: LuaJIT cannot load libtorch.dll Following the guide here as best I could (C drive not X, 64 bit), I have reached the stage of testing Torch with
require('torch')
torch.test()

Upon trying to require the torch module I am given this error:
C:\torch\install\lua\torch\init.lua:13: cannot load 'C:\torch\install\libtorch.dll'
stack traceback:
        [C]: in function 'require'
        C:\torch\install\lua\torch\init.lua:13: in main chunk
        [C]: in function 'require'
        stdin:1: in main chunk
        [C]: at 0x003c19a0

libtorch.dll does exist exactly where lua says it is, and the error message doesn't give any reason why it can't load it. I have redone the whole procedure a couple of times now, same result. Googled for similar issues, didn't find any that matched my problem. At a complete loss on what to do.
If I use luarocks install torch, I am able to require it, but then it doesn't recognize my lapack libs and gives me errors about it during torch.test(). According to the previously linked tutorial I am following, I am supposed to solve this by downloading the torch rockspec file, manually setting the path to my lapack libs, then installing the altered rockspec file, but doing so results in this problem I am writing about.
All I want to do is make spaghetti images but I cannot get torch to work. I apologize for the vagueness.


text:
Q: VB6 inserting file path into SQL FROM clause I am working in VB6 on a Windows 7 desktop to read and work on text files and have run into a problem passing variable to a SELECT statement. The code I have is :
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cm As ADODB.Command

Set conn = New ADODB.Connection
conn.Open _
    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=" & App.Path & ";" & _
    "Extended Properties=""text;HDR=No;FMT=Delimited( )"""

inputFile = "C:\test data\test data.asc"

Set cm = New ADODB.Command
cm.ActiveConnection = conn
cm.CommandType = adCmdText

cm.CommandText = "SELECT * FROM " & inputFile
Set rs = New ADODB.Recordset
rs.Open cm, , adOpenKeyset, adLockOptimistic

The problem is that the path name to the input file contains spaces and when I run the code above, it fails at the rs.OPen line with an error saying Syntax error in FROM clause.
If the path in inputFile does not contain spaces, everything works without a problem.
I have tried many combinations of " ' [] etc around the inputFile but always get the syntax error or another error saying that inputFile.txt can not be found.
Can anyone give me the correct method for handling path/files names with spaces in an SQL statement please?

A: The value supplied for Data Source should always be quoted to avoid such problems.  You can use either the quotation mark " or apostrophe ' to do this, much as you did for the Extended properties value.
Then to use a file name within the Data Source directory as a table name at least "quote" it using brackets [ ], and preferably replace the . for the file extension by the # character.
There is no "OLEDB Provider for text files" but your example shows use of the Jet 4.0 OLEDB Provider with its Text Installable ISAM, which is just fine.
Processing Text Databases offers a lot of information on this topic in general, using VBScript for most examples but it pretty much all applies to VB6 as well.

A: Apparently spaces in the filename should work if you use square brackets [ ].
cm.CommandText = "SELECT * FROM [" & inputFile & "]"

You say in the question you've tried square brackets - could you double check? I don't know about spaces in the directory name.

A: Just had a memory from the distant past and if I remember right the data source is the folder the file is held in and in the select you just have the file name without the path.
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cm As ADODB.Command

Set conn = New ADODB.Connection
conn.Open _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & App.Path & ";" & _
"Extended Properties=""text;HDR=No;FMT=Delimited( )"""

inputFile = "test data.asc"

Set cm = New ADODB.Command
cm.ActiveConnection = conn
cm.CommandType = adCmdText

cm.CommandText = "SELECT * FROM [" & inputFile & "]"
Set rs = New ADODB.Recordset
rs.Open cm, , adOpenKeyset, adLockOptimistic

(assuming the file is in App.Path)


text:
Q: RHEL6 openssl + httpd confusion I have a confusion around openssl + httpd (SSL).
I got a rhel 6 server to manage, from the previous admin. This server hosts a (HTTPS) web site.
Recently, I updated openssl to a more up-to-date version - OpenSSL 1.0.2a 19 Mar 2015
I think now I need to also re-generate the keys / cert for httpd..? Can someone please confirm or correct me here?
Edit:
The issue is even though Openssl is a recent version, a vuln scan continues to say otherwise - TCP 443, openssl older version (<1.0.2) in use.. How can I check if openssl in use is 1.0.2 only and no other version.?
.....
Edit2:
Adding more information after reading a new response.
At the start, the following openssl packages were installed:
# yum list openssl
Installed Packages
openssl.i686 1.0.0-27.el6
openssl.x86_64 1.0.0-27.el6

I notice that the repo configured for packages (different server) has new packages but the rhel6 box doesn't see any new updates.
So I manually copied over recent rpm openssl packages
openssl-1.0.1e-42.el6.i686.rpm
openssl-1.0.1e-42.el6.x86_64.rpm

And removed existing package:
# yum remove openssl-1.0.0-27.el6.i686
It removed this version as well as several dependencies.

Then tried installing a current version:
# yum install openssl-1.0.1e-42.el6.i686.rpm
  Setting up Install Process Examining openssl-1.0.1e-42.el6.i686.rpm:
  openssl-1.0.1e-42.el6.i686 Marking openssl-1.0.1e-42.el6.i686.rpm as
  an update to openssl-1.0.0-27.el6.x86_64
  Error: Nothing to do

So it didn't get installed.
Then I checked current version:
# openssl version
OpenSSL 1.0.2a 19 Mar 2015

It appears this 1.0.2a had also been installed earlier, and now it became the current version.
.....
Edit3:
Adding openssl rpm info:
$ rpm -q openssl
openssl-1.0.0-27.el6.x86_64

.....
So, rpm version and openssl version are different. Not sure if this looks right.
.....
Many thanks.

A: It depends on why you upgraded your OpenSSL:

*

*If you upgraded because it provides a cryptographic algorithm that
wasn't available on your original version, then you will obviously
need to use the newer OpenSSL to create new keys with this new
algorithm.

*If you upgraded because of certain well known bugs in OpenSSL and you believe your site was compromised, then you must replace your certificates. It would be wise to replace them regardless of whether you think you've been compromised - just to be on the safe side; especially if you don't know what the previous admin had done in relation to maintenance. This Red Hat article may help.

*If you only upgraded as part of a regular maintenance process then there is no need to change certificates.  OpenSSL, just like other packages, can be updated by the maintainers at regular intervals, but there is no need to replace certificates each time.

A: You usually don't have to regenerate keys and certificates when you update OpenSSL. That is only needed if there was something wrong with the key/certificate creation like the problem Debian had.

A: No. Keys and certificates are stored in a format independent of OpenSSL version (works even with other SSL/TLS implementations). The only posibility is that OpenSSL 1.0.2 might have disabled features for security reason your old keys rely on (unlikely if you key isn't stone old). But that's easy to check: start your server; if you can connect via TLS, it works.


text:
Q: Sending a div to separate page for printing So I am working on a website that will have a lot of recipes. I want to have a button that sends whatever recipe is being displayed to that page for printing. However, the way I have each page set up is making this complicated. I have a page for each type and have the recipes displayed via the use of divs and javascript. You click a recipe from a list and that calls a function to make the corresponding recipe go from 'none' to 'block'. Here is my current code
$('.main').each(function() {
    if(style.display=="block"){
    var divData = $('.card').html();
    window.location.href = "print.html";
    document.write(divData);
    }

});

How can I alter this code so it calls in the one that has its display set to "block"?

A: You should try using a print stylesheet based on the active recipe class.
Here's more info about print stylesheets
https://css-tricks.com/print-stylesheet-approaches-blacklist-vs-whitelist/


text:
Q: Css not wotrking with url routing im using url routing its working fine but css not working
Here is my code
     <link href='<%= ResolveClientUrl("~/Style/admin.css") %>' rel="stylesheet" type="text/css" />
<link href='<%= ResolveClientUrl("~/Style/reset.css") %>' rel="stylesheet" type="text/css" />
<link href='<%= ResolveClientUrl("~/Style/OuterStyle.css") %>' rel="stylesheet" type="text/css" />
<link href='<%= ResolveClientUrl("~/Style/mfv3_98290.css") %>' rel="stylesheet" type="text/css" />
<link href='<%= ResolveClientUrl("~/Style/mfv4_98290.css") %>' rel="stylesheet" type="text/css" />
<link href='<%= ResolveClientUrl("~/Style/demo.css") %>' rel="stylesheet" type="text/css" />
<link href='<%= ResolveClientUrl("~/Style/slicebox.css") %>' rel="stylesheet" type="text/css" />
<link href='<%= ResolveClientUrl("~/Style/custom.css") %>' rel="stylesheet" type="text/css" />

A: use this,
<link href="<%= Page.ResolveUrl("~/Style/admin.css") %>" rel="stylesheet" type="text/css" />

and put in your code
RouteTable.Routes.IgnoreRoute("{resource}.css/{*pathInfo}");
RouteTable.Routes.IgnoreRoute("{folder}/{*pathInfo}", new {folder="content"});


text:
Q: How to check whether array element matches with string using PowerShell? Hi I want to check whether an string exist or start in set of array.
Example:
$str = "iit.apple"
$arr = ("apple", "mango", "grapes")

I want to check whether an array (arr) element matches or exist or starts with in string

I have tried using foreach loop to read each element but when matches found I am trying to break the loop.

A: Use the intrinsic .Where() method in First mode:
$str = "iit.apple"
$arr = ("apple", "mango", "grapes")

$anyMatches = $arr.Where({$str -like "*$_*"}, 'First').Count -gt 0

If any of the strings in $arr is a substring of $str, the Where(..) method will return a collection consisting of just that one element - so Where(...).Count -gt 0 will evaluate to $true

A: I would use regex and three "or" patterns.
'iit.apple' -match 'apple|mango|grapes'

True

Or
$str -match ($arr -join '|')

True

Or select-string takes an array of patterns:
$arr = "apple", "mango", "grapes"
$str | select-string $arr

iit.apple

A: To complement Mathias's answer here is how you do it with a foreach loop:
$str = "iit.apple"
$arr = "apple", "mango", "grapes"

$result = foreach($element in $arr) {
    if($str -like "*$element*") {
        $true
        break
    }
}
[bool] $result

Enumerable.Any can work too:
$delegate = [System.Func[object, bool]] {
    $str -like "*$($args[0])*"
}
[System.Linq.Enumerable]::Any($arr, $delegate)


text:
Q: How does the Facebook Graph API public post searching works? I've started working with Facebook Graph API this month and I'm currently experiencing some odd behaviors with it.
To start, I'm using the Graph API 1.0 (which supports public post searching), with queries such as those below.

*

*https://graph.facebook.com/v1.0/search?q=foo bar&type=post

*https://graph.facebook.com/v1.0/search?q=foo&type=post
The weird behavior in this case is that the first query returns almost the same number of results that the second one. Thus, no matter how "vague" my query is, I'm getting a limited number of posts (yeah, I'm already considering pagination).
So how does this work? The Graph API Documentation isn't clear about this subject, so any clarification would be really appreciated.

*

*As I understood so far, Facebook does not return all public posts containing the researched terms. Some old questions here in StackTrace support this assumption (example)

*Different apps or different users may retrieve different results (which is another "odd" behavior I found). (example)
Am I correct? If so, is there ANY way to improve my recall? Any paid services from Facebook or specific permissions that I should get for my app? Searching from multiple views (users or apps) would help? Is there any way to query only recent results and therefore obtain more results?
Thank you.
P.S.: I'm aware that Facebook has been planning to remove this functionality by 2015, but for now it's working and I wanted to give a try :-)


text:
Q: HOG descriptor for object detection I would like to know, if there is any implementation for HOG descriptor for objects like "cars" and NOT for Human in MATLAB?
But in case, there is only for Human, can you guide me to that code, and give me so HINTS in order to improve the code to be used for "objects such as cars or motorcycles"

A: There is now a function extractHOGFeatures in the Computer Vision System Toolbox.

A: HOG is a kind of feature descriptor and it can be applied to whatever object you want. The implementation would be no change except for parameters of block size, cell size, block stride, etc. To get a descriptor for cars, you need to provide positive and negative samples of them. Opencv provides the function for users to train the classifier.  It should be same for matlab if it provides the code to train the classifier.

A: Well you can Use VLFeat Toolbox, Its has very effiecient implimentaion of HOG, u can find hOG feature of any object, also u can visualize.
If "im.jpg" if your input image, You can get HOG feature using
hog = vl_hog("im.jpg",8,'verbose')
Here 8 is ur window size, you can adjust accordingly.
For displaying the feature
 imhog = vl_hog('render',hog,'verbose')

A: Here is an excellent Matlab code that fully implements Dalal's algorithm. I have tested and used this code for many major academic projects.
http://hi.baidu.com/fpmaldfoamdfmze/item/4f3b3ac881affcb00c0a7b11
All credit goes to the person who posted this!
HOG is not specific to pedestrian detection. You can use it with any rigid (or apploximately rigid) object.
To use this code, you need to understand how HOG is calculated over a region. The region is divided into overlapping 'blocks'. Blocks consist of a number of 'cells'. A spatial orientation histogram is computed in each block. The final vector is formed by concatenating these spatial histograms.
The parameters that you can tweak are
cellpw, cellph: cell's pixel width and height respectively.
nblockw, nblockh: block size counted by cells number in x and y directions respectively.
nthet: Number of angle bins.
issigned: whether signed or unsigned gradient is taken
overlap: amount of overlap between blocks specified as a fraction
isglobalinterpolate: whether global or local interpolation of 3d histogram
normmethod: type of norm used
You can fist try with the default parameters -
cellpw = 8;
cellph = 8;
nblockw = 2;
nblockh = 2;
nthet = 9;
overlap = 0.5;
isglobalinterpolate = 'localinterpolate';
issigned = 'unsigned';
normmethod = 'l2hys';
In matlab getting the feature is something like
I = imread('car.png');
Ig = rgb2gray(I);
F = hogcalculator(Ig, 8, 8, 2, 2, 9, 0.5,'localinterpolate', 'unsigned', 'l2hys');

The dimension/length of F depends on the paramenters you choose.
Answering your comment,
Yes, you have to build these features for your positive(car) and negative(non-car) images to build a detection system. SVM is typically used as classifier. I suggest using libsvm library -
 http://www.csie.ntu.edu.tw/~cjlin/libsvm/
Once you build your training set, train with your training set. Tweak SVM parameters to get the highest accuracy.
The parameters given in the example may not be the best, you can always try a different set. I would try changing nthet, cellpw and cellph first.
Good luck!


text:
Q: ASP.NET Core 3.1 - Programmatically invoke http request pipeline This question had a similar situation but the guy ended up using HttpClient as a hack: Programmatically invoking the ASP.NET Core request pipeline
Is there a way to trigger the http pipeline (simulate a full request) by providing the payload, headers, verb and url route programmatically WITHOUT using the HttpClient?
I also saw you could do something similar with the TestServer for integration testing but this feels like a hack as well for what I want
Simulate POST request in a unit test using ASP.NET Core


text:
Q: Android KeyStore setKeyEnty throws NPE on String.length I have problem with creating KeyStore with client certificate for authentication. As you can see the exception comming from BounceCastle, so I am unable to debug the BcKeyStoreSpi.engineSetKeyEntry. I have no idea what String is null. All my parameters are filled and seems correct. What is wrong with my solution?
I am able to reproduce this on multiple devices (Android 9, 8.1, 7.0). Also I have already tried to disable proguard but still it is throwing the NPE. Even multiple certificates.
Code
String certAlias = "alias";
PrivateKey privateKey = KeyChain.getPrivateKey(context, certAlias);
X509Certificate[] certChain = KeyChain.getCertificateChain(context, certAlias);
X509Certificate mdmCert = certChain[0];

char[] password = "password".toCharArray();
String alis = "private";
HeldCertificate heldCertificate = new HeldCertificate(
        new KeyPair(
                mdmCert.getPublicKey(),
                privateKey
        ),
        mdmCert
);
X509Certificate[] certificates = new X509Certificate[certChain.length + 1];
certificates[0] = heldCertificate.certificate();
System.arraycopy(certChain, 0, certificates, 1, certChain.length);

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, password);
ks.setKeyEntry(             //this is the problematic part
        alis,
        heldCertificate.keyPair().getPrivate(),
        password,
        certificates

);

Stacktrace
java.security.KeyStoreException: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.leng
    at com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi.engineSetKeyEntry(BcKeyStoreSpi.java:685)
    at java.security.KeyStore.setKeyEntry(KeyStore.java:1179)
    at cz.kctdata.skoenergo.ui.activity.MainActivity$GetCertAsyncTask.doInBackground(MainActivity.java:153)
    at cz.kctdata.skoenergo.ui.activity.MainActivity$GetCertAsyncTask.doInBackground(MainActivity.java:86)
    at android.os.AsyncTask$2.call(AsyncTask.java:333)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:764)


text:
Q: mysql one to one messaging optimized table query I got this schema to work with:
-- store messages between users
CREATE TABLE chat_messages (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    sender_id BIGINT UNSIGNED NOT NULL,
    recipient_id BIGINT UNSIGNED NOT NULL,
    message_body TEXT,
    read_at DATETIME DEFAULT NULL,
    created_at DATETIME NOT NULL,
    PRIMARY KEY(id),
    CONSTRAINT FK_messages_1 FOREIGN KEY (sender_id) REFERENCES profiles (id),
    CONSTRAINT FK_messages_2 FOREIGN KEY (recipient_id) REFERENCES profiles (id)
) ENGINE = INNODB;

I need to run a query against it to get a list of unique active chats for a user, I have this query:
SELECT * FROM chat_messages WHERE recipient_id = :user_id GROUP BY recipient_id ORDER BY created_at DESC

Which returns grouped rows, however:

*

*The returned row includes message_body but it is not the latest message (thinking along the lines of a need to GROUP it BY the previously ordered data set)

*Also, if the user sent messages to another user and did not receive a reply yet, it does not include it in the list (in that case the sender_id should be taken into consideration as well)
Any suggestions to have a performance focused query to achieve all that? Thanks :)

A: You can do what you want with a not exists query:
SELECT cm.*
FROM chat_messages cm
WHERE recipient_id = :user_id AND
      NOT EXISTS (SELECT 1
                  FROM chat_messages cm2
                  WHERE cm2.recipient_id = cm.recipient_id AND
                        cm2.created_at > cm.created_at
                 )
ORDER BY created_at DESC;

For performance, you should have an index on chat_messages(recipient_id, created_at).

A: Here is a query, which should fulfill your needs:
SELECT a.sender_id, a.recipient_id, a.message_body
FROM chat_messages a
INNER JOIN (
  SELECT IF(recipient_id=1, sender_id, recipient_id) user_id,
    MAX(created_at) created_at
  FROM chat_messages
  WHERE 1 IN (recipient_id, sender_id)
  GROUP BY IF(recipient_id=1, sender_id, recipient_id)
) recent
ON
  (
    (a.sender_id = recent.user_id AND a.recipient_id = 1)
  OR
    (a.recipient_id = recent.user_id AND a.sender_id = 1)
  )
  AND a.created_at = recent.created_at

The inner join computes the dialog partner user ids and the date of the most recent message. This is joined with the whole table, to search the corresponding message and retrieve its content.
If you create an index on (sender_id, recipient_id, created_at) it can be used to support the execution. Nevertheless this query is not that light.
I have prepared a SQLFiddle too.


text:
Q: @OneToOne Relationship on Spring mcv I'm tired of trying things and I don't have any results. My user has One country and the country has many user. The problem is when I make a new user.
I don't have any idea where is the problem.
I have this User Bean:
@Entity
@Table(name="usuarios")
public class Usuario {

    @Id
    @GeneratedValue
    @Column(name="id")
    private Integer id;

    @Column(name="nombre", nullable=false)
    private String nombre;

    @OneToOne
    @JoinColumn(name = "id_pais")
    private Pais pais;

    /* Getters & Setters */
    ....
}

The Country Bean:
@Entity
@Table(name="paises")
public class Pais {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private Integer id;

    @Column(name="nombre")
    private String nombre;

    @OneToMany(mappedBy="pais")
    private Set<Usuario> usuarios;

    /* Getters & Setters */

}

The controller:
@Controller
@RequestMapping(value = "/usuario")
public class UsuariosController {

    @Autowired
    private UsuarioService usuarioService;

    @RequestMapping(method = RequestMethod.POST)
    public RedirectView store(Usuario usuario) {
        usuarioService.store(usuario);
        return new RedirectView("../usuario");
    }
    @ModelAttribute("usuario")
    public Usuario getUsuario() {
        return new Usuario();
    }
}

The Service:
@Service
public class UsuarioServiceImplement implements UsuarioService{

    @Autowired
    private UsuarioDAO usuarioDAO;

    public void store(final Usuario usuario) {
        usuarioDAO.store(usuario);
    }
}

The DAO:
@Repository
public class UsuarioHibernateDAO implements UsuarioDAO{

    @Autowired
    private SessionFactory sessionFactory;

    @Transactional(readOnly = false)
    public void store(final Usuario usuario) {
        sessionFactory.getCurrentSession().save(usuario);
    }
}

The form:
<form:form action="../usuario" method="POST" commandName="usuario">

    <!-- nombre -->
    <form:input path="nombre" type="text" class="form-control" id="nombre" />

    <!-- pais -->

    <form:select path="pais" class="form-control">
        <form:option value="1">España</form:option>
    </form:select>
    <input type="submit" class="btn btn-success" value="Enviar" />
</form:form>

And I obtain this:
Estado HTTP 400 -

type Informe de estado

mensaje

descripción El requerimiento enviado por el cliente era sintácticamente incorrecto.

Apache Tomcat/8.0.20

A: I had a same Problem with these,you can set object manually by id.I hope it will solve your problem.
Try this!
usuario.setPais(paisService.getPaisById(request.getParameter("pais")));


text:
Q: Can not use public methods of subclasses java I am using NetBeans to create some desktop application with JTable-s and i have faced the trouble:
I am creating subclass of JTable, assume CustomJTable:
public class CustomJTable extends JTable {

    private Object[][] someData;

    public CustomJTable (Object[][] someData) {
        this.someData = someData;
    }

    public doSomething () {
        // do something
    }
}

public class MyApp {

    ...
    public void someMethod (Object[][] someData) {
        JTable table = new CustomJTable(someData);
        table.doSomething();  // this method does not belong to JTable and
                              // is unusable to me in NetBeans
    }
    ...
}

NetBeans says that doSomething method can not be found in class JTable. For nor I am really confused. Thanks in advice.
This is just a shortened sample code to show the trouble source.

A: You are instantiating instance of JTable and then try to call a method belong to CustomJTable.
Extending JTable in CustomJTable don't give you the methods owned by CustomJTable.
In order to call the method instantiate the right object:
CustomJTable table = new CustomJTable(someData);

A: Because of Runtime Polymorphism it will be resolved at runtime. You need to type cast it.
JTable table = new CustomJTable(someData);
        ((CustomJTable) table).doSomething();


text:
Q: MySQL Delete Session Variable SITUATION: MySQL query uses value, delivered from outside. This is done by declaring and initializing a session variable, that remains valid until the end of session:
SET @id = 0;

SELECT * FROM my_table
WHERE id = @id;

QUESTION: Is it a good practice to delete session variable after the query has finished (for safety reasons)? What is the most adequate way to do this?
STUDIES: I found the following suggestion, but have some doubts as it looks like "uninitialise", not like "undeclare":
SET @id = NULL;

A: I haven't read the manual or anything. But what I've found when using @-variables is that they disappear with the database connection. I guess that's what you call a session. In any case, reconnecting to the database seems to remove all variables.
If you use MySQL with a web server, this means that all your variables get deleted as soon as a page has been delivered. That is actually how I found this out. You cannot keep an SQL @-variable from one http call to another.

A: The direct answer is when using @-variables in MySQL there is no delete/unset a session variable, closing the session will clear all the session variables. Checked the MySQL reference manual 8.0. Was reading through the answers and thought of making it compact Cheers !

A: Using session variables to pass parameters is a bad practice (using global variables often indicates code smell). Therefore there is no adequate or recommended way to deal with your situation(1).
You commented:

Using name parameters is more flexible than place parameters using "?", because adding/removing a variable needs no order changes in code.

This is an illusion. Using this approach, you will still need to document "somewhere" that your procedure requires some variables be declared before calling. This also introduce the very problem you are trying to address.
On the other hand, a stored procedure (or prepared statement) is self-documenting and parameters have a well-known scope and life span.
Now, to answer the specific question:

How to delete/unset a session variable?

SET @id = NULL; is the only way to go. You cannot "undeclare" a session variable, since you cannot "declare" a session variable (try SELECT @dummy_variable_never_declared_before;). MySQL session variables are very similar to shell environment variables.(2)

(1) ... except if you make sure the session is closed after you are done. Closing the session will surely clear all session variables.
(2) I have learnt that bash session variables can indeed be unset.


text:
Q: How Can I Console.log countdownjs module via node.js I'm using countdownjs module
, How Can I Console.log countdownjs for 3 days later, via node.js?

A: Here is a small example how you can use the countdown module:
var now = new Date();
var durationInDays = 3;
var durationInMilliseconds = (durationInDays * 24 * 60 * 60 * 1000);
var future = now.getTime() + durationInMilliseconds;
var countdownInfo = countdown(now, future);

// print it once
console.log(countdownInfo.toString());

// print it every 5 seconds

function repeatedPrint() {
    setTimeout(function () {
        // you have to provide a new start date to get updated information
        countdownInfo = countdown(new Date(), future);
        console.log(countdownInfo.toString());
        repeatedPrint();
    }, 5 * 1000);
}
repeatedPrint();


text:
Q: How to deselect radio button in JFrame I want to deselect my Radio Buttons that I have in my program in JFrame,it exists some method to deselect all Radio Buttons trough one button called Clean ? This button will clean the radion buttons and the texts that have.
The code of Action Performed that will make clean all thinks :
JButton btnClean = new JButton("Clean");
        btnClean.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

            }
        });
        btnClean.setBounds(208, 184, 126, 28);
        contentPane.add(btnClean);

A: Usually JRadioButtons are grouped together in a ButtonGroup object, a logical object that allows only one JRadioButton to be selected at a time. What you will want to do is to call clearSelection() on this ButtonGroup object.
As an aside, you look to be using a null layout with your GUI. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class BunchOButtons extends JPanel {
    private static final String[] RADIO_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
    private ButtonGroup weekDayBtnGroup = new ButtonGroup();

    public BunchOButtons() {
        // JRadioButtons love being held in JPanels that use GridLayout
        JPanel radioPanel = new JPanel(new GridLayout(1, 0));
        radioPanel.setBorder(BorderFactory.createTitledBorder("Week Days"));
        for (String radioText : RADIO_TEXTS) {
            JRadioButton radioButton = new JRadioButton(radioText); // create radiobtn
            radioButton.setActionCommand(radioText); // set its action command text
            weekDayBtnGroup.add(radioButton); // add to ButtonGroup
            radioPanel.add(radioButton);   // add to a GridLayout-using JPanel
        }

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(new JButton(new AbstractAction("Show Selection") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                ButtonModel model = weekDayBtnGroup.getSelection();
                if (model != null) {
                    // if something is selected
                    System.out.println(model.getActionCommand());
                } else {
                    System.out.println("No weekday selected");
                }
            }
        }));
        buttonPanel.add(new JButton(new AbstractAction("Clear Selection") {

            @Override
            public void actionPerformed(ActionEvent e) {
                weekDayBtnGroup.clearSelection();
            }
        }));

        setLayout(new BorderLayout());
        add(radioPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.PAGE_END);
    }

    private static void createAndShowGui() {
        BunchOButtons mainPanel = new BunchOButtons();

        JFrame frame = new JFrame("BunchOButtons");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

A: As your JFrame may contain many JRadioButton components arbitrarily nested in the frame's layout, you may need to recurse down the component hierarchy using Container.getComponents and check if each component is an instanceof JRadioButton, in which case you should cast and .setSelected(false) it, or a Container, in which case you should continue the recursion. To obtain the JFrame's top-level container, use JFrame.getContentPane.
To illustrate this approach with a simple example (containing an implementation of the Clean method requested by the OP):
public class FrameWithRadios extends JFrame {

    public FrameWithRadios() {

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel panelCenter = new JPanel();
        panelCenter.setLayout(new GridLayout(1, 2));

        JRadioButton rb11 = new JRadioButton("Option 1.1");
        JRadioButton rb12 = new JRadioButton("Option 1.2");
        JRadioButton rb13 = new JRadioButton("Option 1.3");

        JPanel panelLeft = new JPanel();
        panelLeft.setLayout(new GridLayout(3, 1));

        panelLeft.add(rb11);
        panelLeft.add(rb12);
        panelLeft.add(rb13);

        panelCenter.add(panelLeft);

        JRadioButton rb21 = new JRadioButton("Option 2.1");
        JRadioButton rb22 = new JRadioButton("Option 2.2");
        JRadioButton rb23 = new JRadioButton("Option 2.3");

        JPanel panelRight = new JPanel();
        panelRight.setLayout(new GridLayout(3, 1));

        panelRight.add(rb21);
        panelRight.add(rb22);
        panelRight.add(rb23);

        panelCenter.add(panelRight);

        JButton bClean = new JButton("Clean");
        bClean.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               clean(getContentPane());
           }
        });
        JPanel panelBottom = new JPanel();
        panelBottom.add(bClean);

        Container cp = getContentPane();
        cp.setLayout(new BorderLayout());

        cp.add(panelCenter, BorderLayout.CENTER);
        cp.add(panelBottom, BorderLayout.SOUTH);
    }

    protected void clean(Component comp) {
        if (comp instanceof JRadioButton) {
            ((JRadioButton) comp).setSelected(false);
        }
        else if (comp instanceof Container) {
            for (Component child: ((Container) comp).getComponents()) {
                clean(child);
            };
        }
    }

    public static void main(String[] args) {
        FrameWithRadios frame = new FrameWithRadios();
        frame.setSize(320, 200);
        frame.setVisible(true);
    }
}

Of course, as others have suggested, you'll most likely want to assign the management of your radio buttons' selection state to a ButtonGroup and use the ButtonGroup.clearSelection method to deselect everything (the above will not work for radio buttons in a ButtonGroup).


text:
Q: Is there a plugin that could replace Filezilla for vim? I'm sick and tired of changing windows all the time just to upload a file. I would like a way to do that fast right from vim. Is there such a thing? I download the files, I edit them and then I want to upload them, all manually, but I don't want to type huge commands to do it each time.
Linux user that likes to do as much as possible from the terminal. That is... everything!

A: I've made one
https://github.com/carlos-cabgj/autodeploy.vim
But It will send your data only when you save using python or pscp and plink

A: Yes, there is hope, and you don't even need to download the files, see netrw:

REMOTE EDITING
    :e dav://machine[:port]/path                  uses cadaver
    :e fetch://[user@]machine/path                uses fetch
    :e ftp://[user@]machine[[:#]port]/path        uses ftp   autodetects <.netrc>
    :e http://[user@]machine/path                 uses http  uses wget
    :e rcp://[user@]machine/path                  uses rcp
    :e rsync://[user@]machine[:port]/path         uses rsync
    :e scp://[user@]machine[[:#]port]/path        uses scp
    :e sftp://[user@]machine/path                 uses sftp

REMOTE READING
    :Nread ?                                      give help
    :Nread "machine:path"                         uses rcp
    :Nread "machine path"                         uses ftp   with <.netrc>
    :Nread "machine id password path"             uses ftp
    :Nread "dav://machine[:port]/path"            uses cadaver
    :Nread "fetch://[user@]machine/path"          uses fetch
    :Nread "ftp://[user@]machine[[:#]port]/path"  uses ftp   autodetects <.netrc>
    :Nread "http://[user@]machine/path"           uses http  uses wget
    :Nread "rcp://[user@]machine/path"            uses rcp
    :Nread "rsync://[user@]machine[:port]/path"   uses rsync
    :Nread "scp://[user@]machine[[:#]port]/path"  uses scp
    :Nread "sftp://[user@]machine/path"           uses sftp

REMOTE WRITING
    :Nwrite ?                                     give help
    :Nwrite "machine:path"                        uses rcp
    :Nwrite "machine path"                        uses ftp   with <.netrc>
    :Nwrite "machine id password path"            uses ftp
    :Nwrite "dav://machine[:port]/path"           uses cadaver
    :Nwrite "ftp://[user@]machine[[:#]port]/path" uses ftp   autodetects <.netrc>
    :Nwrite "rcp://[user@]machine/path"           uses rcp
    :Nwrite "rsync://[user@]machine[:port]/path"  uses rsync
    :Nwrite "scp://[user@]machine[[:#]port]/path" uses scp
    :Nwrite "sftp://[user@]machine/path"          uses sftp

A: I'm not aware of any plugin that works exactly like what you describe. The only FTP plugins I have used is netrw and there's also FTPSync but both seem to be quite far from what you have in mind.
You didn't specify what OS you are using: are you on Windows or Linux? There are a number of very good FTP clients on Mac OS X (like the great Yummy FTP and totally worth the price) with "folder-watchers" that would provide exactly what you want except outside of Vim.
If you are on Linux, this recent thread on reddit may be interesting. Mounting your FTP server is another option.


text:
Q: StartService() doesn't active onStartCommand() function (Manifest is correct) I'm trying to active my service with StartService(), and it should go next to the onStartCommand() function, but it doesn't.
I tried many ways to not use the onStartCommand() function, but I need the information from the Intent in my service.
Here is the code:
MainAcitivty - OnCreate:
    dbHelper = new DBHelper(this);
    listTasks = (ListView)findViewById(R.id.list_todo);

    loadTaskList();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            eventIntent = new Intent(view.getContext(), NewEventActivity.class);
            startActivityForResult(eventIntent, ADD_EVENT_REQUEST);
        }
    });

    Intent serviceIntent = new Intent(this, MyService.class);
    serviceIntent.putExtra("dbHelper", (Parcelable)dbHelper);
    if (!isMyServiceRunning(MyService.class))
    {
        startService(serviceIntent);
    }

}

//gets any service class and check if its alive (running)
private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

MyService:
DBHelper dbHelper;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    startServiceThread();
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Bundle extras = intent.getExtras();
    if (extras != null) {

        dbHelper = (DBHelper)extras.get("dbHelper");
    }
 return super.onStartCommand(intent, flags, startId);
}

Manifest:
(Here i also tried to add the service just with name=".MyService", but it did not change anything)
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:name=".MyApplication">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">

    </activity>
    <activity android:name=".NewEventActivity" />
    <activity android:name=".LockApp">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>
    <service android:name="com.example.user.project.MyService" />
</application>

A:
It is crash in startServiceThread() because it can't get the information from the intent

Then perhaps you should not be starting the thread until onStartCommand().

Anyway, the onStartCommand() does not calls after the startService()

That is because you are crashing on onCreate(). Stop crashing in onCreate(), and you should have better luck with onStartCommand().


text:
Q: Can an Animagus take the form of any animal? Similar to my old question about what animals a Patronus can be, are there any limits to the animal forms an Animagus can be?

*

*We know that the animal form can be much smaller than human (cat, rat, beetle) so I don't think size is a factor.

*I'm not aware of any Animagus who transforms into a magical creature (e.g. unicorn or phoenix) so maybe those aren't possible.
Ultimately, what I'd like to know is whether there could be a T-Rex Animagus... (prompted by a funny comment about difficulty with cut/paste while in animal form)

A: From the existing canon (books, interviews, pottermore till now) the biggest Animagus form we know of was James Potter's stag. (If you go outside canon, JKR claimed - as a jest - that Godric Gryffindor's form was the Giant Squid).
There was never any mention of Animagus form size limitations (clearly you could transform into something bigger as was the case with James, so presumably T-Rex is plausible).
One thing we DO know is that JKR indicated that your Animagus form is NOT something you get to pick and choose and you wouldn't know it before transforming the first time... so you can't simply just pick something "cool".
There was also never any mention of Animagus form being a magical animal. But it's unlikely you will obtain magical powers foreign to you even if you self-Transfigure yourself into the form of a Phoenix or Unicorn.
Wikia lists all known animaguses and their forms.

A: Yes, but some forms are rarer than others

The animal into which one turns, if an Animagus, seems always to be that which becomes the Patronus.
Pottermore - Animagi (behind paywall)

A Patronus can take on the form of any animal, as evidenced by answers to the following questions:
Can a Patronus take the form of any animal?
What different animal forms have Patronuses taken in Harry Potter canon?


text:
Q: How to add changes for NO ENCRYPT DB2 option to db2RestoreStruct I am trying to restore encrypted DB to non-encryped DB. I made changes by setting piDbEncOpts to SQL_ENCRYPT_DB_NO but still restore is being failed. Is there db2 sample code is there where I can check how to set "NO Encrypt" option in DB2. I am adding with below code snippet.
db2RestoreStruct->piDbEncOpts->encryptDb = SQL_ENCRYPT_DB_NO

A: The 'C' API named db2Restore will restore an encrypted-image to a unencrypted database , when used correctly.
You can use a modified version of IBM's samples files: dbrestore.sqc and related files, to see how to do it.
Depending on your 'C' compiler version and settings you might get a lot of warnings from IBM's code, because IBM does not appear to maintain the code of their samples as the years pass. However, you do not need to run IBM's sample code, you can study it to understand how to fix your own C code.
If installed, the samples component must match your Db2-server version+fixpack , and you must use the C include files that come with your Db2-server version+fixpack to get the relevant definitions.
The modifications to IBM's samples code include:

*

*When using the db2Restore API ensure its first argument has a value that is compatible with your server Db2-version-and-fixpack to access the required functionality. If you specify the wrong version number for the first argument, for example a version of Db2 that did not support this functionality, then the API will fail. For example, on my Db2-LUW v11.1.4.6, I used the predefined db2Version1113 , like this:
 db2Restore(db2Version1113, &restoreStruct, &sqlca);

*When setting the restore iOptions field: enable the flag DB2RESTORE_NOENCRYPT, for example, in IBM's example, include the additional flag: restoreStruct.iOptions = DB2RESTORE_OFFLINE | DB2RESTORE_DB | DB2RESTORE_NODATALINK | DB2RESTORE_NOROLLFWD | DB2RESTORE_NOENCRYPT;

*Ensure the restoredDbAlias differs from the encrypted-backup alias name.
I tested with Db2 v11.1.4.6 (db2Version1113 in the API) with gcc 9.3.
I also tested with Db2 v11.5 (db2Version11500 in the API) with gcc 9.3.


text:
Q: 'Stop Further Rules From Processing' doesn't work as expected Basically I have 2 shopping cart rules and I only want one to be applied at any one time.
My first shopping cart rule is a discount code that gives you 10% discount on products in your cart that are in a certain category.
And my second is a little more complex as it gives you 100% discount on a product when a differnet product is added to your cart. For example, if you have a t-shirt and a hat in your cart, then you get the hat for free.
So at the moment when I have the t-shirt and hat in the cart at the same time, I get a discount of £6.00 (which is the price of the hat).
Then when I enter the coupon code, I get a further 10% off. So if my t-shirt was £10 and the hat was £6, The total to be paid would be £9.
I need it so that only one of these rules can be applied at any one time, I don't mind how it works, just as long as customers cannot take advantage of this issue.
I have heard that this is something to do with the priorities of the rules, but I have spent a few hours playing around with different settings but cannot get this to work.
I've attached some screenshots of my rule settings, hopefully they will give you a better idea of what's going on.
Thank you

A: *

*Rules are applied in priority low to high (0 -> 1000)

*Stop further rules: YES means, process THIS rule and then stop.

So if I understand you correctly, you want only one rule processed, so either discount on the hat or on the shirt.
Give the 100% hat discount priority 100 and the shirt priority 200, at least the hat Stop further processing: YES
So if the hat rule is processed it is stopped.
The priorities 100 and 200 are to have space between to add more rules, 1 and 2 would work either.


text:
Q: IIS_WPG (and IIS_IUSRS) member of "Authenticated Users" group? I need a confirmation that IIS_WPG and the newer one IIS_IUSRS are also members of the "Authenticated Users" group. Can someone confirm this or am I wrong?

A: The IIS_WPG user is a the IIS Worker Process Group, and is needed in order for IIS to run / access applciations within a folder
The IIS_IUSRS is a the Internet Guest Account, this is used to allow anonynous access to the folder / files. This is needed if you want the general public to be able to view anything in the folders e.g. a website.
They are not norally part of the "Authenticated Users" group and normally require you to grant access seperatly.


text:
Q: Rearrange data in pgfplotstable I have a \pgfplotstable with data (loaded from a file) like this one:
\pgfplotstableread{
  s       f
  0.0     95.9638
  0.2380665    160.565
  0.511     190.435
  0.705    270.435
  1.0         455.9638
}\data

I need to generate this \pgfplotstable rearranging rows and columns of \data:
\pgfplotstableread{
  s       f
  1.0         270.435
  0.705    190.435
  0.511     160.565
  0.2380665    95.9638
  0.0     <95.9638 or any other value>
}\customdata

The rows are in inverted order and the second column displaced 1 element above.
Any advice, please?

A: You can do this a bit simpler by using inbuilt methods to reverse the order and create a new column that contains the shifted values:
\documentclass{article}
\usepackage{pgfplotstable}
\usepackage{pgfplots}
\begin{document}
\pgfplotstableread{
  s       f
  0.0     95.9638
  0.2380665    160.565
  0.511     190.435
  0.705    270.435
  1.0         455.9638
}\originaldata

\pgfplotstablegetcolumnnamebyindex{1}\of{\originaldata}\to{\secondcolumnname}

\pgfplotstablesort[sort cmp=float >]{\data}{\originaldata}

\pgfplotstableset{
    create on use/shifted/.style={
    create col/expr={\nextrow{\secondcolumnname}*1}}
}

\pgfplotstabletypeset{\originaldata}\hspace*{1cm}
\pgfplotstabletypeset[columns={[index]0,shifted},
    columns/shifted/.style={column name=\secondcolumnname}]\data

\begin{tikzpicture}
\begin{axis}
\addplot table {\originaldata};
\addplot table [y=shifted] {\data};
\end{axis}
\end{tikzpicture}
\end{document}

A: I did it!
\pgfplotstablegetcolumnnamebyindex{0}\of{\data}\to{\firstcolumnname}
\pgfplotstablegetcolumnnamebyindex{1}\of{\data}\to{\secondcolumnname}

\pgfplotstablegetrowsof{\data}
\pgfmathsetmacro\ymax{\pgfmathresult - 1}

\pgfplotstablevertcat{\customdata}{\data};

\pgfplotstablemodifyeachcolumnelement\firstcolumnname\of\customdata\as\cell{
  \pgfmathsetmacro\newrow{\ymax - \pgfplotstablerow}
  \pgfplotstablegetelem{\newrow}{\firstcolumnname}\of\data
  \edef\cell{\pgfplotsretval}
}

\pgfplotstablemodifyeachcolumnelement\secondcolumnname\of\customdata\as\cell{
  \ifnum \pgfplotstablerow < \ymax
    \pgfmathsetmacro\filaant{\ymax - \pgfplotstablerow - 1}
    \pgfplotstablegetelem{\newrow}{\secondcolumnname}\of\data
    \edef\cell{\pgfplotsretval}
  \fi
}


text:
Q: how to add second border to responsive textarea? i'm using twitter bootstrap 3.2.0
here is code:
jsFiddle

.textarea textarea {
  background-color: white;
  background-image: url("http://ello.96.lt/images/as.jpg");
  line-height: 1.56em;
  padding-left: 4.2em;
  padding-right: 0.3em;
  border: solid 1px #525252;
}

      Please leave some of yours contact details below
      <textarea id="email_comment" class="form-control" style="color: #424242 !important;" placeholder="Press here with mouse to edit and start writing a letter for me" rows="14"></textarea>

    <button id="submit" type="button" class="btn btn-sunny text-uppercase btn-lg">Send</button>

i want to do this:
http://jsfiddle.net/bluetidepro/3Rdqy/
http://bookofzeus.com/articles/css/css-styling-textarea-give-notebook-notepad-look/
there is double border in left and bottom.
i really want to add these 2 borders to my textarea. i tryed a lot of ways, but still doesnt work

A: I've added a wrapper element around your textarea, and then used a pseudo element to make the narrower border on the bottom.

.textarea textarea {
  background-color: white;
  background-image: url("http://ello.96.lt/images/as.jpg");
  line-height: 1.56em;
  padding-left: 4.2em;
  padding-right: 0.3em;
  border: solid 1px #525252;
}
.jbutler483 {
  position: relative;
  display: inline-block;
}
.jbutler483:before {
  content: "";
  position: absolute;
  bottom: -1px;
  right: 1px;
  width: 100%;
  background-image: url("http://ello.96.lt/images/as.jpg");
  height: calc(100% - 4px);
  z-index: -1;
  border: 2px solid gray;
}

      Please leave some of yours contact details below

        <textarea id="email_comment" class="form-control" style="color: #424242 !important;" placeholder="Press here with mouse to edit and start writing a letter for me" rows="14"></textarea>

    <button id="submit" type="button" class="btn btn-sunny text-uppercase btn-lg">Send</button>

A: .textarea {
position: relative;
}
.textarea:after{
    content:'';
    position:absolute;
    width: 100%;
    bottom: 10px;
    left: 0;
    border-bottom: 1px solid #F8D3D3;
}

that will make a red border bellow the textarea. Attach your :before and :after on a block element (div) not on the textarea (maybe that's what you tried and did not work). I also suggest that you put a div around the textarea itself, with width: auto, so that your border will scale with your textarea, not the .textarea div that also contains the label.

A: Just add this css
.textarea textarea {
    background-color: white;
    background-image: url("http://ello.96.lt/images/as.jpg");
    line-height: 200%;
    padding-left: 75px;
    padding-right: 0.3em;
    border: solid 1px #525252;
}

Check This DEMO