text:
Q: Unzip Password-protected files I am trying to extract files from a password-protected zip, in a USB drive, using PowerShell. I have looked up many ways but the easiest one doesn't seem to work.
$7ZipPath = "C:\Program Files\7-Zip\7z.exe"
$zipFile = "E:\passwordprotectedtest.zip"
$zipFilePassword = "Foo"

& $7ZipPath e -oE:\ -y -tzip -p "$zipFilePassword" "$zipFile"

I keep getting this error:
7-Zip 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18

Error
Cannot use absolute pathnames for this command

I then moved to the file to my desktop, changed $zipFile = "passwordprotectedtest.zip", changed -oE:\ to -oC:\.
That fixed the pathname error but started getting this error instead
7-Zip 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18

Error
Cannot find archive

A: Try this way:
$7ZipPath = '"C:\Program Files\7-Zip\7z.exe"'
$zipFile = '"e:\passwordprotectedtest.zip"'
$zipFilePassword = "Foo"
$command = "& $7ZipPath e -oe:\ -y -tzip -p$zipFilePassword $zipFile"
iex $command


text:
Q: expression for mysql 5.7 virtual column mysql table has columns order-id, order-item-id. Need to create a expression for generated column (new feature on 5.7) please have a look at the image for v virtual generated column look at the image for easy understanding. Tablename is daily-orders

A: Due to limitations on generated columns, you cannot create an expression that contains subqueries:

Subqueries, parameters, variables, stored functions, and user-defined functions are not permitted.

Since you would like to obtain information on data in multiple records, you have to use a subquery and that is not permitted. However, you can create a view instead of a generated column that contains this additional data. The following sql statement could form the core of such view:
select d1.*, d2.NumberOfItems
from dailyorders d1
inner join (select orderid, count(*) as NumberOfItems from dailyorders group by orderid) d2
on d1.orderid=d2.orderid

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Image Caching I am having a problem with php image caching. I have already posted this on the authors issue page, however it isn't active.
Web server:  NGINX
PHP Version: 5.5.9-1ubuntu4.14
I am getting this error Final image URL is broken. The page looks like this

There should be 100 images displayed but it dies at the third.
The page should look something similar to this (this is the localhost design)

It is returning this URL

There should be a / between the mediapage.zips.me and core, however it is a local image so I don't see why it should even need the host name.
How I am doing this is,
On the top of each page I am calling another page which contains the setup of the class
<?php
    //Calls the php-image things
    include 'test.php';

?>

Inside test.php
<?php
    require_once 'core/classes/ImageCache.php';
    $imagecache = new ImageCache();
?>

Image page
<?php
    //Directory NON-CACHED images are stored in
    $dir    =   "i/";

    //Array of files in the Directory
    $files1 =   scandir($dir);
    //Used to limit results (100's of images)
    $count = 0;
    foreach ($files1 as $key) {
        //If the file name is longer than 3 chars and the count is less
        //than the amount of images I want displayed.
        if (strlen($key) > 3 && $count <= 100){
            $count++;
            //dir2 is the directory/nameofFile.extension
            //Eg: i/testImage.png
            $dir2   =   $dir.''.$key;
            $info = new SplFileInfo($key);
            //Image Cache variable
            $cached_src = $imagecache->cache($dir2);
?>

            <a href="<?php echo $dir2;?>" data-popup="lightbox">

                <img src="<?php echo $cached_src;?>" alt="<?php echo $key;?>" class="img-rounded img-preview">

<?php
        } //End If
    } //End for
?>

I have tried adding a / to the directory name $dir but it says that it cant find the directory when I do that.

A:
        <a href="<?php echo $dir2; ?>" data-popup="lightbox">

            <img src="/<?php echo $cached_src; ?>" alt="<?php echo $key; ?>" class="img-rounded img-preview">

This should work by simpling prepending a slash before the $cached_src.

A: I would take a look at ImageCache github page for reference.  If the cached image doesn't exist yet, the script will use $_SERVER['HTTP_HOST']. So verify what is in that. It looks like if your $_SERVER['HTTP_HOST'] doesn't end with a slash, then your url won't have one.


text:
Q: How to split CSVs from one column to rows in a new table in MSSQL 2008 R2 Imagine the following (very bad) table design in MSSQL2008R2:
Table "Posts":
| Id (PK, int) | DatasourceId (PK, int) | QuotedPostIds (nvarchar(255)) | [...]
|     1        |        1               |                               | [...]
|     2        |        1               |           1                   | [...]
|     2        |        2               |           1                   | [...]
[...]
|   102322     |        2               |     123;45345;4356;76757      | [...]

So, the column QuotedPostIds contains a semicolon-separated list of self-referencing PostIds (Kids, don't do that at home!). Since this design is ugly as a hell, I'd like to extract the values from the QuotedPostIds table to a new n:m relationship table like this:
Desired new table "QuotedPosts":
| QuotingPostId (int) | QuotedPostId (int) | DatasourceId (int) |
|        2            |        1           |         1          |
|        2            |        1           |         2          |
[...]
|      102322         |       123          |         2          |
|      102322         |      45345         |         2          |
|      102322         |       4356         |         2          |
|      102322         |      76757         |         2          |

The primary key for this table could either be a combination of QuotingPostId, QuotedPostId and DatasourceID or an additional artificial key generated by the database.
It is worth noticing that the current Posts table contains about 6,300,000 rows but only about 285,000 of those have a value set in the QuotedPostIds column. Therefore, it might be a good idea to pre-filter those rows. In any case, I'd like to perform the normalization using internal MSSQL functionality only, if possible.
I already read other posts regarding this topic which mostly dealt with split functions but neither could I find out how exactly to create the new table and also copying the appropriate value from the Datasource column, nor how to filter the rows to touch accordingly.
Thank you!
€dit: I thought it through and finally solved the problem using an external C# program instead of internal MSSQL functionality. Since it seems that it could have been done using Mikael Eriksson's suggestion, I will mark his post as an answer.

A: From comments you say you have a string split function that you you don't know how to use with a table.
The answer is to use cross apply something like this.
select P.Id,
       S.Value
from Posts as P
  cross apply dbo.Split(';', P.QuotedPostIds) as S


text:
Q: Laravel 5 Controller Not working I am using Laravel 5 and doing something like this-
app\Http\routes.php
Route::get('test','DashboardController@delete_a_entry');

app\Http\Controllers\DashboardController.php
<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
    public function showProfile($id)
    {
        return view('layouts.customer.dashboard');
    }
}

resources/views/layouts/customer/dashboard
<!DOCTYPE html>

<title>Page Title</title>

This is a Heading

This is a paragraph.

But getting this error

What am I doing wrong?

A: As the error says, the method does not exist.
Laravel is trying to find the method delete_a_entry when accessing in GET http://localhost/test/
I don't see this method in your controller, only a showProfile-method.

A: You should have a method named delete_a_entry, like:
<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
    public function showProfile($id)
    {
        return view('layouts.customer.dashboard');
    }

    public function delete_a_entry($id)
    {
        return 'some stuff';
    }
}

A: just add this to your controller :
     public function delete_a_entry($id)
    {

 //here add you code to delete the entry
        return true;
    }

A: This error occurred because DashboardController doesn't have any delete_a_entry function.
You can fix this in two ways.
Option 1. Remove route
Route::get('test','DashboardController@delete_a_entry');

Option 2. Add this function to DashboardController
public function delete_a_entry()
{
    return 'some stuff';
}


text:
Q: Wrong UITapGestureRecognizer being called (in the wrong UIView) I've got a ViewController which contains a vertical UIScrollView. To said UIScrollView I add multiple subviews, each of which contains a horizontal UIScrollView which contains some images and is paged.
When creating these subviews, I add a UITapGestureRecognizer to their UIScrollViews to detect single taps on them and perform an action depending on which image was being displayed.
The problem I've got is that if I have 2 such subviews and tap the first one in line, it picks up the wrong subview and tries to fire the method on the second one. So, say I tapped the 3rd image of the 1st subview, and the 2nd subview only has 1 page, then the app crashes.
Here's the constructor for my subview:
- (id)init {

    NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"GalleryLeafView"
                                                      owner:nil
                                                    options:nil];
    GalleryLeafView *galleryLeafView = [arrayOfViews objectAtIndex:0];
    self = galleryLeafView;

    if (self) {

        // Set up tap gesture recognizers on the ScrollView
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped)];
        tapGestureRecognizer.numberOfTapsRequired = 1;
        [self.scrollView addGestureRecognizer:tapGestureRecognizer];
    }

    return self;
}

Here's the selector method, just in case:
- (void)imageTapped {

    NSString *filename = [imageFilenames objectAtIndex:[self getCurrentPage]];
    NSString *caption = [captions objectAtIndex:[self getCurrentPage]];

    [self.galleryLeafViewDelegate galleryLeafViewPressedWithFilename:filename caption:caption];
}

Any ideas as to why this happens? Or how I can work around this?

A: Ok, this was a yet another of my rookie mistakes ;/
In the selector method you can see I'm doing stuff on imageFilenames and captions arrays. They should've been strong properties, not just variables set in the .m file. Everything works fine now.


