问:
DateTime::createFromFormat doesn't work properly with format 2017-02
I have a following code, which would returns me previous and next date (selection by months). But I found it not working properly, when user selects a february. This is my code, which is applied to get the dates:

```<code>$dateSelect = @$_GET['datum'] ?: date('Y-m');
$date = DateTime::createFromFormat('Y-m', $dateSelect);
$prevdate = clone $date;

$date->modify('first day of next month');
$this->view->next_month = $date->format('m');
$this->view->next_year = $date->format('Y');

$prevdate->modify('first day of previous month');
$this->view->prev_month = $prevdate->format('m');
$this->view->prev_year = $prevdate->format('Y');
</code>```

I have made an example so you can test it faster: PHP Sandbox

If user selects date 2017-02 then it is processed as 2017-03, which is incorrect. Try changing the value to 2017-01 in the example and you will see it is working properly. Since buttons in my code are filling with these values, my users can't go before February 2017 without manually changing the URL.

答:
As DateTime will populate the missing d part of the date based on the current date, you're effectively getting 2017-02-29 (given that today is the 29th), which isn't valid, but DateTime adjusts to a valid date by rolling forward into the following month, giving 2017-03-01.

You need to force a d part to the date to avoid this default behaviour

```<code>$date = DateTime::createFromFormat('Y-m-d', $dateSelect . '-01');
</code>```

Body:
I have a following code, which would returns me previous and next date (selection by months). But I found it not working properly, when user selects a february. This is my code, which is applied to get the dates:

$dateSelect = @$_GET['datum'] ?: date('Y-m');
$date = DateTime::createFromFormat('Y-m', $dateSelect);
$prevdate = clone $date;

$date->modify('first day of next month');
$this->view->next_month = $date->format('m');
$this->view->next_year = $date->format('Y');

$prevdate->modify('first day of previous month');
$this->view->prev_month = $prevdate->format('m');
$this->view->prev_year = $prevdate->format('Y');

I have made an example so you can test it faster: PHP Sandbox

If user selects date 2017-02 then it is processed as 2017-03, which is incorrect. Try changing the value to 2017-01 in the example and you will see it is working properly. Since buttons in my code are filling with these values, my users can't go before February 2017 without manually changing the URL.

Body:
As DateTime will populate the missing d part of the date based on the current date, you're effectively getting 2017-02-29 (given that today is the 29th), which isn't valid, but DateTime adjusts to a valid date by rolling forward into the following month, giving 2017-03-01.

You need to force a d part to the date to avoid this default behaviour

$date = DateTime::createFromFormat('Y-m-d', $dateSelect . '-01');


来源: stackexchange

问:
Cannot copy case class with repeated parameters
Why can I not use the copy method of a case class with repeated parameters?

For example why does the last line of this code give me the error?

```<code>case class A(i: Int)
case class B(i: Int*)

val a = A(1).copy(i = 2)
val b1 = B(i = Seq(4, 5): _*)
val b2 = B(2, 3).copy(i = Seq(4, 5): _*)
</code>```

value copy is not a member of B

答:
According to scala specs the copy method is not generated, by the compiler, for case classes having a repeated parameter.

A method named copy is implicitly added to every case class unless the class already has a member (directly defined or inherited) with that name, or the class has a repeated parameter.

ContentLicense: CC BY-SA 3.0

Body:
Why can I not use the copy method of a case class with repeated parameters?

For example why does the last line of this code give me the error?

case class A(i: Int)
case class B(i: Int*)

val a = A(1).copy(i = 2)
val b1 = B(i = Seq(4, 5): _*)
val b2 = B(2, 3).copy(i = Seq(4, 5): _*)

value copy is not a member of B


问:
iTextSharp automatically shrinking images when end of the page reach
I'm using iTextSharp to display images in a pdf report. Here I want display two images in a row and it's working as expected but having a issue when end of the page reaches. The issue is that last row images get shrink to fit in same page, it doesn't automatically add it to the next page. All images having same dimension and resolution.

答: The easiest solution (considering all images have the same dimension and resolution) would be to manually insert a new page and pagebreak every time you have inserted the maximum number of images to a page.</p>


问:
Update resource string (Text in GUI) after culture change in WPF
I am working on Localization of WPF application. My question is While i change a language from Combo Box (Drop down), I want to update text of whole application. But i don't know how to do it.

I am using .resx file as my resource file.

E.g. if selected language is English then text will be in english but when i change it to french, I want to update text of buttons from french resource file.

Suggession of good article is also acceptable. I am looking for good solution for big application.

Thanks in advance.

答:
from all solution i saw, the best is to use dictionnary with string, binding to dynamic resources, and a string manager

```<code>using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows;
using System.Linq;
using System.Windows.Markup;
using Trace.Lib;

namespace Atlas.SSUP.Client.Core.Components.Managers
{
    public class StringManager
    {
        public static readonly StringManager Instance = new StringManager();

        /// <summary>
        /// Private constructor for singleton pattern
        /// </summary>
        private StringManager()
        {
        }

        private readonly CultureInfo DefaultCulture = new CultureInfo("fr-FR");

        private ResourceDictionary LanguageDictionary { get; set; }

        private Collection<ResourceDictionary> Root
        {
            get { return Application.Current.Resources.MergedDictionaries[0].MergedDictionaries; }
        }

        /// <summary>
        /// Gets a string from the common resource file.
        /// </summary>
        /// <param name="key">The key.of the desired string.</param>
        /// <returns>The string corresponding to the key provided.</returns>
        public string GetString(string key)
        {
            try
            {
                string value = LanguageDictionary[key] as string;
                if (value == null || value.Contains("String.Empty"))
                    value = string.Empty;

                return value;
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                return string.Empty;
            }
        }

        public void SetCulture( string newSource )
        {
            try
            {
                ResourceDictionary langOld = Root.Single(p => p.Source.OriginalString.Contains("Strings."));
                if (langOld != null)
                {
                    ResourceDictionary lang = LoadDictionary(newSource);
                    if (lang != null)
                    {

                        Application.Current.Resources.BeginInit();

                        Root.Remove(langOld);
                        Root.Insert(0,lang);

                        Application.Current.Resources.EndInit();

                        LanguageDictionary = lang;
                    }
                }
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                throw;
            }
        }

        public void Load()
        {
            Collection<ResourceDictionary> toRemove = new Collection<ResourceDictionary>();
            Collection<ResourceDictionary> toAdd = new Collection<ResourceDictionary>();

            foreach (ResourceDictionary res in Root)
            {
                if (res.Source.OriginalString.Contains("/Atlas.SSUP.Client.Core;Component/Resources/"))
                {
                    ResourceDictionary newDico = LoadDictionary(res.Source.OriginalString.Replace("/Atlas.SSUP.Client.Core;Component/Resources/", ""));
                    if (newDico != null)
                    {
                        toAdd.Add(newDico);
                        toRemove.Add(res);
                    }
                }
            }

            Application.Current.Resources.BeginInit();

            foreach (ResourceDictionary res in toRemove)
                Root.Remove(res);
            foreach (ResourceDictionary res in toAdd)
                Root.Add(res);

            Application.Current.Resources.EndInit();
        }

        private ResourceDictionary LoadDictionary(string source)
        {
            Stream streamInfo = null;
            ResourceDictionary dictionary = null;

            try
            {
                streamInfo = DistantManager.Instance.GetResource(source);

                if (streamInfo != null)
                {
                    Uri baseUri = DistantManager.Instance.GetUri(source);

                    dictionary = XamlReader.Load(streamInfo) as ResourceDictionary;

                    dictionary.Source = baseUri;
                }
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                return null;
            }

            return dictionary;
        }
    }
}
</code>```

and

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:w="clr-namespace:System.Windows;assembly=PresentationCore">

<!-- Font size on map station labels -->
<s:Double x:Key="StationFontSize">12</s:Double>

<!-- FlowDirection LeftToRight ou RightToLeft -->
<w:FlowDirection x:Key="FlowDirection">LeftToRight</w:FlowDirection>

