问:
Styling a wordpress widget title
I've been struggling with this problem for a while now. How do I style my widget title to have this horizontal line besides my widget title and not under it. Like so:enter image description here</p>

答:
Open your current activated theme. Then find registered sidebar function.
There is the attribute before_title etc in register_sidebar function.

You can change the class assigned there. The change will however apply to all widgets in the same widget area (which may be a benefit or problem).

Example:

```<code>register_sidebar( array(
        'name'          => __( 'Sidebar', 'twentyseventeen' ),
        'id'            => 'sidebar-1',
        'description'   => __( 'Add widgets here to appear in your sidebar.', 'twentyseventeen' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ) );
</code>```

Title: Styling a wordpress widget title

Body:
Open your current activated theme. Then find registered sidebar function.
There is the attribute before_title etc in register_sidebar function.

You can change the class assigned there. The change will however apply to all widgets in the same widget area (which may be a benefit or problem).

Example:

register_sidebar( array(
        'name'          => __( 'Sidebar', 'twentyseventeen' ),
        'id'            => 'sidebar-1',
        'description'   => __( 'Add widgets here to appear in your sidebar.', 'twentyseventeen' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ) );


来源: stackexchange

问:
Google maps api authorization error
I have an app with a google maps activity. This used to work just fine, but stopped working recently (not sure exactly when as I havent used the app for a month or so).

Debugging outputs the following:

```<code>04-01 11:49:45.240  20495-20514/com.myapp.trial10 E/GMPM﹕ getGoogleAppId failed with status: 10
04-01 11:49:45.245  20495-20514/com.myapp.trial10 E/GMPM﹕ Uploading is not possible. App measurement disabled
04-01 11:49:45.530  20495-20517/com.myapp.trial10 E/﹕ Device driver API match
    Device driver API version: 23
    User space API version: 23
04-01 11:49:45.530  20495-20517/com.myapp.trial10 E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Fri Mar 21 13:52:50 KST 2014
04-01 11:50:05.030  20495-20628/com.myapp.trial10 E/Google Maps Android API﹕ Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
04-01 11:50:05.035  20495-20628/com.myapp.trial10 E/Google Maps Android API﹕ In the Google Developer Console (https://console.developers.google.com)
    Ensure that the "Google Maps Android API v2" is enabled.
    Ensure that the following Android Key exists:
    API Key: **********************************
</code>```

I have checked and the API key is correct. I have also updated everything in the SDK.

Any ideas please?

答: Fixed. I had to generate a new key for some reason</p>

ContentLicense: CC BY-SA 3.0

Title: Google maps api authorization error

Body:
I have an app with a google maps activity. This used to work just fine, but stopped working recently (not sure exactly when as I havent used the app for a month or so).

Debugging outputs the following:

04-01 11:49:45.240  20495-20514/com.myapp.trial10 E/GMPM﹕ getGoogleAppId failed with status: 10
04-01 11:49:45.245  20495-20514/com.myapp.trial10 E/GMPM﹕ Uploading is not possible. App measurement disabled
04-01 11:49:45.530  20495-20517/com.myapp.trial10 E/﹕ Device driver API match
    Device driver API version: 23
    User space API version: 23
04-01 11:49:45.530  20495-20517/com.myapp.trial10 E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Fri Mar 21 13:52:50 KST 2014
04-01 11:50:05.030  20495-20628/com.myapp.trial10 E/Google Maps Android API﹕ Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
04-01 11:50:05.035  20495-20628/com.myapp.trial10 E/Google Maps Android API﹕ In the Google Developer Console (https://console.developers.google.com)
    Ensure that the "Google Maps Android API v2" is enabled.
    Ensure that the following Android Key exists:
    API Key: **********************************

I have checked and the API key is correct. I have also updated everything in the SDK.

Any ideas please?


问:
Javascript's setInterval lags the browser
I have a live chat working on. And I have used setInterval to display all messages in realtime every 0.5 seconds. But I noticed that setInterval freezes and sometimes crashes the browser. I heard that setTimeout is the best alternative way to use?</p>

```<code>  setInterval(function(){
        $.ajax({
            url: "display_msg.php",
            method: "POST",
            data: {conn:conn},
            success: function(data) {
                $('#chatarea').html(data);
            }
        });
    },500);
</code>```

答:
You are better off using setTimeout which will wait for the previous request to resolve before requesting the data again.

```<code>(function pollMessages() {
  $.ajax({
    url: "display_msg.php",
    method: "POST",
    data: {
      conn: conn
    },
    success: function(data) {
      $('#chatarea').html(data);
      setTimeout(pollMessages, 500)
    }
  });
})()
</code>```

Body:
I have a live chat working on. And I have used setInterval to display all messages in realtime every 0.5 seconds. But I noticed that setInterval freezes and sometimes crashes the browser. I heard that setTimeout is the best alternative way to use?

  setInterval(function(){
        $.ajax({
            url: "display_msg.php",
            method: "POST",
            data: {conn:conn},
            success: function(data) {
                $('#chatarea').html(data);
            }
        });
    },500);

Body:
You are better off using setTimeout which will wait for the previous request to resolve before requesting the data again.

(function pollMessages() {
  $.ajax({
    url: "display_msg.php",
    method: "POST",
    data: {
      conn: conn
    },
    success: function(data) {
      $('#chatarea').html(data);
      setTimeout(pollMessages, 500)
    }
  });
})()


问:
updating gtk to latest version made apps look UGLY
I preivously had gtk 2.14.6 installed, using it through python 2.5 with pygtk 2.12. I just downloaded the gtk 2.22 bundle and extracted it, replacing the old one. (I didn't extract it over the old folder, I just moved the old folder and extracted the new bundle in the same place). However, the same app went from looking very much like a native Windows 7 app to looking very ugly, clunky.. more like a Windows XP theme but it didn't even mimic that well.

How does GTK theming work? How can I get the newest version of GTK (I updated due to instability issues), but have the theme? And why did the older version look better than the newer one?

答:
In your distribution, in etc/gtk-2.0/gtkrc, you need to make sure that "style" is set to "msw-default" and engine set to "wimp". Here's my entire gtkrc, just to make sure you have it:</p>

```<code>gtk-icon-sizes = "gtk-menu=13,13:gtk-small-toolbar=16,16:gtk-large-toolbar=24,24:gtk-dnd=32,32"
gtk-toolbar-icon-size = small-toolbar

# disable images in buttons. i've only seen ugly delphi apps use this feature.
gtk-button-images = 1

# enable/disable images in menus. most "stock" microsoft apps don't use these, except sparingly.
# the office apps use them heavily, though.
gtk-menu-images = 1

# use the win32 button ordering instead of the GNOME HIG one, where applicable
gtk-alternative-button-order = 1

# use the win32 sort indicators direction, as in Explorer
gtk-alternative-sort-arrows = 1

# Windows users don't expect the PC Speaker beeping at them when they backspace in an empty textview and stuff like that
gtk-error-bell = 0

style "msw-default"
{
  GtkWidget::interior-focus = 1
  GtkOptionMenu::indicator-size = { 9, 5 }
  GtkOptionMenu::indicator-spacing = { 7, 5, 2, 2 }
  GtkSpinButton::shadow-type = in

  # Owen and I disagree that these should be themable
  GtkUIManager::add-tearoffs = 0
  #GtkComboBox::add-tearoffs = 0

  GtkComboBox::appears-as-list = 1
  GtkComboBox::focus-on-click = 0

  GOComboBox::add_tearoffs = 0

  GtkTreeView::allow-rules = 0
  GtkTreeView::expander-size = 12

  GtkExpander::expander-size = 12

  GtkScrolledWindow::scrollbar_spacing = 1

  GtkSeparatorMenuItem::horizontal-padding = 2

  engine "wimp"
  {
  }

 }
class "*" style "msw-default"

binding "ms-windows-tree-view"
{
  bind "Right" { "expand-collapse-cursor-row" (1,1,0) }
  bind "Left" { "expand-collapse-cursor-row" (1,0,0) }
}

class "GtkTreeView" binding "ms-windows-tree-view"

style "msw-combobox-thickness" = "msw-default"
{
  xthickness = 0
  ythickness = 0
}

widget_class "*TreeView*ComboBox*" style "msw-combobox-thickness"
widget_class "*ComboBox*GtkFrame*" style "msw-combobox-thickness"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In your distribution, in etc/gtk-2.0/gtkrc, you need to make sure that "style" is set to "msw-default" and engine set to "wimp". Here's my entire gtkrc, just to make sure you have it:

gtk-icon-sizes = "gtk-menu=13,13:gtk-small-toolbar=16,16:gtk-large-toolbar=24,24:gtk-dnd=32,32"
gtk-toolbar-icon-size = small-toolbar

# disable images in buttons. i've only seen ugly delphi apps use this feature.
gtk-button-images = 1

# enable/disable images in menus. most "stock" microsoft apps don't use these, except sparingly.
# the office apps use them heavily, though.
gtk-menu-images = 1

# use the win32 button ordering instead of the GNOME HIG one, where applicable
gtk-alternative-button-order = 1

# use the win32 sort indicators direction, as in Explorer
gtk-alternative-sort-arrows = 1

# Windows users don't expect the PC Speaker beeping at them when they backspace in an empty textview and stuff like that
gtk-error-bell = 0

style "msw-default"
{
  GtkWidget::interior-focus = 1
  GtkOptionMenu::indicator-size = { 9, 5 }
  GtkOptionMenu::indicator-spacing = { 7, 5, 2, 2 }
  GtkSpinButton::shadow-type = in

  # Owen and I disagree that these should be themable
  GtkUIManager::add-tearoffs = 0
  #GtkComboBox::add-tearoffs = 0

  GtkComboBox::appears-as-list = 1
  GtkComboBox::focus-on-click = 0

  GOComboBox::add_tearoffs = 0

  GtkTreeView::allow-rules = 0
  GtkTreeView::expander-size = 12

  GtkExpander::expander-size = 12

  GtkScrolledWindow::scrollbar_spacing = 1

  GtkSeparatorMenuItem::horizontal-padding = 2

  engine "wimp"
  {
  }

 }
class "*" style "msw-default"

binding "ms-windows-tree-view"
{
  bind "Right" { "expand-collapse-cursor-row" (1,1,0) }
  bind "Left" { "expand-collapse-cursor-row" (1,0,0) }
}

class "GtkTreeView" binding "ms-windows-tree-view"

style "msw-combobox-thickness" = "msw-default"
{
  xthickness = 0
  ythickness = 0
}

widget_class "*TreeView*ComboBox*" style "msw-combobox-thickness"
widget_class "*ComboBox*GtkFrame*" style "msw-combobox-thickness"


问:
How to set different color to some text of a textiew and make that text clickable?
In my app i want to use a text view that should have half of its text black and second half should be green, also i want the green part to be clickable.
I found some posts that show how to change color or how to make clickable but i am unable to find a combination of both. i have implemented this idea by myself, but the problem is that the string that should be clickable is not clickable. How to fix this?
Any help will be appreciated.
Here is my code</p>

```<code>String firststring="Hello i am a textiew";
lString secondstring="ClickMe";
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString firstStringSpannable = new SpannableString(firststring);
firstStringSpannable .setSpan(new ForegroundColorSpan(Color.BLACK), 0, firststring.length(), 0);
builder.append(firstStringSpannable );

String space = " ";
SpannableString spaceSpannable = new SpannableString(space);
builder.append(spaceSpannable);

SpannableString secondSpannable = new SpannableString(secondstring);
secondSpannable .setSpan(new ForegroundColorSpan(Color.GREEN), 0,
builder.append(secondSpannable );

textview.setText(builder, TextView.BufferType.SPANNABLE);
String comepleteString = firststring + " " + secondstring;
SpannableString spannableString = new SpannableString(comepleteString);
int startIndex = comepleteString.indexOf(secondstring);
int endIndex = startIndex + secondstring.length();

Spannable Spannable = (Spannable) textview.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View widget) {
//performing some function
    }
};
Spannable.setSpan(myClickableSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code>```

答:
Using setHighlightColor() method works most of the time:

```<code>textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));
</code>```

NOTE: Updated code to 2 different strings into 1 TextView and Second string will be coloured and clickable.

Set your TextView's default color as BLACK
Clickable part of will be GREEN

There is a simple example:

```<code>String stringFirst = "..."
String stringSecond = "..."

SpannableString spannable = new SpannableString(stringFirst + stringSecond);
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
        }

        @Override
        public void onClick(View widget) {
            //Do your click action
        }
    };
    spannable.setSpan(clickableSpan, stringFirst.length()-1, stringFirst.length() + stringSecond.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(spannable);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));