text:
Q: How to make assertions on nested fields with newman response
{
   user: {
          id: 1000
    }

I can make an assertion on the user key
pm.expect(response).to.have.key("user")

How do I make an assertion that id is there?
I tried this and it doesn't work:
pm.expect(response.user).to.have.key("user")

A: Use this:
pm.expect(response.user).to.have.property('id')


text:
Q: Sphinx indexes datetime field incorrectly I am running a PostgreSQL database. I have a table with a field of timestamp without time zone type.
I index this table with Sphinx, here is the part of my config.txt:
source ad: base
{
sql_query_range = SELECT MIN(id), MAX(id) FROM ad
sql_range_step = 1000
sql_query =\
    SELECT ad.id, \
           ad.title, \
           ad.category, \
           ad.subcategory, \
           ad.price, \
           ad.currency, \
           ad.url, \
           ad.photo_urls, \
           ad.city AS location, \
           ad.ad_id, \
           ad.date \
    FROM ad \
    WHERE ad.id BETWEEN $start AND $end

sql_field_string = title
sql_attr_uint = category
sql_attr_uint = subcategory
sql_attr_uint = location
sql_attr_uint = price
sql_attr_string = url
sql_attr_string = ad_id
sql_attr_string = photo_urls
sql_attr_multi = uint filtr from query; \
        SELECT ad_id, filter_value_id \
        from ad_filter_value_list
sql_attr_timestamp = date
}

But in the indexed table the field date contains only the value of the year, i.e. "2015", not the full date. Where can be the mistake?

A: Sphinxes timestamp attribute type is an (unsigned) integer. Really its no different to sql_attr_uint in function.
Its intended for working with a unix-timestamp which is a plain integer.
In mysql there is a UNIX_TIMESTAMP() function to convert the native datetype to a unix-timestamp. Hopefully PostgreSQL has something similer. Looks like extract() function?
https://dba.stackexchange.com/questions/2796/how-do-i-get-the-current-unix-timestamp-from-postgresql


text:
Q: Does it make sense to speak in a total derivative of a functional? Part III In this third part of the series, I will continue the deduction of Noether's theorem initiated in the previous post - Does it make sense to speak in a total derivative of a functional? Part II.
Situation 1
Here, I will consider the validity of the total derivative
\begin{equation}
\frac{d\mathcal{L}}{dx^{μ}}
=\frac{\partial\mathcal{L}}{\partialφ_{r}}\partial_{\mu}φ_{r}+\frac{\partial\mathcal{L}}{\partial\big(\partial_{ν}φ_{r}\big)}\partial_{\mu}\big(\partial_{ν}φ_{r}\big)+∂_{μ}\mathcal{L}.\tag{III.1}\label{eq1}
\end{equation}
We have expressed in Eq. (\ref{eq24}) of the previous post (Does it make sense to speak in a total derivative of a functional? Part II) that
\begin{multline}
\dfrac{S^{\prime}-S}{\varepsilon} \approx \int_{\mathbb{\Omega}}d^{D}x~\left\{
\dfrac{\partial\mathcal{L}}{\partial\phi_{r}}\zeta_{r} + \dfrac{\partial
\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\partial_{\nu}\zeta_{r}\right. \\ \left. + \xi^{\mu
}\left(  \dfrac{\partial\mathcal{L}}{\partial\phi_{r}}\partial_{\mu}\phi
_{r}+\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\partial_{\mu
}\partial_{\nu}\phi_{r}+\partial_{\mu}\mathcal{L}\right)  +\partial_{\mu}%
\xi^{\mu}\mathcal{L}\right\}, \tag{II. 24}\label{eq24}%
\end{multline}
where I'd like to remember that $\zeta_r\equiv\zeta_r(x)$ and $\xi^{\mu}\equiv\xi^{\mu}(x)$.
If what we ask about Eq. (I.$9$) in the first post of this Series (Does it make sense to speak in a total derivative of a functional? Part I) has a yes as an answer, then the following identifications must be valid:
\begin{equation}
\frac{d\zeta_{r}}{dx^{\mu}}=\partial_{\mu}\zeta_{r} \quad\text{and}\quad \frac{d\xi^{\mu}}{dx^{\mu}}=\partial_{\mu}\xi^{\mu}.\tag{III.2}
\end{equation}
 Thus, the Eq. (\ref{eq24}) becomes
\begin{equation}
\dfrac{S^{\prime}-S}{\varepsilon}\approx\int_{\mathbb{\Omega}}d^{D}x~\left\{
\dfrac{\partial\mathcal{L}}{\partial\phi_{r}}\zeta_{r}+\dfrac{\partial
\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\dfrac{d\zeta_{r}}{dx^{\nu}}
+\xi^{\mu}\dfrac{d\mathcal{L}}{dx^{\mu}}+\mathcal{L}\dfrac{d\xi^{\mu}}
{dx^{\mu}}\right\}.\tag{III.3}\label{eq3}
\end{equation}
Now, we do use of identity
\begin{equation}
\dfrac{\partial\mathcal{L}}{\partial\partial_{\mu}\phi_{r}} \dfrac{d\zeta_{r}}{dx^{\mu}}=\frac{d}{dx^{\mu}}\left(\zeta_{r}\frac{\partial\mathcal{L}
}{\partial\partial_{\mu}\phi_{r}}\right)-\zeta_{r}\frac{d}{dx^{\mu}}\frac{\partial\mathcal{L}}{\partial\partial_{\mu}\phi_{r}},\tag{III.4}\label{eq4}
\end{equation}
such that
\begin{equation}
\dfrac{S^{\prime}-S}{\varepsilon}\approx\int_{\mathbb{\Omega}}d^{D}x~\left\{
\left(\dfrac{\partial\mathcal{L}}{\partial\phi_{r}}-\dfrac{d}{dx^{\nu} }\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\right)  \zeta
_{r}+\dfrac{d}{dx^{\nu}}\left(  \zeta_{r}\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}+\xi^{\mu}\mathcal{L}\right)  \right\},\tag{III.5}\label{eq5}
\end{equation}
where we have used
\begin{equation}
\xi^{\mu}\dfrac{d\mathcal{L}}{dx^{\mu}}+\mathcal{L}\dfrac{d\xi^{\mu}}{dx^{\mu
}}=\dfrac{d}{dx^{\mu}}\left(  \xi^{\mu}\mathcal{L}\right).
\end{equation}
We have to said in Does it make sense to speak in a total derivative of a functional? Part II, Eq.(\ref{II19}), that
\begin{equation}
\zeta_{r}\left(  x\right)  +\xi^{\mu
}\left(  x\right)  \partial_{\mu}\phi_{r}\left(  x\right)
=\dfrac{\tilde{\delta}\phi_{r}}{\varepsilon}=\chi_{r}\left(  x\right) ,\tag{II.19}\label{II19}
\end{equation}
so that (\ref{eq5}) becomes
\begin{multline}
\dfrac{S^{\prime}-S}{\varepsilon}\approx\int_{\mathbb{\Omega}}d^{D}x~\left(
\dfrac{\partial\mathcal{L}}{\partial\phi_{r}}-\dfrac{d}{dx^{\nu}}
\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\right)  \zeta
_{r}\\ +\int_{\mathbb{\Omega}}d^{D}x~\dfrac{d}{dx^{\mu}}\left[  \dfrac
{\partial\mathcal{L}}{\partial\partial_{\mu}\phi_{r}}\chi_{r}-\left(
\dfrac{\partial\mathcal{L}}{\partial\partial_{\mu}\phi_{r}}\partial_{\nu}
\phi_{r}-\delta_{\nu}^{\mu}\mathcal{L}\right)  \xi^{\nu}\right].\tag{III.6}\label{eq6}
\end{multline}
And now comes the question: how can we apply the generalized divergence theorem in the second integral on the right side-hand if instead of a partial derivative we have a total derivative?
Situation 2
Before asking the question, let's see what happens if we do not use Eq. (\ref{eq1}). In this case, we can rewrite the Eq. (\ref{eq24}) as:
\begin{equation}
\dfrac{S^{\prime}-S}{\varepsilon}\approx\int_{\mathbb{\Omega}}d^{D}x~\left\{
\dfrac{\partial\mathcal{L}}{\partial\phi_{r}}\chi_{r}+\dfrac{\partial
\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\left(  \partial_{\nu}\zeta
_{r}+\xi^{\mu}\partial_{\mu}\partial_{\nu}\phi_{r}\right)  +\partial_{\nu
}\left(  \xi^{\nu}\mathcal{L}\right)  \right\},\tag{III.7}\label{eq7}
\end{equation}
where we have used (\ref{II19}).
If we add and subtract the term $\partial_{\mu}
\phi_{r}\partial_{\nu}\xi^{\mu}$ in the expression in parentheses of the second term, that last equation becomes
\begin{equation}
\dfrac{S^{\prime}-S}{\varepsilon}\approx\int_{\mathbb{\Omega}}d^{D}x~\left\{
\dfrac{\partial\mathcal{L}}{\partial\phi_{r}}\chi_{r}+\dfrac{\partial
\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\partial_{\nu}\chi_{r}
-\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\partial_{\mu}
\phi_{r}\partial_{\nu}\xi^{\mu}+\partial_{\nu}\left(  \xi^{\nu}\mathcal{L}
\right)  \right\}.\tag{III.8}
\end{equation}
Now, using the identities
\begin{align}
\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\partial_{\nu}
\chi_{r}&=\partial_{\nu}\left(  \chi_{r}\dfrac{\partial\mathcal{L}}
{\partial\partial_{\nu}\phi_{r}}\right)  -\chi_{r}\partial_{\nu}
\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}},\tag{III.9}\label{eq9}\\
-\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\partial_{\mu}
\phi_{r}\partial_{\nu}\xi^{\mu}&=-\partial_{\nu}\left(  \dfrac{\partial
\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\partial_{\mu}\phi_{r}\xi^{\mu
}\right)  +\xi^{\mu}\partial_{\nu}\left(  \dfrac{\partial\mathcal{L}}
{\partial\partial_{\nu}\phi_{r}}\partial_{\mu}\phi_{r}\right),\tag{III.10}\label{eq10}
\end{align}
we obtain
\begin{multline}
\dfrac{S^{\prime}-S}{\varepsilon}\approx\int_{\mathbb{\Omega}
}d^{D}x~\xi^{\mu}\partial_{\nu}\left(  \dfrac{\partial\mathcal{L}}
{\partial\partial_{\nu}\phi_{r}}\partial_{\mu}\phi_{r}\right)+\int_{\mathbb{\Omega}}d^{D}x~\left(
\dfrac{\partial\mathcal{L}}{\partial\phi_{r}}-\partial_{\nu}\dfrac
{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\right)  \chi_{r}
\\+ \int_{\mathbb{\Omega}}d^{D}x~\partial_{\nu}\left[  \dfrac{\partial
\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\chi_{r}-\left(  \dfrac
{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\partial_{\mu}\phi
_{r}-\xi^{\nu}\mathcal{L}\right)  \xi^{\mu}\right].\tag{III.11}\label{eq11}
\end{multline}
Here, considering the validity of Euler-Lagrange's equation
\begin{equation}
\dfrac{\partial\mathcal{L}}{\partial\phi_{r}}-\partial_{\nu}\dfrac
{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}=0, \tag{III.12}\label{eq12}
\end{equation}
and the applicability of divergence theorem over to third integral (Which now seems to be quite reasonable!)
\begin{equation}
\int_{\mathbb{\Omega}}d^{D}x~\partial_{\nu}J^{\nu}=\oint_{\partial
\mathbb{\Omega}}dS_{\nu}~J^{\nu}=0,\tag{III.13}\label{eq13}
\end{equation}
with
\begin{equation}
J^{\nu}=\dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}}\chi
_{r}-\left(  \dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}\phi_{r}
}\partial_{\mu}\phi_{r}-\delta_{\mu}^{\nu}\mathcal{L}\right)  \xi^{\mu},\tag{III.14}\label{eq14}
\end{equation}
when $\varepsilon\rightarrow 0$, we have found
\begin{equation}
\lim_{\varepsilon\rightarrow 0} \dfrac{S^{\prime}-S}{\varepsilon}\approx\int_{\mathbb{\Omega}}d^{D}x~\xi^{\mu
}\partial_{\nu}\left(  \dfrac{\partial\mathcal{L}}{\partial\partial_{\nu}
\phi_{r}}\partial_{\mu}\phi_{r}\right),\tag{III.15}\label{eq15}
\end{equation}
which at first seems to be non-zero.
As we know, it is hoped that
\begin{equation}
\lim_{\varepsilon\rightarrow 0} \dfrac{S^{\prime}-S}{\varepsilon}\approx 0.\tag{III.16}\label{eq16}
\end{equation}
Questions
We have, therefore, two questions:

*

*In the situation (1), when we use the total derivative (\ref{eq1}), the divergence theorem seems nonapplicable over the second integral of the Eq. (\ref{eq6}), so the question is: Is it still possible to apply the divergence theorem the second integral (Eq.(\ref{eq6}))?

*In the situation (2), when we do not use the total derivative, we have a remaining term that is apparently is not null. The question is: Could this term become null? What does it really represent?
Of course, I am considering a possibility of that I have committed some mistake in all the way follow at here, but, at the point of view mathematical, all my calculations seem to be correct. I would be very grateful if anyone could see something besides what I have seen.

A: Concerning situation 1, the main point seems to be that the generalized divergence theorem works with total derivatives, not partial derivatives.

A: According to the conclusions obtained from Part II, we have concluded that situation 1 is, in fact, the correct situation and there, in the second integral of equation \eqref{eq6}, it is valid to make use of the divergence theorem, since it is a total partial derivative.


text:
Q: List all files in resources directory in java project I want to list all files in resources classpath ,I used the following code but get null exception in fList

 String path = request.getSession().getServletContext().getRealPath("/resources/rules");
    File directory = new File(path);
    File[] fList = directory.listFiles();
    for (File file : fList){
        if (file.isFile()){
            System.out.println(file.getName());
        }
    }

A: Here is a working example:
https://github.com/bleujin/aradon/blob/master/src/net/ion/nradon/helpers/ClassloaderResourceHelper.java#L30
public static Iterable<FileEntry> listFilesRelativeToClass(Class<?> clazz, String subdirectory) throws IOException {
    ArrayList<FileEntry> list = new ArrayList<FileEntry>();
    CodeSource src = clazz.getProtectionDomain().getCodeSource();
    if (src == null) {
        return list;
    }
    URL classpathEntry = src.getLocation();
    try {
        // Check if we're loaded from a folder
        File file = new File(new File(classpathEntry.toURI()), subdirectory);
        if (file.isDirectory()) {
            return fileEntriesFor(file.listFiles());
        }
    } catch (URISyntaxException e) {
        // Should never happen, because we know classpathentry is valid
        throw new RuntimeException(e);
    }

    // We're not in a folder, so we must be in a jar or similar
    subdirectory = subdirectory.replace(File.separatorChar, '/');
    if (!subdirectory.endsWith("/")) {
        subdirectory = subdirectory + "/";
    }

    ZipInputStream jarStream = new ZipInputStream(classpathEntry.openStream());
    ZipEntry zipEntry;
    while ((zipEntry = jarStream.getNextEntry()) != null) {
        if (isChild(subdirectory, zipEntry.getName())) {
            String basename = zipEntry.getName().substring(subdirectory.length());
            int indexOfSlash = basename.indexOf('/');
            if (indexOfSlash < 0 || indexOfSlash == basename.length() - 1) {
                list.add(new FileEntry(basename));
            }
        }
    }
    return list;
}

private static boolean isChild(String parent, String name) {
    return name.startsWith(parent);
}

public static Iterable<FileEntry> fileEntriesFor(File[] files) {
    List<FileEntry> fileEntries = new ArrayList<FileEntry>(files.length);
    for (File file : files) {
        String filename = file.getName();
        if (file.isDirectory()) {
            filename += "/";
        }
        fileEntries.add(new FileEntry(filename));
    }
    return fileEntries;
}

}

A: How about this source code?
 String[] resoures = srcDir.list( new java.io.FilenameFilter()
        {
            public boolean accept( File dir, String name )
            {
                String[] extensions = { ".png", ".jar", ".txt" };
                String fileName = name.toLowerCase( Locale.getDefault() );
                for ( int i = 0; i < extensions.length; i++ )
                {
                    if ( fileName.endsWith( extensions[i] ) )
                    {
                        return true;
                    }
                }
                return false;

            }
        } );

Full source here:
http://code.openhub.net/file?fid=kpl9VrAT-CHXE496rmMP8Jbzo5U&cid=y9kXCqEmUoY&s=List%20all%20files%20in%20resoures%20directory%20in%20java%20project&pp=0&fl=Java&ff=1&projSelected=false&filterChecked,=true&mp,=1&mp=1&ml=1&me=1&md=1#L64


text:
Q: Gmail-like ListView with checkboxes (and using the ActionBar) I'm trying to recreate what Google did with the ListView in the Gmail app. In particular, I would like to have each list item include a CheckBox and two TextViews (one on top of the other). I need listeners for when the CheckBox is checked (or clicked) and when anywhere else on the list item is clicked. Lastly, I'd like the ActionBar to reflect that items are selected and provide options like Select All, Select None, etc (see this screenshot).

So far, here's the layout I came up with.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <CheckBox android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal" />

    <LinearLayout android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="6dp"
        android:focusable="true"
        android:clickable="true" >

        <TextView android:id="@+id/titleTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="16sp" />

        <TextView android:id="@+id/dateTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="12sp" />

    </LinearLayout>

</LinearLayout>

This displays everything properly, but I need pointers on how to set up the listeners for the two Views (@+id/checkBox and @+id/linearLayout1). I have looked at the List16 API demo, but they're using the simple_list_item_activated_1 layout and I'm not sure what the XML for that looks like. As their code suggests, I created a ModeCallback class that implements ListView.MultiChoiceModeListener and I set the ListView's choice mode to CHOICE_MODE_MULTIPLE_MODAL, but I don't know how to get the CheckBox in my layout to work with this.
Has anyone successfully copied the Gmail app's ListView behavior? I've searched quite a bit and could not come up with anything (despite several others asking similar questions, like this one - most answers just point back to this same API demo).
Also, for context, I'm loading data from a SQLite database into the list and I've created my own Cursor adapter (which works fine). I have a feeling I need to set up listeners in this class in the newView() and bindView() methods, but everything I've tried hasn't worked.
Any ideas?

A: The mode in the figure is called action mode. If you are using your custom row view and custom adapter, you don't have to use CHOICE_MODE_MULTIPLE_MODAL to start action mode. I tried it once and failed, and I suspect it is used for built-in adapter.
In order to call the action mode by yourself in your code, call method startActionMode in any listener method of any of your view, let it be checkbox, textview or something like that. You then pass the ModeCallback as parameters into it, and do whatever operation you want to do in ModeCallback class.
I don't think this one would work on pre-3.0 Android though.
Here is a brief example. I have a expandable list activity and would like to call out the action mode menu when user check/uncheck the checkbox, and here is my getChildView method in my custom adapter class:
public View getChildView(int groupPosition, int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater inflater =  (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.childrow, null);
        }
        CheckBox cb = (CheckBox)convertView.findViewById(R.id.row_check);
        cb.setChecked(false);   // Initialize
        cb.setTag(groupPosition + "," + childPosition);
        cb.setFocusable(false); // To make the whole row selectable
        cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String tag = (String)buttonView.getTag();
                String[] pos = tag.split(",");
                if (isChecked) {
                    if (mActionMode == null) mActionMode = startActionMode(mMultipleCallback);
                }
                else {
                    if (mActionMode != null) {  // Only operate when mActionMode is available

                        mActionMode.finish();
                        mActionMode = null;
                    }
                }
            }
        });

        TextView tvTop = (TextView)convertView.findViewById(R.id.row_text_top);
        TextView tvBottom = (TextView)convertView.findViewById(R.id.row_text_bottom);
        tvTop.setText(mChildren.get(groupPosition).get(childPosition));
        tvBottom.setText(mChildrenSize.get(groupPosition).get(childPosition));
        return convertView;
    }