<!-- Dialog -->
<s:String x:Key="String.Dialog.OK">OK</s:String>
<s:String x:Key="String.Dialog.Cancel">Cancel</s:String>
<s:String x:Key="String.Dialog.Yes">Yes</s:String>
<s:String x:Key="String.Dialog.No">No</s:String>
</code>```

or you have another solution here but much more complex cbr

Body:
from all solution i saw, the best is to use dictionnary with string, binding to dynamic resources, and a string manager

using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows;
using System.Linq;
using System.Windows.Markup;
using Trace.Lib;

namespace Atlas.SSUP.Client.Core.Components.Managers
{
    public class StringManager
    {
        public static readonly StringManager Instance = new StringManager();

        /// <summary>
        /// Private constructor for singleton pattern
        /// </summary>
        private StringManager()
        {
        }

        private readonly CultureInfo DefaultCulture = new CultureInfo("fr-FR");

        private ResourceDictionary LanguageDictionary { get; set; }

        private Collection<ResourceDictionary> Root
        {
            get { return Application.Current.Resources.MergedDictionaries[0].MergedDictionaries; }
        }

        /// <summary>
        /// Gets a string from the common resource file.
        /// </summary>
        /// <param name="key">The key.of the desired string.</param>
        /// <returns>The string corresponding to the key provided.</returns>
        public string GetString(string key)
        {
            try
            {
                string value = LanguageDictionary[key] as string;
                if (value == null || value.Contains("String.Empty"))
                    value = string.Empty;

                return value;
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                return string.Empty;
            }
        }

        public void SetCulture( string newSource )
        {
            try
            {
                ResourceDictionary langOld = Root.Single(p => p.Source.OriginalString.Contains("Strings."));
                if (langOld != null)
                {
                    ResourceDictionary lang = LoadDictionary(newSource);
                    if (lang != null)
                    {

                        Application.Current.Resources.BeginInit();

                        Root.Remove(langOld);
                        Root.Insert(0,lang);

                        Application.Current.Resources.EndInit();

                        LanguageDictionary = lang;
                    }
                }
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                throw;
            }
        }

        public void Load()
        {
            Collection<ResourceDictionary> toRemove = new Collection<ResourceDictionary>();
            Collection<ResourceDictionary> toAdd = new Collection<ResourceDictionary>();

            foreach (ResourceDictionary res in Root)
            {
                if (res.Source.OriginalString.Contains("/Atlas.SSUP.Client.Core;Component/Resources/"))
                {
                    ResourceDictionary newDico = LoadDictionary(res.Source.OriginalString.Replace("/Atlas.SSUP.Client.Core;Component/Resources/", ""));
                    if (newDico != null)
                    {
                        toAdd.Add(newDico);
                        toRemove.Add(res);
                    }
                }
            }

            Application.Current.Resources.BeginInit();

            foreach (ResourceDictionary res in toRemove)
                Root.Remove(res);
            foreach (ResourceDictionary res in toAdd)
                Root.Add(res);

            Application.Current.Resources.EndInit();
        }

        private ResourceDictionary LoadDictionary(string source)
        {
            Stream streamInfo = null;
            ResourceDictionary dictionary = null;

            try
            {
                streamInfo = DistantManager.Instance.GetResource(source);

                if (streamInfo != null)
                {
                    Uri baseUri = DistantManager.Instance.GetUri(source);

                    dictionary = XamlReader.Load(streamInfo) as ResourceDictionary;

                    dictionary.Source = baseUri;
                }
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                return null;
            }

            return dictionary;
        }
    }
}

and

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:w="clr-namespace:System.Windows;assembly=PresentationCore">

<!-- Font size on map station labels -->
<s:Double x:Key="StationFontSize">12</s:Double>

<!-- FlowDirection LeftToRight ou RightToLeft -->
<w:FlowDirection x:Key="FlowDirection">LeftToRight</w:FlowDirection>

<!-- Dialog -->
<s:String x:Key="String.Dialog.OK">OK</s:String>
<s:String x:Key="String.Dialog.Cancel">Cancel</s:String>
<s:String x:Key="String.Dialog.Yes">Yes</s:String>
<s:String x:Key="String.Dialog.No">No</s:String>

or you have another solution here but much more complex cbr


问:
Espresso Nested Recycler Views UI testing
I have a Horizontal RecyclerView inside a vertical RecyclerView. I'm using this code I found on other question:

```<code>onView(allOf(isDescendantOfA(withRecyclerView(R.id.parentVerticalRecyclerView).atPosition(parentPosition)),
             isDescendantOfA(withRecyclerView(R.id.childHorizontalRecyclerView).atPosition(childPosition)),
                (withText("USA"))))
                .perform(click());

// It is not working for parentPosition > 0
</code>```

but this only works for first row of parent RecyclerView.

How do I click on the element on the child RecyclerView of the second row of parent RecyclerView?

答:
I finally figured out the solution for this:</p>

```<code>onView(allOf(
         withId(R.id.childHorizontalRecyclerView),
         withParent(
           withRecyclerView(R.id.parentVerticalRecyclerView).atPosition(2)
         )
       )
).perform(RecyclerViewActions.actionOnItemAtPosition(3, scrollTo()))
.check(matches(hasDescendant(withText("USA"))));
</code>```

Body:
I have a Horizontal RecyclerView inside a vertical RecyclerView. I'm using this code I found on other question:

onView(allOf(isDescendantOfA(withRecyclerView(R.id.parentVerticalRecyclerView).atPosition(parentPosition)),
             isDescendantOfA(withRecyclerView(R.id.childHorizontalRecyclerView).atPosition(childPosition)),
                (withText("USA"))))
                .perform(click());

// It is not working for parentPosition > 0

but this only works for first row of parent RecyclerView.

How do I click on the element on the child RecyclerView of the second row of parent RecyclerView?

Body:
I finally figured out the solution for this:

onView(allOf(
         withId(R.id.childHorizontalRecyclerView),
         withParent(
           withRecyclerView(R.id.parentVerticalRecyclerView).atPosition(2)
         )
       )
).perform(RecyclerViewActions.actionOnItemAtPosition(3, scrollTo()))
.check(matches(hasDescendant(withText("USA"))));


问:
where to add the line break

make a 0

```<code>def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = ("*   *")
    result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom
    return result

result = number0(5, 5, "*")
print (result)
</code>```

here's what happens when I run the program:

```<code>*****
*   **   **   **   **   *
*****
</code>```

I want to add line break in between middle and height to make it look like a 0 shape with a height of 5.

答:
you just change the present code (1) with (2) :

```<code>1) middle = ("*   *")
   result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom
2) middle = "*   *\n"
   result = toporbottom + "\n" + (middle) * height + toporbottom
</code>```

Thus the modified code would be :

```<code>def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = "*   *\n"
    result = toporbottom + "\n" + (middle) * height  + toporbottom
    return result

result = number0(5, 5, "*")
print (result)
</code>```

This should do the trick

Title: where to add the line break

Body:
make a 0

def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = ("*   *")
    result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom
    return result

result = number0(5, 5, "*")
print (result)

here's what happens when I run the program:

*****
*   **   **   **   **   *
*****

I want to add line break in between middle and height to make it look like a 0 shape with a height of 5.

Body:
you just change the present code (1) with (2) :

1) middle = ("*   *")
   result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom
2) middle = "*   *\n"
   result = toporbottom + "\n" + (middle) * height + toporbottom

Thus the modified code would be :

def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = "*   *\n"
    result = toporbottom + "\n" + (middle) * height  + toporbottom
    return result

result = number0(5, 5, "*")
print (result)

This should do the trick


问:
VueJS how to listen to event from method not from template
I am sending an event from a child component to it's parent. I want to intercept the signal via a method in the parent. But the listening function fires always regardless of whether an event has been emitted. Note that I am using single file components and Vue-router.

As an aside, I have found very few VueJS examples use single file components, and for a noob, transpiling from the simple Vue app in one file to multiple single file components can be confusing.

Parent:

```<code><template>
 ....html here
</template>
<script>
  import Child from './Child.vue'

  export default {
  name: 'Parent',
  data () {
    return {
     stage: 1
    }
  },
  components: {
    Child
  },
  created: function () {
    // the following line always runs even when listen for non-existent event eg this.$on('nonsense'...)
    this.$on('child-event', this.stage = 2)
  }
  }
</code>```

child:

```<code><template>
  <button v-on:click="sendEvent" type="button" class="btn btn-success">Next</button>
</template>