</code>```

If it's not work add the line below

```<code>ds.setColor(ContextCompat.getColor(context, R.color.green));
</code>```

to your updateDrawState method. It looks like this:

```<code>String stringFirst = "..."
String stringSecond = "..."

SpannableString spannable = new SpannableString(stringFirst + stringSecond);
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(ContextCompat.getColor(context, R.color.green));
        }

        @Override
        public void onClick(View widget) {
            //Do your click action
        }
    };
    spannable.setSpan(clickableSpan, stringFirst.length()-1, stringFirst.length() + stringSecond.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(spannable);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));
</code>```

Body:
In my app i want to use a text view that should have half of its text black and second half should be green, also i want the green part to be clickable.
I found some posts that show how to change color or how to make clickable but i am unable to find a combination of both. i have implemented this idea by myself, but the problem is that the string that should be clickable is not clickable. How to fix this?
Any help will be appreciated.
Here is my code

String firststring="Hello i am a textiew";
lString secondstring="ClickMe";
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString firstStringSpannable = new SpannableString(firststring);
firstStringSpannable .setSpan(new ForegroundColorSpan(Color.BLACK), 0, firststring.length(), 0);
builder.append(firstStringSpannable );

String space = " ";
SpannableString spaceSpannable = new SpannableString(space);
builder.append(spaceSpannable);

SpannableString secondSpannable = new SpannableString(secondstring);
secondSpannable .setSpan(new ForegroundColorSpan(Color.GREEN), 0,
builder.append(secondSpannable );

textview.setText(builder, TextView.BufferType.SPANNABLE);
String comepleteString = firststring + " " + secondstring;
SpannableString spannableString = new SpannableString(comepleteString);
int startIndex = comepleteString.indexOf(secondstring);
int endIndex = startIndex + secondstring.length();

Spannable Spannable = (Spannable) textview.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View widget) {
//performing some function
    }
};
Spannable.setSpan(myClickableSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Body:
Using setHighlightColor() method works most of the time:

textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));

NOTE: Updated code to 2 different strings into 1 TextView and Second string will be coloured and clickable.

Set your TextView's default color as BLACK
Clickable part of will be GREEN

There is a simple example:

String stringFirst = "..."
String stringSecond = "..."

SpannableString spannable = new SpannableString(stringFirst + stringSecond);
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
        }

        @Override
        public void onClick(View widget) {
            //Do your click action
        }
    };
    spannable.setSpan(clickableSpan, stringFirst.length()-1, stringFirst.length() + stringSecond.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(spannable);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));

If it's not work add the line below

ds.setColor(ContextCompat.getColor(context, R.color.green));

to your updateDrawState method. It looks like this:

String stringFirst = "..."
String stringSecond = "..."

SpannableString spannable = new SpannableString(stringFirst + stringSecond);
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(ContextCompat.getColor(context, R.color.green));
        }

        @Override
        public void onClick(View widget) {
            //Do your click action
        }
    };
    spannable.setSpan(clickableSpan, stringFirst.length()-1, stringFirst.length() + stringSecond.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(spannable);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));


问:
how to change the src of an when I know the  id?
I display an array of images in a *ngFor loop.

itemimg.component.html

```<code><div *ngFor="let itemimg of itemimgs" [class.selected]="itemimg === selectedItemimg"
            (click)="onSelect(itemimg)">
    <img id="{{itemimg.index}}" class="thumb" src="{{itemimg.imageUrl}}" width="{{itemimg.width}}" height="{{itemimg.height}}"
        style="float: left; margin-right: 3px; margin-bottom: 3px">
</div>
</code>```

When I click on any of the images I want to replace the first image.

itemimg.components.ts (part)

```<code>  onSelect(itemimg: Itemimg): void{
    this.selectedItemimg = itemimg;
    var newsrc = "../../assets/images/" + itemimg.route + ".jpg";
    //alert (newsrc);
    *what-goes-here* = newsrc;    // the problem
  }