A: In addition tocnbuff410's answer use the following code to update checked items count
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
    ++checkBoxCount;
 } else {
    --checkBoxCount;
 }
...

if (mActionMode != null) {
    mActionMode.setSubtitle(checkBoxCount + " item(s) selected.");
}

I can confirm that following code would not work on checkboxes of custom listviews. However, long press would still work:
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new ModeCallback());

Selecting checkbox on custom ListView would not trigger actionmode. Only inbuilt ListViews e.g. extending ListActivity would automatically do that.

A: This will work in SDK 7 (android 2.1) and higher. (together with SherlockActionBar)
Totaly mimic gmail listbox experience.
I override onTouchEvent so press in the left corner side will activate selection mode;
mutch better then trying to click on the tiny cheackbox.
I override performItemClick so pressing not in the left will act as a Regular press action.
I override setItemChecked so it will update mActionMode as needed.
public class SelectListView extends ListView {

    private SherlockFragmentActivity mActivity;
    ActionMode mActionMode;

      public SelectListView(Context context) {
    this( context, null, 0);
}

public SelectListView(Context context, AttributeSet attrs) {
    this( context, attrs, 0);
}

public SelectListView(Context context, AttributeSet attrs, int defStyle) {
    super( context, attrs, defStyle );
    setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    mActivity = (SherlockFragmentActivity) context;
}

    @Override
    public boolean performItemClick(View view, int position, long id) {
        OnItemClickListener mOnItemClickListener = getOnItemClickListener();
        if (mOnItemClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            if (view != null)
                view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
            mOnItemClickListener.onItemClick(this, view, position, id);
            return true;
        }
        return false;
    }

    boolean mSelectionMode = false;
    int mStartPosition;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        final int action = ev.getAction();
        final int x = (int) ev.getX();
        final int y = (int) ev.getY();

        if (action == MotionEvent.ACTION_DOWN && x < getWidth() / 7) {
            mSelectionMode = true;
            mStartPosition = pointToPosition(x, y);
        }
        if (!mSelectionMode)
            return super.onTouchEvent(ev);
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            break;
        case MotionEvent.ACTION_MOVE:
            if (pointToPosition(x, y) != mStartPosition)
                mSelectionMode = false;
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
        default:
            mSelectionMode = false;
            int mItemPosition = pointToPosition(x, y);
            if (mStartPosition != ListView.INVALID_POSITION)
                setItemChecked(mItemPosition, !isItemChecked(mItemPosition));
        }

        return true;
    }

    @Override
    public void setItemChecked(int position, boolean value) {
        super.setItemChecked(position, value);
        // boolean r = getAdapter().hasStableIds();
        int checkedCount = getCheckItemIds().length;

        if (checkedCount == 0) {
            if (mActionMode != null)
                mActionMode.finish();
            return;
        }
        if (mActionMode == null)
            mActionMode = mActivity.startActionMode(new ModeCallback());

        mActionMode.setTitle(checkedCount + " selected");

    }

    class ModeCallback implements ActionMode.Callback {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {

            menu.add(getResources().getString(R.string.aBar_remove)).setIcon(R.drawable.ic_action_trash)
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return true;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            Toast.makeText(mActivity, "Delted  items", Toast.LENGTH_SHORT).show();
            mode.finish();
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mActionMode = null;
            clearChecked();
        }

    }

    public void clearChecked() {
        SparseBooleanArray CItem = getCheckedItemPositions();
        for (int i = 0; i < CItem.size(); i++)
            if (CItem.valueAt(i))
                super.setItemChecked(CItem.keyAt(i), false);
    }

}

you can use any listbox adapter you need.
if you have a checkbox on your list_item_layout tou need to extent your adapter like this:
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_multiple_choice,
            R.id.text1, Cheeses.sCheeseStrings) {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            CheckBox checkBox = (CheckBox) v.findViewById(R.id.CheckBox);
            checkBox.setChecked(((ListView)parent).isItemChecked(position));
            return v;
        }

    };

Don't forget to use android:background="?attr/activatedBackgroundIndicator" on your list_item_layout.xml


text:
Q: Problema com Jquery UI Slide Left Eu estou a desenvolver um projecto e precisava de saber como dar slide numa div para a esquerda. De momento estou a usar:
$('#idDiv').toggle('slide', { direction: 'left', distance: 450 });

Eu queria que a minha div de 500px de width deslizasse e deixasse 50px à mostra. O problema é que quando ela acaba de dar o slide de 450px ela desaparece. Eu sei que o toggle tem a ver com o hide e show, mas será que existe outra maneira (sem usar o animate para dar resize) de dar slide para a esquerda sem que esta desapareça?
Está aqui um exemplo do que disse.