<script>
  export default {
  name: 'Child',
  data () {
    return {
      response_status: 'accepted'
    }
  },
  methods: {
    sendEvent: function () {
      this.$emit('child-event', 'accepted')
    }
  }
</code>```

Any idea what I am doing wrong?

答:
Another way of setting the on event would be referencing the listener method directly from the place where you call the child component.

On your parent template you could do something like:

```<code><Child v-on:child-event="eventIsEmitted"></Child>
</code>```

On your methods:

```<code>eventIsEmitted: function(status) {
    if (status == 'accepted') {
        this.stage = 2;
    }
}
</code>```

Body:
I am sending an event from a child component to it's parent. I want to intercept the signal via a method in the parent. But the listening function fires always regardless of whether an event has been emitted. Note that I am using single file components and Vue-router.

As an aside, I have found very few VueJS examples use single file components, and for a noob, transpiling from the simple Vue app in one file to multiple single file components can be confusing.

Parent:

<template>
 ....html here
</template>

Body:
Another way of setting the on event would be referencing the listener method directly from the place where you call the child component.

On your parent template you could do something like:

<Child v-on:child-event="eventIsEmitted"></Child>

On your methods:

eventIsEmitted: function(status) {
    if (status == 'accepted') {
        this.stage = 2;
    }
}


问:
CSS: center element within a
 element
To center an HTML element I can use the CSS left: 50%;. However, this centers the element with respect to the whole window.

I have an element which is a child of a
 element and I want to center the child with respect to this parent
, not the whole window.

I do not want the container
 to have all its content centered, just the one specific child.

答:
Actually this is very straightforward with CSS3 flex boxes.

.flex-container{
  display: -webkit-box;  /* OLD - iOS 6-, Safari 3.1-6, BB7 */
  display: -ms-flexbox;  /* TWEENER - IE 10 */
  display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
  display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */

  justify-content: center;
  align-items: center;

  width: 400px;
  height: 200px;
  background-color: #3498db;
}

.inner-element{
  width: 100px;
  height: 100px;
  background-color: #f1c40f;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
  <div class="inner-element"></div>
</div></code>```

UPDATE:

It seems that I didn't read the OP edit at the time I wrote this answer. The above code will center all inner elements (without overlapping between them), but the OP wants just an specific element to be centered, not the other inner elements. So @Warface answer second method is more appropiate, but it still requires vertical centering:

.flex-container{
  position: relative;

  /* Other styling stuff */
  width: 400px;
  height: 200px;
  background-color: #3498db;
}

.inner-element{
  position: absolute;
  left: 50%;
  top: 50%;

  transform: translate(-50%,-50%);
  /* or 3d alternative if you will add animations (smoother transitions) */
  transform: translate3d(-50%,-50%,0);

  /* Other styling stuff */
  width: 100px;
  height: 100px;
  background-color: #f1c40f;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
  <p>Other inner elements like this follows the normal flow.</p>
  <div class="inner-element"></div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: CSS: center element within a <div> element

Body:
Actually this is very straightforward with CSS3 flex boxes.

.flex-container{
  display: -webkit-box;  /* OLD - iOS 6-, Safari 3.1-6, BB7 */
  display: -ms-flexbox;  /* TWEENER - IE 10 */
  display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
  display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */

  justify-content: center;
  align-items: center;

  width: 400px;
  height: 200px;
  background-color: #3498db;
}

.inner-element{
  width: 100px;
  height: 100px;
  background-color: #f1c40f;
}

<div class="flex-container">
  <div class="inner-element"></div>
</div>

UPDATE:

It seems that I didn't read the OP edit at the time I wrote this answer. The above code will center all inner elements (without overlapping between them), but the OP wants just an specific element to be centered, not the other inner elements. So @Warface answer second method is more appropiate, but it still requires vertical centering:

.flex-container{
  position: relative;

  /* Other styling stuff */
  width: 400px;
  height: 200px;
  background-color: #3498db;
}

.inner-element{
  position: absolute;
  left: 50%;
  top: 50%;

  transform: translate(-50%,-50%);
  /* or 3d alternative if you will add animations (smoother transitions) */
  transform: translate3d(-50%,-50%,0);

  /* Other styling stuff */
  width: 100px;
  height: 100px;
  background-color: #f1c40f;
}

<div class="flex-container">
  <p>Other inner elements like this follows the normal flow.</p>
  <div class="inner-element"></div>
</div>


问:
Review star rating in Google search results: "The review has no reviewed item specified"
I have a problem in my Structured Data Testing Tool it says "The review has no reviewed item specified."

```<code><!-- Review Star Rating In Google Search Results -->
<b:if cond='data:blog.pageType == "item"'>
    <div>
        <div itemscope itemtype='http://data-vocabulary.org/Review'>
            <div style='display:none;'>
                Item Reviewed: <span itemprop='itemreviewed'><data:post.title/></span>
                Description: <span itemprop='description'><data:blog.metaDescription/></span>
                Rating: <span itemprop='rating'>5</span>
                Reviewed By: <span itemprop='reviewer'><data:post.author/></span>
            </div>
        </div>
    </div>
</b:if>
<!-- Review Star Rating In Google Search Results -->
</code>```

I just aiming for my blogger post to have star rating at Google search result.

答:
Use this code:

```<code><b:if cond='data:blog.pageType == "item"'>
<div style='display:none;'>
<div class='vcard' id='hcard-templatoid'>
<span itemprop='description'><span itemprop='itemreviewed'><data:post.title/></span></span>
<time itemprop='dtreviewed'><data:post.timestampISO8601/></time>
Rating: <span itemprop='rating'>5</span>
Posted by: <span class='fn n'>
<span class='given-name' itemprop='reviewer'><data:post.author/></span>
</span>
</div>
</div>
</b:if>
</code>```

Source: How To Show Star Ratings In Google Search Results - Blogger

Body:
I have a problem in my Structured Data Testing Tool it says "The review has no reviewed item specified."

                Item Reviewed: <data:post.title/>
                Description: <data:blog.metaDescription/>
                Rating: 5
                Reviewed By: <data:post.author/>

I just aiming for my blogger post to have star rating at Google search result.

Body:
Use this code:

<b:if cond='data:blog.pageType == &quot;item&quot;'>
<div style='display:none;'>
<div class='vcard' id='hcard-templatoid'>
<span itemprop='description'><span itemprop='itemreviewed'><data:post.title/></span></span>
<time itemprop='dtreviewed'><data:post.timestampISO8601/></time>
Rating: <span itemprop='rating'>5</span>
Posted by: <span class='fn n'>
<span class='given-name' itemprop='reviewer'><data:post.author/></span>
</span>
</div>
</div>
</b:if>

Source: How To Show Star Ratings In Google Search Results - Blogger


问:
how to print same value as entered in above textbox
The user is asked to enter his/her name and the same name should be displayed in the username asked below by default.
I have tried this code, but it doesn't help me out!

```<code><tr>
        <td class="TrackMediumBlue" align="right" width="138">Manager  Name   :</td>
        <td width="13"> </td>
        <td width="477">
        <input name="ManagerName" type="TEXT" id="ManagerName" size="40"  maxlength="100">                </td>
      </tr>
      <tr>
        <td class="TrackMediumBlue" align="right" width="138">UserName   :</td>
        <td width="13"> </td>
        <td width="477">
        <input name="ManagerName" type="TEXT" value="<?php echo ManagerName ?>" size="40"  maxlength="100">                </td>
      </tr>
</code>```

Please help me out!

答:
You have to do this with javascript:

```<code><tr>
    <td class="TrackMediumBlue" align="right" width="138">Manager Name:</td>
    <td width="13"> </td>
    <td width="477">
        <input name="ManagerName" type="TEXT" id="ManagerName" size="40"  maxlength="100">
    </td>
</tr>
<tr>
    <td class="TrackMediumBlue" align="right" width="138">UserName:</td>
    <td width="13"> </td>
    <td width="477">
        <input name="ManagerName" type="TEXT" id="ManagerName2" size="40"  maxlength="100">
    </td>
</tr>
<script type="text/javascript">
    document.getElementById('ManagerName').addEventListener('blur', function() {
        document.getElementById('ManagerName2').value = this.value;
    });
</script>
</code>```

Add an id attribute to the second input. In the exemple above I use ManagerName2.

Edit: all code together.

Body:
The user is asked to enter his/her name and the same name should be displayed in the username asked below by default.
I have tried this code, but it doesn't help me out!

        Manager  Name   :

        <input name="ManagerName" type="TEXT" id="ManagerName" size="40"  maxlength="100">

        UserName   :

        <input name="ManagerName" type="TEXT" value="<?php echo ManagerName ?>" size="40"  maxlength="100">

Please help me out!

Body:
You have to do this with javascript:

<tr>
    <td class="TrackMediumBlue" align="right" width="138">Manager Name:</td>
    <td width="13">&nbsp;</td>
    <td width="477">
        <input name="ManagerName" type="TEXT" id="ManagerName" size="40"  maxlength="100">
    </td>
</tr>
<tr>
    <td class="TrackMediumBlue" align="right" width="138">UserName:</td>
    <td width="13">&nbsp;</td>
    <td width="477">
        <input name="ManagerName" type="TEXT" id="ManagerName2" size="40"  maxlength="100">
    </td>
</tr>
<script type="text/javascript">
    document.getElementById('ManagerName').addEventListener('blur', function() {
        document.getElementById('ManagerName2').value = this.value;
    });
</script>

Add an id attribute to the second input. In the exemple above I use ManagerName2.

Edit: all code together.


问:
Representing a 3D array with keys in C#
This is a continuation of this question :
Best way to represent sets of 3 values

I want to store the temperature of a substance as a function of time and position. So the temperature changes with location and time. regarding location, I have divided the whole surface of material into i*j small zones, so I can assign a temperature to each zone separately. for example, one should be able to read the temperature of zone[3,5] at time=3 seconds.
my goal is, having a collection, consisting of time,i, and j. So I can access the temperature at time = 3.5 seconds in zone [i=4, j=7]. a 3D array doesn't help, because I need to be able to use time as a key like below:

```<code>temperature[3.5][4,7]
</code>```

here 3.5 is the time, 4 is i and 7 is j.
How would I do that? And how should I access the temperature data?

答:
If you want to implement exactly same interface, then you should use indexer properties. Let's start from the object which returns temperature by position. I'll call it Surface. You can use name Area or whatever you find more appropriate. This object should hold temperature values for each position on your surface or it should go and get those values from storage:

```<code>public class Surface
{
    // you can have time property here as well

    public double this[int i, int j]
    {
        get { return GetTemperatureValueFromDataSource(i,j); }
    }
}
</code>```

Now you need to return these objects for given time from another class:

```<code>public class Temperature
{
    public Surface this[double time]
    {
        get { return GetSurfaceObjectForGivenTime(time); }
    }
}
</code>```

Then interface will be as you want to:

```<code>var temperature = new Temperature();
double value = temperature[3.5][4,7];
</code>```

Note that you should think how to handle situations when you don't have surface temperature data for given time, or if you are trying to get the temperature of surface point outside of available range. E.g. you can return null if there is no data for given time, but you should use null-conditional operator to avoid NullReferenceException:

```<code> double? value = temperature[3.5]?[4,7];
</code>```

Or you can return some NullObject which will have some dummy behavior. Same goes to referencing surface point outside of available range. You can use nullable return type for temperature value. Or you can throw ArgumentOutOfRangeException.

Title: Representing a 3D array with keys in C#

Body:
This is a continuation of this question :
Best way to represent sets of 3 values

I want to store the temperature of a substance as a function of time and position. So the temperature changes with location and time. regarding location, I have divided the whole surface of material into i*j small zones, so I can assign a temperature to each zone separately. for example, one should be able to read the temperature of zone[3,5] at time=3 seconds.
my goal is, having a collection, consisting of time,i, and j. So I can access the temperature at time = 3.5 seconds in zone [i=4, j=7]. a 3D array doesn't help, because I need to be able to use time as a key like below:

temperature[3.5][4,7]

here 3.5 is the time, 4 is i and 7 is j.
How would I do that? And how should I access the temperature data?

Body:
If you want to implement exactly same interface, then you should use indexer properties. Let's start from the object which returns temperature by position. I'll call it Surface. You can use name Area or whatever you find more appropriate. This object should hold temperature values for each position on your surface or it should go and get those values from storage:

public class Surface
{
    // you can have time property here as well

    public double this[int i, int j]
    {
        get { return GetTemperatureValueFromDataSource(i,j); }
    }
}

Now you need to return these objects for given time from another class:

public class Temperature
{
    public Surface this[double time]
    {
        get { return GetSurfaceObjectForGivenTime(time); }
    }
}

Then interface will be as you want to:

var temperature = new Temperature();
double value = temperature[3.5][4,7];

Note that you should think how to handle situations when you don't have surface temperature data for given time, or if you are trying to get the temperature of surface point outside of available range. E.g. you can return null if there is no data for given time, but you should use null-conditional operator to avoid NullReferenceException:

 double? value = temperature[3.5]?[4,7];

Or you can return some NullObject which will have some dummy behavior. Same goes to referencing surface point outside of available range. You can use nullable return type for temperature value. Or you can throw ArgumentOutOfRangeException.


问:
Active Record (Rails) MySQL Secure Connection
Now, I haven't been able to find any good resources on this subject so I'll ask my question here and see if anyone has any suggestions/recommendations.

I will be deploying a Ruby on Rails application soon (Active Record ORM), and my database (MySQL or PostgreSQL) will be located at an external location (outside of 127.0.0.1 range).

I am able to connect to the external MySQL database, simply by unbinding the address in the /etc/mysql/my.conf and adding a user that takes connections from external locations. However, since the data is being transferred from my application server to my MySQL server, how (in)secure is this?

Do I need to do some form of encryption? Does Active Record do anything in the background to protect data from being hijacked (or whatever you call it) during the transfer? Or is my data secure enough by default with MySQL and/or PostgreSQL when working with databases at external locations?

So in short: Is there anything (extra) I should be doing when my MySQL or PostgreSQL database is located at an external location, rather than when it's in localhost range?

Any suggestions, pointers, recommendations and resources would be much appreciated!

Thanks!

答:
As well as looking at the option of running over SSL, you can and should lock the database server to only accept connections from specific IP addresses.

I would generally only run SSL if the connection is entirely untrusted as it can have some performance impacts.

ContentLicense: CC BY-SA 2.5


问:
Catch alternative strings from OR operator with a Regex in Python?
I'd like to catch a certain part of strings where there are alternative Regex branches. How can I safely refer to defined spots in alternative paths. I thought about doing

```<code>m=re.match("(A(?P<name>.+)B|C(?P<name>.+)D)", text)
match=m.group("name")
</code>```

but there is a conflict with redefining the name. Using m.group by an index would be troublesome, since these Regex come from configuration files and I cannot guarantee the nesting level/index value which will lead to the match.

EDIT:
In the setup there are texts to match and regex from separate sources. I'd like to achieve

```<code>import re

for text in ["ABBC", "DEEEF", "GHHI"]:
    for regex in ["(A(.+)C|D(.+)F)", "G(.+)I"]:
        m=re.match(regex, text)
        if m:
            print(m.group(1)) # should actually match the middle characters, but doesn't work generally
            break
</code>```

The number of possible regex can grow in the future, so it has to be a general solution

答:
Your example can be made to work by changing

```<code>            print(m.group(1))
</code>```

to

```<code>            print(filter(None, m.groups())[0])
</code>```

(simply taking the group which contains the match).

Body:
I'd like to catch a certain part of strings where there are alternative Regex branches. How can I safely refer to defined spots in alternative paths. I thought about doing

m=re.match("(A(?P<name>.+)B|C(?P<name>.+)D)", text)
match=m.group("name")

but there is a conflict with redefining the name. Using m.group by an index would be troublesome, since these Regex come from configuration files and I cannot guarantee the nesting level/index value which will lead to the match.

EDIT:
In the setup there are texts to match and regex from separate sources. I'd like to achieve

import re

for text in ["ABBC", "DEEEF", "GHHI"]:
    for regex in ["(A(.+)C|D(.+)F)", "G(.+)I"]:
        m=re.match(regex, text)
        if m:
            print(m.group(1)) # should actually match the middle characters, but doesn't work generally
            break

The number of possible regex can grow in the future, so it has to be a general solution

Body:
Your example can be made to work by changing

            print(m.group(1))

to

            print(filter(None, m.groups())[0])

(simply taking the group which contains the match).


问:
Change Facebook Login Button appearance
I want to change Facebook login button default appearance with my custom one.

this is the default

this is how I want it to be

答:
Custom login Button</p>

```<code>// Add this to the header of your file
#import "ViewController.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

// Add this to the body
@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Add a custom login button to your app
  UIButton *myLoginButton=[UIButton buttonWithType:UIButtonTypeCustom];
  myLoginButton.backgroundColor=[UIColor darkGrayColor];
  myLoginButton.frame=CGRectMake(0,0,180,40);
  myLoginButton.center = self.view.center;
  [myLoginButton setTitle: @"My Login Button" forState: UIControlStateNormal];

  // Handle clicks on the button
  [myLoginButton
    addTarget:self
    action:@selector(loginButtonClicked) forControlEvents:UIControlEventTouchUpInside];

  // Add the button to the view
  [self.view addSubview:myLoginButton];
}

// Once the button is clicked, show the login dialog
-(void)loginButtonClicked
{
  FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
  [login
    logInWithReadPermissions: @[@"public_profile"]
          fromViewController:self
                     handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    if (error) {
      NSLog(@"Process error");
    } else if (result.isCancelled) {
      NSLog(@"Cancelled");
    } else {
      NSLog(@"Logged in");
    }
  }];
}

@end
</code>```

Title: Change Facebook Login Button appearance

Body:
Custom login Button

// Add this to the header of your file
#import "ViewController.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

// Add this to the body
@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Add a custom login button to your app
  UIButton *myLoginButton=[UIButton buttonWithType:UIButtonTypeCustom];
  myLoginButton.backgroundColor=[UIColor darkGrayColor];
  myLoginButton.frame=CGRectMake(0,0,180,40);
  myLoginButton.center = self.view.center;
  [myLoginButton setTitle: @"My Login Button" forState: UIControlStateNormal];

  // Handle clicks on the button
  [myLoginButton
    addTarget:self
    action:@selector(loginButtonClicked) forControlEvents:UIControlEventTouchUpInside];

  // Add the button to the view
  [self.view addSubview:myLoginButton];
}

// Once the button is clicked, show the login dialog
-(void)loginButtonClicked
{
  FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
  [login
    logInWithReadPermissions: @[@"public_profile"]
          fromViewController:self
                     handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    if (error) {
      NSLog(@"Process error");
    } else if (result.isCancelled) {
      NSLog(@"Cancelled");
    } else {
      NSLog(@"Logged in");
    }
  }];
}

