问:
I need a batch program to find the folder name inside another folder
For example

consider:

```<code>H:\reports\test\12345\dailynews.pdf
</code>```

I want to send this PDF through mail by using MSSQL job (sql server 2008 R2).
But every time when another job creates the pdf file the location changes.
like

```<code>H:\reports\test\48596\dailynews.pdf
</code>```

I need a batch program to find the folder name which is present after the test folder.

答:
A recursive check may report same named files existing elsewhere in the tree and may take longer. My suggestion is to use this instead:

@Echo Off
Set "MyFile="
For /D %%A In ("H:\reports\test\*"
) Do If Exist "%%A\dailynews.pdf" Set "MyFile=%%~fA\dailynews.pdf"
If Not Defined MyFile Exit/B
Echo %%MyFile%% = %MyFile%
```

Body:
For example

consider:

H:\reports\test\12345\dailynews.pdf

I want to send this PDF through mail by using MSSQL job (sql server 2008 R2).
But every time when another job creates the pdf file the location changes.
like

H:\reports\test\48596\dailynews.pdf

I need a batch program to find the folder name which is present after the test folder.


来源: stackexchange

问:
Error when creating stored procedure SQL Server 2008 R2
i'am getting error on '{' and 'END'

```<code>CREATE PROCEDURE getLogsdata
{
    @id int
}
AS
BEGIN

END
</code>```

how to remove this errors

答:
Use parenthesis () instead of curly braces {}, and include some code in your procedure.

```<code>create procedure dbo.getLogsdata (@id int) as
  begin;
    set nocount on;

    select *
    from dbo.logs
    where id = @id;
  end;
go
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i'am getting error on '{' and 'END'

CREATE PROCEDURE getLogsdata
{
    @id int
}
AS
BEGIN

END

how to remove this errors

Body:
Use parenthesis () instead of curly braces {}, and include some code in your procedure.

create procedure dbo.getLogsdata (@id int) as
  begin;
    set nocount on;

    select *
    from dbo.logs
    where id = @id;
  end;
go


问:
Select count, inner joins and where statements
This is erp.orders:

```<code>userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01
</code>```

This is prod.referral_order_delivered

```<code>user_id
1
2
</code>```

This request :

```<code>select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"
</code>```

will give me this result:

```<code>userId  count
1       2
2       1
</code>```

This is not the result I want. Among the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered, I want to count how many times they appear in the table erp.orders IN TOTAL.
In my current request, I only count from 2017-06-07 to 2017-07-07.

The result I want is :

```<code>userId  count
1       2
2       4
</code>```

See how userId 3 and 4 are excluded. This is really important. Could you modify my request, please?

答:
Try splitting up your problem. You want:

the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered

and

to count how many times they appear in the table erp.orders IN TOTAL

You already have the former:

```<code>select distinct erp.orders."userId"
from erp.orders inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
</code>```

and the latter simply uses an inner-select:

```<code>select erp.orders."userId", count(erp.orders."userId")
from erp.orders
where
   erp.orders."userId" in (select ...)
group by erp.orders."userId"
</code>```

Body:
This is erp.orders:

userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01

This is prod.referral_order_delivered

user_id
1
2

This request :

select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"

will give me this result:

userId  count
1       2
2       1

This is not the result I want. Among the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered, I want to count how many times they appear in the table erp.orders IN TOTAL.
In my current request, I only count from 2017-06-07 to 2017-07-07.

The result I want is :

userId  count
1       2
2       4

See how userId 3 and 4 are excluded. This is really important. Could you modify my request, please?

Body:
Try splitting up your problem. You want:

the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered

and

to count how many times they appear in the table erp.orders IN TOTAL

You already have the former:

select distinct erp.orders."userId"
from erp.orders inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'

and the latter simply uses an inner-select:

select erp.orders."userId", count(erp.orders."userId")
from erp.orders
where
   erp.orders."userId" in (select ...)
group by erp.orders."userId"


问:
Removing C++ Comment From Source Code
I have some c++ code with /* */ and // style comments.  I want to have a way to remove them all automatically.  Apparently, using an editor (e.g. ultraedit) with some regexp searching for /*, */ and // should do the job. But, on a closer look, a complete solution isn't that simple because the sequences /* or // may not represent a comment if they're inside another comment, string literal or character literal.  e.g.

```<code>printf(" \" \" " "  /* this is not a comment and is surrounded by an unknown number of double-quotes */");
</code>```

is a comment sequence inside a double quote. And, it isn't a simple task to determine if a string is inside a pair of valid double-quotes. While this

```<code>// this is a single line comment /* <--- this does not start a comment block
// this is a second comment line with an */ within
</code>```

is comment sequences inside other comments.

Is there a more comprehensive way to remove comments from a C++ source taking into account string literal and comment?  For example can we instruct the preprocessor to remove comments while doesn't carry out, say, #include directive?

答:
```<code>#include <iostream>
#include<fstream>
using namespace std;

int main() {
    ifstream fin;
    ofstream fout;
    fin.open("input.txt");
    fout.open("output.txt");
    char ch;
    while(!fin.eof()){
        fin.get(ch);
        if(ch=='/'){
            fin.get(ch);
            if(ch=='/' )
            {   //cout<<"Detected\n";
                fin.get(ch);
                while(!(ch=='\n'||ch=='\0'))
                {
                //cout<<"while";
                fin.get(ch);
                }
            }
            if(ch=='*')
            {
                fin.get(ch);
                while(!(ch=='*')){
                    fin.get(ch);
                }
                fin.get(ch);
                if(ch=='/'){
                //  cout<<"Detected Multi-Line\n";
                    fin.get(ch);
                }

            }
        }
        fout<<ch;
    }
    return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Removing C++ Comment From Source Code

Body:
I have some c++ code with /* */ and // style comments.  I want to have a way to remove them all automatically.  Apparently, using an editor (e.g. ultraedit) with some regexp searching for /*, */ and // should do the job. But, on a closer look, a complete solution isn't that simple because the sequences /* or // may not represent a comment if they're inside another comment, string literal or character literal.  e.g.

printf(" \" \" " "  /* this is not a comment and is surrounded by an unknown number of double-quotes */");

is a comment sequence inside a double quote. And, it isn't a simple task to determine if a string is inside a pair of valid double-quotes. While this

// this is a single line comment /* <--- this does not start a comment block
// this is a second comment line with an */ within

is comment sequences inside other comments.

Is there a more comprehensive way to remove comments from a C++ source taking into account string literal and comment?  For example can we instruct the preprocessor to remove comments while doesn't carry out, say, #include directive?


问:
WPF Binding - StringFormat - Not Formatting
I have a ToolTip with a value set as:

```<code>Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"
</code>```

The toolip is displaying as:

72

But I expect it to be:

Reserved (Equity Share: 72%)

What is wrong with my binding?

答:
Try</p>

```<code>StringFormat=Reserved (Equity Share: {0:P0})
</code>```

Body:
I have a ToolTip with a value set as:

Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"

The toolip is displaying as:

72

But I expect it to be:

Reserved (Equity Share: 72%)

What is wrong with my binding?

Body:
Try

StringFormat=Reserved (Equity Share: {0:P0})


问:
how to single select cell in collection view..?
That are code properly working but when i will scroll my collection view then another cell also selected, for example 18 images are available and first show six at run time when i will select any one of the position then next six position image automatic select. why at a time two cell selecting i am  confuse here. please give me solution

here i have take 6 cell at main show storyboard

```<code>UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;

flowLayout.minimumLineSpacing = 15;
CGFloat availableWidthForCells = CGRectGetWidth(self.collectionView.frame) - flowLayout.sectionInset.left - flowLayout.sectionInset.right - flowLayout.minimumInteritemSpacing *2;

cellWidth = availableWidthForCells /6;
    NSLog(@"cellWidth:%f",cellWidth);
flowLayout.itemSize = CGSizeMake(cellWidth, cellWidth);
</code>```

This is my Didselect And didDeselect Method

```<code>-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];

    cell.layer.cornerRadius = cellWidth / 2.0;
    cell.layer.backgroundColor = [UIColor blackColor].CGColor;
    NSLog(@"INDEXPATH:-%ld",(long)indexPath.row);
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.layer.cornerRadius = cellWidth / 2.0;
    cell.layer.backgroundColor = [UIColor whiteColor].CGColor;

}
</code>```

答:
Thanks for Alberto Scampini
this code for swift 3.1</p>

```<code>var selectedIndexPath: IndexPath?

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "SegmentChoiceCVCell", for: indexPath) as! SegmentChoiceCVCell
    //configure cell

    if selectedIndexPath != nil && indexPath == selectedIndexPath {
        cell.checkIcon.backgroundColor = UIColor.black

    }else{

        cell.checkIcon.backgroundColor = UIColor.white
    }

    return cell

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath) as! SegmentChoiceCVCell

        cell.checkIcon.backgroundColor = UIColor.black
    self.selectedIndexPath = indexPath

}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell: SegmentChoiceCVCell = collectionView.cellForItem(at: indexPath) as! SegmentChoiceCVCell

        cell.checkIcon.backgroundColor = white
    selectedIndexPath = nil
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
That are code properly working but when i will scroll my collection view then another cell also selected, for example 18 images are available and first show six at run time when i will select any one of the position then next six position image automatic select. why at a time two cell selecting i am  confuse here. please give me solution

here i have take 6 cell at main show storyboard

UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;

flowLayout.minimumLineSpacing = 15;
CGFloat availableWidthForCells = CGRectGetWidth(self.collectionView.frame) - flowLayout.sectionInset.left - flowLayout.sectionInset.right - flowLayout.minimumInteritemSpacing *2;

cellWidth = availableWidthForCells /6;
    NSLog(@"cellWidth:%f",cellWidth);
flowLayout.itemSize = CGSizeMake(cellWidth, cellWidth);

This is my Didselect And didDeselect Method

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];

    cell.layer.cornerRadius = cellWidth / 2.0;
    cell.layer.backgroundColor = [UIColor blackColor].CGColor;
    NSLog(@"INDEXPATH:-%ld",(long)indexPath.row);
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.layer.cornerRadius = cellWidth / 2.0;
    cell.layer.backgroundColor = [UIColor whiteColor].CGColor;

}

Body:
Thanks for Alberto Scampini
this code for swift 3.1