A: O método .toggle() faz a div aparecer/desaparecer, é melhor usar o método .animate() e animar a margin-left por exemplo. A largura (width) poderia também ser uma alternativa.
Assim para poder fechar e voltar a abrir podes usar uma flag. Uma flag é uma variável útil para saber o estado do elemento.
Neste caso uso-o para guardar informação sobre se está aberto ou fechado. Esta flag no primeiro exemplo é uma variável global, no segundo exemplo está guardada dentro de um campo data do próprio elemento.
Assim a cada clique ele vai verificar com um operador ternário se a flag open tem o valor true ou false e consoante isso retornar "-250px" (caso open for true) ou "0px" (caso open for false):
var open = true;
$(document).click(function () {
  $("#toggle").animate({
    'margin-left': open ? "-250px" : "0px"
  }, 500);
  open = !open;  // mudar a flag para o oposto do que estava usando o operador de negação "!"
});

Exemplo

Outra alternative é ter um campo data no elemento que guarda esta flag sobre estar aberto ou não:
HTML

JS
$(document).click(function () {
  var elemento = $("#toggle");
  elemento.animate({
    'margin-left': elemento.data('open') ? "-250px" : "0px"
  }, 500);

  // mudar a flag para o oposto do que estava usando o operador de negação "!"
  elemento.data('open', !elemento.data('open'));
});

Exemplo

O terceiro exemplo (e talvez melhor) é usando uma classe e transições CSS:
CSS
    #toggle {
        width: 300px;
        height:300px;
        background: #ccc;
        -webkit-transition: margin-left 500ms ease;
        -moz-transition: margin-left 500ms ease;
        -ms-transition: margin-left 500ms ease;
        -o-transition: margin-left 500ms ease;
        transition: margin-left 500ms ease;
    }
    .toggle {
        margin-left: -250px
    }

JS
    $(document).click(function() {
        var $toggle = $("#toggle");
        if ($toggle.hasClass('toggle')) $toggle.removeClass('toggle');
        else $toggle.addClass('toggle');
    });

Exemplo

A: Eu nao estou muito dentro de jQuery e preciso de explicar o codigo quando for fazer a apresentação do meu projecto (PAP) e a maneira que arranjei de solucionar o problema foi:
$(" #sideBarE ").click(function(e)
        {
            var divE = $('#empresas');
            var marginE = divE.css('margin-left');
            //alert(marginE);
            if (marginE == "0px")
                $('#empresas').animate({'margin-left':"-400px"}, 1000);
            else
                $('#empresas').animate({'margin-left':"0px"}, 1000);
            e.stopPropagation();
        });

A: Tu sabe que da pra fazer isso com o translate nas transitions e animations do css ??


text:
Q: arabic in english file in LaTex I want to add an Arabic paragraph in an English LaTex file
I tried using
\usepackage[utf8]{inputenc}
\usepackage{arabtex}
\usepackage[arabic]{babel}

\begin{document}

\end{document}

But when I write the Arabic text it gives me an error
I also tried this one:
\usepackage[utf8]{inputenc}
\usepackage{arabtex}
\usepackage{utf8}
\setcode{utf8}

\< العربية>

but I can only write one word or a line using this one.
I also tryed:
\usepackage[utf8]{inputenc}
\usepackage{polyglossia}
\setdefaultlanguage{english}
\setotherlanguages{arabic}

\begin{document}
\textarabic{النص العربي}
\end{document}

but this one I got the error in \usepackage{polyglossia}
can anyone help.
I use pdfLaTeX compiler.

A: For just a few paragraphs, here is an option:
\documentclass{article}

\usepackage[bidi=default, english]{babel}
\usepackage[LAE, T1]{fontenc}
\babelprovide{arabic}
\addto\extrasarabic{\fontencoding{LAE}\selectfont}
\addto\noextrasarabic{\fontencoding{T1}\selectfont}

\begin{document}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo.

\begin{otherlanguage}{arabic}
لكن لا بد أن أوضح لك أن كل هذه الأفكار المغلوطة حول استنكار النشوة
وتمجيد الألم نشأت بالفعل، وسأعرض لك التفاصيل لتكتشف حقيقة وأساس تلك
السعادة البشرية، فلا أحد يرفض أو يكره أو يتجنب الشعور بالسعادة، ولكن
بفضل هؤلاء الأشخاص الذين لا يدركون بأن السعادة لا بد أن نستشعرها بصورة
أكثر عقلانية ومنطقية فيعرضهم هذا لمواجهة الظروف الأليمة.
\end{otherlanguage}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo.

\end{document}


text:
Q: UML use case diagram: Actors on left and right? I'm currently drawing a use case diagram (using UML2.0) and it's getting quite large and unorganised.
So my question is, is it acceptable to place actors on both the left and right of the system boundary?
I have seen several examples of this but I'm not sure if there are specific reasons why actors are placed on the right as opposed to the left? Or is there no difference really apart from design and aesthetics?

A: You can put them anywhere - the top, the bottom, the left, the right. In most cases, if it fits neatly, I've seen them on the right. They go on the left if necessary. UML doesn't specify this level of detail, though. You should make a diagram that is readable to the intended audience.


text:
Q: Eclipse remote developement I have a J2EE web application. I'm coding it with Eclipse.
Currently I have Eclipse program and my repositery on my own computer.
I would like to put the repositery on a distant server to develop without to have the code physically on my own computer.
The idea is to launch Eclipse from my compture to connect on the distant repositery and to compile and deploy ON the server and not on my computer.
Does Eclipse RSE provide these fonctionnality ? It seems to fetch the code through the network to compile the application.
(An alternative would be to have Eclipse on the remote server and export display on my computer (with X server)...)
Thanks

A: I think Eclipse IDE RSE plugin only helps to edit the remote Java files from your PC. Rest compile/build/deploy has to be done in the remote system only.


text:
Q: not getting output for json .saved in pars.html format

 create object from json string

I am not able to get the o/p for this concept.I am not able to understand what is parsing.

A: Javascript is case-sensitive and you are currently using innerHTml instead of innerHTML, which will not work :
document.getElementById('demo').innerHTML = obj1.fruits[1].name + '' + obj1.fruits[2].price;

Additionally, you may want to simply use a single line to define your JSON string to avoid issues when building it :
var text = '{"fruits":[{"name":"apple","price":"1000"},{"name":"orange","price":"2000"},{"name":"pine","price":"3000"}]}'

Example

create object from json string

DEMO

You can see this example in action here.

A: Use innerHTML instead of innerHTml

  var text = '{"fruits":[' + '{"name":"apple","price":"1000"}, ' + '{"name":"orange","price":"2000"}, ' + '{"name":"pine","price":"3000"} ]  }';
  obj1 = JSON.parse(text);
  document.getElementById("demo").innerHTML = obj1.fruits[1].name + " " + obj1.fruits[2].price;

 create object from json string

A: Errors I could spot:

*

*Forgot to add #dome element on your page

*innerHTml should be innerHTML

*text variable is not being correctly initialised. It's a parsing error. String closing quote and plus '+ should be on the string closing line like in the example below.

 var text = '{"fruits":[{"name":"apple","price":"1000"},' +
   '{"name":"orange","price":"2000"},' +
   '{"name":"pine","price":"3000"}' +
   ']}';

 obj1 = JSON.parse(text);

 document.getElementById("demo").innerHTML = obj1.fruits[1].name + " " + obj1.fruits[1].price;

 create object from json string

</demo>


text:
Q: Angular2. Extending Input decorator Quite often I need to use stream of input values in component. Usually I do it in this way:
export class UserComponent {
    userId$ = new BehaviorSubject<number>(null);
    @Input() set userId(value: number) {
       this.userId$.next(value);
    }
}

I wonder is there a way to create Input$ decorator:
export class UserComponent {
    @Input$() userId$ = new BehaviorSubject<number>(null);
}

A: Yes, it is possible, you could create additional decorator which will replace class field with getter/setter pair, getter will return Subject and setter will do next on this subject.
Please note that it will likely break AOT compilation.
@Input()
@Reactive(false)
public subject:Subject<boolean>; //you don't even need to initialize

export function Reactive(initialValue:any):Function
{
    return function(target:Object, property:string)
    {
        const name:string = `__subject_${property}`;

        Object.defineProperty(target, name, <PropertyDescriptor>{
            enumerable  : false,
            configurable: false,
            writable    : true
        });

        Object.defineProperty(target, property, <PropertyDescriptor>{
            enumerable  : true,
            configurable: false,
            get         : function():any
            {
                if(this[name] === undefined)
                {
                    this[name] = new BehaviorSubject<any>(initialValue);
                }
                return this[name];
            },
            set         : function(val:any):void
            {
                if(this[name] === undefined)
                {
                    this[name] = new BehaviorSubject<any>(initialValue);
                }
                this[name].next(val);
            }
        });
    }
}


text:
Q: How to fix JSON parse error: Unexpected indentifier "object" in React Native? I use Axios to fetch from a rss2json api. I use Hooks to parse the response.data from Axios into a feed. Now I want to parse that feed into react-native-deck-swiper swiper component but I get the error "How to fix JSON parse error: Unexpected indentifier "object" in React Native?".
How can I fix this?
const URL = "https://api.rss2json.com/v1/api.json?rss_url= THE WEBSITE RSS FEED";
const PROXY = "https://api.allorigins.win/raw?url=";

let content = null;
const [feed, setFeed] = useState(null);

useEffect(() => {
        axios.get(URL)
            .then(response => {
                setFeed(response.data)
            })
    }, [URL])

if(feed) {
        content =
        <Swiper
            cards={feed}
            cardIndex={index}
            renderCard={(card) => {
                 <View><Image source={{uri: feed.items[0].thumbnail}}} /></View>
                }}
        ></Swiper>
    }

return (
   <View>{content}</View>
);

Libraries: react-native-deck-swiper, axios
I use rss2json.com to convert my rss feed into json and then use Axios to fetch it.
EDIT:

A: We too have faced this issue before. Even if the data is proper json it was returning the data sometimes in string. We are doing something like this
axios.get(URL)
.then(response => {
  let responseData = response.data
  const responseJson = (typeof responseData == "string" ? JSON.parse(responseData.trim()) : responseData);
  setFeed(responseJson)
})

Can you try loading the swiper like this:
<View>
  {
      feed && <Swiper
            cards={feed}
            cardIndex={index}
            renderCard={(card) => {
                 <View><Image source={{uri: feed.items[0].thumbnail}} /></View>
                }}
        ></Swiper>
  }
  </View>

A: try this way ;)
useEffect(() => {
    axios.get(URL)
       .then(response => {
          // items ==> [{thumbnail: "", ... },{thumbnail: "", ... },{thumbnail: "", ... }]
          const { items } = response.data
          setFeed(items)
    })
}, [URL])

return (
    <View style={styles.container}>
        {
          feed && <Swiper
            cards={feed}
            cardIndex={index}
            renderCard={(card) => {
                <View style={styles.card}>
                  <Image
                    style={styles.cardImage}
                    source={{uri: card.thumbnail}} />
                </View>
            }}
        ></Swiper>
      }
    </View>
  );