@end


问:
Module parse failed: es6 react component with JSX inside .JS file
Webpack Babel loader fails when importing an es6 react component with .js as the filename extension. If the filename extension is changed to .jsx babel compiles properly. Any clue?

var config = {
  entry : {
    "login" : PAGE_DIR + '/login/index.js',
    "app" : PAGE_DIR + '/app/index.js'
  },
  output: {
    path: BUILD_DIR,
    filename: '[name]-bundle.js'
  },
  module : {
  rules : [
     {
        test : /\.(js|jsx)$/,
        include : PAGE_DIR,
    exclude: [
      path.resolve(__dirname, "node_modules"),
    ],
        loaders : ['babel-loader']
      }
  ]
  }
};```
</div>
</div>
</p>

<p>EDIT:</p>

<p>Updating the logs below.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>> webpack -d

Hash: 83d5fd2d0c1113e55b32
Version: webpack 2.2.1
Time: 2057ms
          Asset     Size  Chunks                    Chunk Names
  app-bundle.js  2.28 MB       0  [emitted]  [big]  app
login-bundle.js  1.98 MB       1  [emitted]  [big]  login
  [18] ./~/react-dom/lib/ReactReconciler.js 6.21 kB {0} {1} [built]
  [19] ./~/react/lib/React.js 2.69 kB {0} {1} [built]
  [31] ./~/react/react.js 56 bytes {0} {1} [built]
  [80] ./~/react-dom/index.js 59 bytes {0} {1} [built]
 [109] ./~/react-dom/lib/ReactDOM.js 5.14 kB {0} {1} [built]
 [179] ./~/redux/es/index.js 1.08 kB {0} [built]
 [192] ./app/state/store.js 330 bytes {0} [built]
 [193] ./~/react-redux/es/index.js 194 bytes {0} [built]
 [196] ./app/state/reducer.js 766 bytes {0} [built]
 [209] ./~/react-redux/es/connect/connect.js 5.34 kB {0} [built]
 [215] ./~/react-redux/es/utils/Subscription.js 2.59 kB {0} [built]
 [216] ./~/react-redux/es/utils/shallowEqual.js 677 bytes {0} [built]
 [220] ./~/redux-logger/lib/index.js 4.45 kB {0} [built]
 [228] ./app/pages/app/index.jsx 694 bytes {0} [built]
 [229] ./app/pages/login/index.jsx 2.33 kB {1} [built]
    + 215 hidden modules

ERROR in ./app/components/login.jsx
Module parse failed: /Users/vsank1/Documents/workspace/registration/kudumbayogam/app/components/login.jsx Unexpected token (15:6)
You may need an appropriate loader to handle this file type.
|   render () {
|     return (
|       <form className="login">
|         <input type="email" name="emailid" placeholder="Email ID" onChange={this.changeEmailId.bind(this)} /><br/>
|         <input type="password" name="password" placeholder="Password" onChange={this.changePassword.bind(this)} /><br/>
 @ ./app/pages/login/index.jsx 11:13-50

ERROR in ./app/components/app.jsx
Module parse failed: /Users/vsank1/Documents/workspace/registration/kudumbayogam/app/components/app.jsx Unexpected token (30:3)
You may need an appropriate loader to handle this file type.
|
|     return (
|    <div className='row'>
|     <div className='twelve columns'>
|      Logout
 @ ./app/pages/app/index.jsx 15:11-46</code>```