var selectedIndexPath: IndexPath?

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "SegmentChoiceCVCell", for: indexPath) as! SegmentChoiceCVCell
    //configure cell

    if selectedIndexPath != nil && indexPath == selectedIndexPath {
        cell.checkIcon.backgroundColor = UIColor.black

    }else{

        cell.checkIcon.backgroundColor = UIColor.white
    }

    return cell

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath) as! SegmentChoiceCVCell

        cell.checkIcon.backgroundColor = UIColor.black
    self.selectedIndexPath = indexPath

}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell: SegmentChoiceCVCell = collectionView.cellForItem(at: indexPath) as! SegmentChoiceCVCell

        cell.checkIcon.backgroundColor = white
    selectedIndexPath = nil
}


问:
Running a batch file in relative path?
There is a batch file which I want to run it when I press the button.
My code works fine when I use absolute (full) path. But using relative path causes to occur an exception.
This is my code:

```<code>private void button1_Click(object sender, EventArgs e)
{
    //x64
    System.Diagnostics.Process batchFile_1 = new System.Diagnostics.Process();
    batchFile_1.StartInfo.FileName = @"..\myBatchFiles\BAT1\f1.bat";
    batchFile_1.StartInfo.WorkingDirectory = @".\myBatchFiles\BAT1";
    batchFile_1.Start();
}
</code>```

and the raised exception:

The system cannot find the file specified.

The directory of the batch file is:

```<code>C:\Users\GntS\myProject\bin\x64\Release\myBatchFiles\BAT1\f1.bat
</code>```

The output .exe file is located in:

```<code>C:\Users\GntS\myProject\bin\x64\Release
</code>```

I searched and none of the results helped me. What is the correct way to run a batch file in relative path?!

答:
The batch file would be relative to the working directory (i.e. f1.bat)

However, your working directory should be an absolute path. It is not guaranteed whichever path is current for your application (may be set in .lnk). In particular it's not the exe path.

Sou you should use the path of your exe file as obtained from AppDomain.CurrentDomain.BaseDirectory (or any other well known method) to build the path of your batch file and/or working directory.

Finally - use Path.Combine to determine a correctly formatted path.

Title: Running a batch file in relative path?

Body:
There is a batch file which I want to run it when I press the button.
My code works fine when I use absolute (full) path. But using relative path causes to occur an exception.
This is my code:

private void button1_Click(object sender, EventArgs e)
{
    //x64
    System.Diagnostics.Process batchFile_1 = new System.Diagnostics.Process();
    batchFile_1.StartInfo.FileName = @"..\myBatchFiles\BAT1\f1.bat";
    batchFile_1.StartInfo.WorkingDirectory = @".\myBatchFiles\BAT1";
    batchFile_1.Start();
}

and the raised exception:

The system cannot find the file specified.

The directory of the batch file is:

C:\Users\GntS\myProject\bin\x64\Release\myBatchFiles\BAT1\f1.bat

The output .exe file is located in:

C:\Users\GntS\myProject\bin\x64\Release

I searched and none of the results helped me. What is the correct way to run a batch file in relative path?!


问:
Why JSP doesn't get Struts 2 action fields
I have a little problem with printing field in a jsp page. I've managed persistency with hibernate.

When I go to jsp page, it displays nothing. How can I modify jsp in order to print fields of prodotti of a scontrino?

Action Class

```<code>public class ScontrinoStruts extends ActionSupport implements UserAware{

        private static java.lang.Float iva = 22.00f;

        private String valori;

        private int idScontrino;
        private Date data;
        private java.lang.Float importoTotale;
        private int totalePezzi;

        private int ID_Anagrafica;//idanagrafica
        private Anagrafica anagrafica;
        private AnagraficaDAO anagraficaDAO = AnagraficaDAOFactory.getDAO();

        private int idProdotto;
        private List<Prodotto> prodotti = new ArrayList<Prodotto>();
        private Prodotto prodotto;

        private Scontrino scontrino = new Scontrino();
        List<Scontrino> scontrini = new ArrayList<Scontrino>();
        ScontrinoDAO scontrinoDAO = ScontrinoDAOFactory.getDAO();
        ProdottoDAO prodottoDAO = ProdottoDAOFactory.getDAO();

        public String showScontrino(){
            scontrino = scontrinoDAO.getScontrino(idScontrino);
            return "success";
        }
        //getters and setters
    }
</code>```

struts.xml

```<code>    <action name="showScontrino" method="showScontrino"
        class="it.unirc.pjam.Action.ScontrinoStruts">
        <result name="success">/scontrino.jsp</result>
    </action>
</code>```

JSP

```<code>    <table>
        <tr>
            <td>id</td>
            <td>Descrizione</td>
            <td>prezzo</td>
        </tr>
        <s:iterator value="scontrino.prodotti">
            <tr>
                <td><s:property value="idProdotto" /></td>
                <td><s:property value="descrizione" /></td>
                <td><s:property value="prezzo" /></td>
            </tr>
        </s:iterator>
    </table>
</code>```

答:
The fields a displayed via OGNL expression that is used to traverse the object properties to find the value. Attributes such as value is used to parse for OGNL expression first before returning its value. How OGNL expression is evaluated you can find in this answer.

You can also read this answer to understand what is the action context that is used by OGNL when it's searching the values.

This answer will guide you how to provide getter for the list that is iterated.

Take a deep learning into OGNL language guide with this answer.

This answer will teach you how to use dot notation to access beans' properties.

Body:
I have a little problem with printing field in a jsp page. I've managed persistency with hibernate.

When I go to jsp page, it displays nothing. How can I modify jsp in order to print fields of prodotti of a scontrino?

Action Class

public class ScontrinoStruts extends ActionSupport implements UserAware{

        private static java.lang.Float iva = 22.00f;

        private String valori;

        private int idScontrino;
        private Date data;
        private java.lang.Float importoTotale;
        private int totalePezzi;

        private int ID_Anagrafica;//idanagrafica
        private Anagrafica anagrafica;
        private AnagraficaDAO anagraficaDAO = AnagraficaDAOFactory.getDAO();

        private int idProdotto;
        private List<Prodotto> prodotti = new ArrayList<Prodotto>();
        private Prodotto prodotto;

        private Scontrino scontrino = new Scontrino();
        List<Scontrino> scontrini = new ArrayList<Scontrino>();
        ScontrinoDAO scontrinoDAO = ScontrinoDAOFactory.getDAO();
        ProdottoDAO prodottoDAO = ProdottoDAOFactory.getDAO();

        public String showScontrino(){
            scontrino = scontrinoDAO.getScontrino(idScontrino);
            return "success";
        }
        //getters and setters
    }

struts.xml

    <action name="showScontrino" method="showScontrino"
        class="it.unirc.pjam.Action.ScontrinoStruts">
        <result name="success">/scontrino.jsp</result>
    </action>

JSP

            id
            Descrizione
            prezzo

        <s:iterator value="scontrino.prodotti">

                <s:property value="idProdotto" />
                <s:property value="descrizione" />
                <s:property value="prezzo" />

        </s:iterator>


问:
How do I get placeholder text in firefox and other browsers that don't support the html5 tag option?
This works in Chrome and any other browser that supports placeholder text in HTML5

```<code><input id="name" name="name"  type="text" placeholder="Please enter your name..." required /> <br />
</code>```

But, it doesn't work in 3.5 and earlier of Firefox, and obviously IE8, and possibly other browsers.

How do I achieve the same thing (preferably in HTML/CSS - if not I am open to suggestions), to support all the older browsers? If not every single browser, at least Firefox and IE.

Safari and Chrome already support it (or the latest versions anyway).

Thanks.

答:
Here is a MooTools Plugin, that brings the placeholder to browsers that don't support it yet:

http://mootools.net/forge/p/form_placeholder

Body:
This works in Chrome and any other browser that supports placeholder text in HTML5

<input id="name" name="name"  type="text" placeholder="Please enter your name..." required />

But, it doesn't work in 3.5 and earlier of Firefox, and obviously IE8, and possibly other browsers.

How do I achieve the same thing (preferably in HTML/CSS - if not I am open to suggestions), to support all the older browsers? If not every single browser, at least Firefox and IE.

Safari and Chrome already support it (or the latest versions anyway).

Thanks.


问:
'ufactor' parameter in metis for imbalance clustering
I have been using METIS for clustering social media users.

By default, it was outputting clusters with same number of vertices in each side, which is not ideal in real world scenario. So, I was trying to find way to loosen the constraint of "same number of vertices" and get possible imbalance partition with minimized cut value.

I find a parameter ufactor in the manual which is suitable(I think) for my case but I did not grasp what it is really doing. I have large graph and tried with some value of ufactor. For one data set ufactor=1000 works very well but for another dataset it could not even partition the graph. I can not interpret this result as i did not understand what it's really doing. Here is what i find in the manual about this:

Specifies the maximum allowed load imbalance among the partitions. A value of x indicates that the
      allowed load imbalance is (1 + x)/1000. The load imbalance for the jth constraint is defined to be
      max_i(w[j, i])/t[j, i]), where w[j, i] is the fraction of the overall weight of the jth constraint that
      is assigned to the ith partition and t[j, i] is the desired target weight of the jth constraint for the
      ith partition (i.e., that specified via -tpwgts). For -ptype=rb, the default value is 1 (i.e., load
      imbalance of 1.001) and for -ptype=kway, the default value is 30 (i.e., load imbalance of 1.03).

Can anybody help me to interpret this? Here, what is jth constraints? what is -ptype=rb/kway?

答:
First of all, let me mention that I think METIS is the wrong tool here, because it is used for graph partitioning, where the emphasis is on minimizing the number of edges between partitions while keeping the partitions balanced (more or less equal sizes)

What you probably want to do is community detection within social networks, i.e. the search for clusters which maximize internal connectivity (large number of edges between nodes from the same cluster) and minimize external connectivity (small number of edges between different clusters).

This can be achieved by maximizing the so-called Modularity of the clustering

There are several approaches to tackle this problem, a popular heuristic being Label propagation.

If you don't want to implement the algorithm yourself, I would recommend using a framework like NetworKit (unfortunately, I don't know any other such frameworks yet), which implements Label propagation, some modularity-based algorithms and many helpful tools.

But back to your original question:

What is -ptype=rb/kway?

There are multiple ways how you can approach the graph partitioning problem: You can either try to partition the graph into your desired number of partitions directly (k-way partitioning) or you can split the graph in half repeatedly until you have the desired number of partitions (recursive bisection, rb)

What is the jth constraint?

METIS allows you to try and optimize multiple balance constraints at the same time, i.e. if you have multiple types of calculations on the graph that should all be more or less balanced among the compute nodes.

See the manual:

Many important types of multi-phase and multi-
  physics computations require that multiple quantities be load balanced simultaneously.
  [...]

  METIS includes partitioning routines that can be used to partition a graph in the presence of such multiple balancing
  constraints. Each vertex is now assigned a vector of m weights and the objective of the partitioning routines is
  to minimize the edge-cut subject to the constraints that each one of the m weights is equally distributed among the
  domains.