</code>```

I have been googled this for over three hours but cannot find the answer. Thank you for looking.

答:
Please do the following considering you always want to replace first image in the array:

```<code>onSelect(itemimg: Itemimg): void{
this.selectedItemimg = itemimg;
var newsrc = "../../assets/images/" + itemimg.route + ".jpg";
//alert (newsrc);
this.itemimgs[0].imageUrl = newsrc;
</code>```

}

Title: how to change the src of an< img> when I know the <img> id?

Body:
I display an array of images in a *ngFor loop.

itemimg.component.html

When I click on any of the images I want to replace the first image.

itemimg.components.ts (part)

  onSelect(itemimg: Itemimg): void{
    this.selectedItemimg = itemimg;
    var newsrc = "../../assets/images/" + itemimg.route + ".jpg";
    //alert (newsrc);
    *what-goes-here* = newsrc;    // the problem
  }

I have been googled this for over three hours but cannot find the answer. Thank you for looking.

Body:
Please do the following considering you always want to replace first image in the array:

onSelect(itemimg: Itemimg): void{
this.selectedItemimg = itemimg;
var newsrc = "../../assets/images/" + itemimg.route + ".jpg";
//alert (newsrc);
this.itemimgs[0].imageUrl = newsrc;

}


问:
How to count the unchecked checkboxes in a while loop
```<code>$query = mysql_query("SELECT DISTINCT status, vendor FROM tbl_softwareinstalled WHERE vendor NOT LIKE ''");
$nums = mysql_num_rows($query);
echo "<form name = 'filter' action='softwarefilter.php' method='POST'>
$nums<br>

<table border = 1><tr><td> </td>
<td><strong>Software Vendor</strong></td></tr>";

$ctr1 = 1;
while($fetch = mysql_fetch_array($query)) {
$vendor = $fetch['vendor'];
$status = $fetch['status'];
    if(($ctr1 % 2)==1)
        { print "<tr bgcolor = 'white'>";}
        else
        { print "<tr bgcolor = '#EEEEEE'>"; }
    print "<td><input name= 'chk[]' type='hidden' value='0'>
    <input type = 'checkbox' name = 'chk[]' value = '$vendor' ";

    if ($status == 'Enabled') {
    print "checked = 'checked'></td><td>$vendor</td></tr>"; }
    else {
    print "></td><td>$vendor</td></tr>"; }
    $ctr1++;
}
print "</table>";
print "<input type = 'submit' name = 'submit' value = 'Update Filter'>
</form> ";

$submit = $_POST['submit'];
if(isset($submit))
{
    $chk = $_POST['chk'];
    $count = count($chk);

    if (empty($chk)) {

    echo "qweqwe<br>";
    }

        for ($i=0; $i<$count; $i++) {
        $abc = $chk[$i];
        $query = mysql_query("UPDATE tbl_softwareinstalled SET status = 'Enabled' WHERE vendor = '$abc'");

        }

    echo '<meta http-equiv="refresh" content="0.5;url=/assets/softwarefilter.php">
            <script language="javascript">
            alert("Software filter updated.");
            </script>';
}
</code>```

Hi, how can I count the UNCHECKED CHECKBOXES in a while loop with this block of code?
Let's say for example I have 10 checkboxes with 10 values, the user checked 3 checkboxes (with values: 'abc', 'def', 'ghi'), after submitting it. It will count all the UNCHECKED checkboxes and echoes the value of it. The values of 3 checked checkboxes SHOULD NOT be echoed.

答:
I had worked on a similar thing for counting unchecked boxes.
place two input fields of input type checkbox and input type hidden with different names

```<code><input type="hidden" class="" name="test[]" value="0">
<input type="checkbox" class="" name="checkbox[]" value="1">
</code>```

then on submit

```<code>if (isset($_POST['submit'])) {
    $cnt = array();
    $counter =0;
    $testcnt = 0;
    $cnt = 0;
    if (isset($_POST['test'])) {
        $testcnt = count($_POST['test']);
    }
    if (isset($_POST['checkbox'])) {
        $cnt = count($_POST['checkbox']);
    }
    echo 'the count of unchecked boxes is ';
    print_r($testcnt-$cnt);
}
</code>```

For your case change this to:

```<code><input name= 'unchecked[]' type='hidden' value='0'>
</code>```

then on submit when your checking for isset(submit) you can add the following an d change accordingly

```<code>$unchecked_input = count($_POST['unchecked']);
$chk = $_POST['chk'];
$count = count($chk);
echo $unchecked_input-$count; //will output the count of unchecked boxes
</code>```

Body:
$query = mysql_query("SELECT DISTINCT status, vendor FROM tbl_softwareinstalled WHERE vendor NOT LIKE ''");
$nums = mysql_num_rows($query);
echo "<form name = 'filter' action='softwarefilter.php' method='POST'>
$nums

Software Vendor
";

$ctr1 = 1;
while($fetch = mysql_fetch_array($query)) {
$vendor = $fetch['vendor'];
$status = $fetch['status'];
    if(($ctr1 % 2)==1)
        { print "
";}
        else
        { print "
"; }
    print "<input name= 'chk[]' type='hidden' value='0'>
    <input type = 'checkbox' name = 'chk[]' value = '$vendor' ";

    if ($status == 'Enabled') {
    print "checked = 'checked'>	$vendor
"; }
    else {
    print ">	$vendor
"; }
    $ctr1++;
}
print "
";
print "<input type = 'submit' name = 'submit' value = 'Update Filter'>
</form> ";

$submit = $_POST['submit'];
if(isset($submit))
{
    $chk = $_POST['chk'];
    $count = count($chk);

    if (empty($chk)) {

    echo "qweqwe
";
    }

        for ($i=0; $i<$count; $i++) {
        $abc = $chk[$i];
        $query = mysql_query("UPDATE tbl_softwareinstalled SET status = 'Enabled' WHERE vendor = '$abc'");

        }

    echo '<meta http-equiv="refresh" content="0.5;url=/assets/softwarefilter.php">
            ';
}

Hi, how can I count the UNCHECKED CHECKBOXES in a while loop with this block of code?
Let's say for example I have 10 checkboxes with 10 values, the user checked 3 checkboxes (with values: 'abc', 'def', 'ghi'), after submitting it. It will count all the UNCHECKED checkboxes and echoes the value of it. The values of 3 checked checkboxes SHOULD NOT be echoed.

Body:
I had worked on a similar thing for counting unchecked boxes.
place two input fields of input type checkbox and input type hidden with different names

<input type="hidden" class="" name="test[]" value="0">
<input type="checkbox" class="" name="checkbox[]" value="1">

then on submit

if (isset($_POST['submit'])) {
    $cnt = array();
    $counter =0;
    $testcnt = 0;
    $cnt = 0;
    if (isset($_POST['test'])) {
        $testcnt = count($_POST['test']);
    }
    if (isset($_POST['checkbox'])) {
        $cnt = count($_POST['checkbox']);
    }
    echo 'the count of unchecked boxes is ';
    print_r($testcnt-$cnt);
}

For your case change this to:

<input name= 'unchecked[]' type='hidden' value='0'>

then on submit when your checking for isset(submit) you can add the following an d change accordingly

$unchecked_input = count($_POST['unchecked']);
$chk = $_POST['chk'];
$count = count($chk);
echo $unchecked_input-$count; //will output the count of unchecked boxes


问:
How do I remove/delete a virtualenv?
I created an environment with the following command: virtualenv venv --distribute

Trying to remove it with the following command: rmvirtualenv venv does not work.

I do an lson my current directory and I still see venv

The only way I can remove it seems to be: sudo rm -rf venv

Note that the environment is not active. I'm running Ubuntu 11.10. Any ideas? I've tried rebooting my system to no avail.

答:
if you are windows user, then it's in C:\Users\your_user_name\Envs. You can delete it from there.

Also try in command prompt rmvirtualenv environment name.

I tried with command prompt so it said deleted but it was still existed. So i manually delete it.

ContentLicense: CC BY-SA 4.0

Title: How do I remove/delete a virtualenv?


问:
Query temp space limit in Oracle
I want to run a query which takes a lot of temp space. However, I don't want the query to exhaust all the available temp space. How can this be achieved?</p>

答: You can also create another temporary tablespace with a fixed size and assign the user running the query to that one.</p>

Title: Query temp space limit in Oracle


问:
Angular2 RC5 ngModule: No Provider For NameService
I've a small (big...) problem with angular2 services.
I'm trying to provide services with ngModule providers options, but when I try to get it into my components I got : No provider for ServiceName (here, RankingService).

app.module.ts

import { NgModule }         from '@angular/core'
import { BrowserModule }    from '@angular/platform-browser'
import { FormsModule }      from '@angular/forms'
import { HttpModule }       from '@angular/http'

/*
 * App component and routing
 */
import { AppComponent } from './components/app/app.component'
import { routing }      from './app.routes'

/*
 * Services
 */
import { UserService }      from './services/user.service'
import { RankingService }   from './services/ranking.service'

/*
 * Global components
 */
import { HeaderComponent }  from './components/header/header.component'
import { FooterComponent }  from './components/footer/footer.component'

/*
 * App Components
 */
import { RankingComponent }     from './components/ranking/ranking.component'
import { OthersComponent }      from './components/others/others.component'
import { IpixsComponent }       from './components/ipix/ipixs.component'
import { IpixDetailsComponent } from './components/ipix/ipix-details/ipix-details.component'

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        routing
    ],
    declarations: [
        AppComponent,
        HeaderComponent,
        FooterComponent,
        RankingComponent,
        OthersComponent,
        IpixsComponent,
        IpixDetailsComponent
    ],
    providers: [
        UserService,
        RankingService
    ],
    exports: [ AppComponent ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }
```

<p><strong>ranking.service.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core'

/*
 * Entities
 */
import { RankingUser } from './../entities/ranking-user'

@Injectable()
export class RankingService {
    getRanking() {
        const users: RankingUser[] = [
            { user: { picture : '', name: 'Edwige Chou' }, correlation: 100 },
            { user: { picture : '', name: 'Mathieu Vandeginste' }, correlation: 78 },
            { user: { picture : '', name: 'Isabelle Isa' }, correlation: 51 },
            { user: { picture : '', name: 'Julien Sergent' }, correlation: 39 },
            { user: { picture : '', name: 'Paul Raul' }, correlation: 23 },
            { user: { picture : '', name: 'Johnatan' }, correlation: 17 }
        ]

        return users
    }
}
</code>```

ranking.component.ts

/*
 * Dependencies
 */
import { Component, OnInit } from '@angular/core'

/*
 * Services
 */
import { RankingService } from './../../services/ranking.service'

/*
 * Entities
 */
import { RankingUser } from './../../entities/ranking-user'

@Component({
    moduleId: module.id,
    selector: 'ranking',
    templateUrl: 'ranking.component.html',
    styleUrls: [ 'ranking.component.css' ]
})
export class RankingComponent implements OnInit {
    ranking: RankingUser[]

    constructor(
        private rankingService: RankingService
    ) { }

    ngOnInit() {
        this.getRanking()
    }

    getRanking() {
        this.ranking = this.rankingService.getRanking()
        console.log( this.ranking )
    }
}
```

<p>I looked many times angular doc but I don't see the problem, thank you for your help ;-)</p>

<p>Edit: When I provide service directly in my components, it's works, only provide it into app module doesn't.</p>

<p>Edit 2: I solved my problem, it was my systemjs configuration which was wrong, or rather not conceived to manage that kind of situation: I've created my own package (Twinipix) but my application doesn't contain Twinipix folder but rather public folder, so the problem came from jspm.config.js file:</p>

<pre class="lang-js prettyprint-override"><code>packages[ "Twinipix" ] = {
    main: "../public/main.js"
};
</code>```

I used that configuration to do more logical imports (import the entire application and not a single file), it's juste my perfectionist side!
So, with a more common systemjs configuration, all works perfectly!

答:
Answered by the question asker:

I solved my problem, it was my systemjs configuration which was wrong, or rather not conceived to manage that kind of situation: I've created my own package (Twinipix) but my application doesn't contain Twinipix folder but rather public folder, so the problem came from jspm.config.js file:

```<code>packages[ "Twinipix" ] = {
    main: "../public/main.js"
};
</code>```

I used that configuration to do more logical imports (import the entire application and not a single file), it's just my perfectionist side! So, with a more common systemjs configuration, all works perfectly!

Body:
I've a small (big...) problem with angular2 services.
I'm trying to provide services with ngModule providers options, but when I try to get it into my components I got : No provider for ServiceName (here, RankingService).

app.module.ts

import { NgModule }         from '@angular/core'
import { BrowserModule }    from '@angular/platform-browser'
import { FormsModule }      from '@angular/forms'
import { HttpModule }       from '@angular/http'

/*
 * App component and routing
 */
import { AppComponent } from './components/app/app.component'
import { routing }      from './app.routes'

/*
 * Services
 */
import { UserService }      from './services/user.service'
import { RankingService }   from './services/ranking.service'

/*
 * Global components
 */
import { HeaderComponent }  from './components/header/header.component'
import { FooterComponent }  from './components/footer/footer.component'

/*
 * App Components
 */
import { RankingComponent }     from './components/ranking/ranking.component'
import { OthersComponent }      from './components/others/others.component'
import { IpixsComponent }       from './components/ipix/ipixs.component'
import { IpixDetailsComponent } from './components/ipix/ipix-details/ipix-details.component'

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        routing
    ],
    declarations: [
        AppComponent,
        HeaderComponent,
        FooterComponent,
        RankingComponent,
        OthersComponent,
        IpixsComponent,
        IpixDetailsComponent
    ],
    providers: [
        UserService,
        RankingService
    ],
    exports: [ AppComponent ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

ranking.service.ts

import { Injectable } from '@angular/core'

/*
 * Entities
 */
import { RankingUser } from './../entities/ranking-user'

@Injectable()
export class RankingService {
    getRanking() {
        const users: RankingUser[] = [
            { user: { picture : '', name: 'Edwige Chou' }, correlation: 100 },
            { user: { picture : '', name: 'Mathieu Vandeginste' }, correlation: 78 },
            { user: { picture : '', name: 'Isabelle Isa' }, correlation: 51 },
            { user: { picture : '', name: 'Julien Sergent' }, correlation: 39 },
            { user: { picture : '', name: 'Paul Raul' }, correlation: 23 },
            { user: { picture : '', name: 'Johnatan' }, correlation: 17 }
        ]

        return users
    }
}

ranking.component.ts

/*
 * Dependencies
 */
import { Component, OnInit } from '@angular/core'

/*
 * Services
 */
import { RankingService } from './../../services/ranking.service'

/*
 * Entities
 */
import { RankingUser } from './../../entities/ranking-user'

@Component({
    moduleId: module.id,
    selector: 'ranking',
    templateUrl: 'ranking.component.html',
    styleUrls: [ 'ranking.component.css' ]
})
export class RankingComponent implements OnInit {
    ranking: RankingUser[]

    constructor(
        private rankingService: RankingService
    ) { }

    ngOnInit() {
        this.getRanking()
    }

    getRanking() {
        this.ranking = this.rankingService.getRanking()
        console.log( this.ranking )
    }
}

I looked many times angular doc but I don't see the problem, thank you for your help ;-)

Edit: When I provide service directly in my components, it's works, only provide it into app module doesn't.

Edit 2: I solved my problem, it was my systemjs configuration which was wrong, or rather not conceived to manage that kind of situation: I've created my own package (Twinipix) but my application doesn't contain Twinipix folder but rather public folder, so the problem came from jspm.config.js file:

packages[ "Twinipix" ] = {
    main: "../public/main.js"
};

I used that configuration to do more logical imports (import the entire application and not a single file), it's juste my perfectionist side!
So, with a more common systemjs configuration, all works perfectly!

Body:
Answered by the question asker:

I solved my problem, it was my systemjs configuration which was wrong, or rather not conceived to manage that kind of situation: I've created my own package (Twinipix) but my application doesn't contain Twinipix folder but rather public folder, so the problem came from jspm.config.js file:

packages[ "Twinipix" ] = {
    main: "../public/main.js"
};

I used that configuration to do more logical imports (import the entire application and not a single file), it's just my perfectionist side! So, with a more common systemjs configuration, all works perfectly!


问:
Finding the averege in a loop counting to 100
I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.

```<code>for ($x = 3; $x < 100; $x+=3) {
    echo $x.", ";
}
</code>```

This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?

答:
For the last answer i think we should not do:

//first $i was 0 so we add 1 $i=$i + 1;

Regards

Body:
I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.

for ($x = 3; $x < 100; $x+=3) {
    echo $x.", ";
}

This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?


问:
ClassNotFoundException for JUnit tests in AspectJ project in Eclipse
Google has some answers for this, but they are all for people using Maven. I am not using Maven so I am stumped. I have other projects that are not using the AspectJ plugin and their JUnit tests run fine in Eclipse. I cannot figure out why Eclipse cannot find the class. I right click on the class itself and then I tell it to run as a JUnit test. It works for JUnit tests in my non-AspectJ projects. Can anybody help?</p>

```<code>Class not found BasicSpectrogramPeriodogramTests
java.lang.ClassNotFoundException: BasicSpectrogramPeriodogramTests
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:693)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClasses(RemoteTestRunner.java:429)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
</code>```

答:
The AspectJ plugin may be influencing your build classpath but not the runtime classpath.  Create a launcher entry for your class and then explicitly set the classpath to include the jar.

Use Eclipse's 'load type' function to see where it is loading the class from.

Ctrl-Space-T pulls up a dialog. Enter the target classname, "BasicSpectrogramPeriodogramTests
".  It should display the package name and location in the workspace, either to the right of the classname for all listed classes, or near the bottom of the dialog for a selected class.  This will include the jar and its path if that is how it is being loaded by Eclipse.

Make sure the path for your class is what is in the runtime config classpath.  Add it explicitly at the top of the classpath, even it it is a dup.

Body:
Google has some answers for this, but they are all for people using Maven. I am not using Maven so I am stumped. I have other projects that are not using the AspectJ plugin and their JUnit tests run fine in Eclipse. I cannot figure out why Eclipse cannot find the class. I right click on the class itself and then I tell it to run as a JUnit test. It works for JUnit tests in my non-AspectJ projects. Can anybody help?

Class not found BasicSpectrogramPeriodogramTests
java.lang.ClassNotFoundException: BasicSpectrogramPeriodogramTests
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:693)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClasses(RemoteTestRunner.java:429)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)


问:
SwiftMailer sender domain not allowed using SMTP Dreamhost?
I'm trying to send an email using SwiftMailer and SMTP. The SMTP server is a standard Dreamhost setup. I only get the issue when using an email that is not hosted on dreamhost. For example if I use contact@joescotto.net as the from email, I will have no problems and the email will send. However, if I use contactjoescotto@gmail.com I'll get the following error:

Expected response code 250 but got code "550", with message "550 5.7.1 Sender domain not allowed. Please read: http://dhurl.org/20b D157 "

My email function is as follows:

```<code>/**
 * Sends an email
 * @param  string $name    Sender name
 * @param  string $subject Sender subject
 * @param  string $email   Sender email
 * @param  string $message Sender message
 * @return bool            True if sent, otherwise false
 */