答:
I finally figured it out. I had made a mistake by adding an include folder. My components resided outside the include folder and all these components were not getting parsed with the loader. What I found is webpack only parse files which matches the test pattern and is also inside the include folder.

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'client/assets/js');
var APP_DIR = path.resolve(__dirname, 'app/');

var config = {
  entry : {
    "login" : APP_DIR + '/pages/login/index.js',
    "app" : APP_DIR + '/pages/app/index.js'
  },
  output: {
    path: BUILD_DIR,
    filename: '[name]-bundle.js'
  },
  module : {
    loaders : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel-loader'
      }
    ]
  }
};

module.exports = config;```

Body:
Webpack Babel loader fails when importing an es6 react component with .js as the filename extension. If the filename extension is changed to .jsx babel compiles properly. Any clue?

var config = {
  entry : {
    "login" : PAGE_DIR + '/login/index.js',
    "app" : PAGE_DIR + '/app/index.js'
  },
  output: {
    path: BUILD_DIR,
    filename: '[name]-bundle.js'
  },
  module : {
  rules : [
     {
        test : /\.(js|jsx)$/,
        include : PAGE_DIR,
    exclude: [
      path.resolve(__dirname, "node_modules"),
    ],
        loaders : ['babel-loader']
      }
  ]
  }
};

EDIT:

Updating the logs below.

> webpack -d

Hash: 83d5fd2d0c1113e55b32
Version: webpack 2.2.1
Time: 2057ms
          Asset     Size  Chunks                    Chunk Names
  app-bundle.js  2.28 MB       0  [emitted]  [big]  app
login-bundle.js  1.98 MB       1  [emitted]  [big]  login
  [18] ./~/react-dom/lib/ReactReconciler.js 6.21 kB {0} {1} [built]
  [19] ./~/react/lib/React.js 2.69 kB {0} {1} [built]
  [31] ./~/react/react.js 56 bytes {0} {1} [built]
  [80] ./~/react-dom/index.js 59 bytes {0} {1} [built]
 [109] ./~/react-dom/lib/ReactDOM.js 5.14 kB {0} {1} [built]
 [179] ./~/redux/es/index.js 1.08 kB {0} [built]
 [192] ./app/state/store.js 330 bytes {0} [built]
 [193] ./~/react-redux/es/index.js 194 bytes {0} [built]
 [196] ./app/state/reducer.js 766 bytes {0} [built]
 [209] ./~/react-redux/es/connect/connect.js 5.34 kB {0} [built]
 [215] ./~/react-redux/es/utils/Subscription.js 2.59 kB {0} [built]
 [216] ./~/react-redux/es/utils/shallowEqual.js 677 bytes {0} [built]
 [220] ./~/redux-logger/lib/index.js 4.45 kB {0} [built]
 [228] ./app/pages/app/index.jsx 694 bytes {0} [built]
 [229] ./app/pages/login/index.jsx 2.33 kB {1} [built]
    + 215 hidden modules

ERROR in ./app/components/login.jsx
Module parse failed: /Users/vsank1/Documents/workspace/registration/kudumbayogam/app/components/login.jsx Unexpected token (15:6)
You may need an appropriate loader to handle this file type.
|   render () {
|     return (
|       <form className="login">
|         <input type="email" name="emailid" placeholder="Email ID" onChange={this.changeEmailId.bind(this)} />

|         <input type="password" name="password" placeholder="Password" onChange={this.changePassword.bind(this)} />

 @ ./app/pages/login/index.jsx 11:13-50

ERROR in ./app/components/app.jsx
Module parse failed: /Users/vsank1/Documents/workspace/registration/kudumbayogam/app/components/app.jsx Unexpected token (30:3)
You may need an appropriate loader to handle this file type.
|
|     return (
|

|

|      Logout
 @ ./app/pages/app/index.jsx 15:11-46


问:
I don't understand why is this step necessary to count the number of chars in text document
```<code>lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"
</code>```

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

```<code>no_of_chars = lines.length
</code>```

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

答:
lines is an array. The visualization of an array is similar to the result of joining the array:

```<code>numbers = ['11', '22', '33', '44']
puts numbers
 # 11
 # 22
 # 33
 # 44
puts numbers.join
 # 11223344
</code>```

If the array has new lines at the end (like is the case if you just got lines from a file), you wouldn't be able to tell the two apart. Yet they are different:

```<code>numbers.length      # => 4
numbers.join.length # => 8
</code>```

The length of the array will tell you how many elements the array has. In your case - how many lines in the file. In my case - how many numbers.

If you join the array, you concatenate each individual line. Hence the length of the resulting string will give you how many characters are in the entire file. In my case - how many digits.

Body:
lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

no_of_chars = lines.length

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

Body:
lines is an array. The visualization of an array is similar to the result of joining the array:

numbers = ['11', '22', '33', '44']
puts numbers
 # 11
 # 22
 # 33
 # 44
puts numbers.join
 # 11223344

If the array has new lines at the end (like is the case if you just got lines from a file), you wouldn't be able to tell the two apart. Yet they are different:

numbers.length      # => 4
numbers.join.length # => 8

The length of the array will tell you how many elements the array has. In your case - how many lines in the file. In my case - how many numbers.

If you join the array, you concatenate each individual line. Hence the length of the resulting string will give you how many characters are in the entire file. In my case - how many digits.


问:
Cordova plugin googleplus not getting installed
I am developing an ionic 1 application with firebase integration. I want to add google plus authentication and use cordova-plugin-googleplus for the same.
On executing the function I get error - "TypeError: Cannot read property 'googleplus' of undefined"

I see that this is probably because the plugin is not getting installed properly.
I removed and added plugin again but still I get the same error.

Ionic info

```<code>Cordova CLI: 6.5.0
Gulp version:  CLI version 3.9.1
Gulp local:   Local version 3.9.1
Ionic Version: 1.3.2
Ionic CLI Version: 1.4.0
Ionic App Lib Version: 0.0.16
OS: null
Node Version: v6.10.0
</code>```

I referred this post and Updating cordova and android also doesn't help.

The command cordova plugin list shows the plugin and I can see that in config.xml and package.json files and the repository is cloned in plugins folder.

Commands I tried to install the plugin

```<code>cordova plugin add cordova-plugin-googleplus --save
cordova prepare
</code>```

I tried with ionic too

```<code>ionic plugin add cordova-plugin-googleplus
</code>```

答: Remove all your platforms, try adding the plugin again and re-add your platforms. Is this working ?</p>

Body:
I am developing an ionic 1 application with firebase integration. I want to add google plus authentication and use cordova-plugin-googleplus for the same.
On executing the function I get error - "TypeError: Cannot read property 'googleplus' of undefined"

I see that this is probably because the plugin is not getting installed properly.
I removed and added plugin again but still I get the same error.

Ionic info

Cordova CLI: 6.5.0
Gulp version:  CLI version 3.9.1
Gulp local:   Local version 3.9.1
Ionic Version: 1.3.2
Ionic CLI Version: 1.4.0
Ionic App Lib Version: 0.0.16
OS: null
Node Version: v6.10.0

I referred this post and Updating cordova and android also doesn't help.

The command cordova plugin list shows the plugin and I can see that in config.xml and package.json files and the repository is cloned in plugins folder.

Commands I tried to install the plugin

cordova plugin add cordova-plugin-googleplus --save
cordova prepare

I tried with ionic too

ionic plugin add cordova-plugin-googleplus


问:
How to merge array using same id
I have two arrays and I want to combine them together

1) first look like this:

```<code>[11] => Array
    (
        [id] => 11
        [name] => test
    )
[12] => Array
    (
        [id] => 12
        [name] => test1
    )
</code>```

2) second array look like this:

```<code>[0] => Array
    (
        [offer_id] => 11
        [countries] => Array
            (
                [SA] => Array
                    (
                        [id] => 682
                    )
            )
    )

[1] => Array
    (
        [offer_id] => 12
        [countries] => Array
            (
                [KW] => Array
                    (
                        [id] => 414
                    )
            )
    )
</code>```

I want this result. How is it possible can any one provide solution for same?

```<code>[11] => Array
    (
        [id] => 11
        [name] => test
        [countries] => Array
            (
                [SA] => Array
                    (
                        [id] => 682

                    )

            )

    )
[12] => Array
    (
        [id] => 12
        [name] => test
        [countries] => Array
            (
                [KW] => Array
                    (
                        [id] => 414
                    )
            )
    )