EDIT: Since you clarified that you wanted to look at a fixed number of clusters, I see how graph partitioning could be helpful here. Let me illustrate what ufactor means:

The imbalance of a partitioned graph is (in this simple case) computed as the maximum of the imbalance for each partition, which is roughly the quotient partition size / average partition size. So if we allow a maximum imbalance of 2, this means that the largest partition is twice as big as the average partition. Note however that ufactor doesn't specify the imbalance directly, it specifies how many permille away from 1 the imbalance is allowed to be.
So ufactor=143 actually means that your maximal allowed imbalance is 1.143, which makes sense since your clusters are not that far from each other. So in your case, you will probably use larger values for ufactor to allow the groups to be of quite different sizes.

Consequences of large imbalance

If your imbalance is too large, it might happen that all the strongly-connected parts land in the same partition while only isolated nodes are put in the other partitions. This is due to the fact that the algorithm tries to minimize the number of cut edges between different partitions, which will be lower if we put all the high-degree nodes in the same partition.

What about spectral partitioning, ...?

The general approach of METIS works as follows:

Most input graphs are too large to partition directly, which is why so-called multilevel methods are used:

The graph is first coarsened (nodes are combined while trying to preserve the graph structure) until its size becomes feasible to partition directly

The coarsest graph is partitioned using an initial partitioning technique, where we could use a variety of approaches (combinatorial bisection, spectral bisection, exact solutions using ILPs, ...).

The graph is then uncoarsened, where in each step a small number of nodes are moved from partition to partition in a local search to improve the overall edge cut.

My personal recommendation

I should however note that while graph partitioning might be a valid model for your case, METIS itself might not be the ideal implementation for you:

As you can read on the METIS homepage, it is mostly used for rather sparse graphs ('finite element methods, linear programming, VLSI, and transportation'), whereas social networks are much denser and have a different structure (degrees follow a power-law distribution)

The coarsening approach of METIS uses heavy edge matching to combine nodes which are somehow close together, which works great for the intended applications, for social networks however, clustering-based coarsening techniques might prove more efficient.

Another library that is a bit slower in general, but implements some presets especially for social networks is KaHIP, see the manual for details.

(I should mention however that I am biased in this regard, since I worked extensively with this library ;-) )


问:
How to get String[] from ArrayList<String[]>, I want to actually get String at index 0 from ArrayList<String[]>?
I have a Class

```<code>public class DataRatesString {

private String[] ab1 = {"Auto moto sdhv davjdn adadk", "Rs. 355"} ;
    private String[] ab2 = {"sjg atoiu ", "Rs. 200"} ;
    private String[] ab3 = {"go to UTOP atup auto", "Rs. 3279"} ;
    private String[] ab4 = {"Hid to putho", "Rs. 2424"} ;
    private String[] abo5 = {"pithoo to bittu", "Rs. 8457"} ;

private ArrayList<String[]> abCollection = new ArrayList<>();

 public void setAbCollection() {
        abCollection.add(ab1);
        abCollection.add(ab2);
        abCollection.add(ab3);
        abCollection.add(ab4);
        abCollection.add(ab5);
    }

    public ArrayList<String[]> getAbCollection(){
        return abCollection;
    }

}
</code>```

I have another class from which I am calling the list

```<code>DataRatesString dataRatesString = new DataRatesString();
dataRatesString.setAbCollection();

        ArrayList<String[]> ratesarray = dataRatesString.getAbCollection();
</code>```

Now I want to get all the strings at position 0 of the Arraylist String[]

I have created a method in the same class but since I am new to java I am unable to figure out exactly how to do it.

This is the method that I tried to make

```<code>private List<String> getRatesItemNamelist(){
String[] arraylist;
        ArrayList<String> list = new ArrayList<>();

        arraylist = new String[ratesarray.size()];

        for (int i = 0; i < ratesarray.size(); i++) {
        arraylist = ratesarray.get(i);

        }

            list.add(0, arraylist[arraylist.length]);

        return list;
    }
</code>```

This is not working.

答:
If i understood properly, you want all arraylist data at position 0. but i don't think you can achieve. even you want you have to add string in multiple arraylist and each string add in at 0 position respectively.
why not try to make code simpler something like this</p>

```<code>List<String> data =  new ArrayList();
data.add("demo1");
data.add("demo2");
.......

Fetching data at 0 position, you could do this

data.get(0);

Fetch all data, you could use for each loop

for(String s: data){
   //  here is you each position's data as string
}
</code>```

Body:
I have a Class

public class DataRatesString {

private String[] ab1 = {"Auto moto sdhv davjdn adadk", "Rs. 355"} ;
    private String[] ab2 = {"sjg atoiu ", "Rs. 200"} ;
    private String[] ab3 = {"go to UTOP atup auto", "Rs. 3279"} ;
    private String[] ab4 = {"Hid to putho", "Rs. 2424"} ;
    private String[] abo5 = {"pithoo to bittu", "Rs. 8457"} ;

private ArrayList<String[]> abCollection = new ArrayList<>();

 public void setAbCollection() {
        abCollection.add(ab1);
        abCollection.add(ab2);
        abCollection.add(ab3);
        abCollection.add(ab4);
        abCollection.add(ab5);
    }

    public ArrayList<String[]> getAbCollection(){
        return abCollection;
    }

}

I have another class from which I am calling the list

DataRatesString dataRatesString = new DataRatesString();
dataRatesString.setAbCollection();

        ArrayList<String[]> ratesarray = dataRatesString.getAbCollection();

Now I want to get all the strings at position 0 of the Arraylist String[]

I have created a method in the same class but since I am new to java I am unable to figure out exactly how to do it.

This is the method that I tried to make

private List<String> getRatesItemNamelist(){
String[] arraylist;
        ArrayList<String> list = new ArrayList<>();

        arraylist = new String[ratesarray.size()];

        for (int i = 0; i < ratesarray.size(); i++) {
        arraylist = ratesarray.get(i);

        }

            list.add(0, arraylist[arraylist.length]);

        return list;
    }

This is not working.

Body:
If i understood properly, you want all arraylist data at position 0. but i don't think you can achieve. even you want you have to add string in multiple arraylist and each string add in at 0 position respectively.
why not try to make code simpler something like this

List<String> data =  new ArrayList();
data.add("demo1");
data.add("demo2");
.......

Fetching data at 0 position, you could do this

data.get(0);

Fetch all data, you could use for each loop

for(String s: data){
   //  here is you each position's data as string
}