public static function sendMessage($name, $subject, $email, $message) {
    // Create and setup the transport
    $transport = Swift_SmtpTransport::newInstance($GLOBALS['config']['smtp']['host'], $GLOBALS['config']['smtp']['port'])
        ->setUsername($GLOBALS['config']['smtp']['username'])
        ->setPassword($GLOBALS['config']['smtp']['password']);

    // Create the mailer using your created Transport
    $mailer = Swift_Mailer::newInstance($transport);

    // Create a message
    $message = Swift_Message::newInstance($subject)
        ->setFrom([$email => $name])
        ->setTo(['contact@joescotto.net' => 'Joe Scotto'])
        ->setBody($message);

    // Try to send the message
    if (!$mailer->send($message)) {
        return false;
    }

    // Set email timeout cookie
    setcookie("emailTimeout", true, time() + (60 * 5), '/');

    // Return true on sucessful send
    return true;
}
</code>```

Any help would be great, Thanks!

答: Try no-reply@whatever-server-you-are-on & use the reply-to header for the from address?</p>

Body:
I'm trying to send an email using SwiftMailer and SMTP. The SMTP server is a standard Dreamhost setup. I only get the issue when using an email that is not hosted on dreamhost. For example if I use contact@joescotto.net as the from email, I will have no problems and the email will send. However, if I use contactjoescotto@gmail.com I'll get the following error:

Expected response code 250 but got code "550", with message "550 5.7.1 Sender domain not allowed. Please read: http://dhurl.org/20b D157 "

My email function is as follows:

/**
 * Sends an email
 * @param  string $name    Sender name
 * @param  string $subject Sender subject
 * @param  string $email   Sender email
 * @param  string $message Sender message
 * @return bool            True if sent, otherwise false
 */
public static function sendMessage($name, $subject, $email, $message) {
    // Create and setup the transport
    $transport = Swift_SmtpTransport::newInstance($GLOBALS['config']['smtp']['host'], $GLOBALS['config']['smtp']['port'])
        ->setUsername($GLOBALS['config']['smtp']['username'])
        ->setPassword($GLOBALS['config']['smtp']['password']);

    // Create the mailer using your created Transport
    $mailer = Swift_Mailer::newInstance($transport);

    // Create a message
    $message = Swift_Message::newInstance($subject)
        ->setFrom([$email => $name])
        ->setTo(['contact@joescotto.net' => 'Joe Scotto'])
        ->setBody($message);

    // Try to send the message
    if (!$mailer->send($message)) {
        return false;
    }

    // Set email timeout cookie
    setcookie("emailTimeout", true, time() + (60 * 5), '/');

    // Return true on sucessful send
    return true;
}

Any help would be great, Thanks!


问:
Undefined symbols for architecture x86_64 flex/bison
I am trying to make a simple toy (LET) language as practice using flex/bison. However, I keep getting the following error when I run the command g++ -Wall -std=c++11 repl.cpp -v -o LET:

```<code>Undefined symbols for architecture x86_64:
  "yy_scan_string(char const*)", referenced from:
      _main in repl-030403.o
  "yy_delete_buffer(yy_buffer_state*)", referenced from:
      _main in repl-030403.o
  "yyparse()", referenced from:
      _main in repl-030403.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I have the following files defined,