</code>```

Thank you for the help!

答:
Try this:</p>

```<code>foreach ($array1 as &$arr1) {
    $offer_id = $arr1['id'];    // Search for this offer_id in array 2
    $match = array_filter($array2, function($v) use ($offer_id){
        return $v['offer_id'] == $offer_id;  // Return matching offer id
    });
   $arr1['countries'] = current($match)['countries']; // Assign matched country to array
}
</code>```

Title: How to merge array using same id

Body:
I have two arrays and I want to combine them together

1) first look like this:

[11] => Array
    (
        [id] => 11
        [name] => test
    )
[12] => Array
    (
        [id] => 12
        [name] => test1
    )

2) second array look like this:

[0] => Array
    (
        [offer_id] => 11
        [countries] => Array
            (
                [SA] => Array
                    (
                        [id] => 682
                    )
            )
    )

[1] => Array
    (
        [offer_id] => 12
        [countries] => Array
            (
                [KW] => Array
                    (
                        [id] => 414
                    )
            )
    )

I want this result. How is it possible can any one provide solution for same?

[11] => Array
    (
        [id] => 11
        [name] => test
        [countries] => Array
            (
                [SA] => Array
                    (
                        [id] => 682

                    )

            )

    )
[12] => Array
    (
        [id] => 12
        [name] => test
        [countries] => Array
            (
                [KW] => Array
                    (
                        [id] => 414
                    )
            )
    )

Thank you for the help!

Body:
Try this:

foreach ($array1 as &$arr1) {
    $offer_id = $arr1['id'];    // Search for this offer_id in array 2
    $match = array_filter($array2, function($v) use ($offer_id){
        return $v['offer_id'] == $offer_id;  // Return matching offer id
    });
   $arr1['countries'] = current($match)['countries']; // Assign matched country to array
}


问:
Telegram sharing PDF file with its front page as link
I want to share a PDF file of a book in a telegram group.

First of all, I like to make the front page of the book as a visible icon for the download link.

Second, I want to add an explanation under the link.

How can I do?

Please help and guide.

Thank you

答:
You can use your explanation for all you want with some robots, such as @binambot Telegram bot.

But unfortunately there is no way to show the first page of a PDF file in telegram automatically. You can get a shot from the first page manually and send it as a separate picture.


问:
ui.bootstrap.timepicker returns 2h less than it should
I use ui.bootstrap.timepicker for adding time intervals in my app.
This is where I select time, and on button INSERT&SAVE send data to api.

Problem is, here you can see selected time, but when send it to API, time is 2 hour less.
this is request payload

```<code>{from_time: "2017-03-29T11:37:05.541Z", to_time: "2017-03-29T12:42:05.549Z"}
from_time:"2017-03-29T11:37:05.541Z"
to_time:"2017-03-29T12:42:05.549Z"
</code>```

This is my html

```<code><form class="form" role="form" ng-submit="addRow(fromUrbanTime, toUrbanTime)">
                    <div class="col-md-12">
                        <div class="col-md-6">
                            <div class="col-md-6">
                                <h5><b>{{'FROM'| translate}} (h)</b></h5>
                                <div uib-timepicker ng-model="fromUrbanTime" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian"></div>
                                    <hr>
                            </div>
                            <div class="col-md-6">
                                <h5><b>{{'TO'| translate}} (h)</b></h5>
                                 <div uib-timepicker ng-model="toUrbanTime" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian"></div>
                                 <hr>
                                <button type="submit" class="btn btn-default">Insert & Save</button>
                            </div>
                        </div>
                    </div>
                     <pre class="alert alert-info">Time is: {{fromUrbanTime | date:'shortTime' }}```

Time is: {{toUrbanTime | date:'shortTime' }}```
                </form>
</code>```

and this is my ctrl

```<code>//time picker
$scope.mytime = new Date();

 $scope.hstep = 1;
 $scope.mstep = 5;

 $scope.ismeridian = false;

 $scope.clear = function() {
 $scope.mytime = null;
 };