问:
Searching for help to learn
I'm started to study by myself informatics, beginning with html and css and keep going to reach real programming languages. Sometimes I fell like lost while i'm learning and studying something, so I was looking for suggestions about references, about software to use, (now i'm learning on w3schools and sololearn) or books. thanks again to all! </p>

答:
w3schools is good for beginners, try to apply all examples,
and you can learn from https://www.tutorialspoint.com it's so rich of valuable information.

Also, you can read newest articles publish daily in https://css-tricks.com/
and https://tympanus.net/codrops/

regards

Title: Searching for help to learn


问:
How to delete the contents of a file using the FileOutputStream class in Java?
I'm working with the FileOutputStream class in java, but I don't know how to delete "the contents" of a file (the main reason i need overwrite the file).</p>

答:
Yes, you can do it with FileOutputStream. All the answers given say about PrintWriter but the same can be done with  FileOutputStream. The int representation of space is 32. So simply pass the file to the instance of FileOutputStream as:
    FileOutputStream out = new FileOutputStream(file);
    out.write(32);

This will clear the contents of the file. Surely use this only of u want to do it with FileOutputStream only otherwise use PrintWriter.


答:
Try this:

```<code>private List<String> getRatesItemNamelist(){
    List<String> list = new ArrayList<>();
    for (String[] rates : ratesarray) {
        list.add(rates[0]);
    }
    return list;
}
</code>```

Here in the for loop, rates[0] will get the first String from the String[] array for each element in ratesarray ArrayList.

So the getRatesItemNamelist() function will return a list of String at index 0 from ArrayList ratesarray.

Title: How to get String[] from ArrayList<String[]>, I want to actually get String at index 0 from ArrayList<String[]>?

Body:
Try this:

private List<String> getRatesItemNamelist(){
    List<String> list = new ArrayList<>();
    for (String[] rates : ratesarray) {
        list.add(rates[0]);
    }
    return list;
}

Here in the for loop, rates[0] will get the first String from the String[] array for each element in ratesarray ArrayList.

So the getRatesItemNamelist() function will return a list of String at index 0 from ArrayList ratesarray.


问:
Add item at beginning of array on completion
Almost finished (finally) building a simple to do list.

I'm trying to improve what I've done so far.

One big issue is if say you add a task for e.g. 'Task 1' and then 'Task 2' naturally the array will hold them in that order.

The problem with that is if you 'complete' say Task 2 and then 'uncomplete' it goes back to the top of the list.

But I'm using local storage to save my data so even though it goes to the top of the list on the front end when you refresh it doesn't stay there because in the array it is in position 2.

I'm aware of the 'unshift' method but not sure how to use it here in my completed/uncompleted task methods.

Essentially I want my tasks that go from complete back to uncomplete to be priority and go to the top of the uncompleted task list and thus save that order in my local storage array.

https://jsfiddle.net/1uopkysn/

Thanks

JS

```<code>// To do list

var storeToDos = [];

// Cache DOM
var addToDo = document.getElementById('add-to-do');
var taskHolder = document.getElementById('task-holder');
var uncompleteTasks = document.getElementById('uncompleted-tasks');
var completedTasks = document.getElementById('completed-tasks');

// Bind events
var bindEvents = function(listItem, checkboxEventHandler) {
  // Delete
  var deleteToDo = listItem.querySelector('.delete-to-do');
  deleteToDo.addEventListener('click', deleteTask);
  // Edit
  listItem.querySelector('.edit-to-do').addEventListener('click', editTask);
  listItem.querySelector('.edit-holder').addEventListener('keyup', editTaskEnter);
  // Checkbox
  var checkbox = listItem.querySelector('input.edit-to-do');
  checkbox.onchange = checkboxEventHandler;
}

// Create list item
var createListItem = function() {
  var listItem = document.createElement('li');
  var deleteToDo = document.createElement('div');
  deleteToDo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" stroke="#FFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M7.1 7.1l9.8 9.8M7.1 16.9l9.8-9.8"/></svg>';
  deleteToDo.classList.add('delete-to-do');
  var editToDo = document.createElement('div');
  editToDo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" stroke="#FFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M16 3l5 5L8 21H3v-5z"/></svg>';
  editToDo.classList.add('edit-to-do');
  var toDoStatus = document.createElement('input');
  toDoStatus.type = 'checkbox';
  toDoStatus.classList.add('edit-to-do');
  var editHolder = document.createElement('input');
  editHolder.type = 'text';
  editHolder.classList.add('edit-holder');

  listItem.appendChild(deleteToDo);
  listItem.appendChild(editToDo);
  listItem.appendChild(toDoStatus);
  listItem.appendChild(editHolder);

  return listItem;
}

// Add task
var addTask = function(e) {
  var listItem = createListItem();
  var taskHolderValue = taskHolder.value;
  if(taskHolderValue) {
    var taskHolderElement = document.createElement('label');
    taskHolderElement.classList.add('to-do-item');
    listItem.insertBefore(taskHolderElement, listItem.childNodes[0]);
    var storeToDosObj = {
      value: '',
      id: null,
      completed: false
    }
    storeToDosObj.value = taskHolderValue;
    var listId = storeToDosObj.id = Date.now();
    listItem.id = listId;
    uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
    var storedToDos = localStorage.getItem('todos');
    if(storedToDos) {
      var storedToDosArr = JSON.parse(localStorage.todos);
      storedToDosArr.push(storeToDosObj);
      localStorage.setItem('todos', JSON.stringify(storedToDosArr));
    } else {
      console.log(storeToDos);
      storeToDos.push(storeToDosObj);
      localStorage.setItem('todos', JSON.stringify(storeToDos));
    }
    taskHolderElement.innerHTML = taskHolderValue;
    bindEvents(listItem, taskCompleted);
    taskHolder.value = '';
  } else {
    alert("You didn't add a to a to do!");
  }
}

var addTaskEnter = function(e) {
  var key = 'which' in e ? e.which : e.keyCode;
  if(key === 13) {
    addTask();
  }
}

// Delete task
var deleteTask = function() {
  var listItem = this.parentNode;
  var parentItem = listItem.parentNode;
  var getToDos = JSON.parse(localStorage.getItem('todos'));
  for(var b=0; b<getToDos.length; b++) {
    if(getToDos[b].id == listItem.id) {
      getToDos.splice(b, 1);
      localStorage.setItem('todos', JSON.stringify(getToDos));
    }
  }
  parentItem.removeChild(listItem);
}

// Edit task
var editTask = function() {
  var defaultValue = this.parentNode.querySelector('label').innerHTML;
  var listItem = this.parentNode;
  var listParent = this.parentNode;
  var editedValue = listParent.querySelector('input.edit-holder').value;
  if(listItem.classList.contains('editing') && editedValue) {
    listParent.querySelector('label').innerHTML = editedValue;
    var storedLocalStorage = JSON.parse(localStorage.todos);
    for(var d=0; d<storedLocalStorage.length; d++) {
      if(storedLocalStorage[d].id == listItem.id) {
        storedLocalStorage[d].value = editedValue;
        localStorage.setItem('todos', JSON.stringify(storedLocalStorage));
      }
    }
  }
  listItem.classList.toggle('editing');
  listParent.querySelector('input.edit-holder').value = '';
}

// Edit task enter
var editTaskEnter = function(e) {
  var key = 'which' in e ? e.which : e.keyCode;
  if(key === 13) {
    editTask.call(this);
  }
}

// Task completed
var taskCompleted = function() {
  var listItem = this.parentNode;

  var storedCompletion = JSON.parse(localStorage.getItem('todos'));
  if(storedCompletion) {
    if(listItem.classList.contains('editing')) {

    }
    for(var e=0; e<storedCompletion.length; e++) {
      if(storedCompletion[e].id == listItem.id) {
        if(storedCompletion[e].completed === true) {
          this.parentNode.classList.add('completed');
          uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
          this.parentNode.classList.remove('completed');
          bindEvents(listItem, taskCompleted);
          storedCompletion[e].completed = false;
        } else {
          completedTasks.insertBefore(listItem, completedTasks.childNodes[0]);
          this.parentNode.classList.add('completed');
          bindEvents(listItem, taskUncompleted);
          storedCompletion[e].completed = true;
        }
        localStorage.setItem('todos', JSON.stringify(storedCompletion));
      }
    }
  }
}

// Task uncompleted
var taskUncompleted = function() {
  var listItem = this.parentNode;
  uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
  this.parentNode.classList.remove('completed');
  bindEvents(listItem, taskCompleted);

  if(localStorage) {
    var storedCompletion = JSON.parse(localStorage.getItem('todos'));
  }

  for(var f=0; f<storedCompletion.length; f++) {
    if(storedCompletion[f].id == listItem.id) {
      storedCompletion[f].completed = false;
      localStorage.setItem('todos', JSON.stringify(storedCompletion));
    }
  }
}

// Add task
addToDo.addEventListener("click", addTask);
taskHolder.addEventListener("keyup", addTaskEnter);

// Loop over complete tasks
for(i=0; i<completedTasks.length; i++) {
  var listItem = completedTasks[i];
  uncompleteTasks.appendChild(listItem);
  bindEvents(listItem, completedTasks);
}

// Render local storage
var getToDos = JSON.parse(localStorage.getItem('todos'));
console.log(getToDos);
if(getToDos) {
  for(i=0; i<getToDos.length; i++) {
    var listItem = createListItem();
    listItem.id = getToDos[i].id;
    var storedListItem = document.createElement('label');
    storedListItem.innerHTML = getToDos[i].value;
    listItem.insertBefore(storedListItem, listItem.childNodes[0]);
    if(getToDos[i].completed === true) {
      listItem.querySelector('input').checked = true;
      completedTasks.appendChild(listItem);
      listItem.classList.add('completed');
    } else {
      uncompleteTasks.appendChild(listItem);
    }
    bindEvents(listItem, taskCompleted)
  }
}
</code>```

答:
You can associate timestamps with the items and display them according to timestamps in both completed and uncompleted lists. There is no sorting method in LocalStorage though, likewise you cannot insert before or after specifically.

You can sort the array retrieved from json like this (taken from this answer). you can use timestamp to sort array -
JSFiddle here.

```<code>Array.prototype.sortOnValue = function(key){
    this.sort(function(a, b){
        if(a[key] < b[key]){
            return -1;
        }else if(a[key] > b[key]){
            return 1;
        }
        return 0;
    });
}

var arr = [{country:'France', value:'0'},{country:'Italy', value:'3'},
{country:'England', value:'1'},
{country:'Germany', value:'2'}];

arr.sortOnValue("value");

console.log(arr);
</code>```

Hope this helps.

Body:
Almost finished (finally) building a simple to do list.

I'm trying to improve what I've done so far.

One big issue is if say you add a task for e.g. 'Task 1' and then 'Task 2' naturally the array will hold them in that order.

The problem with that is if you 'complete' say Task 2 and then 'uncomplete' it goes back to the top of the list.

But I'm using local storage to save my data so even though it goes to the top of the list on the front end when you refresh it doesn't stay there because in the array it is in position 2.

I'm aware of the 'unshift' method but not sure how to use it here in my completed/uncompleted task methods.

Essentially I want my tasks that go from complete back to uncomplete to be priority and go to the top of the uncompleted task list and thus save that order in my local storage array.

https://jsfiddle.net/1uopkysn/

Thanks

JS

// To do list

var storeToDos = [];

// Cache DOM
var addToDo = document.getElementById('add-to-do');
var taskHolder = document.getElementById('task-holder');
var uncompleteTasks = document.getElementById('uncompleted-tasks');
var completedTasks = document.getElementById('completed-tasks');

// Bind events
var bindEvents = function(listItem, checkboxEventHandler) {
  // Delete
  var deleteToDo = listItem.querySelector('.delete-to-do');
  deleteToDo.addEventListener('click', deleteTask);
  // Edit
  listItem.querySelector('.edit-to-do').addEventListener('click', editTask);
  listItem.querySelector('.edit-holder').addEventListener('keyup', editTaskEnter);
  // Checkbox
  var checkbox = listItem.querySelector('input.edit-to-do');
  checkbox.onchange = checkboxEventHandler;
}

// Create list item
var createListItem = function() {
  var listItem = document.createElement('li');
  var deleteToDo = document.createElement('div');
  deleteToDo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" stroke="#FFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M7.1 7.1l9.8 9.8M7.1 16.9l9.8-9.8"/></svg>';
  deleteToDo.classList.add('delete-to-do');
  var editToDo = document.createElement('div');
  editToDo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" stroke="#FFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M16 3l5 5L8 21H3v-5z"/></svg>';
  editToDo.classList.add('edit-to-do');
  var toDoStatus = document.createElement('input');
  toDoStatus.type = 'checkbox';
  toDoStatus.classList.add('edit-to-do');
  var editHolder = document.createElement('input');
  editHolder.type = 'text';
  editHolder.classList.add('edit-holder');

  listItem.appendChild(deleteToDo);
  listItem.appendChild(editToDo);
  listItem.appendChild(toDoStatus);
  listItem.appendChild(editHolder);

  return listItem;
}

// Add task
var addTask = function(e) {
  var listItem = createListItem();
  var taskHolderValue = taskHolder.value;
  if(taskHolderValue) {
    var taskHolderElement = document.createElement('label');
    taskHolderElement.classList.add('to-do-item');
    listItem.insertBefore(taskHolderElement, listItem.childNodes[0]);
    var storeToDosObj = {
      value: '',
      id: null,
      completed: false
    }
    storeToDosObj.value = taskHolderValue;
    var listId = storeToDosObj.id = Date.now();
    listItem.id = listId;
    uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
    var storedToDos = localStorage.getItem('todos');
    if(storedToDos) {
      var storedToDosArr = JSON.parse(localStorage.todos);
      storedToDosArr.push(storeToDosObj);
      localStorage.setItem('todos', JSON.stringify(storedToDosArr));
    } else {
      console.log(storeToDos);
      storeToDos.push(storeToDosObj);
      localStorage.setItem('todos', JSON.stringify(storeToDos));
    }
    taskHolderElement.innerHTML = taskHolderValue;
    bindEvents(listItem, taskCompleted);
    taskHolder.value = '';
  } else {
    alert("You didn't add a to a to do!");
  }
}

var addTaskEnter = function(e) {
  var key = 'which' in e ? e.which : e.keyCode;
  if(key === 13) {
    addTask();
  }
}

// Delete task
var deleteTask = function() {
  var listItem = this.parentNode;
  var parentItem = listItem.parentNode;
  var getToDos = JSON.parse(localStorage.getItem('todos'));
  for(var b=0; b<getToDos.length; b++) {
    if(getToDos[b].id == listItem.id) {
      getToDos.splice(b, 1);
      localStorage.setItem('todos', JSON.stringify(getToDos));
    }
  }
  parentItem.removeChild(listItem);
}

// Edit task
var editTask = function() {
  var defaultValue = this.parentNode.querySelector('label').innerHTML;
  var listItem = this.parentNode;
  var listParent = this.parentNode;
  var editedValue = listParent.querySelector('input.edit-holder').value;
  if(listItem.classList.contains('editing') && editedValue) {
    listParent.querySelector('label').innerHTML = editedValue;
    var storedLocalStorage = JSON.parse(localStorage.todos);
    for(var d=0; d<storedLocalStorage.length; d++) {
      if(storedLocalStorage[d].id == listItem.id) {
        storedLocalStorage[d].value = editedValue;
        localStorage.setItem('todos', JSON.stringify(storedLocalStorage));
      }
    }
  }
  listItem.classList.toggle('editing');
  listParent.querySelector('input.edit-holder').value = '';
}

// Edit task enter
var editTaskEnter = function(e) {
  var key = 'which' in e ? e.which : e.keyCode;
  if(key === 13) {
    editTask.call(this);
  }
}

// Task completed
var taskCompleted = function() {
  var listItem = this.parentNode;

  var storedCompletion = JSON.parse(localStorage.getItem('todos'));
  if(storedCompletion) {
    if(listItem.classList.contains('editing')) {

    }
    for(var e=0; e<storedCompletion.length; e++) {
      if(storedCompletion[e].id == listItem.id) {
        if(storedCompletion[e].completed === true) {
          this.parentNode.classList.add('completed');
          uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
          this.parentNode.classList.remove('completed');
          bindEvents(listItem, taskCompleted);
          storedCompletion[e].completed = false;
        } else {
          completedTasks.insertBefore(listItem, completedTasks.childNodes[0]);
          this.parentNode.classList.add('completed');
          bindEvents(listItem, taskUncompleted);
          storedCompletion[e].completed = true;
        }
        localStorage.setItem('todos', JSON.stringify(storedCompletion));
      }
    }
  }
}

// Task uncompleted
var taskUncompleted = function() {
  var listItem = this.parentNode;
  uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
  this.parentNode.classList.remove('completed');
  bindEvents(listItem, taskCompleted);

  if(localStorage) {
    var storedCompletion = JSON.parse(localStorage.getItem('todos'));
  }

  for(var f=0; f<storedCompletion.length; f++) {
    if(storedCompletion[f].id == listItem.id) {
      storedCompletion[f].completed = false;
      localStorage.setItem('todos', JSON.stringify(storedCompletion));
    }
  }
}

// Add task
addToDo.addEventListener("click", addTask);
taskHolder.addEventListener("keyup", addTaskEnter);

// Loop over complete tasks
for(i=0; i<completedTasks.length; i++) {
  var listItem = completedTasks[i];
  uncompleteTasks.appendChild(listItem);
  bindEvents(listItem, completedTasks);
}

// Render local storage
var getToDos = JSON.parse(localStorage.getItem('todos'));
console.log(getToDos);
if(getToDos) {
  for(i=0; i<getToDos.length; i++) {
    var listItem = createListItem();
    listItem.id = getToDos[i].id;
    var storedListItem = document.createElement('label');
    storedListItem.innerHTML = getToDos[i].value;
    listItem.insertBefore(storedListItem, listItem.childNodes[0]);
    if(getToDos[i].completed === true) {
      listItem.querySelector('input').checked = true;
      completedTasks.appendChild(listItem);
      listItem.classList.add('completed');
    } else {
      uncompleteTasks.appendChild(listItem);
    }
    bindEvents(listItem, taskCompleted)
  }
}

Body:
You can associate timestamps with the items and display them according to timestamps in both completed and uncompleted lists. There is no sorting method in LocalStorage though, likewise you cannot insert before or after specifically.

You can sort the array retrieved from json like this (taken from this answer). you can use timestamp to sort array -
JSFiddle here.

Array.prototype.sortOnValue = function(key){
    this.sort(function(a, b){
        if(a[key] < b[key]){
            return -1;
        }else if(a[key] > b[key]){
            return 1;
        }
        return 0;
    });
}

var arr = [{country:'France', value:'0'},{country:'Italy', value:'3'},
{country:'England', value:'1'},
{country:'Germany', value:'2'}];

arr.sortOnValue("value");

console.log(arr);

Hope this helps.


问:
Find which phrases have at most one capital letter
I am using RegEx (php) to find out which Addresses have one or less capital letters. For example:

av. St Joan 128 (Not match)

Av. st joan 122 (match)

av. St joan 212 (match)

Av. St.joan 121 (Not match)

AV. st joan 232 (Not match)

答:
You want to use PHP Preg_Match_all to find all occurances of your pattern.

You can define the pattern as being any capital letter, using PCRE so:

[A-Z] = A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

Example:

```<code>$upper = "string oF Occurances";
$count = preg_match_all("/[A-Z]/",$upper);

// $count shows the number of upper case letters found in string
// $count = 2

if ($count == 1){
     print "string ".$upper." has one Capital letter.";
 }
</code>```

I am working on the assumption you are seaching on a per string
  basis rather than per row basis, as in, your exampled text is five
  strings each of one row.

Body:
You want to use PHP Preg_Match_all to find all occurances of your pattern.

You can define the pattern as being any capital letter, using PCRE so:

[A-Z] = A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

Example:

$upper = "string oF Occurances";
$count = preg_match_all("/[A-Z]/",$upper);

// $count shows the number of upper case letters found in string
// $count = 2

if ($count == 1){
     print "string ".$upper." has one Capital letter.";
 }

I am working on the assumption you are seaching on a per string
  basis rather than per row basis, as in, your exampled text is five
  strings each of one row.


问:
Is this possible to write Win32 .dll files by C#.NET?
Is this possible to write Win32 .dll files by C#.NET ?
If yes, where i can find some tutorials?
If no, so what's your suggestion to write Win32 .DLLs?

Thanks.

答:
You can expose any .NET assembly that you write as a com object.

See these tutorials (for VS 2003, but still valid).


问:
Parsing variable-sized packets
I'm working on a multiplayer game and I'm having an issue with the the way I parse the packets from the connection. When I'm debugging the game it runs at a lower performance and the packets are received, when I'm not, packets aren't fully received and the ParsePacket method isn't called.

My packet structure is this:

2 Bytes Short Command, 2 Bytes Short Payload Size, (Optional) Payload Bytes

```<code>IInputStream inputStream = null;
DataReader dataReader = null;

byte[] data = new byte[1024];
IBuffer buffer = data.AsBuffer();

try
{
    inputStream = StreamSocket.InputStream;

    dataReader = DataReader.FromBuffer(buffer);
    dataReader.InputStreamOptions = InputStreamOptions.Partial;
    dataReader.ByteOrder = ByteOrder.LittleEndian;

    while (connected)
    {
        await inputStream.ReadAsync(buffer, 1024, InputStreamOptions.Partial);
        Debug.WriteLine("Buffer " + buffer.Length);

        if (buffer.Length >= PacketHeaderSize)
        {
            short command = dataReader.ReadInt16();
            short payloadSize = dataReader.ReadInt16();
            byte[] payload = null;

            if (payloadSize == 0)
            {
                UpdateBuffer(buffer, (uint)(PacketHeaderSize + payloadSize));

                Packet packet = new Packet(command, payloadSize, payload);
                ParsePacket(packet);
            }
            else if (payloadSize > 0)
            {
                if (buffer.Length >= (PacketHeaderSize + payloadSize))
                {
                    payload = new byte[payloadSize];
                    dataReader.ReadBytes(payload);

                    UpdateBuffer(buffer, (uint)(PacketHeaderSize + payloadSize));

                    Packet packet = new Packet(command, payloadSize, payload);
                    ParsePacket(packet);
                }
            }
        }
    }
}
catch (Exception e) {
    // ...
}

private void UpdateBuffer(IBuffer buffer, uint bytesRead)
{
    if (buffer.Length > bytesRead)
    {
        byte[] bufferBytes = new byte[buffer.Length - bytesRead];
        System.Buffer.BlockCopy(buffer.ToArray(), (int)bytesRead, bufferBytes, 0, (int)(buffer.Length - bytesRead));
        buffer = bufferBytes.AsBuffer();
    }
    else
    {
        byte[] bufferBytes = new byte[1024];
        buffer = bufferBytes.AsBuffer();
    }
}
</code>```

What I'm doing wrong?

答:
Things fixed to make this work:

Take important variables outside the parsing packets loop as we need the value next time we need to parse another packet.

Read the packet header once if a incomplete app or game packet is received.

Load only the bytes we need

Read the header and payload once it has been fully received using UnconsumedBufferLength.

Code:

```<code>short command = 0;
short payloadSize = 0;
byte[] payload = null;

bool packetHeaderRead = false;

while (connected)
{
    if (!packetHeaderRead)
    {
        if (dataReader.UnconsumedBufferLength < PacketHeaderSize)
        {
            int headerBytesLeft = PacketHeaderSize - (int)dataReader.UnconsumedBufferLength;

            if (headerBytesLeft > 0)
            {
                await dataReader.LoadAsync((uint)headerBytesLeft);
                continue;
            }
        }
        else
        {
            command = dataReader.ReadInt16();
            payloadSize = dataReader.ReadInt16();
            packetHeaderRead = true;
            continue;
        }
    }
    else
    {
        int payloadBytesLeft = payloadSize - (int)dataReader.UnconsumedBufferLength;

        if (payloadBytesLeft > 0)
        {
            await dataReader.LoadAsync((uint)payloadBytesLeft);
        }

        if (payloadSize == 0)
        {
            Packet packet = new Packet(command, payloadSize, payload);
            ParsePacket(packet);

            packetHeaderRead = false;
        }
        else if (dataReader.UnconsumedBufferLength >= payloadSize)
        {
            payload = new byte[payloadSize];
            dataReader.ReadBytes(payload);

            Packet packet = new Packet(command, payloadSize, payload);
            ParsePacket(packet);

            packetHeaderRead = false;
        }
    }
}
</code>```

Title: Parsing variable-sized packets

Body:
I'm working on a multiplayer game and I'm having an issue with the the way I parse the packets from the connection. When I'm debugging the game it runs at a lower performance and the packets are received, when I'm not, packets aren't fully received and the ParsePacket method isn't called.

My packet structure is this:

2 Bytes Short Command, 2 Bytes Short Payload Size, (Optional) Payload Bytes

IInputStream inputStream = null;
DataReader dataReader = null;

byte[] data = new byte[1024];
IBuffer buffer = data.AsBuffer();

try
{
    inputStream = StreamSocket.InputStream;

    dataReader = DataReader.FromBuffer(buffer);
    dataReader.InputStreamOptions = InputStreamOptions.Partial;
    dataReader.ByteOrder = ByteOrder.LittleEndian;

    while (connected)
    {
        await inputStream.ReadAsync(buffer, 1024, InputStreamOptions.Partial);
        Debug.WriteLine("Buffer " + buffer.Length);

        if (buffer.Length >= PacketHeaderSize)
        {
            short command = dataReader.ReadInt16();
            short payloadSize = dataReader.ReadInt16();
            byte[] payload = null;

            if (payloadSize == 0)
            {
                UpdateBuffer(buffer, (uint)(PacketHeaderSize + payloadSize));

                Packet packet = new Packet(command, payloadSize, payload);
                ParsePacket(packet);
            }
            else if (payloadSize > 0)
            {
                if (buffer.Length >= (PacketHeaderSize + payloadSize))
                {
                    payload = new byte[payloadSize];
                    dataReader.ReadBytes(payload);

                    UpdateBuffer(buffer, (uint)(PacketHeaderSize + payloadSize));

                    Packet packet = new Packet(command, payloadSize, payload);
                    ParsePacket(packet);
                }
            }
        }
    }
}
catch (Exception e) {
    // ...
}

private void UpdateBuffer(IBuffer buffer, uint bytesRead)
{
    if (buffer.Length > bytesRead)
    {
        byte[] bufferBytes = new byte[buffer.Length - bytesRead];
        System.Buffer.BlockCopy(buffer.ToArray(), (int)bytesRead, bufferBytes, 0, (int)(buffer.Length - bytesRead));
        buffer = bufferBytes.AsBuffer();
    }
    else
    {
        byte[] bufferBytes = new byte[1024];
        buffer = bufferBytes.AsBuffer();
    }
}

What I'm doing wrong?

Body:
Things fixed to make this work:

Take important variables outside the parsing packets loop as we need the value next time we need to parse another packet.

Read the packet header once if a incomplete app or game packet is received.

Load only the bytes we need

Read the header and payload once it has been fully received using UnconsumedBufferLength.

Code:

short command = 0;
short payloadSize = 0;
byte[] payload = null;

bool packetHeaderRead = false;

while (connected)
{
    if (!packetHeaderRead)
    {
        if (dataReader.UnconsumedBufferLength < PacketHeaderSize)
        {
            int headerBytesLeft = PacketHeaderSize - (int)dataReader.UnconsumedBufferLength;

            if (headerBytesLeft > 0)
            {
                await dataReader.LoadAsync((uint)headerBytesLeft);
                continue;
            }
        }
        else
        {
            command = dataReader.ReadInt16();
            payloadSize = dataReader.ReadInt16();
            packetHeaderRead = true;
            continue;
        }
    }
    else
    {
        int payloadBytesLeft = payloadSize - (int)dataReader.UnconsumedBufferLength;

        if (payloadBytesLeft > 0)
        {
            await dataReader.LoadAsync((uint)payloadBytesLeft);
        }

        if (payloadSize == 0)
        {
            Packet packet = new Packet(command, payloadSize, payload);
            ParsePacket(packet);

            packetHeaderRead = false;
        }
        else if (dataReader.UnconsumedBufferLength >= payloadSize)
        {
            payload = new byte[payloadSize];
            dataReader.ReadBytes(payload);

            Packet packet = new Packet(command, payloadSize, payload);
            ParsePacket(packet);

            packetHeaderRead = false;
        }
    }
}


问:
Youtube Video Id from URL - Swift3
Basically I have a Youtube URL as string, I want to extract the video Id from that URL. I found some code in objective c that is as below:

```<code>NSError *error = NULL;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:@"?.*v=([^&]+)"
                                          options:NSRegularExpressionCaseInsensitive
                                            error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:youtubeURL
                                                options:0
                                                  range:NSMakeRange(0, [youtubeURL length])];
if (match) {
    NSRange videoIDRange = [match rangeAtIndex:1];
    NSString *substringForFirstMatch = [youtubeURL substringWithRange:videoIDRange];
}
</code>```

When I am converting this code to swift3 that is:

```<code>var error: Error? = nil
var regex = try! NSRegularExpression(pattern: "?.*v=([^&]+)", options: .caseInsensitive)
var match = regex!.firstMatch(in: youtubeURL, options: [], range: NSRange(location: 0, length: youtubeURL.length))!
if match {
    var videoIDRange = match.rangeAt(1)
    var substringForFirstMatch = (youtubeURL as NSString).substring(with: videoIDRange)
}
</code>```

Gives error as:

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=2048 "The value “?.*v=([^&]+)” is invalid."

Can anybody help me about this error or anybody explain how to get video id from url in Swift 3.

Thanks in advance

答:
Safer version (without force unwrapping !):

```<code>extension String {
    var youtubeID: String? {
        let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/)|(?<=shorts/))([\\w-]++)"

        let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        let range = NSRange(location: 0, length: count)

        guard let result = regex?.firstMatch(in: self, range: range) else {
            return nil
        }

        return (self as NSString).substring(with: result.range)
    }
}
</code>```

Examples:

```<code>"https://www.youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"https://youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"www.youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"youtube.com/shorts/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"youtube.com/embed/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"

"https://youtu.be/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"youtu.be/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
</code>```

Credits: Usman Nisar's answer

Title: Youtube Video Id from URL - Swift3

Body:
Basically I have a Youtube URL as string, I want to extract the video Id from that URL. I found some code in objective c that is as below:

NSError *error = NULL;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:@"?.*v=([^&]+)"
                                          options:NSRegularExpressionCaseInsensitive
                                            error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:youtubeURL
                                                options:0
                                                  range:NSMakeRange(0, [youtubeURL length])];