text:
Q: model fuzzy assignment problem i wanna ask something about fuzzy assignment, why in fuzzy assignment problem specially in min z form didn't using $tilde{x}$ in $x_{ij}$ meanwhile it is used in $c_{ij}$ and also $z$.
\begin{align*}
 \min \widetilde{z}=&{\sum^{n}_{i=1}}{\sum^{n}_{j=1}}\widetilde{c}_{ij}x_{ij}
\end{align*}

A: The $x$ has no tilde because $x$ is not fuzzy. Instead, $x$ is a binary decision variable whose value is to be chosen to minimize the objective function subject to the constraints.


text:
Q: problema ao deixar itens horizontalmente em uma div
eu queria deixar essa img, o nome, o input, o botão alterar na horizontal, mas não estou conseguindo..
codigo html:

Meu Carrinho

                  <img class="imgcar" src="images/<?= $mostrar['skin_img']?>">

<?= $produtos; ?>

                <input type="text" name="produto" value="<?= $produtos?>" style="display:none" >
                <form method="post">

                    <input type="text" value="<?= $mostrar['skin_quantidade']?>" name="1" id="estoque" style="display:none;">
                    <input type="text" value="<?= $mostrar['skin_preco'];?>" name="preco" id="estoque" style="display:none;">
                    <input type="number" name="id"  value="<?= $mostra['temporario_id']?>" style="display:none;">
                    <input type="number" name="quantidade"  value="<?= $mostra['temporario_quantidade']?>" class="qtdchange" id="qtd" onchange="acrescentar()">
                    <button class="color-white link-bgcolor-green-dark-b" name="alterar" value="Alterar"> Alterar</button>

R$ <?=  number_format($mostra['temporario_preco'], 2,',','.');?>

codigo css:
*{margin:0;padding:0;}
a{
    text-decoration: none;
}
#wrappermenux{

        margin-right: auto; /* 1 */
    margin-left:  auto; /* 1 */

    max-width: 1280px; /* 2 */
    padding-top:  50px; /* 3 */
    padding-bottom: 10px;
}
img.imgcar{
    margin-top: 10px;
    height: 60px;width: 80px;
}
p.nomecar{
    color:#E70408;
    font-size: 22px;
}
p.nomecar:hover{
    color:#00E3FF;

}
input.qtdchange{
    padding-left: 15px;
    width: 45px;
    height: 35px;
}

A: Você precisa de um div exterior generica, em volta do tres elementos
e do atributo display inline...

    <img class="imgcar" src="images/<?= $mostrar['skin_img']?>">

<?= $produtos; ?>

    <input type="text" name="produto" value="<?= $produtos?>" style="display:none" >
    <form method="post">

A: Bom dia colega,
vê se isso te ajuda.

#container {
    display: flex; /* establish flex container */
        flex-direction: row; /* make main axis horizontal (default value) */
        justify-content: center; /* center items horizontally, in this case */
        align-items: center; /* center items vertically, in this case */
    height: 300px; /* for demo purposes */
    border: 1px solid black; /* for demo purposes */
    background-color: #eee; /* for demo purposes */
}

.box {
    width: 300px;
    margin: 5px;
    text-align: center;
}

#bluebox { background: aqua; }
#redbox { background: red; }

DIV #1

DIV #2


text:
Q: Linq Double contains In my DB I have this field :mySerial Double?
I have a Multicritera Search, and I have to search on this field.
User want to search on this field typing the start, the end or anything they want.
So I did this :
results.Where(x => x.mySerial.ToString().Contains(TextBox_mySerial.Text)) ;

When I search for : "88890"
I should have :888900, 888901, 888903, 888908, 888909 as result.
But
I only get : 888889
Linq turn .ToString().Contains my into:
WHERE CONVERT(NVARCHAR(30), [t0].[mySerial], 2) LIKE '%88890%'

But what I want is :
WHERE [mySerial] LIKE '%88890%'

Is there any way to achieve this in Linq or do I have to cast [mySerial] in my view into a varchar ?

A: The problem is that Linq is using a style of 2 for the conversion which results in scientific notation.  So the following query
SELECT CONVERT(NVARCHAR(30), CAST(888900  AS FLOAT), 2)
UNION
SELECT CONVERT(NVARCHAR(30), CAST(888901  AS FLOAT), 2)
UNION
SELECT CONVERT(NVARCHAR(30), CAST(888903  AS FLOAT), 2)
UNION
SELECT CONVERT(NVARCHAR(30), CAST(888909   AS FLOAT), 2)
UNION
SELECT CONVERT(NVARCHAR(30), CAST(888889 AS FLOAT), 2)

Gives these results

8.888890000000000e+005
8.889000000000000e+005
8.889010000000000e+005
8.889030000000000e+005
8.889090000000000e+005

So you either need to cast to int first
results.Where(x => ((int)x.mySerial).ToString().Contains(TextBox_mySerial.Text)) ;

Or enter something like "8.8890" instead.  Really neither one is a very good option so you might want to consider storing the value as a NVarChar instead if you need to do string operations on it instead of numerical ones.

A: if you have a double you want to convert to a string then you HAVE to choose some string representation, as per this:
https://msdn.microsoft.com/en-GB/library/ms187928.aspx you are going to get

Always 16 digits. Always use in scientific notation.

The solution is to provide your preferred format.  Is seems your field is actually an int? (ie all the examples you have given are whole numbers) so x.mySerial.ToString("0") should provide what you want.


text:
Q: binary data to and from text conversion Sometimes i generate data that is as little as 1k. I thought it may be good if i could convert it to text so i can paste it to someone on a forum or on MSN. How can i convert data into text then convert back? How many bits can i use? I must have it compatible with pasting on forums and i would like it to be compatible with msn if the string isnt to long. How can i make the data text safe?
Should i assume the data is only allowed to be 6bits? Is 32-127 the only values available? will i have a problem copy/pasting 127 (ascii for 'DEL'). I am using C#

A: For safe copy and paste, consider UUEncoding or Base64Encoding. .NET has support for Base64 on the Convert class.
Finding sample code in C# that implements UUEncoding or Base64Encoding isn't too hard:
<Link>
http://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/

A: I think the simplest thing would be to use base64 encoding. It will take any binary data and convert it to text suitable for pasting anywhere.
In C# you can use Convert.ToBase64String (or something like this)

A: Does your forum allow file attachments? If so just attach the binary file.


text:
Q: Getting some data from a PHP (json_encode) and now need to access it within the javascript? I am currently using Phonegap and XUI to create web app.
I am retrieving some data from an external domain using a http request via XUI.
This is working correctly and I receive the JSON data back correctly, see the data format below:
({"first":"John","last":"Smith","HighScore":"75"})

So now I want to be able to access the individual assets of the data using javascript.
 x$('#test').xhr(URL,function() {
    loggedin = this.responseText; // This is the data that has been received from the PHP file
    if(loggedin != '1') // If not 1 then will let them in
    {
        alert(loggedin); // Alerts with the data recieved
    }
    else // Login incorrect
    {alert('Sorry you login details were incorrect please try again.');}
});

I know its probably simple to do but I just can't seem to figure it out so any help would be much appreciated.
Thanks,
Kane

A: JSON object accessor syntax is object.key, so if this.responseText is {"first":"John","last":"Smith","HighScore":"75"} then you'd display Smith with this.responseText.last
An example usage for your alert could be:
alert('Hello ' + this.responseText.first + ' ' this.responseText.last + '! You currently have a high score of ' + this.responseText.HighScore + ' points! Play again!');


text:
Q: SELECT 1 percent of distinct values SQL Server 2008 R2
I have a table called Actions, this would be a snippet of what it looks like
ActionID | ActionType | ActionUserID | ActionDateTime
---------+------------+--------------+---------------------
555363     Open         9843           2020-09-15 09:27:55
555364     Process      2563           2020-09-15 09:31:22
555365     Close        8522           2020-09-15 09:37:48
555366     Detour       9843           2020-09-15 09:42:42
555367     Process      9843           2020-09-15 09:51:50
555368     Close        8522           2020-09-15 09:55:45
555369     Open         1685           2020-09-15 09:57:12
555370     Detour       2563           2020-09-15 10:03:23
555371     Detour       9843           2020-09-15 10:04:33
555372     Close        8522           2020-09-15 10:07:44

The table has hundreds of thousands of rows.  What I want to do is review 1% of all actions performed by each user for a specific month.
I know I can get 1% of everything by doing:
SELECT TOP 1 PERCENT *
FROM Actions
WHERE ActionDateTime BETWEEN '09/01/2020' AND '09/30/2020'
ORDER BY NEWID()

I know I can get 1% of a specific user by doing:
SELECT TOP 1 PERCENT *
FROM Actions
WHERE ActionUserID = 9843
  AND ActionDateTime BETWEEN '09/01/2020' AND '09/30/2020'
ORDER BY NEWID()

But what I really want to get is 1% of each user.  I know I could get a list of the users who performed actions during the month by doing:
SELECT DISTINCT(ActionUserID)
WHERE ActionDateTime BETWEEN '09/01/2020' AND '09/30/2020'

However I am not sure how to combine these two queries.

A:
But what I really want to get is 1% of each user.

I would recommend window function percent_rank():
select *
from (
    select a.*, percent_rank() over(partition by actionuserid order by newid()) prn
    from actions a
    where actiondatetime >= '20200901' and actiondatetime < '20201001'
) a
where prn < 0.01

If your version of SQL Server is so old that it does not support percent_rank(), then we can emulate it with rank() and count():
select *
from (
    select a.*,
        rank() over(partition by actionuserid order by newid()) as rn,
        count(*) over(partition by actionuserid) as cnt
    from actions a
    where actiondatetime >= '20200901' and actiondatetime < '20201001'
) a
where 100.0 * rn / cnt  < 1 or (rn = 1 and cnt < 100)

A: You could easily combine the two queries using CROSS APPLY:
SELECT a.*
FROM (
    SELECT DISTINCT ActionUserID
    WHERE ActionDateTime BETWEEN '09/01/2020' AND '09/30/2020'
) u
CROSS APPLY
(
    SELECT TOP 1 PERCENT *
    FROM Actions a
    WHERE a.ActionUserID = u.ActionUserID
    AND ActionDateTime BETWEEN '09/01/2020' AND '09/30/2020'
    ORDER BY NEWID()
) a


text:
Q: How To Overcome CORS issues with Redux React Express and Node? I have a React App that uses React Router and Redux as its state manager. The server side of the app uses Express and Node.
I am making API calls to an external service. I do not have the ability to enable CORS on the external service. Therefore, I need to use my app's server side to make the calls to the external service to remove the browser from the equation, and eliminate any CORS error.
I am able to get my data from the service on the server side successfully. I would like to know if it is possible to share the Redux store in between the client and server with some sort of middleware (looking for examples/resources).
The goal:
1) Handle a click event in the client
2) Have that event call a server side route to external api (don't know how to do this)
3) Then the server handles this route, makes the request, and sends the response to the client (through the shared react store - not sure if this is possible)
4) The store gets the new state, and then sends to the client side components, and the UI updates
Are there any examples/tutorials of this? Not looking for an initial server rendered page, but guides that inform how the above 4 steps can generally be implemented.