//adding new time intervals
$scope.addRow = function(fromUrban, toUrban){
var config = {
             headers: {
                "Content-Type": "application/json",
                "X-HTTP-Method-Override": "POST"}
        };
        var data = {
                        "from_time": fromUrban,
                        "to_time": toUrban
                    };

        $http.post(serviceBase + 'aaaaa/' + $scope.urbanConfig.id + '/screen-intervals', data, config)
                .success(function (data, status, headers, config) {
                    Notification.success({message: $filter('translate')('URBAN_TIME_RANGE'), delay: 3000, positionY: 'bottom', positionX: 'right'});
                    //startTimer();
                    $scope.urbanTimeRange.push(data);
                    $scope.$watchCollection('urbanTimeRange', function (newValue, oldValue, scope) {
}, true);
                })
</code>```

答:
You local timezone seems to be GMT+2. Date objects created in JavaScript are always in the local timezone. Your back-end, however, seems to work in UTC, which is GMT+0, thus the conversion on the backend. If that is the case, then when the backend sends the dates back to the client, including the timezone info, they should again be created in a local timezone, meaning +2 hours.

Example:

```<code>var now = new Date()
console.log(now.toString()); // "Wed Mar 29 2017 15:03:10 GMT+0200 (FLE Daylight Time)"
</code>```

After sent to the server, and converted to ISO format, should be turning into:

```<code>"2017-03-29T13:03:10.000Z"
</code>```

And then if that value is delivered to the client:

```<code>var now = new Date("2017-03-29T13:03:10.000Z");
console.log(now.toString()); // "Wed Mar 29 2017 15:03:10 GMT+0200 (FLE Daylight Time)"
</code>```

Body:
I use ui.bootstrap.timepicker for adding time intervals in my app.
This is where I select time, and on button INSERT&SAVE send data to api.

Problem is, here you can see selected time, but when send it to API, time is 2 hour less.
this is request payload

{from_time: "2017-03-29T11:37:05.541Z", to_time: "2017-03-29T12:42:05.549Z"}
from_time:"2017-03-29T11:37:05.541Z"
to_time:"2017-03-29T12:42:05.549Z"

This is my html

<form class="form" role="form" ng-submit="addRow(fromUrbanTime, toUrbanTime)">

{{'FROM'| translate}} (h)

{{'TO'| translate}} (h)

                                <button type="submit" class="btn btn-default">Insert & Save</button>

Time is: {{fromUrbanTime | date:'shortTime' }}

Time is: {{toUrbanTime | date:'shortTime' }}

                </form>

and this is my ctrl

//time picker
$scope.mytime = new Date();

 $scope.hstep = 1;
 $scope.mstep = 5;

 $scope.ismeridian = false;

 $scope.clear = function() {
 $scope.mytime = null;
 };
//adding new time intervals
$scope.addRow = function(fromUrban, toUrban){
var config = {
             headers: {
                "Content-Type": "application/json",
                "X-HTTP-Method-Override": "POST"}
        };
        var data = {
                        "from_time": fromUrban,
                        "to_time": toUrban
                    };

        $http.post(serviceBase + 'aaaaa/' + $scope.urbanConfig.id + '/screen-intervals', data, config)
                .success(function (data, status, headers, config) {
                    Notification.success({message: $filter('translate')('URBAN_TIME_RANGE'), delay: 3000, positionY: 'bottom', positionX: 'right'});
                    //startTimer();
                    $scope.urbanTimeRange.push(data);
                    $scope.$watchCollection('urbanTimeRange', function (newValue, oldValue, scope) {
}, true);
                })

Body:
You local timezone seems to be GMT+2. Date objects created in JavaScript are always in the local timezone. Your back-end, however, seems to work in UTC, which is GMT+0, thus the conversion on the backend. If that is the case, then when the backend sends the dates back to the client, including the timezone info, they should again be created in a local timezone, meaning +2 hours.

Example:

var now = new Date()
console.log(now.toString()); // "Wed Mar 29 2017 15:03:10 GMT+0200 (FLE Daylight Time)"

After sent to the server, and converted to ISO format, should be turning into:

"2017-03-29T13:03:10.000Z"

And then if that value is delivered to the client:

var now = new Date("2017-03-29T13:03:10.000Z");
console.log(now.toString()); // "Wed Mar 29 2017 15:03:10 GMT+0200 (FLE Daylight Time)"


问:
Console two line output
I have this code which output some value from array, plus - in new line under value a[i]

```<code>Console.Write(a[i] + "\n-");
</code>```

So it looks like this

```<code>a
-
</code>```

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

```<code>a
-b
-c
-d
-
</code>```

I know why this is the case but how can I return one line up after every new line \n? So I can get this

```<code>abcd
----
</code>```

答:
Another approach with Concat:

```<code>char[] a = {'a','b','c','d'};
Console.WriteLine(string.Concat(a));
Console.WriteLine(new string('-',a.Length));
</code>```

https://dotnetfiddle.net/IZdlX5

Title: Console two line output

Body:
I have this code which output some value from array, plus - in new line under value a[i]

Console.Write(a[i] + "\n-");

So it looks like this

a
-

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

a
-b
-c
-d
-

I know why this is the case but how can I return one line up after every new line \n? So I can get this

abcd
----

Body:
Another approach with Concat:

char[] a = {'a','b','c','d'};
Console.WriteLine(string.Concat(a));
Console.WriteLine(new string('-',a.Length));

https://dotnetfiddle.net/IZdlX5


问:
win32: check if window is minimized
How can one check whether a window is minimized using the win32 api?</p>

答: Use the IsIconic Windows API.</p>

Title: win32: check if window is minimized

Body: Use the IsIconic Windows API.


问:
Visual Studio extension window not showing up when debugging
I've developed a Visual Studio extension with two windows that can be displayed via View->Other Windows->... It used to work fine but for some reason those windows don't show anymore in the experimental instance of Visual Studio when debugging.

I have set the debugging options to "Start external program: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe" with "Command line arguments: /rootsuffix Exp"

As said it used to work and the icons of the windows still show under View->Other Windows - they just don't open any window.

I already tried selecting the window with Ctrl+Tab (not listed there) and Ctrl + - + M as recommended here.
Furthermore I tried resetting the experimental VS as described here (plus this tool and resetting the settings of the experimental VS).

Any ideas?

答:
Alright the issue was that the experimental instance showed an old version of the extension.

Resetting it, increasing the version nr and then doing a clean & rebuild made it use the actual, latest one.

The windows could be shown again by fixing some code in the methods to open the windows...those should contain:

ToolWindowPane window = this.FindToolWindow(typeof(TestWindow), 0, true);
var windowFrame = (IVsWindowFrame)window.Frame;            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());


问:
Polldaddy plugin - WordPress
Anyone knows how to remove text at the end of the poll ("Create your own free online surveys now! Powered by Polldaddy"). Thank you.</p>

答:
Taken directly from their website:

How do I remove the Polldaddy.com link from my poll or survey?
  The link to Polldaddy.com only appears in polls and surveys that appear in a free account. They are removed from all content in both our Pro and Corporate accounts. If you have recently signed up for a Pro account and the link has remained in your polls, simple edit and re-save the poll to remove it.

Title: Polldaddy plugin - WordPress


问:
Regex issue with car submodels
I'm pulling car submodels from the DB and I'm building my regular expression on the fly.

Here is an example of a search string:
EX-L Sedan 4-Door

Here is my regular expression:
preg_match("/LX|EX|EX-L|LX-P|LX-S/Ui", $input_line, $output_array);

For some reason the output is EX and not EX-L as it supposed to be. Can someone explain why?

答:
As others have pointed out, the reason for this undesired outcome is because the regex engine is happy to have the first alternative and run for the door since your pattern has no anchors (like: ^, $, and some other lesser known ones).  This is the same short-circuiting behavior you'd see in php's if($x || $y) conditions; if $x is true there is no need to evaluate further.  But enough about that...

I would like to offer some additional logic that I think is relevant to your case/question.

You say your regex is built on the fly, so I am assuming your method goes something like this:

A user identifies which substrings/keywords they want to search for.

$strings=array('LX','EX','EX-L','LX-P','LX-S');
// array of substrings in any order

As mentioned earlier, you need longer strings to precede shorter ones with identical starting characters.

rsort($strings);
// sort DESC, longer strings precede shorter strings when leading characters match

Pipe all strings into a single regex pattern with implode().

$piped_regex='/\b(?:'.implode('|',$array).')\b/i';
// word boundaries ensure the string is not part of a larger word; remove if not desired
// pattern: /\b(?:LX-S|LX-P|LX|EX-L|EX)\b/i

While programmatically condensing your similar strings into a concise pattern as Wiktor recommended is possible, it's probably not worth the effort with your on-the-fly patterns.

Finally run preg_match() as normal.

```<code>$input_line='EX-L Sedan 4-Door';
if(preg_match($piped_regex,$input_line,$output_array)){
    var_export($output_array);
}
// output: array(0=>'EX-L')
</code>```

I hope stepping out this method is helpful to you and future SO readers.

Title: Regex issue with car submodels

Body:
As others have pointed out, the reason for this undesired outcome is because the regex engine is happy to have the first alternative and run for the door since your pattern has no anchors (like: ^, $, and some other lesser known ones).  This is the same short-circuiting behavior you'd see in php's if($x || $y) conditions; if $x is true there is no need to evaluate further.  But enough about that...

I would like to offer some additional logic that I think is relevant to your case/question.

You say your regex is built on the fly, so I am assuming your method goes something like this:

A user identifies which substrings/keywords they want to search for.

$strings=array('LX','EX','EX-L','LX-P','LX-S');
// array of substrings in any order

As mentioned earlier, you need longer strings to precede shorter ones with identical starting characters.

rsort($strings);
// sort DESC, longer strings precede shorter strings when leading characters match

Pipe all strings into a single regex pattern with implode().

$piped_regex='/\b(?:'.implode('|',$array).')\b/i';
// word boundaries ensure the string is not part of a larger word; remove if not desired
// pattern: /\b(?:LX-S|LX-P|LX|EX-L|EX)\b/i

While programmatically condensing your similar strings into a concise pattern as Wiktor recommended is possible, it's probably not worth the effort with your on-the-fly patterns.

Finally run preg_match() as normal.

$input_line='EX-L Sedan 4-Door';
if(preg_match($piped_regex,$input_line,$output_array)){
    var_export($output_array);
}
// output: array(0=>'EX-L')

I hope stepping out this method is helpful to you and future SO readers.


问:
convert large data in json format
i have a table named  mobile in which all the mobile data is contained which have more then 7000 records now i want to display in json format but some how records are not showing here is my code kindly check ..

```<code><?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
var_dump($result);

$myArray = array();

while($row = mysqli_fetch_assoc($result)){

    $myArray[] = $row;

}

mysqli_close($conn);

header('Content-Type: application/json');

//$json = file_get_contents('json.json');

/*

$myArray = array("user1" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34),"user2" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34));

*/

$json = json_encode($myArray);

echo $json;

?>
</code>```

table

答:
You can do this by following way:</p>

```<code>var obj = JSON.parse($myArray);
echo obj;
</code>```

Title: convert large data in json format

Body:
i have a table named  mobile in which all the mobile data is contained which have more then 7000 records now i want to display in json format but some how records are not showing here is my code kindly check ..

<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
var_dump($result);

$myArray = array();

while($row = mysqli_fetch_assoc($result)){

    $myArray[] = $row;

}

mysqli_close($conn);

header('Content-Type: application/json');

//$json = file_get_contents('json.json');

/*

$myArray = array("user1" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34),"user2" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34));

*/

$json = json_encode($myArray);

echo $json;

?>

table

Body:
You can do this by following way:

var obj = JSON.parse($myArray);
echo obj;


问:
Bootstrap - Auto expanding container, row & row columns' width with content
I have following html:

```<code><div class="container">
 <div class="row">
    <div class="col-md-6">
        <ul>
            <li>Long Content 1<li>
        </ul>
    </div>
    <div class="col-md-6">
        <ul>
            <li>Long Content 2<li>
        </ul>
    </div>
 </div>
</div>
</code>```

I will be adding dynamic content into each ul element. I want col-md-* elements and their parents to expand  themselves horizontally with the content, even if they horizontally overflow the screen window. I don't mind horizontal scrolling on the screen. How can I achieve this?

答:
You can use the display:inline-block property of css for the li. Please see the example below:

ul li{
display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
 <div class="row">
    <div class="col-md-6">
        <ul>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
        </ul>
    </div>
    <div class="col-md-6">
        <ul>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
        </ul>
    </div>
 </div>
</div></code>```

Body:
I have following html:

Long Content 1

Long Content 2

I will be adding dynamic content into each ul element. I want col-md-* elements and their parents to expand  themselves horizontally with the content, even if they horizontally overflow the screen window. I don't mind horizontal scrolling on the screen. How can I achieve this?

Body:
You can use the display:inline-block property of css for the li. Please see the example below:

ul li{
display:inline-block;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
 <div class="row">
    <div class="col-md-6">
        <ul>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
            <li>Long Content 1<li>
        </ul>
    </div>
    <div class="col-md-6">
        <ul>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
            <li>Long Content 2<li>
        </ul>
    </div>
 </div>
</div>


问:
Pascal error: ; expected but . found
Pascal:

; expected but . found

When I change my code around to fix it, it then doesn't display the answer. Can't see what I've done wrong. (It's part of a bigger program hence the block at the end and the procedure). If you know how to fix this or an easier way to write it out I'd appreciate it. It needs to remain with a function though.

```<code>procedure temperature;
  function Sum(var F,M:integer):integer;
  var
    c:integer;
  begin
    M:=(F-32);
    c:=M*(5 div 9);
    writeln('In Centigrade that is ',c);
    writeln('Give me the temperature in Fahrenheit to convert to Centigrade');
    readln(F);
    writeln(sum);
    readln;
  end;
  procedure finished;
  begin
  end;
begin

  initialise;
  repeat
    displaymenu(choice);
    case choice of
      1: throwdice;
      2: heightweight;
      3: textwords;
      4: temperature;
      0: finished;
    end;
  until choice=0;
  readln;
end.
</code>```

答:
Your conditional repeat loop does not have a begin, nor an end. If a while, if, repeat-until, try-else etc has more than one line of code in it, you must use a begin and an end. (end; not end.).

So, formatted properly, your code should be:

```<code> procedure temperature;
  function Sum(var F,M:integer):integer;
  var
    c:integer;
  begin
    readln(F);{This line needs to be first to get F to use in the calculation. This program is all wrong. Read from what? You must define the file you are reading from - ReadLn(FileName,VariableToReadTo)}
    M:=(F-32);{Make sure you are declaring these somewhere.}
    C:=M*(5 div 9);
    writeln('In Centigrade that is '+IntToStr(C));{Need to define file to WriteTo. You also must Append the file to write to it.}
    writeln('Give me the temperature in Fahrenheit to convert to Centigrade.');{Need to define file to WriteTo. You also must Append the file to write to it.}

    writeln(sum);{Need to define file to WriteTo - WriteLn(FileName, VariableToWrite). You also must Append the file to write to it.}
    readln;{This line does not have any arguments. What is this supposed to do? Is your program finished?}
  end;
  procedure finished;{Empty procedure}
  begin
  end;
begin
  initialise;
  repeat
    begin{Didn't have this. Need begin and end because of multiple lines.}
        displaymenu(choice);
        case choice of
        1: throwdice;
        2: heightweight;
        3: textwords;
        4: temperature;
        0: finished;
    end;
  until choice=0;
  readln;{What does this do??}
end.a{Characters outside of code end.}
</code>```

Title: Pascal error: ; expected but . found

Body:
Pascal:

; expected but . found

When I change my code around to fix it, it then doesn't display the answer. Can't see what I've done wrong. (It's part of a bigger program hence the block at the end and the procedure). If you know how to fix this or an easier way to write it out I'd appreciate it. It needs to remain with a function though.

procedure temperature;
  function Sum(var F,M:integer):integer;
  var
    c:integer;
  begin
    M:=(F-32);
    c:=M*(5 div 9);
    writeln('In Centigrade that is ',c);
    writeln('Give me the temperature in Fahrenheit to convert to Centigrade');
    readln(F);
    writeln(sum);
    readln;
  end;
  procedure finished;
  begin
  end;
