问:
Target images inside slider
I have made a custom slider.. with a bit of help.. I need some help targeting images when clicking the next button.

my codepen is here
https://codepen.io/erayner/pen/LLBwOj

essentially when I click the next button i just want to hide one of the images.

```<code>//example of one of the slides
<div class="row slide slide2">
        <div class="col-sm-6 slide2-container">
            <div class="slide2-container1">
                <h4>Burglar</h4>
                <p>A burglar looks for an easy entry point</p>
                <ul>
                    <li>Unlocked doors</li>
                    <li>Open windows</li>
                </ul>
                <p>To keep burglars out, effective security should</p>
                <p><span>Discover</span> them on the edge of your property before they get in.</p>
                <p><span>Enforce</span> existing security measures to maintain high security standards.</p>
                <p><span>Harden</span> security tools to make entry difficult.</p>
            </div>
            <div class="slide2-container2">
                <h4>Cyber Hacker</h4>
                <p>Cyber attackers look for easy entry points</p>
                <ul>
                    <li>Social engineering/phishing to get an unsuspecting user to expose their network credentials or install malware</li>
                    <li>Exploiting a vulnerability in a web-based application or service</li>
                </ul>
                <p>To keep attackers out, effective security should</p>
                <p><span>Discover</span> when malicious sites, applications or downloads are being accessed.</p>
                <p><span>Enforce</span> existing security measures to block this activity.</p>
                <p><span>Harden</span> security tools to make entry difficult before a connection is established.</p>
            </div>
        </div>
        <div class="col-sm-6 slide2">
            <img src="http://ciscosecurity.co.nz/test-images/state-2.svg" class="svg svg1">
            <img src="http://ciscosecurity.co.nz/test-images/state-1.svg" class="svg">
        </div>
    </div>

//jquery im trying to get to hide '.active .svg(1,2,3)'
jQuery('.arrow-left, .arrow-right').click(function (e) {
    e.preventDefault();
    if ($('.active').hasClass('slide2')) {
        $('.svg2').hide();
    } else {
        $('.svg2').show();
    }
    t($(this));
});
</code>```

any help greatly appreciated.
Cheers

EDIT: Updated jQuery -> 'previous' button doesn't work with code but 'next' does

答:
Just a matter of targeting the correct element here is an example that I think is trying to do what you want.

https://codepen.io/natedog213/pen/RgJZYd?editors=1111

```<code>if ($('.slide2').hasClass('current')){
   $('.slide2').children().last().css('top', '-300px');
}else{
   $('.slide2').children().last().css('top' , '100px');
}
</code>```

Title: Target images inside slider

Body:
I have made a custom slider.. with a bit of help.. I need some help targeting images when clicking the next button.

my codepen is here
https://codepen.io/erayner/pen/LLBwOj

essentially when I click the next button i just want to hide one of the images.

//example of one of the slides

Burglar

A burglar looks for an easy entry point

Unlocked doors

Open windows

To keep burglars out, effective security should

Discover them on the edge of your property before they get in.

Enforce existing security measures to maintain high security standards.

Harden security tools to make entry difficult.

Cyber Hacker

Cyber attackers look for easy entry points

Social engineering/phishing to get an unsuspecting user to expose their network credentials or install malware

Exploiting a vulnerability in a web-based application or service

To keep attackers out, effective security should

Discover when malicious sites, applications or downloads are being accessed.

Enforce existing security measures to block this activity.

Harden security tools to make entry difficult before a connection is established.

//jquery im trying to get to hide '.active .svg(1,2,3)'
jQuery('.arrow-left, .arrow-right').click(function (e) {
    e.preventDefault();
    if ($('.active').hasClass('slide2')) {
        $('.svg2').hide();
    } else {
        $('.svg2').show();
    }
    t($(this));
});

any help greatly appreciated.
Cheers

EDIT: Updated jQuery -> 'previous' button doesn't work with code but 'next' does

Body:
Just a matter of targeting the correct element here is an example that I think is trying to do what you want.

https://codepen.io/natedog213/pen/RgJZYd?editors=1111

if ($('.slide2').hasClass('current')){
   $('.slide2').children().last().css('top', '-300px');
}else{
   $('.slide2').children().last().css('top' , '100px');
}


来源: stackexchange

问:
How to change CPLEX parameters in oplrun?
Is there a way to let oplrun take a specific CPLEX parameter, such as  CPX_PARAM_LPMETHOD (Linear Programming method). In the reference here, it is called by various names for different languages:

```<code>C Name: CPX_PARAM_LPMETHOD

C++ Name: RootAlg

Java Name: RootAlg

.NET Name: RootAlg

InteractiveOptimizer: lpmethod
</code>```

But there is no reference about the OPL or oplrun.

Is it possible to change this parameter in an oplrun session? Or do I have to use these other languages/interfaces?

答:
It's not possible to do this (directly) using oplrun command line options. You can, however, use oplrun to execute a specific run configuration that has an associated settings file (a .ops file). For example:

```<code>oplrun [options] -p project-dir [run-configuration ...]
</code>```

When you use the IDE to set individual parameters, the OPL names for the parameters are stored in the .ops file. For example, the CPLEX parameter CPX_PARAM_TILIMIT is named tiLimit in OPL (see here for more).

Alternately, you could export your OPL model using the -e oplrun option. Then, you could run that using the CPLEX interactive and use a parameter file or set them in the command line itself (see here for the syntax).

Lastly, you can surely use one of the programming language APIs available in CPLEX to accomplish the same thing. This would provide the most control, but may take more time (depending on how comfortable you are with programming).

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to let oplrun take a specific CPLEX parameter, such as  CPX_PARAM_LPMETHOD (Linear Programming method). In the reference here, it is called by various names for different languages:

C Name: CPX_PARAM_LPMETHOD

C++ Name: RootAlg

Java Name: RootAlg

.NET Name: RootAlg

InteractiveOptimizer: lpmethod

But there is no reference about the OPL or oplrun.

Is it possible to change this parameter in an oplrun session? Or do I have to use these other languages/interfaces?

Body:
It's not possible to do this (directly) using oplrun command line options. You can, however, use oplrun to execute a specific run configuration that has an associated settings file (a .ops file). For example:

oplrun [options] -p project-dir [run-configuration ...]

When you use the IDE to set individual parameters, the OPL names for the parameters are stored in the .ops file. For example, the CPLEX parameter CPX_PARAM_TILIMIT is named tiLimit in OPL (see here for more).

Alternately, you could export your OPL model using the -e oplrun option. Then, you could run that using the CPLEX interactive and use a parameter file or set them in the command line itself (see here for the syntax).

Lastly, you can surely use one of the programming language APIs available in CPLEX to accomplish the same thing. This would provide the most control, but may take more time (depending on how comfortable you are with programming).


问:
how to show data in listview from web service in android
my webservice return a data in the format

 ab
 cdef

i have to show to this return data in listview here is my welcome.xml in which i have to display data

welcome.xml

```<code>  <?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
  <ImageView android:id="@+id/welcome" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/main" android:layout_gravity="center_horizontal" />
  -
- <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:id="@+id/Relative01">
  <ListView android:id="@+id/lvevent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/welcome" android:background="@drawable/wel_bg" android:layout_marginBottom="50dip" />
  </RelativeLayout>
- <TableLayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_below="@+id/Relative01">
- <TableRow>
  <Button android:id="@+id/btn_index" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/cap_button" android:paddingRight="15dip" android:layout_marginRight="50dip" />
  <Button android:id="@+id/btn_event" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/button" android:layout_toRightOf="@+id/btn_index" android:paddingLeft="25dip" android:layout_marginLeft="30dip" />
  </TableRow>
  </TableLayout>
  </LinearLayout>
</code>```

how can i show data in listview.

following code i am using for parser:

MYXMLHandler.java :

```<code>package org.parsing;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyXMLHandler extends DefaultHandler{
 Boolean currentElement = false;
 String currentValue = null;
 public static SitesList sitesList = null;

 public static SitesList getSitesList() {
  return sitesList;
 }

 public static void setSitesList(SitesList sitesList) {
  MyXMLHandler.sitesList = sitesList;
 }

 /** Called when tag starts ( ex:- <name>AndroidPeople</name>
  * -- <name> )*/
 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {

  currentElement = true;

  if (localName.equals("content"))
  {
   /** Start */
   sitesList = new SitesList();
  } /*else if (localName.equals("website")) {
   *//** Get attribute value *//*
   String attr = attributes.getValue("category");
   sitesList.setCategory(attr);
  }*/

 }

 /** Called when tag closing ( ex:- <name>AndroidPeople</name>
  * -- </name> )*/
 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {

  currentElement = false;

  /** set value */
  if (localName.equalsIgnoreCase("title"))
   sitesList.setTitle(currentValue);
  else if (localName.equalsIgnoreCase("description"))
   sitesList.setDescription(currentValue);

 }

 /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
  * -- to get AndroidPeople Character ) */
 public void characters(char[] ch, int start, int length)
   throws SAXException {

  if (currentElement) {
   currentValue = new String(ch, start, length);
   currentElement = false;
  }

 }

}
</code>```

SitesList.java:

```<code>package org.parsing;

import java.util.ArrayList;

public class SitesList {

 /** Variables */
 private ArrayList<String> title = new ArrayList<String>();
 private ArrayList<String> description = new ArrayList<String>();
 //private ArrayList<String> category = new ArrayList<String>();

 /** In Setter method default it will return arraylist
  *  change that to add  */

 public ArrayList<String> getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title.add(title);
 }

 public ArrayList<String> getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description.add(description);
 }

 /*public ArrayList<String> getCategory() {
  return category;
 }

 public void setCategory(String category) {
  this.category.add(category);
 }
*/
}
</code>```

XMLParsingExample.java:

```<code>package org.parsing;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class XMLParsingExample extends Activity {
 /** Create Object For SiteList Class */
 SitesList sitesList = null;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  /** Create a new layout to display the view */
  LinearLayout layout = new LinearLayout(this);
  layout.setOrientation(1);

  /** Create a new textview array to display the results */
  TextView title[];
  TextView description[];
  //TextView category[];

  try {

   /** Handling XML */
   SAXParserFactory spf = SAXParserFactory.newInstance();
   SAXParser sp = spf.newSAXParser();
   XMLReader xr = sp.getXMLReader();

   /** Send URL to parse XML Tags */
   URL sourceUrl = new URL(
     "http://208.109.97.179:1010/webservices/newsevents.php");

   /** Create handler to handle XML Tags ( extends DefaultHandler ) */
   MyXMLHandler myXMLHandler = new MyXMLHandler();
   xr.setContentHandler((ContentHandler) myXMLHandler);
   xr.parse(new InputSource(sourceUrl.openStream()));

  } catch (Exception e) {
   System.out.println("XML Pasing Excpetion = " + e);
  }

  /** Get result from MyXMLHandler SitlesList Object */
  sitesList = MyXMLHandler.sitesList;

  /** Assign textview array lenght by arraylist size */
  title = new TextView[sitesList.getTitle().size()];
  description = new TextView[sitesList.getDescription().size()];
  //category = new TextView[sitesList.getName().size()];

  /** Set the result text in textview and add it to layout */
  for (int i = 0; i < sitesList.getTitle().size(); i++) {
   title[i] = new TextView(this);
   title[i].setText("Title = "+sitesList.getTitle().get(i));
   description[i] = new TextView(this);
   description[i].setText("Website = "+sitesList.getDescription().get(i));
   //category[i] = new TextView(this);
   //category[i].setText("Website Category = "+sitesList.getCategory().get(i));

   layout.addView(title[i]);
   layout.addView(description[i]);
   //layout.addView(category[i]);
  }

  /** Set the layout view to display */
  setContentView(layout);

 }

}
</code>```

after checking my code tell me where i am wrong and tell the correct answer.

答: One solution can be, parse the XML response from web service and store the parsed data in array(s). Then simply use array adapter to populate the ListView.</p>

ContentLicense: CC BY-SA 2.5

Body:
my webservice return a data in the format

 ab
 cdef

i have to show to this return data in listview here is my welcome.xml in which i have to display data

welcome.xml

  <?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
  <ImageView android:id="@+id/welcome" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/main" android:layout_gravity="center_horizontal" />
  -
- <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:id="@+id/Relative01">
  <ListView android:id="@+id/lvevent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/welcome" android:background="@drawable/wel_bg" android:layout_marginBottom="50dip" />
  </RelativeLayout>
- <TableLayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_below="@+id/Relative01">
- <TableRow>
  <Button android:id="@+id/btn_index" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/cap_button" android:paddingRight="15dip" android:layout_marginRight="50dip" />
  <Button android:id="@+id/btn_event" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/button" android:layout_toRightOf="@+id/btn_index" android:paddingLeft="25dip" android:layout_marginLeft="30dip" />
  </TableRow>
  </TableLayout>
  </LinearLayout>

how can i show data in listview.

following code i am using for parser:

MYXMLHandler.java :

package org.parsing;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyXMLHandler extends DefaultHandler{
 Boolean currentElement = false;
 String currentValue = null;
 public static SitesList sitesList = null;

 public static SitesList getSitesList() {
  return sitesList;
 }

 public static void setSitesList(SitesList sitesList) {
  MyXMLHandler.sitesList = sitesList;
 }

 /** Called when tag starts ( ex:- <name>AndroidPeople</name>
  * -- <name> )*/
 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {

  currentElement = true;

  if (localName.equals("content"))
  {
   /** Start */
   sitesList = new SitesList();
  } /*else if (localName.equals("website")) {
   *//** Get attribute value *//*
   String attr = attributes.getValue("category");
   sitesList.setCategory(attr);
  }*/

 }

 /** Called when tag closing ( ex:- <name>AndroidPeople</name>
  * -- </name> )*/
 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {

  currentElement = false;

  /** set value */
  if (localName.equalsIgnoreCase("title"))
   sitesList.setTitle(currentValue);
  else if (localName.equalsIgnoreCase("description"))
   sitesList.setDescription(currentValue);

 }

 /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
  * -- to get AndroidPeople Character ) */
 public void characters(char[] ch, int start, int length)
   throws SAXException {

  if (currentElement) {
   currentValue = new String(ch, start, length);
   currentElement = false;
  }

 }

}

SitesList.java:

package org.parsing;

import java.util.ArrayList;

public class SitesList {

 /** Variables */
 private ArrayList<String> title = new ArrayList<String>();
 private ArrayList<String> description = new ArrayList<String>();
 //private ArrayList<String> category = new ArrayList<String>();

 /** In Setter method default it will return arraylist
  *  change that to add  */

 public ArrayList<String> getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title.add(title);
 }

 public ArrayList<String> getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description.add(description);
 }

 /*public ArrayList<String> getCategory() {
  return category;
 }

 public void setCategory(String category) {
  this.category.add(category);
 }
*/
}

XMLParsingExample.java:

package org.parsing;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class XMLParsingExample extends Activity {
 /** Create Object For SiteList Class */
 SitesList sitesList = null;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  /** Create a new layout to display the view */
  LinearLayout layout = new LinearLayout(this);
  layout.setOrientation(1);

  /** Create a new textview array to display the results */
  TextView title[];
  TextView description[];
  //TextView category[];

  try {

   /** Handling XML */
   SAXParserFactory spf = SAXParserFactory.newInstance();
   SAXParser sp = spf.newSAXParser();
   XMLReader xr = sp.getXMLReader();

   /** Send URL to parse XML Tags */
   URL sourceUrl = new URL(
     "http://208.109.97.179:1010/webservices/newsevents.php");

   /** Create handler to handle XML Tags ( extends DefaultHandler ) */
   MyXMLHandler myXMLHandler = new MyXMLHandler();
   xr.setContentHandler((ContentHandler) myXMLHandler);
   xr.parse(new InputSource(sourceUrl.openStream()));

  } catch (Exception e) {
   System.out.println("XML Pasing Excpetion = " + e);
  }

  /** Get result from MyXMLHandler SitlesList Object */
  sitesList = MyXMLHandler.sitesList;

  /** Assign textview array lenght by arraylist size */
  title = new TextView[sitesList.getTitle().size()];
  description = new TextView[sitesList.getDescription().size()];
  //category = new TextView[sitesList.getName().size()];

  /** Set the result text in textview and add it to layout */
  for (int i = 0; i < sitesList.getTitle().size(); i++) {
   title[i] = new TextView(this);
   title[i].setText("Title = "+sitesList.getTitle().get(i));
   description[i] = new TextView(this);
   description[i].setText("Website = "+sitesList.getDescription().get(i));
   //category[i] = new TextView(this);
   //category[i].setText("Website Category = "+sitesList.getCategory().get(i));

   layout.addView(title[i]);
   layout.addView(description[i]);
   //layout.addView(category[i]);
  }

  /** Set the layout view to display */
  setContentView(layout);

 }

}

after checking my code tell me where i am wrong and tell the correct answer.


问:
Erratic Counter Code By VHDL
I just wrote a VHDL code but it doesn’t work correctly. I want to write an erratic counter with D Flip-Flop that count like this: 0 –> 13 –> 5 –> 7 –> 12 –> 6 –> 3 –> 15 –> 10 -> 0.
It should have these properties:

It should be structural

Four outputs (3 down to 0)

It should have an asynchronous reset

It should have an enable

It should have an active high clock.

I wrote my code below but I know it’s not OK. Can anyone help me please?

```<code>library IEEE ;
use IEEE.std_logic_1164.all ;
-- and_gate
entity and_gate is
  port(Input1, Input2:in bit;
  Output:out bit);
end and_gate;
architecture behavioral of and_gate is
  begin
    Output <= (Input1 and Input2) ;
end behavioral;
-- or_gate
entity or_gate is
  port(Input1, Input2:in bit;
  Output:out bit);
end or_gate;
architecture behavioral of or_gate is
  begin
  Output <= (Input1 or Input2);
end behavioral;
-- not_gate
entity not_gate is
  port(Input : in bit; Output : out bit);
end not_gate;
architecture behavioral of not_gate is
begin
  Output <= not(Input);
end behavioral;
-- D-FF
entity DFF is
    port(CLK,RESET,EN,DIN :in bit;
    COUNT  :out bit);
    end DFF;
architecture behavioral of DFF is
begin
    LSEQ :process(RESET,CLK)
    begin
        if(RESET ='0')then
            COUNT  <='0';
        elsif(CLK'event and CLK ='1')then
            if(EN ='1')then
                COUNT  <=DIN;
        end if;
    end if;
 end process;
end behavioral;
-- counter
entity counter is
    port (CLK,RESET,EN: in bit;
         COUNT : out bit_vector(3 downto 0));
end counter;

architecture counter_structural of counter is

component and_gate
    port(Input1,Input2 : in bit; Output: out bit);
end component;

component or_gate
    port(Input1,Input2 : in bit; Output : out bit);
end component;

component not_gate
    port(Input : in bit; Output : out bit);
end component;

component DFF
    port(CLK,RESET,EN,DIN :in bit; COUNT  :out bit);
end component;

signal A,B,C,D,ai,bi,ci,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15 : bit;

begin
    Gate1: not_gate port map (A,ai);
    Gate2: not_gate port map (B,bi);
    Gate3: and_gate port map (ai,bi,a1);
    Gate4: and_gate port map (C,D,a2);
    Gate5: or_gate  port map (a1,a2,a3);
    Gate6: DFF port map (CLK,RESET,EN,a3,COUNT(0));
    Gate7: and_gate port map (ai,B,a4);
    Gate8: not_gate port map (c,ci);
    Gate9: and_gate port map (ai,D,a5);
    Gate10: or_gate port map (a4,ci,a6);
    Gate11: or_gate port map (a5,a6,a7);
    Gate12: DFF port map (CLK,RESET,EN,a7,COUNT(1));
    Gate13: and_gate port map (A,B,a8);
    Gate14: and_gate port map (C,D,a9);
    Gate15: or_gate port map (a8,a9,a10);
    Gate16: DFF port map (CLK,RESET,EN,a10,COUNT(2));
    Gate17: and_gate  port map (ai,B,a11);
    Gate18: and_gate  port map (ci,D,a12);
    Gate19: and_gate  port map (ai,D,a13);
    Gate20: or_gate port map (a11,a12,a14);
    Gate21: or_gate port map (a13,a14,a15);
    Gate22: DFF port map (CLK,RESET,EN,a15,COUNT(3));
end counter_structural ;
</code>```

答:
Use a ring counter. A ring counter is just n registers with their inputs and outputs chained in a ring. The output of the final register can also be used as the output of the counter. The values that you want to output can be used as the register's initial and reset values. Make sure that the register's initial values are the reverse of what you want to output because the ring counter will output the initial value on register n, then n-1, n-2, etc.

In this case you can use:

```<code>register value
0        0
1        10
2        15
3        3
4        6
5        12
6        7
7        5
8        13
9        0
</code>```

Edit: Another benefit of using the ring counter is reuse of components. A structural ring counter only needs one component, a register. This will stop your code from being bloated by all of the component declarations like it is now.

Title: Erratic Counter Code By VHDL