LET.y:

```<code>%{
#include <iostream>
#include <cstdio>
#include <string>

#include "AST.hpp"
#include "GENERATED_CODE/LET_parser.hpp"
#include "GENERATED_CODE/LET_lexer.hpp"

using namespace std;

extern int yylex();
extern char* yytext;
extern int yyparse();
extern Pgm* prog;
void yyerror (char const *s) {
   fprintf (stderr, "%s\n", s);
}
%}

%output "./PARSER/GENERATED_CODE/LET_parser.cpp"
%defines "./PARSER/GENERATED_CODE/LET_parser.hpp"

%union {
    Pgm* prog;
    int value;
    char* var;
    char cval;
    Exp* exp;
    string* str;
}

%token TTRUE
%token TFALSE
%token TLET
%token TIN
%token TIF
%token TTHEN
%token TELSE
%token TISZERO
%token TASSIGN
%token TLPAREN
%token TRPAREN
%token TPLUS
%token TMINU
%token TMULT
%token TDIVI
%token TREMI
%token TCOMMA
%token <value> TNUM
%token <var> TVAR

%type <prog> Prog
%type <exp> Exp
%type <str> Vari
/* Causes Bison to give more detailed error messages when parsing */
%error-verbose

%%

/* Bison Grammar Declarations */
Prog: Exp                 { prog = new Pgm($1); }

Vari: TVAR        { $$ = new string(yytext);}

Exp: TNUM                                 { $$ = new ConstExp(atoi(yytext)); }
   | TVAR                                 { $$ = new VarExp(yytext); }
   | TTRUE                                { $$ = new TrueExp; }
   | TFALSE                               { $$ = new FalseExp; }
   | TISZERO TLPAREN Exp TRPAREN          { $$ = new IsZeroExp($3); }
   | TMINU TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new DiffExp($3, $5); }
   | TPLUS TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new SumExp($3, $5); }
   | TMULT TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new MultExp($3, $5); }
   | TDIVI TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new QuotExp($3, $5); }
   | TREMI TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new RemiExp($3, $5); }
   | TIF Exp TTHEN Exp TELSE Exp          { $$ = new IfExp($2, $4, $6); }
   | TLET Vari TASSIGN Exp TIN Exp        { $$ = new LetExp(*$2, $4, $6); }
</code>```

LET.l:

```<code>%{
#include <iostream>
#include <cstdio>

#include "AST.hpp"
#include "GENERATED_CODE/LET_parser.hpp"

using namespace std;

int yylex();
void yyerror (char const *s) {
   fprintf (stderr, "%s\n", s);
}
%}

%option c++
%option header-file = "./PARSER/GENERATED_CODE/LET_lexer.hpp"
%option outfile     = "./PARSER/GENERATED_CODE/LET_lexer.cpp"
%option noyywrap

digit [0-9]
alpha [a-zA-Z]
ws [ \t\n]+

%%
"#".*[\n]                      { /* No Action Taken */ }
{ws}                           { /* No Action Taken */ }
"true"                         { return TTRUE; }
"false"                        { return TFALSE; }
"let"                          { return TLET; }
"in"                           { return TIN; }
"if"                           { return TIF; }
"then"                         { return TTHEN; }
"else"                         { return TELSE; }
"zero?"                        { return TISZERO; }
"="                            { return TASSIGN; }
"("                            { return TLPAREN; }
")"                            { return TRPAREN; }
"+"                            { return TPLUS; }
"-"                            { return TMINU; }
"*"                            { return TMULT; }
"/"                            { return TDIVI; }
"%"                            { return TREMI; }
","                            { return TCOMMA; }
"-"?{digit}+                   { return TNUM; }
[a-zA-Z][a-z|0-9|\_|\'|\-|\?]* { return TVAR; }
</code>```