begin

  initialise;
  repeat
    displaymenu(choice);
    case choice of
      1: throwdice;
      2: heightweight;
      3: textwords;
      4: temperature;
      0: finished;
    end;
  until choice=0;
  readln;
end.

Body:
Your conditional repeat loop does not have a begin, nor an end. If a while, if, repeat-until, try-else etc has more than one line of code in it, you must use a begin and an end. (end; not end.).

So, formatted properly, your code should be:

 procedure temperature;
  function Sum(var F,M:integer):integer;
  var
    c:integer;
  begin
    readln(F);{This line needs to be first to get F to use in the calculation. This program is all wrong. Read from what? You must define the file you are reading from - ReadLn(FileName,VariableToReadTo)}
    M:=(F-32);{Make sure you are declaring these somewhere.}
    C:=M*(5 div 9);
    writeln('In Centigrade that is '+IntToStr(C));{Need to define file to WriteTo. You also must Append the file to write to it.}
    writeln('Give me the temperature in Fahrenheit to convert to Centigrade.');{Need to define file to WriteTo. You also must Append the file to write to it.}

    writeln(sum);{Need to define file to WriteTo - WriteLn(FileName, VariableToWrite). You also must Append the file to write to it.}
    readln;{This line does not have any arguments. What is this supposed to do? Is your program finished?}
  end;
  procedure finished;{Empty procedure}
  begin
  end;
begin
  initialise;
  repeat
    begin{Didn't have this. Need begin and end because of multiple lines.}
        displaymenu(choice);
        case choice of
        1: throwdice;
        2: heightweight;
        3: textwords;
        4: temperature;
        0: finished;
    end;
  until choice=0;
  readln;{What does this do??}
end.a{Characters outside of code end.}


问:
I am using react and axios. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response
axios. post error.

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

I am using the axios, react and redux.

My code is:

```<code>  const config = {
    method: 'post',
    url: addActivityUrl,
    data:data,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
    },
  };

  return function (dispatch) {
    axios.request(config)
        .then(function(response){
          dispatch({type:ADD_ACTIVITY_SUCCESS,payload:response.data});
        } )
        .catch((error)=> {
          dispatch({type:ADD_ACTIVITY_ERROR,payload:error});
        })
  }
}
</code>```

I set the breakpoint in the error callback function. When I send a post request,the error above will show me.

I looked for the answer on Stack Overflow. I don't found the answer yet.

I don't know the reason.

答:
Most you have an issue with custom request headers.

When using custom request header you will get a CORS preflight. This type of request use HTTP OPTIONS and includes Access-Control-Request-Headers listing the headers the client wants to include in the request.

Your client code need to reply to CORS preflight with the appropriate CORS headers. That header needs to contain the same values the Access-Control-Request-Headers.

Body:
axios. post error.

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

I am using the axios, react and redux.

My code is:

  const config = {
    method: 'post',
    url: addActivityUrl,
    data:data,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
    },
  };

  return function (dispatch) {
    axios.request(config)
        .then(function(response){
          dispatch({type:ADD_ACTIVITY_SUCCESS,payload:response.data});
        } )
        .catch((error)=> {
          dispatch({type:ADD_ACTIVITY_ERROR,payload:error});
        })
  }
}

I set the breakpoint in the error callback function. When I send a post request,the error above will show me.

I looked for the answer on Stack Overflow. I don't found the answer yet.

I don't know the reason.


问:
Could not launch emulator in Android Studio
I tried to launch application in emulator in android Studio in ubuntu 14.04 and it shows the following errors.

Error shown while gradle build is in process:

/home/next/NTE/MachineSetup/android-sdk-linux/tools/emulator -netdelay
  none -netspeed full -avd Nexus_5X_API_24
  Could not launch
  '/home/next/NTE/MachineSetup/android-sdk-linux/tools/qemu/linux-x86/qemu-system-x86_64':
  No such file or directory

Error appear after gradle build completed:

12/02 16:47:57: Launching app Error while waiting for device: The
  emulator process for AVD Nexus_5X_API_24 was killed.

I have attached screenshots for your reference.

答:
The first error's reason is below:

There are two emulators: one in $SDK/tools, another one in $SDK/emulator.

The one in $SDK/tools cannot start.

Please place $SDK/emulator before $SDK/tools in your $PATH variable, it should fix the problem.


问:
Fetching JSON and iterating through the values in react-native
I'm new to react native, and I'm trying to simply iterate through a sample json file but am receiving the error undefined is not a function (evaluating 'this.state.results.map')

I have set the state initially to be an object, so not sure why i am receiving this error.

Here is the JS:

```<code>import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {results: []};
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results : { responseData }
        });
      })
      .done();
  }
  render() {
    return this.renderJSON();
  }
  renderJSON() {
    contents = this.state.results.map((item) => {
      <View key={item.movies.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.movies.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);
</code>```

EDIT

So i have edited the renderJSON() to and also removed the braces of responseData as you said, as it was already an object:

```<code>renderJSON() {

    console.log(this.state.results.description);
    contents = this.state.results.movies.map((item) => {
      <View key={item.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
</code>```

I added a console log to see if i can output some of the data, and i can see the description. The sample JSON i am using is (demo from react):

```<code>{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}
</code>```

I can log the description and title. But I am still receiving: ReactNativeJS: undefined is not an object (evaluating 'this.state.results.movies.map')

And if I try logging console.log(this.state.results.movies[0].title) I am receiving undefined is not an object (evaluating 'this.state.results.movies[0]')

```<code>fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
        this.setState({
          results : responseData
        });
      })
      .done();
  }
</code>```

console.log(responseData) shows:

```<code>03-29 13:49:53.028  3062  4143 I ReactNativeJS: { title: 'The Basics - Networking',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   description: 'Your app fetched this from a remote endpoint!',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   movies:
03-29 13:49:53.028  3062  4143 I ReactNativeJS:    [ { title: 'Star Wars', releaseYear: '1977' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Back to the Future', releaseYear: '1985' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'The Matrix', releaseYear: '1999' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Inception', releaseYear: '2010' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Interstellar', releaseYear: '2014' } ] }
</code>```

console.log(this.state.results.movies);

```<code>03-29 14:18:05.483  3062  4726 I ReactNativeJS: undefined
03-29 14:18:05.510  3062  4726 I ReactNativeJS: [ { title: 'Star Wars', releaseYear: '1977' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Back to the Future', releaseYear: '1985' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'The Matrix', releaseYear: '1999' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Inception', releaseYear: '2010' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Interstellar', releaseYear: '2014' } ]
</code>```

答:
React components using ES6 classes don't autobind this to non React methods. In your constructor, add:

this.renderJSON = this.renderJSON.bind(this)

Body:
I'm new to react native, and I'm trying to simply iterate through a sample json file but am receiving the error undefined is not a function (evaluating 'this.state.results.map')

I have set the state initially to be an object, so not sure why i am receiving this error.

Here is the JS:

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {results: []};
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results : { responseData }
        });
      })
      .done();
  }
  render() {
    return this.renderJSON();
  }
  renderJSON() {
    contents = this.state.results.map((item) => {
      <View key={item.movies.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.movies.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);

EDIT

So i have edited the renderJSON() to and also removed the braces of responseData as you said, as it was already an object:

renderJSON() {

    console.log(this.state.results.description);
    contents = this.state.results.movies.map((item) => {
      <View key={item.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }

I added a console log to see if i can output some of the data, and i can see the description. The sample JSON i am using is (demo from react):

{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}

I can log the description and title. But I am still receiving: ReactNativeJS: undefined is not an object (evaluating 'this.state.results.movies.map')

And if I try logging console.log(this.state.results.movies[0].title) I am receiving undefined is not an object (evaluating 'this.state.results.movies[0]')

fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
        this.setState({
          results : responseData
        });
      })
      .done();
  }

console.log(responseData) shows:

03-29 13:49:53.028  3062  4143 I ReactNativeJS: { title: 'The Basics - Networking',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   description: 'Your app fetched this from a remote endpoint!',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   movies:
03-29 13:49:53.028  3062  4143 I ReactNativeJS:    [ { title: 'Star Wars', releaseYear: '1977' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Back to the Future', releaseYear: '1985' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'The Matrix', releaseYear: '1999' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Inception', releaseYear: '2010' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Interstellar', releaseYear: '2014' } ] }

console.log(this.state.results.movies);

03-29 14:18:05.483  3062  4726 I ReactNativeJS: undefined
03-29 14:18:05.510  3062  4726 I ReactNativeJS: [ { title: 'Star Wars', releaseYear: '1977' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Back to the Future', releaseYear: '1985' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'The Matrix', releaseYear: '1999' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Inception', releaseYear: '2010' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Interstellar', releaseYear: '2014' } ]


问:
Alternative to HtmlUnit
I have been researching about the headless browsers available till to date and found HtmlUnit being used pretty extensively. Do we have any alternative to HtmlUnit with possible advantage compared to HtmlUnit?

Thanks
Nayn

答:
I use webkit as a headless browser, through Qt's Python bindings: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtwebkit.html

Webkit is the render engine used by Chrome and Safari, and is very flexible.

One of my reasons for choosing it over HtmlUnit was ease of setting up:

```<code>sudo apt-get install python-qt4
</code>```

Title: Alternative to HtmlUnit

Body:
I use webkit as a headless browser, through Qt's Python bindings: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtwebkit.html

Webkit is the render engine used by Chrome and Safari, and is very flexible.

One of my reasons for choosing it over HtmlUnit was ease of setting up:

sudo apt-get install python-qt4