Body:
I just wrote a VHDL code but it doesn’t work correctly. I want to write an erratic counter with D Flip-Flop that count like this: 0 –> 13 –> 5 –> 7 –> 12 –> 6 –> 3 –> 15 –> 10 -> 0.
It should have these properties:

It should be structural

Four outputs (3 down to 0)

It should have an asynchronous reset

It should have an enable

It should have an active high clock.

I wrote my code below but I know it’s not OK. Can anyone help me please?

library IEEE ;
use IEEE.std_logic_1164.all ;
-- and_gate
entity and_gate is
  port(Input1, Input2:in bit;
  Output:out bit);
end and_gate;
architecture behavioral of and_gate is
  begin
    Output <= (Input1 and Input2) ;
end behavioral;
-- or_gate
entity or_gate is
  port(Input1, Input2:in bit;
  Output:out bit);
end or_gate;
architecture behavioral of or_gate is
  begin
  Output <= (Input1 or Input2);
end behavioral;
-- not_gate
entity not_gate is
  port(Input : in bit; Output : out bit);
end not_gate;
architecture behavioral of not_gate is
begin
  Output <= not(Input);
end behavioral;
-- D-FF
entity DFF is
    port(CLK,RESET,EN,DIN :in bit;
    COUNT  :out bit);
    end DFF;