Makefile:

```<code>generate-parser: clean flex bison

clean:
    rm -rf PARSER/GENERATED_CODE
    mkdir -p PARSER/GENERATED_CODE

flex:
    flex PARSER/LET.l

bison:
    bison -d PARSER/LET.y
</code>```

repl.cpp:

```<code>#include <cstdio>

#include "./PARSER/AST.hpp"
#include "./PARSER/GENERATED_CODE/LET_parser.hpp"
#include "./PARSER/GENERATED_CODE/LET_lexer.hpp"

using namespace std;

extern YY_BUFFER_STATE yy_scan_string(const char * str);
extern void yy_delete_buffer(YY_BUFFER_STATE buffer);

int main() {
    char input[] = "RAINBOW UNICORN 1234 UNICORN";

    YY_BUFFER_STATE state = yy_scan_string(input);
    yyparse();
    yy_delete_buffer(state);

    return 0;
}
</code>```

答:
The basic problem is that you do not seem to be compiling the generated scanner and parser, nor are you linking the compiled scanner and parser into your executable. So when you attempt to create the executable, none of the symbols defined in the scanner (yy_scan_string and yy_delete_buffer) nor in the parser (yyparse) exist.

When you add the compilation lines to your Makefile, remember that the scanner depends on the parser because it must include the header file generated by bison in order to have the token types defined.

That being the case, the parser cannot depend on the scanner, which is why it is not correct to #include the scanner's header file in the bison prologue. It is also incorrect to #include the parser header file in the bison prologue, because the bison-generated parser already includes the necessary prototypes and definitions.

Finally, you are asking flex to generate a C++ lexer, but your code uses the C interface (which includes the functions yy_scan_string and yy_delete_buffer). Personally, I would just delete the %option c++ from your scanner prologue. If you really want to use the C++ API, you will need to carefully read the flex manual chapter on C++ scanners, and then make appropriate changes to your bison definition so that it knows how to invoke the lexer.

Although this is not related to your question, the use of yytext in a parser is almost never correct, since the contents of yytext will normally correspond to the next token in the input. (LR(1) parsers always lookahead one token.) You should do the necessary semantic conversions in your scanner actions.

Body:
I am trying to make a simple toy (LET) language as practice using flex/bison. However, I keep getting the following error when I run the command g++ -Wall -std=c++11 repl.cpp -v -o LET:

Undefined symbols for architecture x86_64:
  "yy_scan_string(char const*)", referenced from:
      _main in repl-030403.o
  "yy_delete_buffer(yy_buffer_state*)", referenced from:
      _main in repl-030403.o
  "yyparse()", referenced from:
      _main in repl-030403.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have the following files defined,

LET.y:

%{
#include <iostream>
#include <cstdio>
#include <string>

#include "AST.hpp"
#include "GENERATED_CODE/LET_parser.hpp"
#include "GENERATED_CODE/LET_lexer.hpp"

using namespace std;

extern int yylex();
extern char* yytext;
extern int yyparse();
extern Pgm* prog;
void yyerror (char const *s) {
   fprintf (stderr, "%s\n", s);
}
%}

%output "./PARSER/GENERATED_CODE/LET_parser.cpp"
%defines "./PARSER/GENERATED_CODE/LET_parser.hpp"

%union {
    Pgm* prog;
    int value;
    char* var;
    char cval;
    Exp* exp;
    string* str;
}

%token TTRUE
%token TFALSE
%token TLET
%token TIN
%token TIF
%token TTHEN
%token TELSE
%token TISZERO
%token TASSIGN
%token TLPAREN
%token TRPAREN
%token TPLUS
%token TMINU
%token TMULT
%token TDIVI
%token TREMI
%token TCOMMA
%token <value> TNUM
%token <var> TVAR

%type <prog> Prog
%type <exp> Exp
%type <str> Vari
/* Causes Bison to give more detailed error messages when parsing */
%error-verbose

%%

/* Bison Grammar Declarations */
Prog: Exp                 { prog = new Pgm($1); }

Vari: TVAR        { $$ = new string(yytext);}

Exp: TNUM                                 { $$ = new ConstExp(atoi(yytext)); }
   | TVAR                                 { $$ = new VarExp(yytext); }
   | TTRUE                                { $$ = new TrueExp; }
   | TFALSE                               { $$ = new FalseExp; }
   | TISZERO TLPAREN Exp TRPAREN          { $$ = new IsZeroExp($3); }
   | TMINU TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new DiffExp($3, $5); }
   | TPLUS TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new SumExp($3, $5); }
   | TMULT TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new MultExp($3, $5); }
   | TDIVI TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new QuotExp($3, $5); }
   | TREMI TLPAREN Exp TCOMMA Exp TRPAREN { $$ = new RemiExp($3, $5); }
   | TIF Exp TTHEN Exp TELSE Exp          { $$ = new IfExp($2, $4, $6); }
   | TLET Vari TASSIGN Exp TIN Exp        { $$ = new LetExp(*$2, $4, $6); }

LET.l:

%{
#include <iostream>
#include <cstdio>

#include "AST.hpp"
#include "GENERATED_CODE/LET_parser.hpp"

using namespace std;

int yylex();
void yyerror (char const *s) {
   fprintf (stderr, "%s\n", s);
}
%}

%option c++
%option header-file = "./PARSER/GENERATED_CODE/LET_lexer.hpp"
%option outfile     = "./PARSER/GENERATED_CODE/LET_lexer.cpp"
%option noyywrap

digit [0-9]
alpha [a-zA-Z]
ws [ \t\n]+

%%
"#".*[\n]                      { /* No Action Taken */ }
{ws}                           { /* No Action Taken */ }
"true"                         { return TTRUE; }
"false"                        { return TFALSE; }
"let"                          { return TLET; }
"in"                           { return TIN; }
"if"                           { return TIF; }
"then"                         { return TTHEN; }
"else"                         { return TELSE; }
"zero?"                        { return TISZERO; }
"="                            { return TASSIGN; }
"("                            { return TLPAREN; }
")"                            { return TRPAREN; }
"+"                            { return TPLUS; }
"-"                            { return TMINU; }
"*"                            { return TMULT; }
"/"                            { return TDIVI; }
"%"                            { return TREMI; }
","                            { return TCOMMA; }
"-"?{digit}+                   { return TNUM; }
[a-zA-Z][a-z|0-9|\_|\'|\-|\?]* { return TVAR; }

Makefile:

generate-parser: clean flex bison

clean:
    rm -rf PARSER/GENERATED_CODE
    mkdir -p PARSER/GENERATED_CODE

flex:
    flex PARSER/LET.l

bison:
    bison -d PARSER/LET.y

repl.cpp:

#include <cstdio>

#include "./PARSER/AST.hpp"
#include "./PARSER/GENERATED_CODE/LET_parser.hpp"
#include "./PARSER/GENERATED_CODE/LET_lexer.hpp"

using namespace std;

extern YY_BUFFER_STATE yy_scan_string(const char * str);
extern void yy_delete_buffer(YY_BUFFER_STATE buffer);

int main() {
    char input[] = "RAINBOW UNICORN 1234 UNICORN";

    YY_BUFFER_STATE state = yy_scan_string(input);
    yyparse();
    yy_delete_buffer(state);

    return 0;
}


问:
Changing font color in link
I must first advise that I am new to coding. Please be gentle. I am attempting to change the color of the font in a link to an embedded video contained in an eBay listing. This code was generated by the "embed" feature of YouTube, and I simply pasted it into the html of the item description. I cannot get the color of the font to change when changing the color code. It always stays the same. I can change the font size, though. Why does this work and not color changes? Here is the line of code for the embedded video I am working with. Any help is appreciated.
   This is an edit after I posted the question. I pasted the code into my question but it shows up as my link. I do not know how to make the actual code appear in my query without showing up as the resulting link.

For a video click here

答:
Remove the tag  and use inline CSS to change the color, like this

```<code><b>
  <font face="Verdana" size="12">
   <i>
    <a href="https://www.youtube.com/watch?v=482ywzMbVfE" style="color: #000000">For a video click here</a>
   </i>
   </font>
</b>
</code>```

Notice the style="color: #000000" attribute added to the  tag.

You can also use inline CSS to change the font and make it italics. Just remove the tags ,  an use the font-family and font-style CSS properties like this,

```<code><b>
 <a href="https://www.youtube.com/watch?v=482ywzMbVfE" style="color: #000000; font-family: Verdana; font-size: 40px; font-style: italic;">For a video click here</a>
</b>
</code>```

Notice the style="color: #000000; font-family: Verdana; font-size: 40px; font-style: italic;" attribute added to the  tag.

Hope this helps :)