A: Thanks for the suggestions.
It turns out that I was severely over thinking the solution. All I really needed was the ability to launch a server side function (get resources from external API) from the client side event (load component). Sort of like how submitting a form, has an action that launches a server side function.
In my component:
componentDidMount() {
    const product_api_results = productApi.getProductItems()
    console.log('product_api_results in CART Component: ', product_api_results)
    /* now I have results and can put it in the Redux Store via action to reducer for other components to work with on client */
  }

The productAPI.getProductItems() that the component calls:
export function getProductItems () {
  return axios.get('/api/get-products') // triggers a server side route
    .then(function (response) {
      console.log('client side response: ', response)
      return response
    })
}

In Express server.js file, the server will see this url and then get the proper data. The shopify.get() is from the shopify-node-api module:
app.get('/api/get-products', function (req, res) { // '/api/get-products' called from client
  shopify.get('/admin/products.json', function (err, data, headers) {
    res.send(data)
  })
})


text:
Q: How to concatenate values of a string in MySQL I'm trying to concat values column values in MySQL db but I get an error

FUNCTION sales.STRING_AGG does not exist

SELECT
    city,
    STRING_AGG(email,';') email_list
FROM
    sales.customers
GROUP BY
    city;

What I'm I missing?

A: Do you mean?
SELECT city,
       GROUP_CONCAT(email) email_list
FROM sales.customers
GROUP BY city;

A: You need to use group_concat
SELECT  city,
        group_concat(email) email_list
FROM customers
GROUP BY city;

DEMO
You can also order by inside of the group_concat() function like this:
group_concat(email order by email) email_list

Or change separator from default , to ;
group_concat(email order by email desc separator ';') email_list


text:
Q: bash script works on online compiler but not within Linux I'm trying to make a bash script that
- takes in two inputs (and only two)
- then prints out all the even numbers between the two numbers
- prints out orange beside any number divisible also by 7
- prints out banana beside any number divisible also by 11
- prints out pear beside any number divisible also by 13
finally prints out a statement "what is with the fruit obsession?"
it works fine within this compiler (http://www.compileonline.com/execute_bash_online.php)
but in Linux it error messages saying that $Input2 is not a recognised identifier and that there is an unexpected end of file after the last line
    #!/bin/bash
     read -p "Type in Two integer inputs you want evaluated, followed by [ENTER]:" Input1 Input2
      if [ -z $Input1 ]; then
        echo "Please enter a valid first integer"
        read -r Input1 Input2
    exit 1
    fi
    if [ -z $Input2 ];
  then
        echo "Please enter a valid second integer"
        read Input2
    fi
    if [ $# -gt 2 ]; then
    echo "Too many numbers have been inputted"
    fi
  echo "You entered: $Input1,$Input2"
  echo "Here are all the even numbers between your two values:"
  echo ""
  # if Input 1 is larger than Input 2
  while [ $((Input2)) -lt $Input1 ]; do
    if [ $((Input1 % 2)) -gt 0 ];then
  echo -en "$((Input1 = $Input1 - 1)) "
  else
  echo -en "$((Input1 = $Input1 - 2)) "
  fi
    if [ $((Input1 % 7)) -eq 0 ]; then
    echo -en "orange "
    fi
    if [ $((Input1 % 11)) -eq 0 ]; then
    echo -en "banana "
    fi
    if [ $((Input1 % 13)) -eq 0 ]; then
    echo -en "pear "
    fi
    echo
  done;

    while [ $((Input1)) -lt $Input2 ]; do
    if [ $((Input2 % 2)) -gt 0 ];then
    echo -en "$((Input2 = $Input2 - 1)) "
  else
    echo -en "$((Input2 = $Input2 - 2)) "
  fi

    if [ $((Input2 % 7)) -eq 0 ]; then
    echo -en "orange "
    fi
    if [ $((Input2 % 11)) -eq 0 ]; then
    echo -en "banana "
    fi
    if [ $((Input2 % 13)) -eq 0 ]; then
    echo -en "pear "
    fi
    echo
  done;

  echo "what is with the fruit obsession?"
  exit 0

A: Use dos2unix to convert windows-style line terminators \r\n to *nix-style \n:
dos2unix fruit.sh

Note I used the inverse unix2dos on the script and then when I run it I get the same errors:

$ ./fruit.sh
Type in Two integer inputs you want evaluated, followed by [ENTER]:2 8
You entered: 2,8
Here are all the even numbers between your two values:

6
4
2
what is with the fruit obsession?
$ unix2dos fruit.sh
unix2dos: converting file fruit.sh to DOS format ...
$ ./fruit.sh
Type in Two integer inputs you want evaluated, followed by [ENTER]:1 2
': not a valid identifier `Input2
./fruit.sh: line 36: syntax error near unexpected token `done'
'/fruit.sh: line 36: `  done;
$

A: This code is not only shorter and easier to read, but it should also run MUCH faster. It's output is near identical to the original script, the exception being how it handles input.
As I tested this on a Linux machine, I don't know how it runs under cygwin.
#!/bin/bash

repeat=yes
while [ $repeat = "yes" ]; do
    read -p "Type in Two integer inputs you want evaluated, followed by [ENTER]: " Input1 Input2 Input3
    repeat=no
    [ -z $Input2 ] && { echo "Incorect: Not Enough Inputs"; repeat=yes ;}
    [ ! -z $Input3 ] && { echo "Incorect: Too many inputs"; repeat=yes;}
done

echo -e "You entered: $Input1,$Input2\nHere are all the even numbers between your two values:"

if [ $Input1 -lt $Input2 ]; then
    larg=$Input1 ; small=$Input2
else
    larg=$Input2 ; small=$Input1
fi

while [ $larg -lt $small ]; do
    ((small % 2)) && { echo ; echo -en "$((small = $small - 1)) " ;}
    ((small % 7)) || echo -en "orange "
    ((small % 11)) || echo -en "banana "
    ((small % 13)) || echo -en "pear "
    small=$(($small - 1))
done
echo


text:
Q: draw(_ rect: CGRect) distortion on different iOS versions I'm doing a searchBar for studies, but I found some distortion in the layout in different versions of iOS, I don't remember and I don't know any relevant changes between the OS that can accomplish this, I'm a little lost.
override public func draw(_ rect: CGRect) {
    drawPosition()
}

iOS 15

iOS 12.4

private lazy var widthLeftView: CGFloat = 0.0

private func drawPosition() {
    searchView.addSubview(searchIcon)

    widthConstraint = searchView.widthAnchor.constraint(equalToConstant: calculateWidthLeftView())

    NSLayoutConstraint.activate([
        searchView.heightAnchor.constraint(equalToConstant: searchViewSize),
        widthConstraint,
        searchIcon.heightAnchor.constraint(equalToConstant: searchIconSize),
        searchIcon.widthAnchor.constraint(equalToConstant: searchIconSize),
        searchIcon.centerYAnchor.constraint(equalTo: searchView.centerYAnchor),
        searchIcon.trailingAnchor.constraint(
            equalTo: searchView.trailingAnchor,
            constant: 0)
    ])
    searchBarTextField.leftView = searchView
    searchBarTextField.leftViewMode = .always
}

private func calculateWidthLeftView() -> Double {
    self.layoutIfNeeded()
    let widht = self.frame.size.width - 54
    let widhLeft = widht / 2
    return widhLeft
}

A: Problem fixed by removing the override draw() function and putting it to be called inside the override layoutSubViews
public override func layoutSubviews() {
    super.layoutSubviews()
    drawPosition()
}

This decision was good for two reasons, first it fixed the bug, and second, I found that overwriting draw() impacts performance and fills up the iPhone's memory little by little,


text:
Q: Animated text with CSS wave How It Works
The .png image represented below is clipped to the text with animation;

In Action

body { background: #000000; }

.Wave-Loader {
 text-transform: uppercase;
 font-family: 'Cabin Condensed', sans-serif;
 font-weight: bold;
 font-size: 100pt;
 text-align: center;
 height: 120px;
 line-height: 110px;
 vertical-align: bottom;
 position: absolute;
 left: 0;
 right: 0;
 top: 100px;
 bottom: 0;
}

.Wave-Loader.Wave {
 background-image: url("http://i.imgur.com/uFpLbYt.png");
 -moz-background-clip: text;
 -o-background-clip: text;
   -webkit-background-clip: text;
  background-clip: text;
 color: transparent;
 text-shadow: 0px 0px rgba(255, 255, 255, 0.06);
 animation: Wave-Loader 1s infinite linear;
 background-size: 200px 100px;
 background-repeat: repeat-x;
 opacity: 1;
}
@keyframes Wave-Loader {
 0% { background-position: 0 bottom; }
 100% { background-position: 200px bottom; }
}

loading

Question
Instead of using an image, how can I replace with a pure CSS shape as I would like to implement my colour tween which will change the colour of the white wave you see in my demo above going from red to green.
NOTE: Black background is only being used for StackOverflow whereas my background may vary in colour.

Examples Of A Wave Effect

#wave {
  position: relative;
  height: 70px;
  width: 600px;
  background: #000000;
}
#wave:before {
  content: "";
  display: block;
  position: absolute;
  border-radius: 100% 50%;
  width: 340px;
  height: 80px;
  background-color: white;
  right: -5px;
  top: 40px;
}
#wave:after {
  content: "";
  display: block;
  position: absolute;
  border-radius: 100% 50%;
  width: 300px;
  height: 70px;
  background-color: #000000;
  left: 0;
  top: 27px;
}

svg {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
}
.container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  vertical-align: middle;
  overflow: hidden;
}

  <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:red;"></path>
  </svg>

A: You may achieve text filled by an animated wave with several techniques. Here is an approach with SVG using the pattern element. The text is filled with a wave shaped pattern and the pattern is animated with SMIL animations. Here is what it looks like :

This approach will allow you to fill the pattern with a non plain background (like a gradient) and display your text over an image or any non plain background.
You can see this in action here : Animated wave clipped with text.

body,html{margin:0;padding:0;height:100%;}
body{
  background:url('https://farm9.staticflickr.com/8760/17195790401_ceeeafcddb_o.jpg');
  background-size:cover;
  font-family: 'Cabin Condensed', sans-serif;
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
}
svg{font-weight:bold;max-width:600px;height:auto;}
<svg viewbox="0 0 100 20">
  <defs>
    <linearGradient id="gradient" x1="0" x2="0" y1="0" y2="1">
      <stop offset="5%" stop-color="#326384"/>
      <stop offset="95%" stop-color="#123752"/>
    </linearGradient>
    <pattern id="wave" x="0" y="0" width="120" height="20" patternUnits="userSpaceOnUse">
      <path id="wavePath" d="M-40 9 Q-30 7 -20 9 T0 9 T20 9 T40 9 T60 9 T80 9 T100 9 T120 9 V20 H-40z" fill="url(#gradient)">
        <animateTransform attributeName="transform" type="translate" begin="0s" dur="1.5s" from="0,0" to="40,0" repeatCount="indefinite" />
      </path>
    </pattern>
  </defs>
  <text text-anchor="middle" x="50" y="15" font-size="17" fill="url(#wave)"  fill-opacity="0.6">LOADING</text>
  <text text-anchor="middle" x="50" y="15" font-size="17" fill="url(#gradient)" fill-opacity="0.1">LOADING</text>
</svg>