architecture behavioral of DFF is
begin
    LSEQ :process(RESET,CLK)
    begin
        if(RESET ='0')then
            COUNT  <='0';
        elsif(CLK'event and CLK ='1')then
            if(EN ='1')then
                COUNT  <=DIN;
        end if;
    end if;
 end process;
end behavioral;
-- counter
entity counter is
    port (CLK,RESET,EN: in bit;
         COUNT : out bit_vector(3 downto 0));
end counter;

architecture counter_structural of counter is

component and_gate
    port(Input1,Input2 : in bit; Output: out bit);
end component;

component or_gate
    port(Input1,Input2 : in bit; Output : out bit);
end component;

component not_gate
    port(Input : in bit; Output : out bit);
end component;

component DFF
    port(CLK,RESET,EN,DIN :in bit; COUNT  :out bit);
end component;

signal A,B,C,D,ai,bi,ci,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15 : bit;

begin
    Gate1: not_gate port map (A,ai);
    Gate2: not_gate port map (B,bi);
    Gate3: and_gate port map (ai,bi,a1);
    Gate4: and_gate port map (C,D,a2);
    Gate5: or_gate  port map (a1,a2,a3);
    Gate6: DFF port map (CLK,RESET,EN,a3,COUNT(0));
    Gate7: and_gate port map (ai,B,a4);
    Gate8: not_gate port map (c,ci);
    Gate9: and_gate port map (ai,D,a5);
    Gate10: or_gate port map (a4,ci,a6);
    Gate11: or_gate port map (a5,a6,a7);
    Gate12: DFF port map (CLK,RESET,EN,a7,COUNT(1));
    Gate13: and_gate port map (A,B,a8);
    Gate14: and_gate port map (C,D,a9);
    Gate15: or_gate port map (a8,a9,a10);
    Gate16: DFF port map (CLK,RESET,EN,a10,COUNT(2));
    Gate17: and_gate  port map (ai,B,a11);
    Gate18: and_gate  port map (ci,D,a12);
    Gate19: and_gate  port map (ai,D,a13);
    Gate20: or_gate port map (a11,a12,a14);
    Gate21: or_gate port map (a13,a14,a15);
    Gate22: DFF port map (CLK,RESET,EN,a15,COUNT(3));
end counter_structural ;

Body:
Use a ring counter. A ring counter is just n registers with their inputs and outputs chained in a ring. The output of the final register can also be used as the output of the counter. The values that you want to output can be used as the register's initial and reset values. Make sure that the register's initial values are the reverse of what you want to output because the ring counter will output the initial value on register n, then n-1, n-2, etc.

In this case you can use:

register value
0        0
1        10
2        15
3        3
4        6
5        12
6        7
7        5
8        13
9        0

Edit: Another benefit of using the ring counter is reuse of components. A structural ring counter only needs one component, a register. This will stop your code from being bloated by all of the component declarations like it is now.


问:
How can I merge duplicate objects with Linq while concatenating a property?
I have an object:

```<code>private class User
    {
        public string fullname { get; set; }
        public string manager { get; set; }
        public string businessunit { get; set; }
        public string employeeid { get; set; }
        public string mainphone { get; set; }
        public string fax { get; set; }
        public string mobile { get; set; }
        public string email { get; set; }
        public string street3 { get; set; }
        public string street2 { get; set; }
        public string street1 { get; set; }
        public string city { get; set; }
        public string stateorprovince { get; set; }
        public string ziporpostalcode { get; set; }
        public string department { get; set; }
        public string countryorregion { get; set; }
        public string salesarea { get; set; }
        public string title { get; set; }
        public string username { get; set; }
        public string companyname { get; set; }
        public string securityroles { get; set; }
        public User()
        {

        }
    }
</code>```

I also have a list of that object:

```<code>List<User> users = new List<User>();
</code>```

What I'd like to do is merge all Users in the list with the same fullname while concatenating all of their different securityroles into the same securityroles property.

I was thinking something along the lines of this would work:

```<code>users = (from user in users
                 group user by user.fullname
                 /*not sure what to put here*/).ToList();
</code>```

答:
Thank you D Stanley and mzaverez. This function works but I might change it since the merge function executes multiple queries:

```<code>private User Merge(IEnumerable<User> users)
    {
        User u = new User();
        if (!users.Any())
        {
            return u;
        }
        else
        {
            u.fullname = users.First().fullname;
            u.manager = users.First().manager;
            u.businessunit = users.First().businessunit;
            u.employeeid = users.First().employeeid;
            u.mainphone = users.First().mainphone;
            u.fax = users.First().fax;
            u.mobile = users.First().mobile;
            u.email = users.First().email;
            u.street1 = users.First().street1;
            u.street2 = users.First().street2;
            u.street3 = users.First().street3;
            u.city = users.First().city;
            u.stateorprovince = users.First().stateorprovince;
            u.ziporpostalcode = users.First().ziporpostalcode;
            u.department = users.First().department;
            u.countryorregion = users.First().countryorregion;
            u.salesarea = users.First().salesarea;
            u.title = users.First().title;
            u.username = users.First().username;
            u.companyname = users.First().companyname;
            u.securityroles = string.Join(", ", users.Select(x => x.securityroles));
            return u;
        }
    }
</code>```

That function is called by the very helpful Linq code D Stanley suggested below:

```<code>users = (from user in users
         group user by user.fullname into g
         select Merge(g)
        ).ToList();
</code>```

Body:
I have an object:

private class User
    {
        public string fullname { get; set; }
        public string manager { get; set; }
        public string businessunit { get; set; }
        public string employeeid { get; set; }
        public string mainphone { get; set; }
        public string fax { get; set; }
        public string mobile { get; set; }
        public string email { get; set; }
        public string street3 { get; set; }
        public string street2 { get; set; }
        public string street1 { get; set; }
        public string city { get; set; }
        public string stateorprovince { get; set; }
        public string ziporpostalcode { get; set; }
        public string department { get; set; }
        public string countryorregion { get; set; }
        public string salesarea { get; set; }
        public string title { get; set; }
        public string username { get; set; }
        public string companyname { get; set; }
        public string securityroles { get; set; }
        public User()
        {

        }
    }

I also have a list of that object:

List<User> users = new List<User>();

What I'd like to do is merge all Users in the list with the same fullname while concatenating all of their different securityroles into the same securityroles property.

I was thinking something along the lines of this would work:

users = (from user in users
                 group user by user.fullname
                 /*not sure what to put here*/).ToList();

Body:
Thank you D Stanley and mzaverez. This function works but I might change it since the merge function executes multiple queries:

private User Merge(IEnumerable<User> users)
    {
        User u = new User();
        if (!users.Any())
        {
            return u;
        }
        else
        {
            u.fullname = users.First().fullname;
            u.manager = users.First().manager;
            u.businessunit = users.First().businessunit;
            u.employeeid = users.First().employeeid;
            u.mainphone = users.First().mainphone;
            u.fax = users.First().fax;
            u.mobile = users.First().mobile;
            u.email = users.First().email;
            u.street1 = users.First().street1;
            u.street2 = users.First().street2;
            u.street3 = users.First().street3;
            u.city = users.First().city;
            u.stateorprovince = users.First().stateorprovince;
            u.ziporpostalcode = users.First().ziporpostalcode;
            u.department = users.First().department;
            u.countryorregion = users.First().countryorregion;
            u.salesarea = users.First().salesarea;
            u.title = users.First().title;
            u.username = users.First().username;
            u.companyname = users.First().companyname;
            u.securityroles = string.Join(", ", users.Select(x => x.securityroles));
            return u;
        }
    }

That function is called by the very helpful Linq code D Stanley suggested below:

users = (from user in users
         group user by user.fullname into g
         select Merge(g)
        ).ToList();


问:
Removing newline after
 tags?
I am having a problem with removing linebreaks after the
 tag, as everytime it prints, it adds a line break straight after it, so something like
Hello World!

Hello Again World!
 prints out like this:

```<code>Hello World!

Hello Again World!
</code>```

I am unsure on what tags I need to change in CSS, but I expect it's something to do with the padding or margins

I also want to keep the vertical padding if at all possible.

答:
</p>

```<code><style>
h1 {
    padding: 0px;
    margin: 0px;
}
</style>
</code>```

Title: Removing newline after <h1> tags?

Body:
I am having a problem with removing linebreaks after the
 tag, as everytime it prints, it adds a line break straight after it, so something like
Hello World!

Hello Again World!
 prints out like this:

Hello World!

Hello Again World!

I am unsure on what tags I need to change in CSS, but I expect it's something to do with the padding or margins

I also want to keep the vertical padding if at all possible.


问:
Wrapper for arbitrary function in Go
Is it possible to create a wrapper for arbitrary function in Go that would take the same arguments and return the same value?

I'm not talking about the wrapper that would look exactly the same, it may look differently, but it should solve the problem.

For example the problem might be to create a wrapper of arbitrary function that first looks for the result of the function call in cache and only in case of cache miss executes the wrapped function.

答:
The best I've come up with is to take a function def and return an interface, which will need type assertion afterwards:

```<code>func Wrapper(metaParams string, f func() (interface{}, string, error)) (interface{}, error) {
    // your wrapper code
    res, metaResults, err := f()
    // your wrapper code
    return res, err
}
</code>```

Then to use this also takes a little work to function like a wrapper:

```<code>resInterface, err := Wrapper("data for wrapper", func() (interface{}, string, error) {
    res, err := YourActualFuntion(whatever, params, needed)
    metaResults := "more data for wrapper"
    return res, metaResults, err
}) // note f() is not called here! Pass the func, not its results
if err != nil {
    // handle it
}
res, ok := resInterface.(actualType)
if !ok {
    // handle it
}
</code>```

The upside is this is somewhat generic, can handle anything with 1 return type + error, and doesn't require reflection.

The downside is this takes a lot of work to use as it's not a simple wrapper or decorator.

Title: Wrapper for arbitrary function in Go

Body:
The best I've come up with is to take a function def and return an interface, which will need type assertion afterwards:

func Wrapper(metaParams string, f func() (interface{}, string, error)) (interface{}, error) {
    // your wrapper code
    res, metaResults, err := f()
    // your wrapper code
    return res, err
}

Then to use this also takes a little work to function like a wrapper:

resInterface, err := Wrapper("data for wrapper", func() (interface{}, string, error) {
    res, err := YourActualFuntion(whatever, params, needed)
    metaResults := "more data for wrapper"
    return res, metaResults, err
}) // note f() is not called here! Pass the func, not its results
if err != nil {
    // handle it
}
res, ok := resInterface.(actualType)
if !ok {
    // handle it
}

The upside is this is somewhat generic, can handle anything with 1 return type + error, and doesn't require reflection.

The downside is this takes a lot of work to use as it's not a simple wrapper or decorator.


问:
Does apache / php blocks a single file to be processed from the same client concurrently?
I have everything setup and running with KalturaCE & Drupak and the server (Ubuntu 8.02+Apache2+PHP5+MySql) is working fine.
The issue here I am having is unclassified.

When I play two videos together from my site, the second video which I played later doesn't start until the first completes its buffering. I did some HTTP watch and came to know that,
both of the entries request the file with the URL as follows,

```<code>/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxx/flavor/1/version/100000
</code>```

so the first video which I played receives a 302 redirect response to the URL as follows,

```<code>/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxxx/flavor/1/version/100000/a.flv?novar=0
</code>```

and starts buffering and playing. While the second video which I started later just wait for a response till the first video end its buffering and then the second video receives its 302 redirect and start buffering

My question is, why can't both videos buffer concurrently? and Obviously this is what I require.

Your help is highly anticipated and much welcome.

答:
I posted several suggestions at http://drupal.org/node/1002144 for the same question, this is one of them:

In Apache space, a possible cause might be MaxClients (or, the capacity of your Apache server to respond to multiple requests). If that apache setting or server capacity is low, then the server may be dropping your connections into its backlog until the first connection is completed. You can test this using regular large files which take some time to download on the server - that will establish whether it's KalturaCE or Apache which is causing the issue. To see this you'd either need a site which is already sitting at max for MaxClients (ie, not an unused dev site), or a very low MaxClients setting (like, 1!).

Body:
I have everything setup and running with KalturaCE & Drupak and the server (Ubuntu 8.02+Apache2+PHP5+MySql) is working fine.
The issue here I am having is unclassified.

When I play two videos together from my site, the second video which I played later doesn't start until the first completes its buffering. I did some HTTP watch and came to know that,
both of the entries request the file with the URL as follows,

/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxx/flavor/1/version/100000

so the first video which I played receives a 302 redirect response to the URL as follows,

/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxxx/flavor/1/version/100000/a.flv?novar=0

and starts buffering and playing. While the second video which I started later just wait for a response till the first video end its buffering and then the second video receives its 302 redirect and start buffering

My question is, why can't both videos buffer concurrently? and Obviously this is what I require.

Your help is highly anticipated and much welcome.


问:
Code working locally but not in Server, SQL and null string related
Hello i have the following cs code

```<code> SqlConnection con = new SqlConnection();
        SqlCommand com = new SqlCommand();
        String comando = "";
        con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["INBIOTECAConnectionString"].ToString());
        SqlDataReader leer = null;
        String diaUltimo = "";
        String fecha = DateTime.Now.ToString("dd/MM/yyyy");

        try
        {
            con.Open();
            comando = " SELECT TOP 1 hora FROM SI_RegEntrada  WHERE nombre = '" + name + "' and dia = '"+fecha+"' ORDER BY id DESC;";
            com = new SqlCommand(comando, con);
            leer = com.ExecuteReader();
            while (leer.Read())
            {
                diaUltimo = leer[0].ToString();
            }

            if (diaUltimo.Equals(""))
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        catch (Exception ex)
        {
            return true;
        }
        finally
        {
            con.Close();
            con.Dispose();
            com.Dispose();
            com = null;
            con = null;
        }
</code>```

It's supposed to be pretty simple, it's gonna check if there's an entry on the SI_RegEntrada table today (fecha) from any user (name).

```<code>SELECT TOP 1 hora FROM SI_RegEntrada  WHERE nombre = '" + name + "' and dia = '"+fecha+"' ORDER BY id DESC;
</code>```

ok, so far so good, i proceed to read the results on the var diaUltimo.

On my local server, if there are no results (meaning that today, that user, hasn't interact with the system), diaUltimo will get the value of

```<code> diaUltimo = ""
</code>```

so I check for that in the if/else condition a return true or false.
In the live server, it always falls on the catch clause, and return always true.

I was thinking that, maybe diaUltimo will get some kind of null value, or some sql error.

I cannot debug or interact with the live server.

答:
First, temporarily replace the string contents of comando to be a SQL command which is not dependent on your table or rows...something like:

```<code>static string commando = "Select to_char(sysdate) from dual";
</code>```

This will do 2 things: it will test whether your connection object and SQLExecute both work as expected AND it will test the default format mask on date fields in your live database.

If you do not get any results then I would begin diagnosing the exception by not returning 'true' but instead raising an internal exception and passing the ex object contents out for your to inspect.

Body:
Hello i have the following cs code

 SqlConnection con = new SqlConnection();
        SqlCommand com = new SqlCommand();
        String comando = "";
        con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["INBIOTECAConnectionString"].ToString());
        SqlDataReader leer = null;
        String diaUltimo = "";
        String fecha = DateTime.Now.ToString("dd/MM/yyyy");

        try
        {
            con.Open();
            comando = " SELECT TOP 1 hora FROM SI_RegEntrada  WHERE nombre = '" + name + "' and dia = '"+fecha+"' ORDER BY id DESC;";
            com = new SqlCommand(comando, con);
            leer = com.ExecuteReader();
            while (leer.Read())
            {
                diaUltimo = leer[0].ToString();
            }

            if (diaUltimo.Equals(""))
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        catch (Exception ex)
        {
            return true;
        }
        finally
        {
            con.Close();
            con.Dispose();
            com.Dispose();
            com = null;
            con = null;
        }

It's supposed to be pretty simple, it's gonna check if there's an entry on the SI_RegEntrada table today (fecha) from any user (name).

SELECT TOP 1 hora FROM SI_RegEntrada  WHERE nombre = '" + name + "' and dia = '"+fecha+"' ORDER BY id DESC;

ok, so far so good, i proceed to read the results on the var diaUltimo.

On my local server, if there are no results (meaning that today, that user, hasn't interact with the system), diaUltimo will get the value of

 diaUltimo = ""

so I check for that in the if/else condition a return true or false.
In the live server, it always falls on the catch clause, and return always true.

I was thinking that, maybe diaUltimo will get some kind of null value, or some sql error.

I cannot debug or interact with the live server.

Body:
First, temporarily replace the string contents of comando to be a SQL command which is not dependent on your table or rows...something like:

static string commando = "Select to_char(sysdate) from dual";

This will do 2 things: it will test whether your connection object and SQLExecute both work as expected AND it will test the default format mask on date fields in your live database.

If you do not get any results then I would begin diagnosing the exception by not returning 'true' but instead raising an internal exception and passing the ex object contents out for your to inspect.


问:
How does Windows Store purchase work?
I'm having questions about how does exactly windows apps do the purchase. Let me clarify my question.
In UWP coding we use these codes to check if the product is purchased or not:

```<code>   var License = CurrentApp.LicenseInformation;
   var Listing = await CurrentApp.LoadListingInformationAsync();
</code>```

And the question is that, how does this method understands that if we purchased it or not? It does do an HTTP Request every time?(I need details) Or loads from a file (Again I need details, What file, where)? I used to deal with Listing Simulator and It was an XML file. I think that store saves an XML file in a place that I don't know.

It's a real question for me to understand that how it works. I found nothing in Microsoft documents.

答:
I don't think you really read the Microsoft documentation.

It says right in the docs for LoadListingInformationAsync method:

"Calling this method requires an internet connection."

From that remark it's easy to infer that it is making an HTTP request everytime

The LicenseInformation property however does not need an internet connection.

Title: How does Windows Store purchase work?

Body:
I'm having questions about how does exactly windows apps do the purchase. Let me clarify my question.
In UWP coding we use these codes to check if the product is purchased or not:

   var License = CurrentApp.LicenseInformation;
   var Listing = await CurrentApp.LoadListingInformationAsync();

And the question is that, how does this method understands that if we purchased it or not? It does do an HTTP Request every time?(I need details) Or loads from a file (Again I need details, What file, where)? I used to deal with Listing Simulator and It was an XML file. I think that store saves an XML file in a place that I don't know.

It's a real question for me to understand that how it works. I found nothing in Microsoft documents.


问:
Apply function doesn't replace values in dataframe
I'm trying to replace nan values of age based on the median of some corresponding groups. I've made a table called grouped_median using groupby. This is my code:

```<code>def fillAges(row, grouped_median):
    return grouped_median.loc[row['Sex'], row['Class'], row['Title']]['Age']

df['Age'] = df.apply(lambda x : fillAges(x, grouped_median) if np.isnan(x['Age']) else x['Age'], axis=1)

df
</code>```

If I print only this part:

```<code>print(df.apply(lambda x : fillAges(x, grouped_median) if np.isnan(x['Age']) else x['Age'], axis=1))
</code>```

The values are correct but then once I look at the df, the nan values are not replaced. I appreciate any help. Thank you!

EDIT: As Nathaniel said, this code works fine. Indeed df is a big dataframe concatenated from both train and test datasets with one extra flag column that is either "train" or "test". Then this is what I was doing:

```<code>df[df['flag']=='train']['Age'] = df[df['flag']=='train'].apply(lambda x : fillAges(x, grouped_median) if np.isnan(x['Age']) else x['Age'], axis=1)
</code>```

and it wouldn't work. This would give me this warning but I thought it was only a warning not meaning that it wasn't doing actually anything!!! "A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: pandas.pydata.org/pandas-docs/stable/…

All what I needed to do was to remove the [df['flag']=='train'] part from the left.

I'm still not sure why this approach wasn't working. If anyone has an insight, I appreciate to know it. Thank you

答:
You'll have to format for function to take a series and return a series rather than operate on just an element of the series. I've added the function series_op below that should do this for you.

```<code>def fillAges(row, grouped_median):
    return grouped_median.loc[row['Sex'], row['Class'], row['Title']]['Age']

def series_op(x):
    x['Age'] = fillAges(x, grouped_median) if np.isnan(x['Age']) else x['Age']
    return x

corrected_df = df.apply(series_op, axis=1)
</code>```

I don't have your data nor grouped_median so I can't replicate your problem.  With some test data that I've cooked up, I am able to get this to work correctly, but also able to get yours to work correctly.

Body:
I'm trying to replace nan values of age based on the median of some corresponding groups. I've made a table called grouped_median using groupby. This is my code:

def fillAges(row, grouped_median):
    return grouped_median.loc[row['Sex'], row['Class'], row['Title']]['Age']

df['Age'] = df.apply(lambda x : fillAges(x, grouped_median) if np.isnan(x['Age']) else x['Age'], axis=1)

df

If I print only this part:

print(df.apply(lambda x : fillAges(x, grouped_median) if np.isnan(x['Age']) else x['Age'], axis=1))

The values are correct but then once I look at the df, the nan values are not replaced. I appreciate any help. Thank you!

EDIT: As Nathaniel said, this code works fine. Indeed df is a big dataframe concatenated from both train and test datasets with one extra flag column that is either "train" or "test". Then this is what I was doing:

df[df['flag']=='train']['Age'] = df[df['flag']=='train'].apply(lambda x : fillAges(x, grouped_median) if np.isnan(x['Age']) else x['Age'], axis=1)

and it wouldn't work. This would give me this warning but I thought it was only a warning not meaning that it wasn't doing actually anything!!! "A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: pandas.pydata.org/pandas-docs/stable/…

All what I needed to do was to remove the [df['flag']=='train'] part from the left.

I'm still not sure why this approach wasn't working. If anyone has an insight, I appreciate to know it. Thank you

Body:
You'll have to format for function to take a series and return a series rather than operate on just an element of the series. I've added the function series_op below that should do this for you.

def fillAges(row, grouped_median):
    return grouped_median.loc[row['Sex'], row['Class'], row['Title']]['Age']

def series_op(x):
    x['Age'] = fillAges(x, grouped_median) if np.isnan(x['Age']) else x['Age']
    return x

corrected_df = df.apply(series_op, axis=1)

I don't have your data nor grouped_median so I can't replicate your problem.  With some test data that I've cooked up, I am able to get this to work correctly, but also able to get yours to work correctly.


问:
How to efficiently swap elements in a dataframe?
Suppose that we have the following dataframe:

```<code>set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
TRUE), R2 = sample(LETTERS[1:5], 10, replace = TRUE)))

    x R1 R2
1   1  B  B
2   2  B  A
3   3  C  D
4   4  E  B
5   5  B  D
6   6  E  C
7   7  E  D
8   8  D  E
9   9  D  B
10 10  A  D
</code>```

I want to do the following: if the difference between the level index
of factor R1 and that of factor R2 is an odd number, the levels of the
two factors need to be switched between them, which can be performed
through the following code:

```<code>for(ii in 1:dim(tmp)[1]) {
   kk <- which(levels(tmp$R2) %in% tmp[ii,'R2'], arr.ind = TRUE) -
which(levels(tmp$R1) %in% tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}
</code>```

More concise and efficient ways to achieve this?

P.S. A slightly different situation is the following.

```<code>set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
 TRUE), R2 = sample(LETTERS[2:6], 10, replace = TRUE)))

   x R1 R2
   1  C  B
   2  B  B
   3  C  E
   4  E  C
   5  E  B
   6  D  E
   7  E  E
   8  D  F
   9  C  D
  10  A  E
</code>```

Notice that the factor levels between the two factors, R1 and R2, slide by one level; that is, factor R1 does not have level F while factor R2 does not have level A. I want to swap the factor levels based on the combined levels of the two factors as shown below:

```<code>tl <- unique(c(levels(tmp$R1), levels(tmp$R2)))
for(ii in 1:dim(tmp)[1]) {
   kk <- which(tl %in% tmp[ii,'R2'], arr.ind = TRUE) - which(tl %in%
      tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}
</code>```

How to go about this case? Thanks!

答:
A solution using dplyr. dt is the final output. Notice that we need to use if_else from dplyr here, not the common ifelse from base R.

```<code>library(dplyr)

dt <- tmp %>%
  mutate(R1_new = if_else((as.numeric(R2) - as.numeric(R1)) %% 2 != 0, R2, R1),
         R2_new = if_else((as.numeric(R2) - as.numeric(R1)) %% 2 != 0, R1, R2)) %>%
  select(x, R1 = R1_new, R2 =  R2_new)
</code>```

Update

For the updated case, add one mutate call to redefine the factor level of R1 and R2. The rest is the same.

```<code>tl <- unique(c(levels(tmp$R1), levels(tmp$R2)))

dt <- tmp %>%
  mutate(R1 = factor(R1, levels = tl), R2 = factor(R2, levels = tl)) %>%
  mutate(R1_new = if_else((as.numeric(R2) - as.numeric(R1)) %% 2 != 0, R2, R1),
         R2_new = if_else((as.numeric(R2) - as.numeric(R1)) %% 2 != 0, R1, R2)) %>%
  select(x, R1 = R1_new, R2 =  R2_new)
</code>```

Body:
Suppose that we have the following dataframe:

set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
TRUE), R2 = sample(LETTERS[1:5], 10, replace = TRUE)))

    x R1 R2