Title: Changing font color in link

Body:
Remove the tag <font color="#000000"> and use inline CSS to change the color, like this

<b>
  <font face="Verdana" size="12">
   <i>
    <a href="https://www.youtube.com/watch?v=482ywzMbVfE" style="color: #000000">For a video click here</a>
   </i>
   </font>
</b>

Notice the style="color: #000000" attribute added to the <a> tag.

You can also use inline CSS to change the font and make it italics. Just remove the tags <font face="Verdana" size="12">, <i> an use the font-family and font-style CSS properties like this,

<b>
 <a href="https://www.youtube.com/watch?v=482ywzMbVfE" style="color: #000000; font-family: Verdana; font-size: 40px; font-style: italic;">For a video click here</a>
</b>

Notice the style="color: #000000; font-family: Verdana; font-size: 40px; font-style: italic;" attribute added to the <a> tag.

Hope this helps :)


问:
How to get size of all files in an S3 bucket with versioning?
I know this command can provide the size of all files in a bucket:

```<code>aws s3 ls mybucket --recursive --summarize --human-readable
</code>```

But this does not account for versioning.

If I run this command:

```<code>aws s3 ls s3://mybucket/myfile --human-readable
</code>```

It will show something like "100 MiB" but it may have 10 versions of this file which will be more like "1 GiB" total.

The closest I have is getting the sizes of every version of a given file:

```<code>aws s3api list-object-versions --bucket mybucket --prefix "myfile" --query 'Versions[?StorageClass=`STANDARD`].Size' > /tmp/s3_myfile_version_sizes
</code>```

Then take the sum of all version sizes.

But I would have to rerun this command for every file in a bucket.

Is there an easier way to do this?

答:
You can run list-object-versions on the bucket as a whole:

```<code>aws s3api list-object-versions --bucket my-bucket --query 'Versions[*].Size'
</code>```

Use jq to sum it up:

```<code>aws s3api list-object-versions --bucket my-bucket --query 'Versions[*].Size' | jq add
</code>```

Or, if you need a human readable output:

```<code>aws s3api list-object-versions --bucket my-bucket --query 'Versions[*].Size' | jq add | numfmt  --to=iec-i --suffix=B
</code>```

You can also add a prefix in case you want to know the size of a given "folder" and maybe get also the number of version objects:

```<code>aws s3api list-object-versions --bucket my-bucket --prefix my-folder --query 'Versions[*].Size' | jq 'length|add'
</code>```

Or you can use jq filtering to write more complex filters, for example, including only non-current objects:

```<code>aws s3api list-object-versions --bucket my-bucket --prefix my-folder | jq '[.Versions[]|select(.IsLatest == false)|.Size] | length,add'
</code>```

If jq is not available, using the --output text option unfortunately results in tab-separated values, so here's a hack to force it to separate lines and then add up the total:

```<code>aws s3api list-object-versions --bucket my-bucket --query 'Versions[*].[Size,Size]' --output text  | awk '{s+=$1} END {printf "%.0f", s}'
</code>```

If you have a large number of objects, it might be better to use data provided by the Amazon S3 Storage Inventory:

Amazon S3 inventory provides a comma-separated values (CSV) flat-file output of your objects and their corresponding metadata on a daily or weekly basis for an S3 bucket or a shared prefix (that is, objects that have names that begin with a common string).

Body:
I know this command can provide the size of all files in a bucket:

aws s3 ls mybucket --recursive --summarize --human-readable

But this does not account for versioning.

If I run this command:

aws s3 ls s3://mybucket/myfile --human-readable

It will show something like "100 MiB" but it may have 10 versions of this file which will be more like "1 GiB" total.

The closest I have is getting the sizes of every version of a given file:

aws s3api list-object-versions --bucket mybucket --prefix "myfile" --query 'Versions[?StorageClass=`STANDARD`].Size' > /tmp/s3_myfile_version_sizes

Then take the sum of all version sizes.

But I would have to rerun this command for every file in a bucket.

Is there an easier way to do this?

Body:
You can run list-object-versions on the bucket as a whole:

aws s3api list-object-versions --bucket my-bucket --query 'Versions[*].Size'

Use jq to sum it up:

aws s3api list-object-versions --bucket my-bucket --query 'Versions[*].Size' | jq add

Or, if you need a human readable output:

aws s3api list-object-versions --bucket my-bucket --query 'Versions[*].Size' | jq add | numfmt  --to=iec-i --suffix=B

You can also add a prefix in case you want to know the size of a given "folder" and maybe get also the number of version objects:

aws s3api list-object-versions --bucket my-bucket --prefix my-folder --query 'Versions[*].Size' | jq 'length|add'

Or you can use jq filtering to write more complex filters, for example, including only non-current objects:

aws s3api list-object-versions --bucket my-bucket --prefix my-folder | jq '[.Versions[]|select(.IsLatest == false)|.Size] | length,add'

If jq is not available, using the --output text option unfortunately results in tab-separated values, so here's a hack to force it to separate lines and then add up the total:

aws s3api list-object-versions --bucket my-bucket --query 'Versions[*].[Size,Size]' --output text  | awk '{s+=$1} END {printf "%.0f", s}'

If you have a large number of objects, it might be better to use data provided by the Amazon S3 Storage Inventory:

Amazon S3 inventory provides a comma-separated values (CSV) flat-file output of your objects and their corresponding metadata on a daily or weekly basis for an S3 bucket or a shared prefix (that is, objects that have names that begin with a common string).


问:
excessive dependence on ajax
I am a newbie to web development. I am trying to develop a web site and it uses fairly large
number of ajax requests. In between i came across a friend who said that excessive dependency
on ajax request can be a performance concern and makes the browser to utilize huge amount of
network utility and cpu usage. Is this true..?

Does excessive dependency on ajax pose serious performance issues.?

答: No. If you'd have to reload the whole page every time you make an ajax request, you would need much more cpu time and network traffic. Though, if you use ajax to reload the clock in the status bar every second from the server, you should replace this with a javascript function...</p>

Title: excessive dependence on ajax


问:
Is there a way to get the zoom level in SVG?
Is there a function that returns the level of the zoom? Or how could you get the level of the zoom with onZoom?

I would like to add/hide some certain elements on SVG when the level of the zoom gets to a certain level. When zoomed enough, an element would be replaced with another element.

答:
getZoom() gives you relative zoom (relative to initial zoom) while getSizes() return real zoom.

Here are all public API methods https://github.com/ariutta/svg-pan-zoom#public-api


问:
ExpressJS does not seem to work with ajax calls
I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.

My ajax call:

```<code>$.ajax({
        method: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });
</code>```

In my express:

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', function (req, res) {
  var user = req.body.user;
  var password = req.body.pass;
  if(user == 'john' && password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!');
});
</code>```

Any help is greatly appreciated.

答:
I think you have to parse request to JSON.

your code is:-

```<code>$.ajax({
        method: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login",

        //here you used JSON.stringify and on server side you have to parse it to use 'user' and 'pass' as a key of json

        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });
</code>```

on the server side

```<code><br>
app.post('/login', function (req, res) {

//parse data to JSON for further use
  var dataObj = JSON.parse(req.body.data);
  if(dataObj.user == 'john' && dataObj.password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});
</code>```

Body:
I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.

My ajax call:

$.ajax({
        method: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });

In my express:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', function (req, res) {
  var user = req.body.user;
  var password = req.body.pass;
  if(user == 'john' && password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!');
});

Any help is greatly appreciated.

Body:
I think you have to parse request to JSON.

your code is:-

$.ajax({
        method: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login",

        //here you used JSON.stringify and on server side you have to parse it to use 'user' and 'pass' as a key of json

        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });

on the server side

<br>
app.post('/login', function (req, res) {

//parse data to JSON for further use
  var dataObj = JSON.parse(req.body.data);
  if(dataObj.user == 'john' && dataObj.password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});


问:
Method that takes Input from user in C#
I'm switching to C# from C++ and I'm trying to learn the methods. Can you help me create a method that takes 2 variables as input from the user? In C++ it was pretty easy just making a void method and adding & before the variable's name like: void Input( int &a, int &b) which would save any changes in their value in the main function. Is there a way to do that in C#?

答:
In C# you have two options for T &x of C++:

ref parameters - these have the same capabilities as C++ reference parameters, and

out parameters - these allow passing data back from a method, but not into the method.

In your case, out is more appropriate, because it lets you pass variables that have not been previously assigned:

```<code>void Input( out int a, out int b) {
    ... // Read and assign a and b
}
</code>```

You can call this method like this:

```<code>// In C# 7
Input(out int a, out int b);
// Prior to C# 7
int a, b;
Input(out a, out b);
</code>```

Note that unlike C++ where taking reference is automatic, C# requires you to mark it with the keyword out.

Title: Method that takes Input from user in C#

Body:
In C# you have two options for T &x of C++:

ref parameters - these have the same capabilities as C++ reference parameters, and

out parameters - these allow passing data back from a method, but not into the method.

In your case, out is more appropriate, because it lets you pass variables that have not been previously assigned:

void Input( out int a, out int b) {
    ... // Read and assign a and b
}

You can call this method like this:

// In C# 7
Input(out int a, out int b);
// Prior to C# 7
int a, b;
Input(out a, out b);

Note that unlike C++ where taking reference is automatic, C# requires you to mark it with the keyword out.


答:
You can achieve this using ref (C# Reference). This is equal to the C++ & references.

An example:

```<code>class RefExample
{
    static void Method(ref int i)
    {
        // The following statement would cause a compiler error if i
        // were boxed as an object.
        i = i + 44;
    }

    static void Main()
    {
        int val = 1;
        Method(ref val);
        Console.WriteLine(val);

        // Output: 45
    }
}
</code>```

Worth to mention that the usage of ref in C# should be pretty rare unlike in C++. Please refer to Jon Skeet's article about parameter passing.

Title: Method that takes Input from user in C#

Body: I'm switching to C# from C++ and I'm trying to learn the methods. Can you help me create a method that takes 2 variables as input from the user? In C++ it was pretty easy just making a void method and adding & before the variable's name like: void Input( int &a, int &b) which would save any changes in their value in the main function. Is there a way to do that in C#?

Body:
You can achieve this using ref (C# Reference). This is equal to the C++ & references.

An example:

class RefExample
{
    static void Method(ref int i)
    {
        // The following statement would cause a compiler error if i
        // were boxed as an object.
        i = i + 44;
    }

    static void Main()
    {
        int val = 1;
        Method(ref val);
        Console.WriteLine(val);

        // Output: 45
    }
}

Worth to mention that the usage of ref in C# should be pretty rare unlike in C++. Please refer to Jon Skeet's article about parameter passing.


问:
Ruby version error
I'm using RVM with my 2.3.1@market gemset and getting error while trying to run my specs saying that

```<code>Your Ruby version is 2.3.1, but your Gemfile specified 2.0.0
</code>```

So I added ruby '2.3.1' to my Gemfile but I'm still getting error that I need `2.0.0' anyway. I've also tried to reinstall bundler, which didn't help.

UPD: When I'm specifying any version than ruby '2.3.1' this line isn't ignored. For example if ruby '2.1.2' is specified then I'm getting error that

```<code> Your Ruby version is 2.3.1, but your Gemfile specified 2.1.2
</code>```

but when I'm specifying ruby '2.3.1' I'm getting

```<code>Your Ruby version is 2.3.1, but your Gemfile specified 2.0.0
</code>```

答:
try running

gem install bundler

or

gem update bundler

this may solve your problem

if that doesn't help then please check ruby -v for you project and make sure that you have ruby 2.3.1 installed for that you can use rvm install 2.3.1 and make if default to your project by echo 2.3.1 > .ruby-version

Title: Ruby version error

Body:
I'm using RVM with my 2.3.1@market gemset and getting error while trying to run my specs saying that

Your Ruby version is 2.3.1, but your Gemfile specified 2.0.0

So I added ruby '2.3.1' to my Gemfile but I'm still getting error that I need `2.0.0' anyway. I've also tried to reinstall bundler, which didn't help.

UPD: When I'm specifying any version than ruby '2.3.1' this line isn't ignored. For example if ruby '2.1.2' is specified then I'm getting error that

 Your Ruby version is 2.3.1, but your Gemfile specified 2.1.2

but when I'm specifying ruby '2.3.1' I'm getting

Your Ruby version is 2.3.1, but your Gemfile specified 2.0.0


问:
How to divide multiple columns with each other in Pandas
I have a dataframe with 52 columns with sales data (weekly) and 52 columns with the sold quantity. I want to create another 52 colums with the price per soldunit.

The division does not work for some reason. I get

ValueError: Wrong number of items passed 2, placement implies 1

Also, can this be achieved in a more elegant (pandas way) by removing the for loop?

This is what I have...

```<code>#calculate cost per unit
for i in range(0,52):
    cw = i + 1
    i = i + 5
    print cw
    data['Cost' + str(cw)] = data.iloc[:,i:i+1] / sap_data.iloc[:,i+52:i+1+52]
</code>```

答:
You can use Pandas pandas.DataFrame.divide function. Is this what you're looking for?

```<code>df = pd.DataFrame({'sales 1': [100,200,300], 'sales 2': [400,500,600], 'quantity 1': [10,20,30], 'quantity 2': [40,50,60]})
print(df)
       quantity 1  quantity 2  sales 1  sales 2
0          10          40      100      400
1          20          50      200      500
2          30          60      300      600
</code>```

Creating 2 new data frames, one for the sales columns df1 and the other one of the quantity columns df2. In your case, you would have to set it to 52 instead of 2.

```<code>df1 = df.iloc[:, :2]
df2 = df.iloc[:,2:]
print(df1)
           quantity 1  quantity 2
0          10          40
1          20          50
2          30          60
print(df2)
       sales 1  sales 2
0      100      400
1      200      500
2      300      600
</code>```

Renaming the columns in df2 with the names from df1.

```<code>df2.columns = df1.columns
</code>```

Then, creating df3, a new data frame.

```<code>df3 = df2.divide(df1, axis= 1)
</code>```

df3 is the result of the division you need. If you want to have all of this data in one data frame, all you have to do is to rename the columns and concatenate the 3 data frames.

```<code>print(df3)
         quantity 1  quantity 2
0        10.0        10.0
1        10.0        10.0
2        10.0        10.0
</code>```

Body:
I have a dataframe with 52 columns with sales data (weekly) and 52 columns with the sold quantity. I want to create another 52 colums with the price per soldunit.

The division does not work for some reason. I get

ValueError: Wrong number of items passed 2, placement implies 1

Also, can this be achieved in a more elegant (pandas way) by removing the for loop?

This is what I have...

#calculate cost per unit
for i in range(0,52):
    cw = i + 1
    i = i + 5
    print cw
    data['Cost' + str(cw)] = data.iloc[:,i:i+1] / sap_data.iloc[:,i+52:i+1+52]

Body:
You can use Pandas pandas.DataFrame.divide function. Is this what you're looking for?

df = pd.DataFrame({'sales 1': [100,200,300], 'sales 2': [400,500,600], 'quantity 1': [10,20,30], 'quantity 2': [40,50,60]})
print(df)
       quantity 1  quantity 2  sales 1  sales 2
0          10          40      100      400
1          20          50      200      500
2          30          60      300      600

Creating 2 new data frames, one for the sales columns df1 and the other one of the quantity columns df2. In your case, you would have to set it to 52 instead of 2.

df1 = df.iloc[:, :2]
df2 = df.iloc[:,2:]
print(df1)
           quantity 1  quantity 2
0          10          40
1          20          50
2          30          60
print(df2)
       sales 1  sales 2
0      100      400
1      200      500
2      300      600

Renaming the columns in df2 with the names from df1.

df2.columns = df1.columns

Then, creating df3, a new data frame.

df3 = df2.divide(df1, axis= 1)

df3 is the result of the division you need. If you want to have all of this data in one data frame, all you have to do is to rename the columns and concatenate the 3 data frames.

print(df3)
         quantity 1  quantity 2
0        10.0        10.0
1        10.0        10.0
2        10.0        10.0