if (match) {
    NSRange videoIDRange = [match rangeAtIndex:1];
    NSString *substringForFirstMatch = [youtubeURL substringWithRange:videoIDRange];
}

When I am converting this code to swift3 that is:

var error: Error? = nil
var regex = try! NSRegularExpression(pattern: "?.*v=([^&]+)", options: .caseInsensitive)
var match = regex!.firstMatch(in: youtubeURL, options: [], range: NSRange(location: 0, length: youtubeURL.length))!
if match {
    var videoIDRange = match.rangeAt(1)
    var substringForFirstMatch = (youtubeURL as NSString).substring(with: videoIDRange)
}

Gives error as:

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=2048 "The value “?.*v=([^&]+)” is invalid."

Can anybody help me about this error or anybody explain how to get video id from url in Swift 3.

Thanks in advance

Body:
Safer version (without force unwrapping !):

extension String {
    var youtubeID: String? {
        let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/)|(?<=shorts/))([\\w-]++)"

        let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        let range = NSRange(location: 0, length: count)

        guard let result = regex?.firstMatch(in: self, range: range) else {
            return nil
        }

        return (self as NSString).substring(with: result.range)
    }
}

Examples:

"https://www.youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"https://youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"www.youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"youtube.com/shorts/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"youtube.com/embed/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"