1   1  B  B
2   2  B  A
3   3  C  D
4   4  E  B
5   5  B  D
6   6  E  C
7   7  E  D
8   8  D  E
9   9  D  B
10 10  A  D

I want to do the following: if the difference between the level index
of factor R1 and that of factor R2 is an odd number, the levels of the
two factors need to be switched between them, which can be performed
through the following code:

for(ii in 1:dim(tmp)[1]) {
   kk <- which(levels(tmp$R2) %in% tmp[ii,'R2'], arr.ind = TRUE) -
which(levels(tmp$R1) %in% tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}

More concise and efficient ways to achieve this?

P.S. A slightly different situation is the following.

set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
 TRUE), R2 = sample(LETTERS[2:6], 10, replace = TRUE)))

   x R1 R2
   1  C  B
   2  B  B
   3  C  E
   4  E  C
   5  E  B
   6  D  E
   7  E  E
   8  D  F
   9  C  D
  10  A  E

Notice that the factor levels between the two factors, R1 and R2, slide by one level; that is, factor R1 does not have level F while factor R2 does not have level A. I want to swap the factor levels based on the combined levels of the two factors as shown below:

tl <- unique(c(levels(tmp$R1), levels(tmp$R2)))
for(ii in 1:dim(tmp)[1]) {
   kk <- which(tl %in% tmp[ii,'R2'], arr.ind = TRUE) - which(tl %in%
      tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}

How to go about this case? Thanks!

Body:
A solution using dplyr. dt is the final output. Notice that we need to use if_else from dplyr here, not the common ifelse from base R.

library(dplyr)

dt <- tmp %>%
  mutate(R1_new = if_else((as.numeric(R2) - as.numeric(R1)) %% 2 != 0, R2, R1),
         R2_new = if_else((as.numeric(R2) - as.numeric(R1)) %% 2 != 0, R1, R2)) %>%
  select(x, R1 = R1_new, R2 =  R2_new)

Update

For the updated case, add one mutate call to redefine the factor level of R1 and R2. The rest is the same.

tl <- unique(c(levels(tmp$R1), levels(tmp$R2)))

dt <- tmp %>%
  mutate(R1 = factor(R1, levels = tl), R2 = factor(R2, levels = tl)) %>%
  mutate(R1_new = if_else((as.numeric(R2) - as.numeric(R1)) %% 2 != 0, R2, R1),
         R2_new = if_else((as.numeric(R2) - as.numeric(R1)) %% 2 != 0, R1, R2)) %>%
  select(x, R1 = R1_new, R2 =  R2_new)


问:
Rspec 2.3 on Rails 3.0.3 giving some controller access problems?
It seems a bunch of my Rspec tests now fail after moving my application to Rspec 2.3 and Rails 3.0.3

An example is here:

```<code>it "should not be able to access 'destroy'" do
  delete :destroy
  response.should redirect_to(signin_path)
  flash[:error].should == "You must be signed in to view this page."
end
</code>```

will give me the error:

```<code>1) FriendshipsController when not logged in: should not be able to access 'destroy'
 Failure/Error: delete :destroy
 No route matches {:controller=>"friendships", :action=>"destroy"}
 # ./spec/controllers/friendships_controller_spec.rb:21:in `block (3 levels) in <top (required)>'
</code>```

In my routes.rb file, I've mapped the resources for this controller...

```<code>resources :friendships
</code>```

Same for

```<code>get :edit
get :show
put :update
</code>```

Only one that seems to work is

```<code>post :create
</code>```

But this I cannot confirm 100%.

Any thoughts? Thanks for your time!

UPDATE:

```<code>get :new
</code>```

also works and my UserSessions controller (Authlogic) doesn't seem to suffer from this problem. Nothing I've done different in my UserSessions controller, model, or test that I can tell.

答:
In the spec, try calling the method by: </p>

```<code>delete :destroy, :id => "1"
</code>```

Body:
It seems a bunch of my Rspec tests now fail after moving my application to Rspec 2.3 and Rails 3.0.3

An example is here:

it "should not be able to access 'destroy'" do
  delete :destroy
  response.should redirect_to(signin_path)
  flash[:error].should == "You must be signed in to view this page."
end

will give me the error:

1) FriendshipsController when not logged in: should not be able to access 'destroy'
 Failure/Error: delete :destroy
 No route matches {:controller=>"friendships", :action=>"destroy"}
 # ./spec/controllers/friendships_controller_spec.rb:21:in `block (3 levels) in <top (required)>'

In my routes.rb file, I've mapped the resources for this controller...

resources :friendships

Same for

get :edit
get :show
put :update

Only one that seems to work is

post :create

But this I cannot confirm 100%.

Any thoughts? Thanks for your time!

UPDATE:

get :new

also works and my UserSessions controller (Authlogic) doesn't seem to suffer from this problem. Nothing I've done different in my UserSessions controller, model, or test that I can tell.

Body:
In the spec, try calling the method by:

delete :destroy, :id => "1"


问:
How to shorten many if statements
I'm fairly new to programming and not sure if there is any way to shorten this code. Basically, whatever value is entered for x determines the number of # after the '.' </p>

```<code>    String x = mSharedPreferences.getString("title", "3");
    if (x.equals("1")){
        df = new DecimalFormat("#.#");
    }
    else if(x.equals("2")){
        df = new DecimalFormat("#.##");
    }
    else if(x.equals("3")){
        df = new DecimalFormat("#.###");
    }
    else if(x.equals("4")){
        df = new DecimalFormat("#.####");
    }
</code>```

答:
You can entirely eliminate all if statements by calling setMaximumFractionDigits():

```<code>DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(Integer.parseInt(x));
</code>```

If you had wanted a format like "0.000" instead, also call setMinimumFractionDigits():

```<code>int decimals = Integer.parseInt(x);
DecimalFormat df = new DecimalFormat("0");
df.setMinimumFractionDigits(decimals);
df.setMaximumFractionDigits(decimals);
</code>```

Specify a pattern like "#.###" or "0.000" is actually just shorthand for calling the various setter methods of DecimalFormat.

Title: How to shorten many if statements

Body:
I'm fairly new to programming and not sure if there is any way to shorten this code. Basically, whatever value is entered for x determines the number of # after the '.'

    String x = mSharedPreferences.getString("title", "3");
    if (x.equals("1")){
        df = new DecimalFormat("#.#");
    }
    else if(x.equals("2")){
        df = new DecimalFormat("#.##");
    }
    else if(x.equals("3")){
        df = new DecimalFormat("#.###");
    }
    else if(x.equals("4")){
        df = new DecimalFormat("#.####");
    }

Body:
You can entirely eliminate all if statements by calling setMaximumFractionDigits():

DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(Integer.parseInt(x));

If you had wanted a format like "0.000" instead, also call setMinimumFractionDigits():

int decimals = Integer.parseInt(x);
DecimalFormat df = new DecimalFormat("0");
df.setMinimumFractionDigits(decimals);
df.setMaximumFractionDigits(decimals);

Specify a pattern like "#.###" or "0.000" is actually just shorthand for calling the various setter methods of DecimalFormat.


问:
Getting OneSignal UserID with Unity (C#)
In my app, I have some push notification subscribers (OneSignal). I am trying to get the user id's like this:

```<code>OneSignal.GetIdsAvailable(IdsAvailable);
....
....
private void IdsAvailable(string userID, string pushToken)
{
    playeridx = userID;
    System.Diagnostics.Debug.WriteLine("UserID:" + userID);
    System.Diagnostics.Debug.WriteLine("pushToken:" + pushToken);
}
</code>```

But I get an error: "OneSignal does not contain a definition for GetIdsAvailable."

Any ideas?

答: It looks like you are using a method found in the OneSignal Windows SDK. If you want to do this in Unity, setup the Unity SDK (if you haven't done so already) and then perhaps use GetPermissionSubscriptionState to retrieve the userId and pushToken of the current user, instead of using .GetIdsAvailable().

Body:
In my app, I have some push notification subscribers (OneSignal). I am trying to get the user id's like this:

OneSignal.GetIdsAvailable(IdsAvailable);
....
....
private void IdsAvailable(string userID, string pushToken)
{
    playeridx = userID;
    System.Diagnostics.Debug.WriteLine("UserID:" + userID);
    System.Diagnostics.Debug.WriteLine("pushToken:" + pushToken);
}

But I get an error: "OneSignal does not contain a definition for GetIdsAvailable."

Any ideas?


答:
```<code>  switch (x) {
            case "1":  xx;
                     break;
            case "2":  xx;
                     break;
            case "3":  xx;
                     break;
            case "4":  xx;
                     break;
            default:
                     break;
        }
</code>```

Use switch statement: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Title: How to shorten many if statements

Body:
  switch (x) {
            case "1":  xx;
                     break;
            case "2":  xx;
                     break;
            case "3":  xx;
                     break;
            case "4":  xx;
                     break;
            default:
                     break;
        }

Use switch statement: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html


问:
is it possible to passing a variable/function-return as a template argument
Is it possible to pass a variable or a value returned by a function as a template argument.

Example:

```<code>QVariantHash options;
options.insert("fontStyle", fontStyleObject);  // QFont fontStyleObject
options.insert("fontColor", fontColorObject);  // QColor fontColorObject
Q_FOREACH(const QVariant &option, options){
    qDebug() << option.value<option.typeName()>();
}
</code>```

As you saw, I have passed option.typeName() as a template argument and that method returns the type of the object as QString.

I have already done that but there is an error message: error: C2974: 'QVariant::value': invalid template argument for 'T', type expected.

Is it possible to pass a variable or a value returned by a function as a template argument? and if not, what's the alternative way to do that?

答:
It's possible if the template has a non-type template parameter and the function call is a constant expression. For example</p>

```<code>#include <type_traits>

constexpr int foo() {
    return 42;
}

template <int x>
std::integral_constant<int, x> bar() { return {}; }

int main() {
    bar<foo()>();
}
</code>```

Body:
Is it possible to pass a variable or a value returned by a function as a template argument.

Example:

QVariantHash options;
options.insert("fontStyle", fontStyleObject);  // QFont fontStyleObject
options.insert("fontColor", fontColorObject);  // QColor fontColorObject
Q_FOREACH(const QVariant &option, options){
    qDebug() << option.value<option.typeName()>();
}

As you saw, I have passed option.typeName() as a template argument and that method returns the type of the object as QString.

I have already done that but there is an error message: error: C2974: 'QVariant::value': invalid template argument for 'T', type expected.

Is it possible to pass a variable or a value returned by a function as a template argument? and if not, what's the alternative way to do that?

Body:
It's possible if the template has a non-type template parameter and the function call is a constant expression. For example

#include <type_traits>

constexpr int foo() {
    return 42;
}

template <int x>
std::integral_constant<int, x> bar() { return {}; }

int main() {
    bar<foo()>();
}


答:
Change the lines

```<code>if (diaUltimo.Equals(""))
{
  return false;
}
else
{
 return true;
}
</code>```

to

```<code>if(!String.IsNullOrEmpty(diaUltimo))
{
 return true;
}
else
{
 return false;
}
</code>```

It will work double duty in checking that you assigned value is neither null or empty

Title: Code working locally but not in Server, SQL and null string related

Body:
Change the lines

if (diaUltimo.Equals(""))
{
  return false;
}
else
{
 return true;
}

to

if(!String.IsNullOrEmpty(diaUltimo))
{
 return true;
}
else
{
 return false;
}

It will work double duty in checking that you assigned value is neither null or empty


问:
unable to load script from assets 'index.android.bundle'
I'm new in react-native.
I have run react native project on Ubuntu by using 'react-native run-android' command. And I got the error on emulator
"Unable to load script from assets 'index.android.bundle'.Make sure your bundle is packaged correctly or you are running a package server."</p>

答:
It seems to be a problem in the newest version of React Native (0.46). Using the previous version seems to solve the problem react-native init name --version react-native@0.45.1 and removes the error when running react-native run-android.

Edit: It is now fixed in version 0.46.1.


问:
Bash/php - any way to implement tab key autocomplete for arguments?
I have a PHP command line script which kicks off a job to a job server, with the job name being an argument. The job names are namespaced, such as Foo:Bar_Baz_JobName. Is there a way I could implement auto-completion, like how typing the first few letters of a filename and pressing tab bash completes the file name for you. I know it can be done, because tab-completion works on ubuntu with apt-get, I just don't know if it can be done in PHP.</p>

答:
About readline_completion_function

I would say that considering the type of interaction you are looking for (apt-get autocomplete)
this method is not good.

In fact before to get a autocomplete function you have to run the script and then you'll access the autocomplete function.

The autocomplete function is partial. So, it like the bash autocomplete not the zsh.

In the shell:

```<code>➜  ~ php test.php (enter)
Custom command: (tab)
a b c
Custom command: (tab)
a b c
</code>```

The code is:

```<code><?php
// test.php
class AutoController
{

    private static function getCommandsArray()
    {
        $my_dir = array('a', 'b', 'c');
        return $my_dir;
    }

    /**
     * The callback which is returning an array with strings, which will be
     * auto-completed.
     *
     * @param $input
     * @param $index
     * @return array
     */
    private static function completionCallback($input, $index)
    {
        return self::getCommandsArray();
    }

    /**
     * The method which is handling the autocompletion. After it's runned, you can
     * autocomplete your commands by hitting the tab-button.
     */
    public function actionCompl()
    {
        readline_completion_function(array('self', 'completionCallback'));

        $command_input = readline("Custom command: ");

        passthru('echo ' . $command_input);
    }
}

$a = new AutoController();
$a->actionCompl();
</code>```

About runtime autocomplete

As suggested by c9s it is possible to obtain this kind of functionality but extending autocomplete functionality of your bash, not with PHP.

So, if you see the autocomplete function of CLIFramework for example you'll see:

```<code>BashGenerator.php
ZshGenerator.php
</code>```

Which is used to generate the bash script to extends the bash or zsh autocomplete.

So, it depends on the shell you are using the way you have to make the autocomplete.

Some references:

zsh autocompletion

bash autocompletion

fish autocompletion (the link is more python oriented than php...)

Body:
About readline_completion_function

I would say that considering the type of interaction you are looking for (apt-get autocomplete)
this method is not good.

In fact before to get a autocomplete function you have to run the script and then you'll access the autocomplete function.

The autocomplete function is partial. So, it like the bash autocomplete not the zsh.

In the shell:

➜  ~ php test.php (enter)
Custom command: (tab)
a b c
Custom command: (tab)
a b c

The code is:

<?php
// test.php
class AutoController
{

    private static function getCommandsArray()
    {
        $my_dir = array('a', 'b', 'c');
        return $my_dir;
    }

    /**
     * The callback which is returning an array with strings, which will be
     * auto-completed.
     *
     * @param $input
     * @param $index
     * @return array
     */
    private static function completionCallback($input, $index)
    {
        return self::getCommandsArray();
    }

    /**
     * The method which is handling the autocompletion. After it's runned, you can
     * autocomplete your commands by hitting the tab-button.
     */
    public function actionCompl()
    {
        readline_completion_function(array('self', 'completionCallback'));

        $command_input = readline("Custom command: ");

        passthru('echo ' . $command_input);
    }
}

$a = new AutoController();
$a->actionCompl();

About runtime autocomplete

As suggested by c9s it is possible to obtain this kind of functionality but extending autocomplete functionality of your bash, not with PHP.

So, if you see the autocomplete function of CLIFramework for example you'll see:

BashGenerator.php
ZshGenerator.php

Which is used to generate the bash script to extends the bash or zsh autocomplete.

So, it depends on the shell you are using the way you have to make the autocomplete.

Some references:

zsh autocompletion

bash autocompletion

fish autocompletion (the link is more python oriented than php...)


问:
Can you wrap lines in a kivy file?
I have a couple of lines in my kv. file that are really long (80+ chars), and I was wondering if there was a way to wrap/continue them on the next line.

For example, how do I go from this

```<code>Line:
    points: self.pos[0] + 5, self.pos[1] + 2, self.pos[0] + self.width - 5, self.pos[1] + 2
</code>```

to

```<code>Line:
    points: self.pos[0] + 5, self.pos[1] + 2,
            self.pos[0] + self.width - 5, self.pos[1] + 2
</code>```

or something similar.

答:
Acording to https://kivy.org/docs/api-kivy.lang.html#valid-expressons, you can use  line continuation character (\):

```<code>Line:
    points:
        self.pos[0] + 5, self.pos[1] + 2,\
        self.pos[0] + self.width - 5, self.pos[1] + 2
</code>```

New line shouldn’t add an indentation level. Note that the following syntax is invalid:

```<code>Line:
    points: self.pos[0] + 5, self.pos[1] + 2,\
            self.pos[0] + self.width - 5, self.pos[1] + 2
</code>```

Another valid example:

```<code>canvas:
    Rectangle:
        pos:
            self.center_x-5,\
            0
        size:
            10,\
            self.height
</code>```

Title: Can you wrap lines in a kivy file?

Body:
I have a couple of lines in my kv. file that are really long (80+ chars), and I was wondering if there was a way to wrap/continue them on the next line.

For example, how do I go from this

Line:
    points: self.pos[0] + 5, self.pos[1] + 2, self.pos[0] + self.width - 5, self.pos[1] + 2

to

Line:
    points: self.pos[0] + 5, self.pos[1] + 2,
            self.pos[0] + self.width - 5, self.pos[1] + 2

or something similar.

Body:
Acording to https://kivy.org/docs/api-kivy.lang.html#valid-expressons, you can use  line continuation character (\):

Line:
    points:
        self.pos[0] + 5, self.pos[1] + 2,\
        self.pos[0] + self.width - 5, self.pos[1] + 2

New line shouldn’t add an indentation level. Note that the following syntax is invalid:

Line:
    points: self.pos[0] + 5, self.pos[1] + 2,\
            self.pos[0] + self.width - 5, self.pos[1] + 2

Another valid example:

canvas:
    Rectangle:
        pos:
            self.center_x-5,\
            0
        size:
            10,\
            self.height


问:
Form new array from associative arrays
I have 3 arrays and looks like this

```<code>Array1
(
[0] => Array
    (
        [Month] => 'Jan 2015'
        [Total] => 10
    )

[1] => Array
    (
        [Month] => 'Feb 2015'
        [Total] => 8
    )

[2] => Array
    (
        [Month] => 'Mar 2015'
        [Total] => 10
    )
)

Array2
(
[0] => Array
    (
        [Month] => 'Jan 2016'
        [Total] => 7
    )

[1] => Array
    (
        [Month] => 'Feb 2016'
        [Total] => 5
    )

[2] => Array
    (
        [Month] => 'Mar 2016'
        [Total] => 15
    )
)

Array3
(
[0] => Array
    (
        [Month] => 'Jan 2017'
        [Total] => 13
    )

[1] => Array
    (
        [Month] => 'Feb 2017'
        [Total] => 10
    )

[2] => Array
    (
        [Month] => 'Mar 2017'
        [Total] => 11
    )
)
</code>```

All 3 arrays are of the same size.

What I want to achieve is to output identical months sequentially and corresponding values in the same order. The new arrays should look like this:

Desired result:

```<code>$months = array['Jan 2015','Jan 2016','Jan 2017', 'Feb 2015', 'Feb 2016'...'Mar 2016','Mar 2017'];
$totals = array[10,7,13,5,5,...,15,11];
</code>```

答:
You can use a foreach loop:</p>

```<code>$months = array();
$totals = array();

foreach($array as $var){
    $months[] = $var['Month'];
    $totals[] = $var['Total'];
}
</code>```

Title: Form new array from associative arrays

Body:
I have 3 arrays and looks like this

Array1
(
[0] => Array
    (
        [Month] => 'Jan 2015'
        [Total] => 10
    )

[1] => Array
    (
        [Month] => 'Feb 2015'
        [Total] => 8
    )

[2] => Array
    (
        [Month] => 'Mar 2015'
        [Total] => 10
    )
)

Array2
(
[0] => Array
    (
        [Month] => 'Jan 2016'
        [Total] => 7
    )

[1] => Array
    (
        [Month] => 'Feb 2016'
        [Total] => 5
    )

[2] => Array
    (
        [Month] => 'Mar 2016'
        [Total] => 15
    )
)

Array3
(
[0] => Array
    (
        [Month] => 'Jan 2017'
        [Total] => 13
    )

[1] => Array
    (
        [Month] => 'Feb 2017'
        [Total] => 10
    )

[2] => Array
    (
        [Month] => 'Mar 2017'
        [Total] => 11
    )
)

All 3 arrays are of the same size.

What I want to achieve is to output identical months sequentially and corresponding values in the same order. The new arrays should look like this:

Desired result:

$months = array['Jan 2015','Jan 2016','Jan 2017', 'Feb 2015', 'Feb 2016'...'Mar 2016','Mar 2017'];
$totals = array[10,7,13,5,5,...,15,11];

Body:
You can use a foreach loop:

$months = array();
$totals = array();

foreach($array as $var){
    $months[] = $var['Month'];
    $totals[] = $var['Total'];
}


问:
Running kubernetes autoscalar
I have a replication controller running with the following spec:

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: owncloud-controller
spec:
  replicas: 1
  selector:
    app: owncloud
  template:
    metadata:
      labels:
        app: owncloud
    spec:
      containers:
      - name: owncloud
        image: adimania/owncloud9-centos7
        ports:
          - containerPort: 80
        volumeMounts:
          - name: userdata
            mountPath: /var/www/html/owncloud/data
        resources:
          requests:
            cpu: 400m
      volumes:
        - name: userdata
          hostPath:
            path: /opt/data
</code>```

Now I run a hpa using autoscale command.

```<code>$ kubectl autoscale rc owncloud-controller --max=5 --cpu-percent=10
</code>```

I have also started heapster using kubernetes run command.

```<code>$ kubectl run heapster --image=gcr.io/google_containers/heapster:v1.0.2 --command -- /heapster --source=kubernetes:http://192.168.0.103:8080?inClusterConfig=false --sink=log
</code>```

After all this, the autoscaling never kicks in. From logs, it seems that the actual CPU utilization is not getting reported.

```<code>$ kubectl describe hpa owncloud-controller
Name:               owncloud-controller
Namespace:          default
Labels:             <none>
Annotations:            <none>
CreationTimestamp:      Thu, 26 May 2016 14:24:51 +0530
Reference:          ReplicationController/owncloud-controller/scale
Target CPU utilization:     10%
Current CPU utilization:    <unset>
Min replicas:           1
Max replicas:           5
ReplicationController pods: 1 current / 1 desired
Events:
  FirstSeen LastSeen    Count   From                SubobjectPath   Type        Reason          Message
  --------- --------    -----   ----                -------------   --------    ------          -------
  44m       8s      92  {horizontal-pod-autoscaler }            Warning     FailedGetMetrics    failed to get CPU consumption and request: metrics obtained for 0/1 of pods
  44m       8s      92  {horizontal-pod-autoscaler }            Warning     FailedComputeReplicas   failed to get CPU utilization: failed to get CPU consumption and request: metrics obtained for 0/1 of pods
</code>```

What am I missing here?

答:
I installed hepaster under the name space "kube-system" and it worked. After running heapster, make sure it's running before you use HPA for your application.

How to run Heapster with Kubernetes cluster

I put all files here https://gitlab.com/abushoeb/kubernetes/tree/master/heapster. They are collected from the official Kubernetes Repository and made minor changes.

How to run Heapster

Go to the directory heapster where you have grafana.yaml, heapster.yaml and influxdb.yaml and run following command

```<code>$ kubectl create -f  .
</code>```

How to stop Heapster

Go to the same heapster directory and then run following command

```<code>$ kubectl delete -f  .
</code>```

How to check Heapster is running

You can access heapster metric model from the pod where heapster is running to make sure heapster is working. It can be accessed via web browser by accessing http://heapster-pod-ip:heapster-service-port/api/v1/model/metrics/. The same result can be seen by executing following command.

```<code>$ curl -L http://heapster-pod-ip:heapster-service-port/api/v1/model/metrics/
</code>```

If you see the list of metrics then heapster is running correctly. You can also browse grafana dashboard to see it (find the ip of the pod where grafana is running and the access it http://grafana-pod-ip:grafana-service-port).

Full documentation of Heapster Metric Model are available here.

Also just run ($ kubectl cluster-info) and see if it shows results like this:

Kubernetes master is running at https://cluster-ip:6443

Heapster is running at https://cluster-ip:6443/api/v1/proxy/namespaces/kube-system/services/heapster

kubernetes-dashboard is running at https://cluster-ip:6443/api/v1/proxy/namespaces/kube-system/services/kubernetes-dashboard

monitoring-grafana is running at https://cluster-ip:6443/api/v1/proxy/namespaces/kube-system/services/monitoring-grafana

monitoring-influxdb is running at https://cluster-ip:6443/api/v1/proxy/namespaces/kube-system/services/monitoring-influxdb

Check influxdb

You can also check influxdb if it has data in it. Install Influxdb Client on your local machine to get connected to infuxdb database.

```<code>$ influx -host <cluster-ip> -port <influxdb-service-port>
</code>```

Some Sample influxdb queries

show databases

use db-name

show measurements

select value from "cpu/node_capacity"

Reference and Help

https://github.com/kubernetes/heapster/blob/master/docs/influxdb.md

https://github.com/kubernetes/heapster/blob/master/docs/debugging.md

https://blog.kublr.com/how-to-utilize-the-heapster-influxdb-grafana-stack-in-kubernetes-for-monitoring-pods-4a553f4d36c9

http://www.dasblinkenlichten.com/installing-cadvisor-and-heapster-on-bare-metal-kubernetes/

http://blog.arungupta.me/kubernetes-monitoring-heapster-influxdb-grafana/

Title: Running kubernetes autoscalar

Body:
I have a replication controller running with the following spec:

apiVersion: v1
kind: ReplicationController
metadata:
  name: owncloud-controller
spec:
  replicas: 1
  selector:
    app: owncloud
  template:
    metadata:
      labels:
        app: owncloud
    spec:
      containers:
      - name: owncloud
        image: adimania/owncloud9-centos7
        ports:
          - containerPort: 80
        volumeMounts:
          - name: userdata
            mountPath: /var/www/html/owncloud/data
        resources:
          requests:
            cpu: 400m
      volumes:
        - name: userdata
          hostPath:
            path: /opt/data

Now I run a hpa using autoscale command.

$ kubectl autoscale rc owncloud-controller --max=5 --cpu-percent=10

I have also started heapster using kubernetes run command.

$ kubectl run heapster --image=gcr.io/google_containers/heapster:v1.0.2 --command -- /heapster --source=kubernetes:http://192.168.0.103:8080?inClusterConfig=false --sink=log

After all this, the autoscaling never kicks in. From logs, it seems that the actual CPU utilization is not getting reported.

$ kubectl describe hpa owncloud-controller
Name:               owncloud-controller
Namespace:          default
Labels:             <none>
Annotations:            <none>
CreationTimestamp:      Thu, 26 May 2016 14:24:51 +0530
Reference:          ReplicationController/owncloud-controller/scale
Target CPU utilization:     10%
Current CPU utilization:    <unset>
Min replicas:           1
Max replicas:           5
ReplicationController pods: 1 current / 1 desired
Events:
  FirstSeen LastSeen    Count   From                SubobjectPath   Type        Reason          Message
  --------- --------    -----   ----                -------------   --------    ------          -------
  44m       8s      92  {horizontal-pod-autoscaler }            Warning     FailedGetMetrics    failed to get CPU consumption and request: metrics obtained for 0/1 of pods
  44m       8s      92  {horizontal-pod-autoscaler }            Warning     FailedComputeReplicas   failed to get CPU utilization: failed to get CPU consumption and request: metrics obtained for 0/1 of pods

What am I missing here?

Body:
I installed hepaster under the name space "kube-system" and it worked. After running heapster, make sure it's running before you use HPA for your application.

How to run Heapster with Kubernetes cluster

I put all files here https://gitlab.com/abushoeb/kubernetes/tree/master/heapster. They are collected from the official Kubernetes Repository and made minor changes.

How to run Heapster

Go to the directory heapster where you have grafana.yaml, heapster.yaml and influxdb.yaml and run following command

$ kubectl create -f  .

How to stop Heapster

Go to the same heapster directory and then run following command

$ kubectl delete -f  .

How to check Heapster is running

You can access heapster metric model from the pod where heapster is running to make sure heapster is working. It can be accessed via web browser by accessing http://heapster-pod-ip:heapster-service-port/api/v1/model/metrics/. The same result can be seen by executing following command.

$ curl -L http://heapster-pod-ip:heapster-service-port/api/v1/model/metrics/

If you see the list of metrics then heapster is running correctly. You can also browse grafana dashboard to see it (find the ip of the pod where grafana is running and the access it http://grafana-pod-ip:grafana-service-port).

Full documentation of Heapster Metric Model are available here.

Also just run ($ kubectl cluster-info) and see if it shows results like this:

Kubernetes master is running at https://cluster-ip:6443

Heapster is running at https://cluster-ip:6443/api/v1/proxy/namespaces/kube-system/services/heapster

kubernetes-dashboard is running at https://cluster-ip:6443/api/v1/proxy/namespaces/kube-system/services/kubernetes-dashboard

monitoring-grafana is running at https://cluster-ip:6443/api/v1/proxy/namespaces/kube-system/services/monitoring-grafana

monitoring-influxdb is running at https://cluster-ip:6443/api/v1/proxy/namespaces/kube-system/services/monitoring-influxdb

Check influxdb

You can also check influxdb if it has data in it. Install Influxdb Client on your local machine to get connected to infuxdb database.

$ influx -host <cluster-ip> -port <influxdb-service-port>

Some Sample influxdb queries

show databases

use db-name

show measurements

select value from "cpu/node_capacity"

Reference and Help

https://github.com/kubernetes/heapster/blob/master/docs/influxdb.md

https://github.com/kubernetes/heapster/blob/master/docs/debugging.md

https://blog.kublr.com/how-to-utilize-the-heapster-influxdb-grafana-stack-in-kubernetes-for-monitoring-pods-4a553f4d36c9

http://www.dasblinkenlichten.com/installing-cadvisor-and-heapster-on-bare-metal-kubernetes/

http://blog.arungupta.me/kubernetes-monitoring-heapster-influxdb-grafana/

ContentLicense: CC BY-SA 4.0


问:
Why UWP Flipview doesn't flip to second item?
I have a control to manage a FlipView (flipView) and I want synchronize SelectedIndex with a ListBox (subMenuList) to navigate between my contents. And because product owners have wonderfull requirements, I have another ListBox (shortcutList) in a control for the first item of the FlipView which is also binded to SelectedIndex of the FlipView.

Warning : some items of the lists are collapsed to simulate shortcuts to Flipview contents.

Those controls are perfectly synchronized together but the second item of FlipView :

Using mouse: on the first click, I can go to page 1 and when I flip back to shortcutList, I can not go to page 1 but I can go anywhere else. And then, when I flip back again to shortcutList, I can go to page 1 again and so on !

Using touch: I can tap go to page 1 as long as I want, I never reach my first page but I can go anywhere else.

I extract the specific part of my project to reproduce the use case on Github, that way everyone can understand what I mean.

I hope someone can tell me why UWP Flipview doesn't flip to second item ? And thanks to try to help me to find an issue.

答:
I also commited a dirty fix on Github using directions of Martin Zikmund

How to solve this? I think you will have to use code. This XAML
  solution although almost works is quite fragile. The easiest solution
  would be to replace the ListBox in FlipContent0Control with three
  simple buttons and in their Click handlers navigate to the appropriate
  page.

and a tip from Jawahar

it is because your finger is still touching the control, so flipview
  cannot animate. So I gave a small break after before navigating. By
  the time user would have released the finger and it works !!!

in the following post.

So, three steps to resolve :

Replace SelectedIndex in FlipContent0Control with Tapped event on each ListBoxItem inner canvas.

Provide a event on tap to raise the target index to select in the FlipView.

Add a Task.Delay(100) in the method handler of event TargetedIndexChanged


答:
Another suggestion posted at http://drupal.org/node/1002144 for the same question -

It's possible that this behaviour might be due to a mysql query lock. If KalturaCE's SQL was locking a table until the first request is completed (I have no reason to believe this is the case, just floating possible causes), then a second request might hang like this.

I'm not familiar enough with CE to suggest that this is the case, but you could easily debug using mtop on the server during the request to see if this is what's actually happening.

Title: Does apache / php blocks a single file to be processed from the same client concurrently?

Body:
I have everything setup and running with KalturaCE & Drupak and the server (Ubuntu 8.02+Apache2+PHP5+MySql) is working fine.
The issue here I am having is unclassified.

When I play two videos together from my site, the second video which I played later doesn't start until the first completes its buffering. I did some HTTP watch and came to know that,
both of the entries request the file with the URL as follows,

/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxx/flavor/1/version/100000

so the first video which I played receives a 302 redirect response to the URL as follows,

/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxxx/flavor/1/version/100000/a.flv?novar=0

and starts buffering and playing. While the second video which I started later just wait for a response till the first video end its buffering and then the second video receives its 302 redirect and start buffering

My question is, why can't both videos buffer concurrently? and Obviously this is what I require.

Your help is highly anticipated and much welcome.


问:
Iterate Multilevel Multidimensional Array
I have to iterate multidimensional array with php. My array data as following:

```<code>Array
(

[id] => Array
    (
        ['2'] => Array
            (
                [0] => 2
            )

        ['1'] => Array
            (
                [0] => 1
            )

    )

[summary] => Array
    (
        ['2'] => Array
            (
                [0] => Summary 1
            )

        ['1'] => Array
            (
                [0] => Summary 2
            )

    )

[review] => Array
    (
        ['2'] => Array
            (
                [0] => Review 2
            )

        ['1'] => Array
            (
                [0] => Summary 2
            )

    )

[nickname] => ABCD
)
</code>```

I want to make set of results like array('id','summary','review', 'nickname')

答:
You can try this:

```<code>$array = array(
    'id'        => array(2 => array(2), 1 => array(1)),
    'summary'   => array(2 => array('Summary ' . 1), 1 => array('Summary ' . 2)),
    'review'    => array(2 => array('Review  ' . 2), 1 => array('Review  ' . 2)),
    'nickname'  => 'ABCD'
);

$out = array();
foreach ($array as $col => $data) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $out[$key][$col] = $value[0];
        }
    }
}