EDIT ----
I switched from CSS keyframe animations to SMIL animations for this example as Firefox doesn't support CSS keyframes on the elements defined in the <defs> tag yet (see https://bugzilla.mozilla.org/show_bug.cgi?id=1118710).


text:
Q: latex math symbol for pointer in object oriented context I need to use the pointer symbol (like P->a) in math latex. If I use normal characters like hyphen and > it doesn't look good. I guess there should be a specific symbol for it in latex, but I didn't find it anywhere.
The hyphen should be connected to the edge of ">", like when you type --> in microsoft office and it changes it automatically.
Any idea?

A: You can create your own by joining two - and > in math mode:

\documentclass{article}
\makeatletter
\newcommand{\my@arrow}[1]{\ooalign{$#1-\mkern-5mu-$\cr\hidewidth$#1>$}}
\newcommand{\myarrow}{\mathrel{\mathpalette\my@arrow\relax}}
\makeatother
\begin{document}
$A \rightarrow B$ \par
$A \longrightarrow B$ \par
$A -> B$ \par
$A \myarrow B_{A \myarrow B_{A \myarrow B}}$
\end{document}

The use of \mathpalette is explained in The mysteries of \mathpalette. It's used as a helper function for \mathchoice to scale math content to the required style (size).


text:
Q: List the tab/shp files properties within folders/sub folders w.r.t relative folder path Currently i am using this command line
For /R "U:\01 My Proj" %f in (*.tab) do ogrinfo -al -so "%f" >>U:\New.txt
to extract all the tab file related information as a text.Instead of giving the path folder...is it possible to run this command w.r.t to the folder wherein which the bat file has been copied ? (Another thing is the sub folders name will have spaces )
What i am trying to do is..save this command as a bat file using notepad & want to run it different folders (like..i'll copy the bat file to the respective folder & execute it).
Will /* in place of Path_folder work ? I've tried that too

A: Just leave out the /R option. That makes it recursive:
For  %%f in (*.tab) do ogrinfo -al -so "%%f" >>U:\New.txt


text:
Q: Ubuntu routing - setting one IP for incoming connections and one IP for outgoing connections I'm trying to set one IP for incoming connections and one IP for outgoing connections on my Ubuntu server with the outgoing IP blocked for incoming connections.
Here's a copy of my ifconfig (I'm censoring some IPv6 IPs with *)
eth0      Link encap:Ethernet  HWaddr *
          inet addr:45.35.100.115  Bcast:45.35.100.255  Mask:255.255.255.0
          inet6 addr: * Scope:Link
          inet6 addr: * Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:9570 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8519 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2448510 (2.4 MB)  TX bytes:6822014 (6.8 MB)

eth0:1    Link encap:Ethernet  HWaddr *
          inet addr:50.100.12.12  Bcast:0.0.0.0  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:10479 errors:0 dropped:0 overruns:0 frame:0
          TX packets:10479 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:3275913 (3.2 MB)  TX bytes:3275913 (3.2 MB)

Output of IP route list:
default via 45.33.126.1 dev eth0  metric 100
45.35.100.0/24 dev eth0  proto kernel  scope link  src 45.35.100.115
50.100.12.0/24 dev eth0  proto kernel  scope link  src 50.100.12.12

Output of /etc/network/interfaces:
auto eth0
allow-hotplug eth0

iface eth0 inet6 auto

iface eth0 inet static
    address 45.35.100.115/24
    gateway 45.35.100.1
    up   ip addr add 50.100.12.12/24 dev eth0 label eth0:1
    down ip addr del 50.100.12.12/24 dev eth0 label eth0:1

Please let me know how I can set one IP to receive incoming connections and one IP for all outgoing connections. The outgoing IP should not allow any incoming traffic.


text:
Q: How to run a flow once, automatically when starting mule? I have a java class that creates a clean MongoDB database with seeded collections.  It automatically identifies if the database is missing and creates it.  I would like to run this when I start MuleEsb.  This way I don't need to remember to invoke it before I start mule.  I was hoping to put it inside a flow and run that flow once, automatically when mule starts up.
Is there a way to do this one-time operation when mule starts?
--- Update ---
As per the conversation below I added the following to my mule config and the flow is automatically triggered.
<quartz:connector name="Quartz" validateConnections="true"/>

<flow name="testService1">
    <quartz:inbound-endpoint name="runOnce" repeatCount="0" repeatInterval="1" jobName="job1" connector-ref="Quartz">
        <quartz:event-generator-job>
            <quartz:payload>foo</quartz:payload>
        </quartz:event-generator-job>
    </quartz:inbound-endpoint>

    <logger message="INBOUND HEADERS = #[headers:inbound:*]" level="WARN"/>
</flow>

A: I created a JIRA a month ago to request such a feature: http://www.mulesoft.org/jira/browse/MULE-6877
For now, you can use a trick: a Quartz inbound endpoint with an event generator job repeatCount = 0 that will trigger your flow only once at startup.
Alternatively, you can listen to context events and invoke a flow when a specific event is triggered. The following shows a listener that invokes a startup and a shutdown flow:
package com.acme;

import org.mule.DefaultMuleEvent;
import org.mule.DefaultMuleMessage;
import org.mule.MessageExchangePattern;
import org.mule.api.MuleException;
import org.mule.api.MuleRuntimeException;
import org.mule.api.context.notification.MuleContextNotificationListener;
import org.mule.config.i18n.MessageFactory;
import org.mule.construct.Flow;
import org.mule.context.notification.MuleContextNotification;

public class FlowInvokingContextListener implements MuleContextNotificationListener<MuleContextNotification>
{
    private Flow startingFlow;
    private Flow stoppingFlow;

    public void onNotification(final MuleContextNotification notification)
    {
        if (notification.getAction() == MuleContextNotification.CONTEXT_STARTED)
        {
            sendNotificationToFlow(notification, startingFlow);
        }
        else if (notification.getAction() == MuleContextNotification.CONTEXT_STOPPING)
        {
            sendNotificationToFlow(notification, stoppingFlow);
        }
    }

    private void sendNotificationToFlow(final MuleContextNotification notification, final Flow flow)
    {
        try
        {
            final DefaultMuleEvent event = new DefaultMuleEvent(new DefaultMuleMessage(notification,
                notification.getMuleContext()), MessageExchangePattern.REQUEST_RESPONSE, startingFlow);
            flow.process(event);
        }
        catch (final MuleException me)
        {
            throw new MuleRuntimeException(MessageFactory.createStaticMessage("Failed to invoke: "
                                                                              + startingFlow), me);
        }
    }

    public void setStartingFlow(final Flow startingFlow)
    {
        this.startingFlow = startingFlow;
    }

    public void setStoppingFlow(final Flow stoppingFlow)
    {
        this.stoppingFlow = stoppingFlow;
    }
}

Configured with:
<spring:beans>
    <spring:bean name="flowInvokingContextListener"
        class="com.acme.FlowInvokingContextListener"
        p:startingFlow-ref="startFlow" p:stoppingFlow-ref="stopFlow" />
</spring:beans>

<notifications>
    <notification event="CONTEXT" />
    <notification-listener ref="flowInvokingContextListener" />
</notifications>

A: Another option is to use a custom agent that does it:
http://www.mulesoft.org/documentation/display/current/Mule+Agents


text:
Q: Django admin : How to call an action on a click of custom button? I have a django admin view displaying a list of orders. I have added a custom button, which when clicked should perform a certain action.

So I have a function defined in my services.py file as :
def penalty(order):
  #Do something

So, how should I call this function when Penalty is clicked. I can create a view, but how to call it?

A: All u need is here:

https://medium.com/@hakibenita/how-to-add-custom-action-buttons-to-django-admin-8d266f5b0d41

Follow the easy steps and your ready to go.
Many others all around the web.

A: The following answers could be helpful for solving your problems.

*

*How do I call a Django function on button click?

*Django: How can I call a view function from template?

*Call Django on HTML button click

A: You can add a URL like this to call a function
     def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path(
                'penalty/<int:id>',
                self.admin_site.admin_view(self.penalty),
                name='penalty'
            )
        ]
        return custom_urls + urls

from a button click in Django admin


text:
Q: MongoDB Aggregate query with AND condition I have this MongoDB query in PHP:
$data = $collection->aggregate(
    array('$match' => array(
        'PATIENT_ID' => $singoloPatientId
    )),
    array('$group' => array(
        '_id' => '$PATIENT_ID',
        'massi1' => array(
            '$max' => $dnameth_value
        )
    ))
);

which works. Now I want to add another where condition with AND:
experiment = $experimentInput

How do I go about this?

A: try this
$data=$collection->aggregate(
    array('$match'=> array(
        '$and' => array(
            'PATIENT_ID'=>$singoloPatientId,
            'experiment'=>$experimentInput
            ))),
    array('$group' => array(
        '_id' => '$PATIENT_ID',
        'massi1' => array(
            '$max' => $dnameth_value
        )
    ))
)

A: Just append the expression with the condition to the existing $match query:
$data = $collection->aggregate(
    array('$match' => array(
        'PATIENT_ID' => $singoloPatientId,
        'experiment' => $experimentInput
    )),
    array('$group' => array(
        '_id' => '$PATIENT_ID',
        'massi1' => array(
            '$max' => $dnameth_value
        )
    ))
);

From the docs:

MongoDB provides an implicit AND operation when specifying a comma
  separated list of expressions. Using an explicit AND with the $and
  operator is necessary when the same field or operator has to be
  specified in multiple expressions.


text:
Q: Best practice for maintaining packages to be installed in chef I am trying to write cookbook for installing software in windows. when i use windows_package, installable is getting downloaded and installed. But post installation installable is not getting deleted. do we need to manually delete that file.
Is there any best practice to do this.

A: Generally downloaded intermediary files are left in place because it makes the idempotence (don't redownload if you don't have to) checks easier. You could do fancier things where it only downloads if it isn't installed or if the version changes, but this is usually not worth the hassle.


text:
Q: Popup textbox on website on touchscreen monitor i want a textbox to popup whenever i use my touchscreen monitor to click on a textbox on a specific website.  I would prefer not to interfere with the code of the website. Is there another way i can do this? Maybe writing it as a plugin for the browser.

A: found a google chrome extension, Virtual Keyboard Interface


text:
Q: Syncing MAMP PRO 3 databases over Dropbox? There are various articles on syncing MAMP Pro databases across computers with Dropbox, but none of them seem to work for me on MAMP Pro 3. I can sync site files fine, but servers and databases seem out of reach.
I'm on Mac OS X Yosemite on both desktop and laptop, using MAMP Pro 3 and Dropbox.
Has anybody managed to work this out yet?


text:
Q: Appmaker retrieving records upon user role I am developing a Ticketing system and I have two dashboards for the submitted tickets, one for the admin and the other for the user. The admin should see all the submitted tickets by all users and the user should see only his submitted tickets. I don't know how to retrieve the records upon the user role.

A: How we do it is we use a function to filter the records using the security roles. For example our function uses
var user = convertName(app.user.username);
var role = app.user.role;
var ds = app.datasources.DashFilters;
ds.query.clearFilters();
if (!guestBoolean){
  if (role.User || role.Admins){
    ds.query.filters.Roles.name._equals = user;
    ds.query.filters.event_status._notContains = 'Pending';
    ds.query.filters.event_status._notEquals = 'Closed';
  }
  if (role.QADirector){
    ds.query.filters.event_status._notContains = 'Pending';
  }
  }
  if (guestBoolean){
    ds.query.filters.event_status._notContains = 'Pending';
  }
  ds.load();
}

The main difference with my function is we have related roles for each record in the data model and that can vary so we check for the current user being a role related to a record. That part is the !guestBoolean. The role.Admins and role.QADirector are using the built in security roles we have assigned to our app.
So in short, query the records using a function which looks for the current logged in user and filter based on your criteria from there.


text:
Q: EmitMapper Flattering Config NullReferenceException I am using EmitMapper with Flattering Configuration form EmitMapper samples to map my Entities to DTOs.
The problem is the I am getting NullReferenceException in the case if the source value is the property of the object, which is null, for example:
public class User
{
  public Guid Id { get; set; }
  public Company Company { get; set; }
}

public class Company
{
  public Guid Id { get; set; }
}

public class UserDTO
{
  public Guid Id { get; set; }
  public Guid CompanyId{ get; set; }
}

I am mapping User to UserDTO: var mapper = ObjectMapperManager.DefaultInstance.GetMapper<User, UserDTO>(
                new FlatteringConfig()
            );
var dto = mapper.Map(new User());
When EmitMapper will try to get CompanyId, it will call the getter of Company object Id property, but it is null.
Any help will be much appriciated.


text:
Q: Excel 2010: Delete contents of cell if value in B equals text Program: Excel 2010:
Question:
If E6=text then delete the value of A6 in Cells B6:C100
Basically when text in E6 equals "text"  then match all instances where A6 is found in B6:C100 and delete contents.
|  A Name  |  B Contents  |  C Contents  |  D Contents  |  E Values  |
----------------------------------------------------------------------
|  Angel   |  Basic       |  Angel       |  D Contents  |  Defined   |
----------------------------------------------------------------------
|  Zeus    |  Zeus        |  Angel       |  D Contents  |  Defined   |
----------------------------------------------------------------------

In the above, Angel in row C2 would be deleted.  Zeus in B3 would be deleted
Below is the result:
|  A Name  |  B Contents  |  C Contents  |  D Contents  |  E Values  |
----------------------------------------------------------------------
|  Angel   |  Basic       |              |  D Contents  |  Defined   |
----------------------------------------------------------------------
|  Zeus    |              |  Angel       |  D Contents  |  Defined   |
----------------------------------------------------------------------

Conditional formatting is preferred as it is a non Macro enabled book.
{Edit}
Perhaps a formula that could be similar to:  if e6='text' then if B6:C100 contain A6 "" so rather than deleting the cell contents it overwrites them with a "".
Thank you in advance.

A: If you can have your results on a separate worksheet, the best solution I can think of is to create another worksheet and use the following methods:

*

*Copy and paste links of your contents into the new worksheet.

*Use a formula like =IF(Original!$A1=Original!B1,"",Original!B1) but with the cells referencing your original sheet.

*Just copy this formula for all your cells in B2:C100
When you finish, just hide your source data worksheet and it should work.  Easy non-VBA solution.


text:
Q: Android display English digits while phone language is Arabic? My phone language is Arabic.
In my application the EditText displays the digits in English (OK) but the TextView displays the digits in arabic!
How Can I force the TextView to display digits in English despite the phone language?

A: You can use values-country, like: values-en for english or values-nl for dutch or values-fr for french and add a strings.xml with the values you need


text:
Q: @RequestHeader required property behavior for request paramter and value Can we make a header parameter mandatory but not the value using @RequestHeader?
For example if we use,
@RequestHeader(value = "abc", required = true)

both parameter and it value has to be there.
Edit:
Suppose i call some rest api has above request header param with "abc" but no value. So in this case i am able to invoke the rest api successfully since i have invoke with "abc" header param even i did not enter a value to it. Due to some governance tool rule, i need to have a specific header param but i dont want force user to enter any value.

A: Spring 5.2 and lower
The @RequestHeader doesn't provide additional facility to check the value of the parameter to be mandatory i.e. not null.
Given below are the available fields as per Spring Doc

*

*defaultValue: The default value to use as a fallback.

*name: The name of the request header to bind to.

*required: Whether the header is required; null values are allowed

*value: Alias for name()

So what you can do is read the parameter either with the help of @RequestHeader or inject a HttpServletRequest request, read by request.getHeader(...) and check inside the controller method if the value exists and then can call methods to perform the necessary logic.
Although you can make sure that the parameter exists with the help of required attribute for e.g. @RequestHeader(value = "Authorization", required = true) String authorization).
Spring 5.3+
The required field was tightened up, both the property and the value should exist. From the release notes:

The @RequestHeader annotation detect a null conversion result value and treat it as missing. In order to allow an empty value to be injected as a null argument, either set required=false on the argument annotation, e.g. @RequestParam(required=false), or declare the argument as @Nullable.

A: As @Mudassar said, @RequestHeader doesn't provide additional facility to check the value of the parameter to be mandatory i.e. not null.
It is related to this issue: https://github.com/spring-projects/spring-framework/issues/23939
I developed a workaround for this problem using an annotation @RequestHeaderNonNull that I've created: https://github.com/armandoalmeida/request-header-required-non-null
I hope I've helped you!


text:
Q: Every compact subset of $\mathbb{R}$ is the support of a Borel measure. Another Solution. This question is already discussed in Math Stack: Is every compact subset of $\Bbb{R}$ the support of some Borel measure?
But my question is not above.
I want to ask that why my solution is not correct.
For given compact set $K$, let measure $\mu$ be the Lebesgue measure restricted on $K$. Then why $\mu$ doesn't satisfy given condtions?


text:
Q: Makefile rule only works if file exists before make is invoked Consider the following (MCVE of a) Makefile:
my_target: prepare test.bin

prepare:
    echo >test.dat

%.bin: %.dat
    cp $? $@

If you run make in a clean directory, it fails:
echo >test.dat
make: *** No rule to make target 'test.bin', needed by 'my_target'. Stop.

Run it again and it succeeds:
echo >test.dat
cp test.dat test.bin

What seems to happen is that the rule to make *.bin from *.dat only recognises that it knows how to make test.bin if test.dat exists before anything is executed, even though according to the output it has already created test.dat before it tries to create test.bin.
This is inconvenient for me as I have to prepare a few files first (import them from a different, earlier part of the build).
Is there a solution?  Perhaps some way to allow the rules to be (re)evaluated in the light of the files which are now present?

A: There are a number of issues with your makefile.  However based on your comments I'm inclined to assume that the MCVE here is just a little too "M" and it's been reduced so much that it has a number of basic problems.  So I won't discuss them, unless you want me to.
The issue here is that you're creating important files without indicating to make that that's what you're doing.  Make keeps internally a cache of the contents of directories that it's worked with, for performance reasons, and that cache is only updated when make invokes a rule that it understands will modify it.
Here your target is prepare but the recipe actually creates a completely different file, test.dat.  So, make doesn't modify its internal cache of the directory contents and when it checks the cache to see if the file test.dat exists, it doesn't.
You need to be sure that your makefile is written such that it doesn't trick make: if a recipe creates a file foo then the target name should be foo, not bar.

A: This happens for wildcard targets, like %.bin. They get evaluated at the first pass. You could add an explicit target of test.bin. Or, follow the advice of tkausl and have test.dat depend on prepare (a phony target). In this case, you don't need the double dependency anymore:
my_target: test.bin

A: you have to write
test.dat:  prepare

or (when when you want to stay with wildcards)
%.dat: prepare
    @:

Usually, you might want to create and use .stamp files instead of a prepare target.


text:
Q: Display form selection in div in React I am trying to create a UI that updates as the client selects an option from a dropdown menu. I've tried to set this up as follows: A react Parent (App) that renders two child components (Inputs and Display). Inputs renders a dropdown menu form. Display renders html output that displays the selection made in Input.
Example below:
    var Inputs=React.createClass({
    getInitialState: function() {
        return {value: 'cat'}
    },
    handleChange: function() {
        this.setState({value: event.target.value})
    },
    render: function() {
        return (

                <form>
                    <select value={this.state.value}
                        onChange={this.handleChange}>
                        <option value='cat'> Cat </option>
                        <option value='dog'> Dog </option>
                    </select>
                </form>

        )
    }
})

var Display=React.createClass({
    render: function(){
        return (

                 {this.props.l1}

        )
    }
})

var App = React.createClass({
    render: function() {
        return (

                <Inputs ref="inputs" />
                <Display l1={this.refs.inputs.state.value} />

        )
    }
})

ReactDOM.render(
<App />,
document.getElementById('app')
  );

I expect the value to change when the client selects a new value from the dropdown.
More fundamentally, I think I'm misunderstanding how states and properties are passed in React.

A: Because you want both of the components to render data based on selections you should let the App do the state management and pass data as props to each one.
var App = React.createClass({
    getInitialState: function() {
        return {value: 'cat'};
    },
    handleChange: function(e) {
        e.preventDefault();
        this.setState({value: e.target.value});
    },
    render: function() {
        return (

                <Inputs value={this.state.value} onChange={this.handleChange} />
                <Display l1={this.state.value} />

        )
    }
});

var Inputs = React.createClass({
    render: function() {
        return (

                <form>
                    <select value={this.props.value}
                        onChange={this.props.onChange}>
                        <option value='cat'> Cat </option>
                        <option value='dog'> Dog </option>
                    </select>
                </form>

        )
    }
});


text:
Q: How to use GraphQL queries while using nuxt-apollo? I am trying to query the data from a Django endpoint which lists all my articles using Graphene Django. I followed all documentations but cannot understand how to fetch data in vuex action.
When using GraphiQl I can get the data answer. I have arranged my nuxt.config.js
apollo: {
    tokenName: "nuxt-apollo", // specify token name
    cookieAttributes: {
      expires: 7 // optional, default: 7 (days)
    },
    defaultOptions: {
      $query: {
        fetchPolicy: "network-only",
        errorPolicy: "all"
      }
    },
    watchLoading: "@/apollo/loadingHandler.js",
    errorHandler: "@/apollo/errorHandler.js",
    clientConfigs: {
      default: {
        httpEndpoint: 'http://localhost:8000/api/articles/graphql/'
      }
    }
  },

Now In my vuex store, but I cannot figure how to query and use data, I tried to query as below but no success:
async fetchArticles({ commit }) {
    try {
      const response =  this.$axios.$get(
        'articles/graphql/',
        {
          query: query({
            query: gql`
              query Articles {
                allArticles {
                  id
                  title
                }
              }
            `
          })
        }
      )

    } catch (error) {
      commit('setError', error)
    }
  },

Can you help me to fix my query?
Thanks

A: You can simply install graphql-tag library for creating queries to send over Apollo Client.
Also you can create file named article.graphql :
query Articles {
    allArticles {
      id
      title
    }
 }

Also pass parameters to query like this:
query ($param: [String]) {
   //your query
}

And usage in store:
import articleQuery from './queries/article.graphql';
....
// some store action
async fetchArticles({ commit }) {
    const client = this.app.apolloProvider.clients.default;

    // Optional Param
    // const param = format(new Date(), 'yyyy-MM-dd');

    const queryResult =
       await client.query({
          query: articleQuery,
          // Optional (if query contain parameter you can use)
          // variables: { param }
        });
}