"https://youtu.be/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
"youtu.be/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"

Credits: Usman Nisar's answer


问:
php search help
following are my posted variables from search form:

```<code>$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];
</code>```

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

```<code>if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....
</code>```

i need some professional approach for this.

答:
you can do something like this

```<code>$where = array();

if(strcmp($_REQUEST['city'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['city'] . "'";
}
if(strcmp($_REQUEST['location'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['location'] . "'";
}
if(strcmp($_REQUEST['noofbedrooms'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['noofbedrooms'] . "'";
}
if(strcmp($_REQUEST['addeddate'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['addeddate'] . "'";
}
if(strcmp($_REQUEST['pricefrom'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['pricefrom'] . "'";
}
...... // check for all the fields

when create the SQL using

$SQL = implode(" OR ", $where);
</code>```

after that you can use this on some SQL like

```<code>"SELECT * FROM WHERE {$SQL}";
</code>```

Title: php search help

Body:
following are my posted variables from search form:

$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....

i need some professional approach for this.

Body:
you can do something like this

$where = array();

if(strcmp($_REQUEST['city'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['city'] . "'";
}
if(strcmp($_REQUEST['location'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['location'] . "'";
}
if(strcmp($_REQUEST['noofbedrooms'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['noofbedrooms'] . "'";
}
if(strcmp($_REQUEST['addeddate'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['addeddate'] . "'";
}
if(strcmp($_REQUEST['pricefrom'], "")){
    $where[] = "SEARCH_COLUMN = '" . $_REQUEST['pricefrom'] . "'";
}
...... // check for all the fields

when create the SQL using

$SQL = implode(" OR ", $where);

after that you can use this on some SQL like

"SELECT * FROM WHERE {$SQL}";


问:
Slide content animation

This is my content and different content has different behaviour such as when the 1st column click column 2, column 3, column 4 move to right and if 4th column click it push all the content to left.

Jquery

```<code>$("#toogle-1").click(function () {
    $(".WSUA__column__two").animate({ left: '50%' });
    $(".WSUA__column__three").animate({ right: '-25%' });
    $(".WSUA__column__four").animate({ right: '-50%' });
    $("span.hidden-menu.toogle-1").show();
    $("div.hidden-cross.toogle-1").show();
    $("#toogle-1").hide();
    $("#toogle-2").addClass("unclickable");
    $("#toogle-3").addClass("unclickable");
    $("#toogle-4").addClass("unclickable");
});
$("div.hidden-cross.toogle-1").click(function () {
    $(".WSUA__column__two").animate({ left: '25%' });
    $(".WSUA__column__three").animate({ right: '0%' });
    $(".WSUA__column__four").animate({ right: '-25%' });
    $(".hidden-menu").hide();
    $("div.hidden-cross.toogle-1").hide();
    $("#toogle-1").show();
    $("#toogle-2").removeClass("unclickable");
    $("#toogle-3").removeClass("unclickable");
    $("#toogle-4").removeClass("unclickable");
});
</code>```

Is there any way to create a function without declare toogle-1, toogle-2, toogle-3, and toogle-4? Let's say i want to create another content like this and i have to duplicate all the jquery and change all the toogle.

答:
Is this what you mean?

  jQuery(document).ready(function() {
   jQuery('.container > div:nth-child(odd)').click(function() {
    jQuery(this).nextAll().toggleClass('siblings-move-odd');
    jQuery(this).toggleClass('active-odd');
   });
   jQuery('.container > div:nth-child(even)').click(function() {
    jQuery(this).prevAll().toggleClass('siblings-move-even');
    jQuery(this).toggleClass('active-even');
   });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   .container {
   }
   .container > div {
    display: inline-block;
    width: 25%;
    float: left;
    position: relative;
    transition: left 1s ease-in;
    left: 0;
   }
   .container > div.siblings-move-odd {
    left: 25%;
    transition: left 1s ease-in;
   }
   .container > div.siblings-move-even {
    left: -25%;
    transition: left 1s ease-in;
   }
   .container div .right {
    background: grey;
    height: 18px;
    width: 0%;
    display: inline-block;
    position: absolute;
    transition: width 1s ease-in;
   }
   .container div:nth-child(odd) .right {
    left: 100%;
   }
   .container div:nth-child(even) .right {
    right: 100%;
   }
   .container > div.active-odd .right {
    width: 100%;
    transition: width 1s ease-in;
   }
   .container > div.active-even .right {
    width: 100%;
    transition: width 1s ease-in;
   }</code>```

    1

    2

    3

    4

```

Title: Slide content animation

Body:
This is my content and different content has different behaviour such as when the 1st column click column 2, column 3, column 4 move to right and if 4th column click it push all the content to left.

Jquery

$("#toogle-1").click(function () {
    $(".WSUA__column__two").animate({ left: '50%' });
    $(".WSUA__column__three").animate({ right: '-25%' });
    $(".WSUA__column__four").animate({ right: '-50%' });
    $("span.hidden-menu.toogle-1").show();
    $("div.hidden-cross.toogle-1").show();
    $("#toogle-1").hide();
    $("#toogle-2").addClass("unclickable");
    $("#toogle-3").addClass("unclickable");
    $("#toogle-4").addClass("unclickable");
});
$("div.hidden-cross.toogle-1").click(function () {
    $(".WSUA__column__two").animate({ left: '25%' });
    $(".WSUA__column__three").animate({ right: '0%' });
    $(".WSUA__column__four").animate({ right: '-25%' });
    $(".hidden-menu").hide();
    $("div.hidden-cross.toogle-1").hide();
    $("#toogle-1").show();
    $("#toogle-2").removeClass("unclickable");
    $("#toogle-3").removeClass("unclickable");
    $("#toogle-4").removeClass("unclickable");
});

Is there any way to create a function without declare toogle-1, toogle-2, toogle-3, and toogle-4? Let's say i want to create another content like this and i have to duplicate all the jquery and change all the toogle.

Body:
Is this what you mean?

  jQuery(document).ready(function() {
   jQuery('.container > div:nth-child(odd)').click(function() {
    jQuery(this).nextAll().toggleClass('siblings-move-odd');
    jQuery(this).toggleClass('active-odd');
   });
   jQuery('.container > div:nth-child(even)').click(function() {
    jQuery(this).prevAll().toggleClass('siblings-move-even');
    jQuery(this).toggleClass('active-even');
   });
  });

   .container {
   }
   .container > div {
    display: inline-block;
    width: 25%;
    float: left;
    position: relative;
    transition: left 1s ease-in;
    left: 0;
   }
   .container > div.siblings-move-odd {
    left: 25%;
    transition: left 1s ease-in;
   }
   .container > div.siblings-move-even {
    left: -25%;
    transition: left 1s ease-in;
   }
   .container div .right {
    background: grey;
    height: 18px;
    width: 0%;
    display: inline-block;
    position: absolute;
    transition: width 1s ease-in;
   }
   .container div:nth-child(odd) .right {
    left: 100%;
   }
   .container div:nth-child(even) .right {
    right: 100%;
   }
   .container > div.active-odd .right {
    width: 100%;
    transition: width 1s ease-in;
   }
   .container > div.active-even .right {
    width: 100%;
    transition: width 1s ease-in;
   }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div style="background-color: red;">
    1
    <div class="right">
    </div>
   </div>
   <div style="background-color: blue;">
    2
    <div class="right">
    </div>
   </div>
   <div style="background-color: green;">
    3
    <div class="right">
    </div>
   </div>
   <div style="background-color: purple;">
    4
    <div class="right">
    </div>
   </div>
  </div>


问:
Naming of parse string and assign value
Sometimes I have this kind of code, Any advise to improve the readability
of result[0], result[1]...event the naming of result</p>

```<code>var productData = "Egg 1.24 1.36";
var result = productData..Split(new char[] { ' ' });

var product = new
{
Name = result[0],
BuyPrice = result[1],
SellPrice = result[2],
};
</code>```

答: I don't how you get productData but is it possible to maybe get it as a json? That would improve the readability alot instead of splitting it and get string based on positions. </p>

Title: Naming of parse string and assign value

Body:
Sometimes I have this kind of code, Any advise to improve the readability
of result[0], result[1]...event the naming of result

var productData = "Egg 1.24 1.36";
var result = productData..Split(new char[] { ' ' });

var product = new
{
Name = result[0],
BuyPrice = result[1],
SellPrice = result[2],
};


问:
Designing / combining redux reducers
I am cleaning up my reducer setup which was wrong from the beginning. I using the redux doco and the ducks pattern to set it right.

I want to separate/divide my state like the doco suggests:

```<code>{
    domainData1 : {},
    domainData2 : {},
    appState1 : {},
    appState2 : {},
    ui : {
        uiState1 : {},
        uiState2 : {},
    }
}
</code>```

In my case I have some albums, catalogs and photos which I'm trying to manage. The state should look something like this:

```<code>{
    //domainData
    albums : {...},
    catalogs : {...},
    photos : {...},

    //appState
    selectedAlbum : {...},

    //uiState
    ui : {
        loading : {},
        uiState2 : {},
    }
}
</code>```

I have put all code belonging to albums in one file where actions, action creators, recuders and API is located
similar for catalogs and photos.
Then I combine the reducers with combineReducers in a separate file.

Code below...

My question is... when I do stuff on albums I will want all the domain data to go into the albums branch of the state. But I don't want the ui and app state stuff to go into the albums branch - this should go in to the app and ui state branches. that's not possible with my setup, e.g. when loading albums I set the loading flag in the "albums" reducer, this is the fed til the combineReducer, and the result is that the loading state becomes part of the albums branch of the state...

Albums module:

```<code>import { createRequest, responseHandler, notAuthorized } from './apiUtils';
import { List, Map, fromJS } from 'immutable';

//actions
const REQUEST_ALBUMS = 'REQUEST_ALBUMS';
const FETCH_ALBUMS_SUCCESS = 'FETCH_ALBUMS_SUCCESS';
const FETCH_ALBUM_SUCCESS = 'FETCH_ALBUM_SUCCESS';
const REQUEST_ALBUM = 'REQUEST_ALBUM';
const CREATE_ALBUM = 'CREATE_ALBUM';
const CREATE_ALBUM_SUCCESS = 'CREATE_ALBUM_SUCCESS';
const UPDATE_ALBUM = 'UPDATE_ALBUM';
const UPDATE_ALBUM_SUCCESS = 'UPDATE_ALBUM_SUCCESS';

// Reducer
var init = Map(fromJS({
  albums: [],
  album: [],
  loading: false,
}));

var newState = null;

export function reducer(state=init, action={}) {
  switch (action.type) {

    case FETCH_ALBUMS_SUCCESS: {
      newState = state
        .set('albums', fromJS(action.payload.albums))
        .set('loading', false);
      return newState;
    }

    case REQUEST_ALBUMS: {
      return state.set('loading', true);
    }

    case FETCH_ALBUM_SUCCESS: {
      newState = state
        .set('album', fromJS(action.payload.album))
        .set('loading', false);
      return newState;
    }

    case REQUEST_ALBUM: {
      return state.set('loading', true);
    }

    case CREATE_ALBUM: {
      return state.set('loading', true);
    }

    case CREATE_ALBUM_SUCCESS: {
      newState = state
        .set('album', fromJS(action.payload.album))
        .set('loading', false);
      return newState;
    }

    case UPDATE_ALBUM: {
      return state.set('loading', true);
    }

    case UPDATE_ALBUM_SUCCESS: {
      newState = state
        .set('album', fromJS(action.payload.album))
        .set('loading', false);
      return newState;
    }
  }
  return state;
}

// Action Creators
export function getAlbumsPending(response) {
  return {
    type: REQUEST_ALBUMS,
  };
}

export function getAlbumsSuccess(response) {
  return {
    type: FETCH_ALBUMS_SUCCESS,
    payload: response,
  };
}

export function getAlbumPending(response) {
  return {
    type: REQUEST_ALBUM,
  };
}

export function getAlbumSuccess(response) {
  return {
    type: FETCH_ALBUM_SUCCESS,
    payload: response,
  };
}

function createAlbumPending(response) {
  return {
    type: CREATE_ALBUM,
  };
}

function createAlbumSuccess(response) {
  return {
    type: CREATE_ALBUM_SUCCESS,
    payload: response,
  };
}

export function updateAlbumPending(response) {
  return {
    type: UPDATE_ALBUM,
  };
}

export function updateAlbumSuccess(response) {
  return {
    type: UPDATE_ALBUM_SUCCESS,
    payload: response,
  };
}

//API

export function fetchAlbums() {
  //API url
  const url = '/api/albums.json';

  //make the call
  return dispatch => {

    dispatch(getAlbumsPending());

    fetch(createRequest('GET', url, null))
    .then(response => responseHandler(response))
    .then(data => dispatch(getAlbumsSuccess(data)))
    .catch(error => console.log('request failed', error));
  };
}

export function fetchAlbum(id) {
  //url
  var url = '/api/albums/'.concat(id);

  return dispatch => {
    dispatch(getAlbumPending());

    fetch(createRequest('GET', url, null))
    .then(response => responseHandler(response))
    .then(data => dispatch(getAlbumSuccess({ album: data })))
    .catch(error => console.log('request failed', error));
  };
}

export function createAlbum(params) {
  //API url
  const url = '/api/albums/';

  return dispatch => {

    dispatch(createAlbumPending());

    fetch(createRequest('POST', url, params))
    .then(response => responseHandler(response))
    .then(data => dispatch(createAlbumSuccess({ album: data })))
    .catch(error => console.log('request failed', error));
  };
}

export function updateAlbum(params) {
  //API url
  var url = '/api/albums/'.concat(params.id);

  //make the call
  return dispatch => {

    dispatch(updateAlbumPending());

    fetch(createRequest('PUT', url, params))
    .then(response => responseHandler(response))
    .then(data => dispatch(updateAlbumSuccess({ album: data })))
    .catch(error => console.log('request failed', error));
  };
}
</code>```

CombineRecucer:

```<code>import { combineReducers } from 'redux';
import { reducer as albumReducer } from '../actions/album';
import { reducer as catalogReducer } from '../actions/catalog';

export default combineReducers({
  albums: albumReducer,  // <- loading flag ends up here
  catalogs: catalogReducer,
  loading: // I want loading flag here
});
</code>```

Sorry for the long post - no potato

答:
You just move that logic to the Loading reducer responsible for that slice of the state.

```<code>// ducks/Loading.js

import {
  REQUEST_ALBUM,
  CREATE_ALBUM,
  CREATE_ALBUM_SUCCESS
} from 'ducks/Albums'
// remember to also export from the Albums duck.

export const reducer = (state, action) => {
  switch (action.type) {
    case REQUEST_ALBUM:
    case CREATE_ALBUM:
      return state.set('loading', true)

    case CREATE_ALBUM_SUCCESS:
      return state.set('loading', false)
  }
}
</code>```

You can import the action types from the other duck file.
The Albums reducer is only responsible for updating its own slice of the state.

Multiple reducers can listen to the same action types, and do some changes to their own slice. So CREATE_ALBUM_SUCCESS can also trigger some change in the Albums reducer.

You can also implement this in some other way. For instance by using a key in the meta field of an action. This avoids having to do lots of imports and exports, since the reducer doesn't have to know the type of the action.

```<code>// loading reducer
export const reducer = (state = false, action) =>
  (action.meta && action.meta.loading !== undefined)
    ? action.meta.loading
    : state

// action creator
export const updateAlbumPending = () => ({
  type: UPDATE_ALBUM,
  meta: {
    loading: true
  }
})
</code>```

Title: Designing / combining redux reducers

Body:
I am cleaning up my reducer setup which was wrong from the beginning. I using the redux doco and the ducks pattern to set it right.

I want to separate/divide my state like the doco suggests:

{
    domainData1 : {},
    domainData2 : {},
    appState1 : {},
    appState2 : {},
    ui : {
        uiState1 : {},
        uiState2 : {},
    }
}

In my case I have some albums, catalogs and photos which I'm trying to manage. The state should look something like this:

{
    //domainData
    albums : {...},
    catalogs : {...},
    photos : {...},

    //appState
    selectedAlbum : {...},

    //uiState
    ui : {
        loading : {},
        uiState2 : {},
    }
}

I have put all code belonging to albums in one file where actions, action creators, recuders and API is located
similar for catalogs and photos.
Then I combine the reducers with combineReducers in a separate file.

Code below...

My question is... when I do stuff on albums I will want all the domain data to go into the albums branch of the state. But I don't want the ui and app state stuff to go into the albums branch - this should go in to the app and ui state branches. that's not possible with my setup, e.g. when loading albums I set the loading flag in the "albums" reducer, this is the fed til the combineReducer, and the result is that the loading state becomes part of the albums branch of the state...

Albums module:

import { createRequest, responseHandler, notAuthorized } from './apiUtils';
import { List, Map, fromJS } from 'immutable';

//actions
const REQUEST_ALBUMS = 'REQUEST_ALBUMS';
const FETCH_ALBUMS_SUCCESS = 'FETCH_ALBUMS_SUCCESS';
const FETCH_ALBUM_SUCCESS = 'FETCH_ALBUM_SUCCESS';
const REQUEST_ALBUM = 'REQUEST_ALBUM';
const CREATE_ALBUM = 'CREATE_ALBUM';
const CREATE_ALBUM_SUCCESS = 'CREATE_ALBUM_SUCCESS';
const UPDATE_ALBUM = 'UPDATE_ALBUM';
const UPDATE_ALBUM_SUCCESS = 'UPDATE_ALBUM_SUCCESS';

// Reducer
var init = Map(fromJS({
  albums: [],
  album: [],
  loading: false,
}));

var newState = null;

export function reducer(state=init, action={}) {
  switch (action.type) {

    case FETCH_ALBUMS_SUCCESS: {
      newState = state
        .set('albums', fromJS(action.payload.albums))
        .set('loading', false);
      return newState;
    }

    case REQUEST_ALBUMS: {
      return state.set('loading', true);
    }

    case FETCH_ALBUM_SUCCESS: {
      newState = state
        .set('album', fromJS(action.payload.album))
        .set('loading', false);
      return newState;
    }

    case REQUEST_ALBUM: {
      return state.set('loading', true);
    }

    case CREATE_ALBUM: {
      return state.set('loading', true);
    }

    case CREATE_ALBUM_SUCCESS: {
      newState = state
        .set('album', fromJS(action.payload.album))
        .set('loading', false);
      return newState;
    }

    case UPDATE_ALBUM: {
      return state.set('loading', true);
    }

    case UPDATE_ALBUM_SUCCESS: {
      newState = state
        .set('album', fromJS(action.payload.album))
        .set('loading', false);
      return newState;
    }
  }
  return state;
}

// Action Creators
export function getAlbumsPending(response) {
  return {
    type: REQUEST_ALBUMS,
  };
}

export function getAlbumsSuccess(response) {
  return {
    type: FETCH_ALBUMS_SUCCESS,
    payload: response,
  };
}

export function getAlbumPending(response) {
  return {
    type: REQUEST_ALBUM,
  };
}

export function getAlbumSuccess(response) {
  return {
    type: FETCH_ALBUM_SUCCESS,
    payload: response,
  };
}

function createAlbumPending(response) {
  return {
    type: CREATE_ALBUM,
  };
}

function createAlbumSuccess(response) {
  return {
    type: CREATE_ALBUM_SUCCESS,
    payload: response,
  };
}

export function updateAlbumPending(response) {
  return {
    type: UPDATE_ALBUM,
  };
}

export function updateAlbumSuccess(response) {
  return {
    type: UPDATE_ALBUM_SUCCESS,
    payload: response,
  };
}

//API

export function fetchAlbums() {
  //API url
  const url = '/api/albums.json';

  //make the call
  return dispatch => {

    dispatch(getAlbumsPending());

    fetch(createRequest('GET', url, null))
    .then(response => responseHandler(response))
    .then(data => dispatch(getAlbumsSuccess(data)))
    .catch(error => console.log('request failed', error));
  };
}

export function fetchAlbum(id) {
  //url
  var url = '/api/albums/'.concat(id);

  return dispatch => {
    dispatch(getAlbumPending());

    fetch(createRequest('GET', url, null))
    .then(response => responseHandler(response))
    .then(data => dispatch(getAlbumSuccess({ album: data })))
    .catch(error => console.log('request failed', error));
  };
}

export function createAlbum(params) {
  //API url
  const url = '/api/albums/';

  return dispatch => {

    dispatch(createAlbumPending());

    fetch(createRequest('POST', url, params))
    .then(response => responseHandler(response))
    .then(data => dispatch(createAlbumSuccess({ album: data })))
    .catch(error => console.log('request failed', error));
  };
}

export function updateAlbum(params) {
  //API url
  var url = '/api/albums/'.concat(params.id);

  //make the call
  return dispatch => {

    dispatch(updateAlbumPending());

    fetch(createRequest('PUT', url, params))
    .then(response => responseHandler(response))
    .then(data => dispatch(updateAlbumSuccess({ album: data })))
    .catch(error => console.log('request failed', error));
  };
}

CombineRecucer:

import { combineReducers } from 'redux';
import { reducer as albumReducer } from '../actions/album';
import { reducer as catalogReducer } from '../actions/catalog';

export default combineReducers({
  albums: albumReducer,  // <- loading flag ends up here
  catalogs: catalogReducer,
  loading: // I want loading flag here
});

Sorry for the long post - no potato

Body:
You just move that logic to the Loading reducer responsible for that slice of the state.

// ducks/Loading.js

import {
  REQUEST_ALBUM,
  CREATE_ALBUM,
  CREATE_ALBUM_SUCCESS
} from 'ducks/Albums'
// remember to also export from the Albums duck.

export const reducer = (state, action) => {
  switch (action.type) {
    case REQUEST_ALBUM:
    case CREATE_ALBUM:
      return state.set('loading', true)

    case CREATE_ALBUM_SUCCESS:
      return state.set('loading', false)
  }
}

You can import the action types from the other duck file.
The Albums reducer is only responsible for updating its own slice of the state.

Multiple reducers can listen to the same action types, and do some changes to their own slice. So CREATE_ALBUM_SUCCESS can also trigger some change in the Albums reducer.

You can also implement this in some other way. For instance by using a key in the meta field of an action. This avoids having to do lots of imports and exports, since the reducer doesn't have to know the type of the action.

// loading reducer
export const reducer = (state = false, action) =>
  (action.meta && action.meta.loading !== undefined)
    ? action.meta.loading
    : state

// action creator
export const updateAlbumPending = () => ({
  type: UPDATE_ALBUM,
  meta: {
    loading: true
  }
})


问:
I cant use do until and if with Form.visible control
I was trying to create a Form using Do Until. The thing is when ı run this code I get an exception : "System.InvalidCastException".
So here is the code Im trying to run:

```<code>    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim x As Boolean = False
    Do Until x
        If Form2.Visible = False & Form3.Visible = False & Form4.Visible = False Then
            x = True
        End If
    Loop
End
End Sub
</code>```

Also as an explanation of what I'm trying to do: When form2,form3 and form4 is NOT visible The Program will End

答:
In VB.NET the logical operator to use is And or better AndAlso

```<code>If Form2.Visible = False AndAlso
   Form3.Visible = False AndAlso
   Form4.Visible = False Then
   x = True
End if
</code>```

AndAlso is better because if the left side of the operator is false then it breaks immediately the test without evaluating the rest of the line

Of course, keep in mind that this loop is an infinite loop if any of these forms is visible. It will continue to run ad infinitum and you cannot do anything to the other forms to allow it to exit. This will effectively crush your UI.

At least you need to add an Application.DoEvents here to allow some other action to happen inside that loop.

Body:
I was trying to create a Form using Do Until. The thing is when ı run this code I get an exception : "System.InvalidCastException".
So here is the code Im trying to run:

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim x As Boolean = False
    Do Until x
        If Form2.Visible = False & Form3.Visible = False & Form4.Visible = False Then
            x = True
        End If
    Loop
End
End Sub

Also as an explanation of what I'm trying to do: When form2,form3 and form4 is NOT visible The Program will End

Body:
In VB.NET the logical operator to use is And or better AndAlso

If Form2.Visible = False AndAlso
   Form3.Visible = False AndAlso
   Form4.Visible = False Then
   x = True
End if

AndAlso is better because if the left side of the operator is false then it breaks immediately the test without evaluating the rest of the line

Of course, keep in mind that this loop is an infinite loop if any of these forms is visible. It will continue to run ad infinitum and you cannot do anything to the other forms to allow it to exit. This will effectively crush your UI.

At least you need to add an Application.DoEvents here to allow some other action to happen inside that loop.