foreach ($out as &$data) {
    $data += array('nickname' => $array['nickname']);
}

var_dump($out);
</code>```

Output:

```<code>array (size=2)
  2 =>
    array (size=4)
      'id' => int 2
      'summary' => string 'Summary 1' (length=9)
      'review' => string 'Review  2' (length=9)
      'nickname' => string 'ABCD' (length=4)
  1 => &
    array (size=4)
      'id' => int 1
      'summary' => string 'Summary 2' (length=9)
      'review' => string 'Review  2' (length=9)
      'nickname' => string 'ABCD' (length=4)
</code>```

OwnerDisplayName: Magecode

Body:
I have to iterate multidimensional array with php. My array data as following:

Array
(

[id] => Array
    (
        ['2'] => Array
            (
                [0] => 2
            )

        ['1'] => Array
            (
                [0] => 1
            )

    )

[summary] => Array
    (
        ['2'] => Array
            (
                [0] => Summary 1
            )

        ['1'] => Array
            (
                [0] => Summary 2
            )

    )

[review] => Array
    (
        ['2'] => Array
            (
                [0] => Review 2
            )

        ['1'] => Array
            (
                [0] => Summary 2
            )

    )

[nickname] => ABCD
)

I want to make set of results like array('id','summary','review', 'nickname')

Body:
You can try this:

$array = array(
    'id'        => array(2 => array(2), 1 => array(1)),
    'summary'   => array(2 => array('Summary ' . 1), 1 => array('Summary ' . 2)),
    'review'    => array(2 => array('Review  ' . 2), 1 => array('Review  ' . 2)),
    'nickname'  => 'ABCD'
);

$out = array();
foreach ($array as $col => $data) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $out[$key][$col] = $value[0];
        }
    }
}

foreach ($out as &$data) {
    $data += array('nickname' => $array['nickname']);
}

var_dump($out);

Output:

array (size=2)
  2 =>
    array (size=4)
      'id' => int 2
      'summary' => string 'Summary 1' (length=9)
      'review' => string 'Review  2' (length=9)
      'nickname' => string 'ABCD' (length=4)
  1 => &
    array (size=4)
      'id' => int 1
      'summary' => string 'Summary 2' (length=9)
      'review' => string 'Review  2' (length=9)
      'nickname' => string 'ABCD' (length=4)