问:
jQuery autocomplete - how to prevent auto focus when minLength is zero

 var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

    $("#test").autocomplete({
        minLength: 0,
        source: availableTags,
        autoFocus: true,
        select: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $(this).val(ui.item.label);
            }
        },
        open: function (event, ui) {
            var menu = $(this).data("uiAutocomplete").menu;
            var items = $('li', menu.element);

            for (var i = 0; i < items.length; i++) {
                if (items.eq(i).text().startsWith($(this).val())) {
                    menu.focus(null, items.eq(i));
                    break;
                }
            }
        },
        focus: function (event, ui) {
            event.preventDefault();
            if ($(this).val() == "" && !event.keyCode) {
                //debugger;
                $('.ui-menu-item a').removeClass('ui-state-focus');
            }
            else {
                //$(this).data("uiAutocomplete").menu.element.children().first().focus();
            }
        }
    }).on("focus", function () {
        $(this).autocomplete("search", "");
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
    <label for="test" class="col-md-3 col-lg-3 control-label"></label>
    <div class="col-md-9 col-lg-7">
        <input id="test" type="text" class="form-control" />
    </div>
</div></code>```

While tabbing through the page, inputs with autocomplete are filling out by default with the first option in dropdown. If I set minLength = 1, problem solved. However, I have to keep minLength = 0 in order to pop up the dropdown when the input is focused.

One thought is that removing the focus class when first popping up the dropdown. But the problem is when I press the arrowdown, the second option is focused instead of the first one.

I cannot find any solution to manually focus the first option. Please help.

Any other solutions are more than welcome. Thanks in advance.

答:
Okay, this is what I got to fix my problem. Instead of using autoFocus, I manually set the focus in open function.

    $("#test").autocomplete({
        minLength: 0,
        source: availableTags,
        //autoFocus: true,
        select: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $(this).val(ui.item.label);
            }
        },
        open: function (event, ui) {
            var menu = $(this).data("uiAutocomplete").menu;
            var items = $('li', menu.element);

            if ($(this).val().length > 0) {
                for (var i = 0; i < items.length; i++) {
                    if (items.eq(i).text().toUpperCase().includes($(this).val().toUpperCase())) {
                        menu.focus(null, items.eq(i));
                        break;
                    }
                }
            }
        },
        focus: function (event, ui) {
            event.preventDefault();
        }
    }).on("focus", function () {
        $(this).autocomplete("search", "");
    });```

Body:
 var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

    $("#test").autocomplete({
        minLength: 0,
        source: availableTags,
        autoFocus: true,
        select: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $(this).val(ui.item.label);
            }
        },
        open: function (event, ui) {
            var menu = $(this).data("uiAutocomplete").menu;
            var items = $('li', menu.element);

            for (var i = 0; i < items.length; i++) {
                if (items.eq(i).text().startsWith($(this).val())) {
                    menu.focus(null, items.eq(i));
                    break;
                }
            }
        },
        focus: function (event, ui) {
            event.preventDefault();
            if ($(this).val() == "" && !event.keyCode) {
                //debugger;
                $('.ui-menu-item a').removeClass('ui-state-focus');
            }
            else {
                //$(this).data("uiAutocomplete").menu.element.children().first().focus();
            }
        }
    }).on("focus", function () {
        $(this).autocomplete("search", "");
    });

        <input id="test" type="text" class="form-control" />

While tabbing through the page, inputs with autocomplete are filling out by default with the first option in dropdown. If I set minLength = 1, problem solved. However, I have to keep minLength = 0 in order to pop up the dropdown when the input is focused.

One thought is that removing the focus class when first popping up the dropdown. But the problem is when I press the arrowdown, the second option is focused instead of the first one.

I cannot find any solution to manually focus the first option. Please help.

Any other solutions are more than welcome. Thanks in advance.


来源: stackexchange

问:
pandas dataframe create a new column whose values are based on groupby sum on another column
I am trying to create a new column amount_0_flag for a df, the values in that column are based on groupby another column key, for which if amount sum is 0, assigned True to amount_0_flag, otherwise False. The df looks like,

```<code>key    amount    amount_0_flag    negative_amount
1       1.0      True             False
1       1.0      True             True
2       2.0      False            True
2       3.0      False            False
2       4.0      False            False
</code>```

so when df.groupby('key'), cluster with key=1, will be assigned True to amount_0_flag for each element of the cluster, since within the cluster, one element has negative 1 and another element has postive 1 as their amounts.

```<code>df.groupby('key')['amount'].sum()
</code>```

only gives the sum of amount for each cluster not considering values in negative_amount and I am wondering how to also find the cluster and its rows with 0 sum amounts consdering negative_amount values using pandas/numpy.

答:
Let's try this where I created a 'new_column' showing the comparison to your 'amount_0_flag':

```<code>df['new_column'] = (df.assign(amount_n = df.amount * np.where(df.negative_amount,-1,1))
                      .groupby('key')['amount_n']
                      .transform(lambda x: sum(x)<=0))
</code>```

Output:

```<code>   key  amount  amount_0_flag  negative_amount  new_column
0    1     1.0           True            False        True
1    1     1.0           True             True        True
2    2     2.0          False             True       False
3    2     3.0          False            False       False
4    2     4.0          False            False       False
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a new column amount_0_flag for a df, the values in that column are based on groupby another column key, for which if amount sum is 0, assigned True to amount_0_flag, otherwise False. The df looks like,

key    amount    amount_0_flag    negative_amount
1       1.0      True             False
1       1.0      True             True
2       2.0      False            True
2       3.0      False            False
2       4.0      False            False

so when df.groupby('key'), cluster with key=1, will be assigned True to amount_0_flag for each element of the cluster, since within the cluster, one element has negative 1 and another element has postive 1 as their amounts.

df.groupby('key')['amount'].sum()

only gives the sum of amount for each cluster not considering values in negative_amount and I am wondering how to also find the cluster and its rows with 0 sum amounts consdering negative_amount values using pandas/numpy.

Body:
Let's try this where I created a 'new_column' showing the comparison to your 'amount_0_flag':

df['new_column'] = (df.assign(amount_n = df.amount * np.where(df.negative_amount,-1,1))
                      .groupby('key')['amount_n']
                      .transform(lambda x: sum(x)<=0))

Output:

   key  amount  amount_0_flag  negative_amount  new_column
0    1     1.0           True            False        True
1    1     1.0           True             True        True
2    2     2.0          False             True       False
3    2     3.0          False            False       False
4    2     4.0          False            False       False


问:
Defining implicit format for Enumeration objects via trait in Scala
I am attempting to define an implicit trait for multiple objects to be used when de-serializing JSON values for Enumerations. I understand how to do this within an object, but I was hoping to template this behavior to keep my code DRY. I can accomplish this by doing something like:

```<code>object SomeEnum extends Enumeration {
  type SomeEnum = Value
  val FIRST: SomeEnum = Value("First")
  val SECOND: SomeEnum = Value("Second")
  implicit object SomeEnumFormat extends Format[SomeEnum] {
    def writes(o: SomeEnum): JsValue = JsString(o.toString)

    def reads(json: JsValue): JsResult[SomeEnum] = json match {
      case JsString(x) => JsSuccess(SomeEnum.withName(x.toLowerCase.capitalize))
      case _ => JsError()
    }
  }
}
</code>```

Below is what I have been attempting:

```<code>object SomeEnum extends Mappable {
  val FIRST: SomeEnum = Value("First")
  val SECOND: SomeEnum = Value("Second")
}

object SomeOtherEnum extends Mappable {
  val ABC: SomeOtherEnum = Value("Abc")
  val DEF: SomeOtherEnum = Value("Def")
}

trait Mappable extends Enumeration {
  implicit val enumMapper: JdbcType[Value] with BaseTypedType[Value] = MappedColumnType.base[Value,String](_.toString, this.withName)

  def unapply[Type](s: String): Option[Value] = values.find(s == _.toString)

  implicit object someFormat extends Format[Class[_ <: Mappable]] {
    def writes(o: Class[_ <: Mappable]): JsValue = JsString(o.toString)

    def reads(json: JsValue): JsResult[Value] = json match {
      case JsString(x) => JsSuccess(this.asInstanceOf[Mappable].withName(x.toLowerCase.capitalize))
      case _ => JsError()
    }
  }
}
</code>```

I would expect that the inherited trait would have acted the same way a providing a template version of the implicit object for the class extending the trait, but instead I am getting the following error:

```<code>found   : Mappable#Value
required: Mappable.this.Value
</code>```

If I put the return type of read to JsResult[Mappable#Value] The code does not compile because no implicit declaration is found for the specified enumeration type. Any help would be greatly appreciated.

答:
I initially misunderstood what was happening, and the following was the solution which worked

object SomeEnum extends Mappable {
  type SomeEnum = Value
  val FIRST: SomeEnum = Value("First")
  val SECOND: SomeEnum = Value("Second")
}

object SomeOtherEnum extends Mappable {
  type SomeOtherEnum = Value
  val ABC: SomeOtherEnum = Value("Abc")
  val DEF: SomeOtherEnum = Value("Def")
}

trait Mappable extends Enumeration {
  implicit val enumMapper: JdbcType[Value] with BaseTypedType[Value] = MappedColumnType.base[Value,String](_.toString, this.withName)

  def unapply[Type](s: String): Option[Value] = values.find(s == _.toString)

  implicit object someFormat extends Format[Value] {
    def writes(o: Value): JsValue = JsString(o.toString)

    def reads(json: JsValue): JsResult[Value] = json match {
      case JsString(x) => JsSuccess(withName(x.toLowerCase.capitalize))
      case _ => JsError()
    }
  }
}
```

Body:
I am attempting to define an implicit trait for multiple objects to be used when de-serializing JSON values for Enumerations. I understand how to do this within an object, but I was hoping to template this behavior to keep my code DRY. I can accomplish this by doing something like:

object SomeEnum extends Enumeration {
  type SomeEnum = Value
  val FIRST: SomeEnum = Value("First")
  val SECOND: SomeEnum = Value("Second")
  implicit object SomeEnumFormat extends Format[SomeEnum] {
    def writes(o: SomeEnum): JsValue = JsString(o.toString)

    def reads(json: JsValue): JsResult[SomeEnum] = json match {
      case JsString(x) => JsSuccess(SomeEnum.withName(x.toLowerCase.capitalize))
      case _ => JsError()
    }
  }
}

Below is what I have been attempting:

object SomeEnum extends Mappable {
  val FIRST: SomeEnum = Value("First")
  val SECOND: SomeEnum = Value("Second")
}

object SomeOtherEnum extends Mappable {
  val ABC: SomeOtherEnum = Value("Abc")
  val DEF: SomeOtherEnum = Value("Def")
}

trait Mappable extends Enumeration {
  implicit val enumMapper: JdbcType[Value] with BaseTypedType[Value] = MappedColumnType.base[Value,String](_.toString, this.withName)

  def unapply[Type](s: String): Option[Value] = values.find(s == _.toString)

  implicit object someFormat extends Format[Class[_ <: Mappable]] {
    def writes(o: Class[_ <: Mappable]): JsValue = JsString(o.toString)

    def reads(json: JsValue): JsResult[Value] = json match {
      case JsString(x) => JsSuccess(this.asInstanceOf[Mappable].withName(x.toLowerCase.capitalize))
      case _ => JsError()
    }
  }
}

I would expect that the inherited trait would have acted the same way a providing a template version of the implicit object for the class extending the trait, but instead I am getting the following error:

found   : Mappable#Value
required: Mappable.this.Value

If I put the return type of read to JsResult[Mappable#Value] The code does not compile because no implicit declaration is found for the specified enumeration type. Any help would be greatly appreciated.


问:
I'm installing a Microsoft.Azure.NotificationHubs Installation Class withExpirationTime property in null
I have a doubt about ExpirationTime property which belongs to Installation class, this Installation class is on Microsoft.Azure.NotificationHubs project.
Here is link for the documentation about it https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.installation?view=azure-dotnet

My question is, what will happen to the installation that goes without value in ExpirationTime  property on Azure? Do they expire? Or I don’t have to worry about it anymore, and if they expire, is there a way to get the property value? Is there any example?

I'm using this code to register the installation of the devices on azure, and I'm worry about if they're going to expire some day and I will need to register again all the devices.

```<code>var hubConnectionString = "myazureconnectionstring";
string hub = "myhubname";
NotificationHubClient HubClient=NotificationHubClient.CreateClientFromConnectionString(hubConnectionString, hub, true);

Installation installation= new Installation
{
     PushChannel = device.DeviceToken,
     Platform = device.Type==DeviceType.iOS? NotificationPlatform.Apns: NotificationPlatform.Gcm,
     InstallationId = device.registrationId ?? await HubClient.CreateRegistrationIdAsync()
};
await HubClient.CreateOrUpdateInstallationAsync(installation);
</code>```

regards.

答:
The default expiration time is infinity. So you don’t have to worry about it expiring.

Here is the sample code to get the expiration time. This is at the hub level

var namespaceManager =NamespaceManager.CreateFromConnectionString(“******”);

NotificationHubDescription desc = namespaceManager.GetNotificationHub("apnstest_amol");

Var expiration = desc.RegistrationTtl;

Thanks,
Amol

ContentLicense: CC BY-SA 4.0

Body:
I have a doubt about ExpirationTime property which belongs to Installation class, this Installation class is on Microsoft.Azure.NotificationHubs project.
Here is link for the documentation about it https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.installation?view=azure-dotnet

My question is, what will happen to the installation that goes without value in ExpirationTime  property on Azure? Do they expire? Or I don’t have to worry about it anymore, and if they expire, is there a way to get the property value? Is there any example?

I'm using this code to register the installation of the devices on azure, and I'm worry about if they're going to expire some day and I will need to register again all the devices.

var hubConnectionString = "myazureconnectionstring";
string hub = "myhubname";
NotificationHubClient HubClient=NotificationHubClient.CreateClientFromConnectionString(hubConnectionString, hub, true);

Installation installation= new Installation
{
     PushChannel = device.DeviceToken,
     Platform = device.Type==DeviceType.iOS? NotificationPlatform.Apns: NotificationPlatform.Gcm,
     InstallationId = device.registrationId ?? await HubClient.CreateRegistrationIdAsync()
};
await HubClient.CreateOrUpdateInstallationAsync(installation);

regards.


问:
How to use LINQ to add two fields in a class that is in the List?
I looked through some answers in here, but could not find exactly what I want.
So, I decided to post that questions:

I have objects of a class A and I have a List.

Class has the following definition:

```<code>    public decimal Discount { get; set; }
    public decimal Deposit { get; set; }
    public decimal Total { get; set; }
</code>```

I have a number of those classes in the list.

I calculated Total of Discounts and Deposits:

```<code>var DepositTotal = myList.Sum(x => x.Deposit);
var DiscountTotal = myList.Sum(x => x.Deposit);
</code>```

Now, I need to calculate Sum(Deposit,Discount) for each class and assign the result to Total field, so I will be able to get Total for each class later on

How can I do that?

答:
You really should not be trying to modify items in LINQ queries because readers of your code will not expect it to happen.

Unfortunately you can easily do that so even with Select:

```<code>    list.Select(x => {x.Total = x.Discount + x.Deposit; return x;});
</code>```

Note: better solution could be to have computed property Total instead of field:

```<code> public decimal Total => Discount + Deposit;
</code>```

Body:
I looked through some answers in here, but could not find exactly what I want.
So, I decided to post that questions:

I have objects of a class A and I have a List.

Class has the following definition:

    public decimal Discount { get; set; }
    public decimal Deposit { get; set; }
    public decimal Total { get; set; }

I have a number of those classes in the list.

I calculated Total of Discounts and Deposits:

var DepositTotal = myList.Sum(x => x.Deposit);
var DiscountTotal = myList.Sum(x => x.Deposit);

Now, I need to calculate Sum(Deposit,Discount) for each class and assign the result to Total field, so I will be able to get Total for each class later on

How can I do that?

Body:
You really should not be trying to modify items in LINQ queries because readers of your code will not expect it to happen.

Unfortunately you can easily do that so even with Select:

    list.Select(x => {x.Total = x.Discount + x.Deposit; return x;});

Note: better solution could be to have computed property Total instead of field:

 public decimal Total => Discount + Deposit;


问:
Creating Yocto Mender for Raspberrypi 3
I need help creating Mender for Raspberry Pi3. I can create the image, but when using Win32Image to burn the Disk Image it doesn't boot.

Here is my additional conf.log

```<code>MENDER_ARTIFACT_NAME = "release-1"
INHERIT += "mender-full"
MACHINE ?= "raspberrypi3"
RPI_USE_U_BOOT = "1"
MENDER_PARTITION_ALIGNMENT_KB = "4096"
MENDER_BOOT_PART_SIZE_MB = "40"
IMAGE_INSTALL_append = " kernel-image kernel-devicetree"
IMAGE_FSTYPES_remove += " rpi-sdimg"
DISTRO_FEATURES_append = " systemd"
VIRTUAL-RUNTIME_init_manager = "systemd"
DISTRO_FEATURES_BACKFILL_CONSIDERED = "sysvinit"
VIRTUAL-RUNTIME_initscripts = ""
IMAGE_FSTYPES = "ext4"
</code>```

and bblayers

```<code>POKY_BBLAYERS_CONF_VERSION = "2"

BBPATH = "${TOPDIR}"
BBFILES ?= ""

BBLAYERS ?= " \
  /home/ubuntu/pyro/poky/meta \
  /home/ubuntu/pyro/poky/meta-poky \
  /home/ubuntu/pyro/poky/meta-yocto-bsp \
  /home/ubuntu/pyro/openembedded-core/meta \
  /home/ubuntu/pyro/meta-openembedded/meta-oe \
  /home/ubuntu/pyro/meta-openembedded/meta-python \
  /home/ubuntu/pyro/meta-openembedded/meta-networking \
  /home/ubuntu/pyro/meta-raspberrypi \
  /home/ubuntu/pyro/meta-mender/meta-mender-core \
  /home/ubuntu/pyro/meta-mender/meta-mender-demo \
  /home/ubuntu/pyro/meta-mender/meta-mender-raspberrypi \
  "
</code>```

I can create the rpi-basic image as follows:

```<code>            ubuntu@ip-172-31-6-3:~/pyro/build$ bitbake rpi-basic-image
            Parsing recipes: 100% |######################################################################################| Time: 0:00:54
            Parsing of 870 .bb files complete (0 cached, 870 parsed). 1347 targets, 71    skipped, 0 masked, 0 errors.
            NOTE: Resolving any missing task queue dependencies

            Build Configuration:
            BB_VERSION        = "1.34.0"
            BUILD_SYS         = "x86_64-linux"
            NATIVELSBSTRING   = "universal"
            TARGET_SYS        = "arm-poky-linux-gnueabi"
            MACHINE           = "raspberrypi3"
            DISTRO            = "poky"
            DISTRO_VERSION    = "2.3.2"
            TUNE_FEATURES     = "arm armv7ve vfp thumb neon vfpv4 callconvention-hard    cortexa7"
            TARGET_FPU        = "hard"
            meta
            meta-poky
            meta-yocto-bsp    = "pyro:2021e95bcd986e5bcfe457da5c3e16d60241d050"
            meta-raspberrypi  = "pyro:40447de4782d76f1e23e67ba05e272c27f6ec250"
            meta-mender-core
            meta-mender-raspberrypi = "pyro:b40f05c82ebc97c18ddf8ac426af4657ddba9425"

            Initialising tasks: 100%    |###################################################################################| Time: 0:00:04
            NOTE: Executing SetScene Tasks
            NOTE: Executing RunQueue Tasks
            NOTE: Tasks Summary: Attempted 2976 tasks of which 2953 didn't need to be    rerun and all succeeded.
            ubuntu@ip-172-31-6-3:~/pyro/build$
</code>```

Maybe I am missing some steps?

答: The pyro branch of meta-raspberrypi does not support the RPI_USE_U_BOOT setting.  For that (and older) branches you need to use 'KERNEL_IMAGETYPE_rpi = "uImage"' instead.</p>

Title: Creating Yocto Mender for Raspberrypi 3

Body:
I need help creating Mender for Raspberry Pi3. I can create the image, but when using Win32Image to burn the Disk Image it doesn't boot.

Here is my additional conf.log

MENDER_ARTIFACT_NAME = "release-1"
INHERIT += "mender-full"
MACHINE ?= "raspberrypi3"
RPI_USE_U_BOOT = "1"
MENDER_PARTITION_ALIGNMENT_KB = "4096"
MENDER_BOOT_PART_SIZE_MB = "40"
IMAGE_INSTALL_append = " kernel-image kernel-devicetree"
IMAGE_FSTYPES_remove += " rpi-sdimg"
DISTRO_FEATURES_append = " systemd"
VIRTUAL-RUNTIME_init_manager = "systemd"
DISTRO_FEATURES_BACKFILL_CONSIDERED = "sysvinit"
VIRTUAL-RUNTIME_initscripts = ""
IMAGE_FSTYPES = "ext4"

and bblayers

POKY_BBLAYERS_CONF_VERSION = "2"

BBPATH = "${TOPDIR}"
BBFILES ?= ""

BBLAYERS ?= " \
  /home/ubuntu/pyro/poky/meta \
  /home/ubuntu/pyro/poky/meta-poky \
  /home/ubuntu/pyro/poky/meta-yocto-bsp \
  /home/ubuntu/pyro/openembedded-core/meta \
  /home/ubuntu/pyro/meta-openembedded/meta-oe \
  /home/ubuntu/pyro/meta-openembedded/meta-python \
  /home/ubuntu/pyro/meta-openembedded/meta-networking \
  /home/ubuntu/pyro/meta-raspberrypi \
  /home/ubuntu/pyro/meta-mender/meta-mender-core \
  /home/ubuntu/pyro/meta-mender/meta-mender-demo \
  /home/ubuntu/pyro/meta-mender/meta-mender-raspberrypi \
  "

I can create the rpi-basic image as follows:

            ubuntu@ip-172-31-6-3:~/pyro/build$ bitbake rpi-basic-image
            Parsing recipes: 100% |######################################################################################| Time: 0:00:54
            Parsing of 870 .bb files complete (0 cached, 870 parsed). 1347 targets, 71    skipped, 0 masked, 0 errors.
            NOTE: Resolving any missing task queue dependencies

            Build Configuration:
            BB_VERSION        = "1.34.0"
            BUILD_SYS         = "x86_64-linux"
            NATIVELSBSTRING   = "universal"
            TARGET_SYS        = "arm-poky-linux-gnueabi"
            MACHINE           = "raspberrypi3"
            DISTRO            = "poky"
            DISTRO_VERSION    = "2.3.2"
            TUNE_FEATURES     = "arm armv7ve vfp thumb neon vfpv4 callconvention-hard    cortexa7"
            TARGET_FPU        = "hard"
            meta
            meta-poky
            meta-yocto-bsp    = "pyro:2021e95bcd986e5bcfe457da5c3e16d60241d050"
            meta-raspberrypi  = "pyro:40447de4782d76f1e23e67ba05e272c27f6ec250"
            meta-mender-core
            meta-mender-raspberrypi = "pyro:b40f05c82ebc97c18ddf8ac426af4657ddba9425"

            Initialising tasks: 100%    |###################################################################################| Time: 0:00:04
            NOTE: Executing SetScene Tasks
            NOTE: Executing RunQueue Tasks
            NOTE: Tasks Summary: Attempted 2976 tasks of which 2953 didn't need to be    rerun and all succeeded.
            ubuntu@ip-172-31-6-3:~/pyro/build$

Maybe I am missing some steps?


问:
how do I update and array of users with rails 3
I am trying to pass an array of user objects from flash to rails 3 and update them all at once. Here is the code that I am using.

```<code>  def update_by_fbid
    if params[:users]

     params[:users].each do |u|
       puts u
        user = User.find_by_fbid(u.fbid)
        user.update_attributes(:first_name => u.first_name, :last_name => u.last_name)
      end
    end
    render :json => {:updated_users => true}
  end
</code>```

Here is my code from Flash

```<code>private function updateUsers(e:Event):void
{
    var users:Array = [{fbid:"93847566", first_name:"Joe", last_name:"Blow"},
        {fbid:"7654321", first_name:"Ronda", last_name:"Smith"}
        ];

    var vars : URLVariables = new URLVariables();
        vars.users = users;

    var request : URLRequest = new URLRequest("http://localhost:3000/update");
    request.method = URLRequestMethod.POST;
    request.data = vars;

    var loader : URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, registerHandler);
    loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    loader.load(request);
    }
</code>```

here is the error that I am seeing in the terminal

```<code>Started POST "/update" for 127.0.0.1 at Sat Jan 22 13:41:42 -0600 2011
  Processing by UsersController#update_by_fbid as HTML
  Parameters: {"users"=>"[object Object]"}
Completed   in 8ms

NoMethodError (undefined method `fbid' for "[object Object]":String):
  app/controllers/users_controller.rb:68:in `update_by_fbid'
  app/controllers/users_controller.rb:66:in `each'
  app/controllers/users_controller.rb:66:in `update_by_fbid'

Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.8ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.9ms)
</code>```

Still a little new at rails so I am sure I am just selecting my objects from the parmas incorrectly or something of that nature. Hoping someone can school me a bit on what I am doing wrong on the rails side of things.

-m

答:
You're accessing fbid like it is a method of one of the items in params[:user]. What you actually want is this:

```<code>params[:users].each do |u|
  user = User.find_by_fbid(u[:fbid])
  user.update_attributes(:first_name => u[:first_name], :last_name => u[:last_name])
end
</code>```

Assuming that you have NOT prevented mass assignment on the first_name and last_name attributes, you can simplify what you're doing to:

```<code>params[:users].each do |u|
  user = User.find_by_fbid u[:fbid]
  user.update_attributes u
end
</code>```

Just make sure that you have prevented mass assignment on sensitive attributes, like fbid. You can add this at the top of your model to do this safely (whitelist):

```<code>attr_accessible :first_name, :last_name
</code>```

You should double check your indenting in your source. In your question it's a bit wonky, which can lead to confusion on which end corresponds to what.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to pass an array of user objects from flash to rails 3 and update them all at once. Here is the code that I am using.

  def update_by_fbid
    if params[:users]

     params[:users].each do |u|
       puts u
        user = User.find_by_fbid(u.fbid)
        user.update_attributes(:first_name => u.first_name, :last_name => u.last_name)
      end
    end
    render :json => {:updated_users => true}
  end

Here is my code from Flash

private function updateUsers(e:Event):void
{
    var users:Array = [{fbid:"93847566", first_name:"Joe", last_name:"Blow"},
        {fbid:"7654321", first_name:"Ronda", last_name:"Smith"}
        ];

    var vars : URLVariables = new URLVariables();
        vars.users = users;

    var request : URLRequest = new URLRequest("http://localhost:3000/update");
    request.method = URLRequestMethod.POST;
    request.data = vars;

    var loader : URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, registerHandler);
    loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    loader.load(request);
    }

here is the error that I am seeing in the terminal

Started POST "/update" for 127.0.0.1 at Sat Jan 22 13:41:42 -0600 2011
  Processing by UsersController#update_by_fbid as HTML
  Parameters: {"users"=>"[object Object]"}
Completed   in 8ms

NoMethodError (undefined method `fbid' for "[object Object]":String):
  app/controllers/users_controller.rb:68:in `update_by_fbid'
  app/controllers/users_controller.rb:66:in `each'
  app/controllers/users_controller.rb:66:in `update_by_fbid'

Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.8ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.9ms)

Still a little new at rails so I am sure I am just selecting my objects from the parmas incorrectly or something of that nature. Hoping someone can school me a bit on what I am doing wrong on the rails side of things.

-m

Body:
You're accessing fbid like it is a method of one of the items in params[:user]. What you actually want is this:

params[:users].each do |u|
  user = User.find_by_fbid(u[:fbid])
  user.update_attributes(:first_name => u[:first_name], :last_name => u[:last_name])
end

Assuming that you have NOT prevented mass assignment on the first_name and last_name attributes, you can simplify what you're doing to:

params[:users].each do |u|
  user = User.find_by_fbid u[:fbid]
  user.update_attributes u
end

Just make sure that you have prevented mass assignment on sensitive attributes, like fbid. You can add this at the top of your model to do this safely (whitelist):

attr_accessible :first_name, :last_name

You should double check your indenting in your source. In your question it's a bit wonky, which can lead to confusion on which end corresponds to what.


问:
Ubuntu 16.04 lightdm segmentation fault
I'm newbie into Linux world, and i have installed Ubuntu 16.04 LTS x64 with graphics driver for Cirrus Logic 5440 graphics card. What happened, I could not start X-server, Lightdm display manager breaks on segmentation fault caused by libc.so.6, this is part of Xorg0.log log file:

```<code>[   684.494] (EE) Backtrace:
[   684.494] (EE) 0: /usr/lib/xorg/Xorg (xorg_backtrace+0x4e) [0x557fcc97c6ce]
[   684.494] (EE) 1: /usr/lib/xorg/Xorg (0x557fcc7ca000+0x1b6a69) [0x557fcc980a69]
[   684.494] (EE) 2: /lib/x86_64-linux-gnu/libc.so.6 (0x7f6db03c3000+0x354b0) [0x7f6db03f84b0]
[   684.494] (EE)
[   684.494] (EE) Segmentation fault at address 0x0
[   684.494] (EE) Fatal server error:
[   684.494] (EE) Caught signal 11 (Segmentation fault). Server aborting
</code>```

Could someone help me, I can't see what is wrong. Libc is installed and exist in /lib and /lib64 directory. Thanks very much!

答:
This is a reported and fixed bug.

To fix it, run:

```<code>$ sudo apt-get install git
</code>```

Install the dependent packages for OpenChrome

```<code>$ sudo apt-get build-dep xserver-xorg-video-openchrome
</code>```

clone the OpenChrome repository to your device:

```<code>$ git clone git://anongit.freedesktop.org/openchrome/xf86-video-openchrome
</code>```

After you finish cloning it, cd into it.

```<code>$ cd xf86-video-openchrome
</code>```

Generate any needed scripts

```<code>$ ./autogen.sh --prefix=/usr --enable-debug --enable-xv-debug --enable-viaregtool
</code>```

If there were no errors, compile OpenChrome

```<code>$ make
$ sudo make install
</code>```

Title: Ubuntu 16.04 lightdm segmentation fault

Body:
I'm newbie into Linux world, and i have installed Ubuntu 16.04 LTS x64 with graphics driver for Cirrus Logic 5440 graphics card. What happened, I could not start X-server, Lightdm display manager breaks on segmentation fault caused by libc.so.6, this is part of Xorg0.log log file:

[   684.494] (EE) Backtrace:
[   684.494] (EE) 0: /usr/lib/xorg/Xorg (xorg_backtrace+0x4e) [0x557fcc97c6ce]
[   684.494] (EE) 1: /usr/lib/xorg/Xorg (0x557fcc7ca000+0x1b6a69) [0x557fcc980a69]
[   684.494] (EE) 2: /lib/x86_64-linux-gnu/libc.so.6 (0x7f6db03c3000+0x354b0) [0x7f6db03f84b0]
[   684.494] (EE)
[   684.494] (EE) Segmentation fault at address 0x0
[   684.494] (EE) Fatal server error:
[   684.494] (EE) Caught signal 11 (Segmentation fault). Server aborting

Could someone help me, I can't see what is wrong. Libc is installed and exist in /lib and /lib64 directory. Thanks very much!

Body:
This is a reported and fixed bug.

To fix it, run:

$ sudo apt-get install git

Install the dependent packages for OpenChrome

$ sudo apt-get build-dep xserver-xorg-video-openchrome

clone the OpenChrome repository to your device:

$ git clone git://anongit.freedesktop.org/openchrome/xf86-video-openchrome

After you finish cloning it, cd into it.

$ cd xf86-video-openchrome

Generate any needed scripts

$ ./autogen.sh --prefix=/usr --enable-debug --enable-xv-debug --enable-viaregtool

If there were no errors, compile OpenChrome

$ make
$ sudo make install


问:
Cannot upload files for release in Github
I want ot create a release for my Github project, but when I try to upload my binary (which is a .zip file) to the release, I get the following error message:

Something went really wrong, and we can’t process that file.

I get the same error message if I try to upload some other files (e.g. my readme file). What could be wrong?

答: Files cannot be uploaded because your network provider doesn't allow, use different network or apply vpn for uploading the files.</p>


问:
Change button text on click
So, I followed an online course from www.code.org to accomodate myself with JavaScript. I used elements such as setProperty(); and onEvent();. I used an online editor to add a button and the following code to change the button's text when the user clicks it:

```<code>onEvent("button1","click", function()
 {
  setProperty("button1","text","Hello there!");
 });
</code>```

My question is: How can I do this thing in HTML, by using the <button> tag?

答:
Simply write the whole onclick event handler function inside the button tag only.</p>

```<code><button type="buttton" onclick="this.innerHTML='Text changed'"></button>
</code>```

Title: Change button text on click

Body:
So, I followed an online course from www.code.org to accomodate myself with JavaScript. I used elements such as setProperty(); and onEvent();. I used an online editor to add a button and the following code to change the button's text when the user clicks it:

onEvent("button1","click", function()
 {
  setProperty("button1","text","Hello there!");
 });

My question is: How can I do this thing in HTML, by using the <button> tag?

Body:
Simply write the whole onclick event handler function inside the button tag only.

<button type="buttton" onclick="this.innerHTML='Text changed'"></button>


问:
Extract and sort data from a workbook to another with VBA
So my question is simple "How to extract and sort data from a workbook to another"?

I have a document ( let's name it "devices" ) sent over the network, as a result of an another document ( "devices used" ), which sorts some devices used by people in that day. it doesn't arrange the data.

What I wanna do is take that data from that document, and sort it as a table in another workbook.

I know I have to declare the workbook and the sheets, but how to extract and sort the data it's out of my power of knowledge ( yes, I'm new to vba ).

Regards,
Alex

答:
This is my code until now. but my problem is that I don;t know how to copy all data according to the data from my IF.

Sub timp_sortare_deviceuri()

Dim HPS13 As Workbook
Set HPS13 = ActiveWorkbook

Dim sheet_date As Worksheet
Set sheet_date = Sheets("Sheet1")

Dim HPS1 As Workbook

Dim ultimul_rand_detectat As Integer

Application.Workbooks.Open ("C:\Users\Piulitsa\Desktop\HPS1.xlsx")

Set HPS1 = ActiveWorkbook

ultimul_rand_detectat = HPS1.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

'Debug.Print ultimul_rand_detectat

For rand = 1 To ultimul_rand_detectat

urmatorul_rand = HPS13.Sheets("Sheet1").Cells(Rows.Count, 11).End(xlUp).Row + 1

If HPS1.Sheets("Sheet1").Range("A" & rand).Value = "Data Document:" Then

```<code>HPS13.Sheets("Sheet1").Range("K" & urmatorul_rand).Value = HPS1.Sheets("Sheet1").Range("B" & rand).Value
</code>```

End If

Next rand

End Sub

Body:
This is my code until now. but my problem is that I don;t know how to copy all data according to the data from my IF.

Sub timp_sortare_deviceuri()

Dim HPS13 As Workbook
Set HPS13 = ActiveWorkbook

Dim sheet_date As Worksheet
Set sheet_date = Sheets("Sheet1")

Dim HPS1 As Workbook

Dim ultimul_rand_detectat As Integer

Application.Workbooks.Open ("C:\Users\Piulitsa\Desktop\HPS1.xlsx")

Set HPS1 = ActiveWorkbook

ultimul_rand_detectat = HPS1.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

'Debug.Print ultimul_rand_detectat

For rand = 1 To ultimul_rand_detectat

urmatorul_rand = HPS13.Sheets("Sheet1").Cells(Rows.Count, 11).End(xlUp).Row + 1

If HPS1.Sheets("Sheet1").Range("A" & rand).Value = "Data Document:" Then

HPS13.Sheets("Sheet1").Range("K" & urmatorul_rand).Value = HPS1.Sheets("Sheet1").Range("B" & rand).Value

End If

Next rand

End Sub


问:
Elastic Beanstalk Application Can't Connect to Database but Server Can
I have an Elastic Beanstalk application that can't connect to the database but the server it's running on can connect to the database just fine.

When I try to deploy my elastic beanstalk application, it gives me a database error Access Denied (the deploy process needs to connect to the database in order to run migrations.  My database is on RDS.  I have the environment variables for the database configured in the environment.  I have the security groups set up to allow the environment servers to connect to RDS.  When I ssh into the server, I can open a database connection through the database terminal to the database.  It's only the application that can't connect.  What is going wrong?

答:
The problem is non-alphanumeric characters in the database password.  In this case, the particular culprit is "$".  Changing the database password to be purely alphanumeric solves it.

Elastic beanstalk environment variables are passed to your application through a shell script that it generates.  If you have a dollar sign in your password, Linux will interpret this as a shell variable embedded in the password and will ignore anything after the dollar sign in the password.


问:
Simple way to find if two different lists contain exactly the same elements?
What is the simplest way to find if two Lists contain exactly the same elements, in the standard Java libraries?

It shouldn't matter if the two Lists are the same instance or not, and it shouldn't matter if the type parameter of the Lists are different.

e.g.

```<code>List list1
List<String> list2;
// ... construct etc

list1.add("A");
list2.add("A");
// the function, given these two lists, should return true
</code>```

There's probably something staring me in the face I know :-)

EDIT: To clarify, I was looking for the EXACT same elements and number of elements, in order.

答:
Very late to the party but wanted to add this null safe check:</p>

```<code>Objects.equals(list1, list2)
</code>```

Body:
What is the simplest way to find if two Lists contain exactly the same elements, in the standard Java libraries?

It shouldn't matter if the two Lists are the same instance or not, and it shouldn't matter if the type parameter of the Lists are different.

e.g.

List list1
List<String> list2;
// ... construct etc

list1.add("A");
list2.add("A");
// the function, given these two lists, should return true

There's probably something staring me in the face I know :-)

EDIT: To clarify, I was looking for the EXACT same elements and number of elements, in order.

Body:
Very late to the party but wanted to add this null safe check:

Objects.equals(list1, list2)


问:
Query with GROUP BY and ORDER BY not working when multiple columns in SELECT are chosen
I'm updating an old website and one of the queries isn't working anymore:

```<code>SELECT * FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

I noticed if I dropped the GROUP BY it works, but the result set doesn't match the original:

```<code>SELECT * FROM tbl WHERE col1 IS NULL ORDER BY col2
</code>```

So I tried reading up on GROUP BY in the docs to see what might be the issue, and it seemed to suggest not using * to select all the fields, but explicitly using the column name so I tried it with just the column that was being ordered and grouped:

```<code>SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

Which works but after looking through the code the query requires 2 columns in the query so whoever added * was overdoing it, but if I add that column produces an error, similarly adding a third column produces the same error:

```<code>SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
SELECT col1, col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

Can anyone tell me why this last query doesn't work?  I can't decipher why from the docs, but this is the minimum query required to get the result set I need.

Running the query in Adminer I get this error

```<code>Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'name.table.column'
which is not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by
</code>```

答:
This query:

```<code>SELECT *
FROM tbl
WHERE col1 IS NULL
GROUP BY col1
ORDER BY col1;
</code>```

never really worked.  It may have seemed to work, but you were just lucky.  You have unaggregated columns in the SELECT.  These come from an arbitrary row.

You can do something like this to get values from other columns:

```<code>SELECT col1, min(col2), min(col3)
FROM tbl t
WHERE col1 IS NULL AND
GROUP BY col1
ORDER BY col1;
</code>```

Body:
I'm updating an old website and one of the queries isn't working anymore:

SELECT * FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

I noticed if I dropped the GROUP BY it works, but the result set doesn't match the original:

SELECT * FROM tbl WHERE col1 IS NULL ORDER BY col2

So I tried reading up on GROUP BY in the docs to see what might be the issue, and it seemed to suggest not using * to select all the fields, but explicitly using the column name so I tried it with just the column that was being ordered and grouped:

SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

Which works but after looking through the code the query requires 2 columns in the query so whoever added * was overdoing it, but if I add that column produces an error, similarly adding a third column produces the same error:

SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
SELECT col1, col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

Can anyone tell me why this last query doesn't work?  I can't decipher why from the docs, but this is the minimum query required to get the result set I need.

Running the query in Adminer I get this error

Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'name.table.column'
which is not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by

Body:
This query:

SELECT *
FROM tbl
WHERE col1 IS NULL
GROUP BY col1
ORDER BY col1;

never really worked.  It may have seemed to work, but you were just lucky.  You have unaggregated columns in the SELECT.  These come from an arbitrary row.

You can do something like this to get values from other columns:

SELECT col1, min(col2), min(col3)
FROM tbl t
WHERE col1 IS NULL AND
GROUP BY col1
ORDER BY col1;


问:
Preventing IE / Edge from preloading video
I have a page which dynamically displays dozens of videos (for technical reasons) on each page load. My specifications require me to have each video clickable in the HTML.

IE:

```<code>    <video id="video-01448_1" preload="none" controls="">
        <source src="https://downloadurl.com/filename1.mp4" type="video/mp4">
    </video>
    <video id="video-01448_2" preload="none" controls="">
        <source src="https://downloadurl.com/filename2.mp4" type="video/mp4">
    </video>
    ... more videos
</code>```

preload="none" works in Chrome, FireFox and other browsers, but IE will still preload a few seconds of each video. This is fine when only a couple videos are on the page, but it slows down or literally crashes IE/Edge when 100+ video links are on the page.

This is a known issue with Microsoft, however not a bug as preload is merely considered a suggestion for the browser.

See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7117594/

My question... Is there a simple solution or workaround for this situation?

答:
I couldn't find a simple solution to this issue anywhere online, so I figured out a vanilla JavaScript answer using Bootstrap modals:

```<code>    <a href="#modalId" data-toggle="modal" onclick="addSrcToVideo('videoId','/videoFileLocation.mp4'" >View Video</a>

    <script>
    function addSrcToVideo(vidId, src) {
        var video = document.getElementById(vidId);
        video.src = src;
    }
    </script>
</code>```

This simply uses JavaScript to add the source a the time you click the modal link. Since the src does not exist at the time of the page load, there is nothing to preload in IE/Edge. As mentioned in the comments of the original post, you can add an image thumbnail or you can just auto play the video using JS.

Note: I don't think this is the best option as it doesn't create a <source src=...> attribute. If you have a better solution that works, I can mark yours as the answer.

Body:
I have a page which dynamically displays dozens of videos (for technical reasons) on each page load. My specifications require me to have each video clickable in the HTML.

IE:

    <video id="video-01448_1" preload="none" controls="">
        <source src="https://downloadurl.com/filename1.mp4" type="video/mp4">
    </video>
    <video id="video-01448_2" preload="none" controls="">
        <source src="https://downloadurl.com/filename2.mp4" type="video/mp4">
    </video>
    ... more videos

preload="none" works in Chrome, FireFox and other browsers, but IE will still preload a few seconds of each video. This is fine when only a couple videos are on the page, but it slows down or literally crashes IE/Edge when 100+ video links are on the page.

This is a known issue with Microsoft, however not a bug as preload is merely considered a suggestion for the browser.

See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7117594/

My question... Is there a simple solution or workaround for this situation?

Body:
I couldn't find a simple solution to this issue anywhere online, so I figured out a vanilla JavaScript answer using Bootstrap modals:

    <a href="#modalId" data-toggle="modal" onclick="addSrcToVideo('videoId','/videoFileLocation.mp4'" >View Video</a>

    <script>
    function addSrcToVideo(vidId, src) {
        var video = document.getElementById(vidId);
        video.src = src;
    }
    </script>

This simply uses JavaScript to add the source a the time you click the modal link. Since the src does not exist at the time of the page load, there is nothing to preload in IE/Edge. As mentioned in the comments of the original post, you can add an image thumbnail or you can just auto play the video using JS.

Note: I don't think this is the best option as it doesn't create a <source src=...> attribute. If you have a better solution that works, I can mark yours as the answer.


问:
Error: pandoc document conversion failed with error 2 with pkgdown / rmarkdown
I'm trying to build a website with pkgdown so I ran pkgdown::build_site().

This throws the following error:

Building article 'index.html'

Error: pandoc document conversion failed with error 2

There was a similar problem on SO but the answer didn't solve my issue.

My guess was that the problem was in the header of my vignette which currently is:

```<code>output:
  rmarkdown::html_vignette:
    smart: false
    toc: true
</code>```

I tried changing it to:

```<code>output: rmarkdown::html_vignette
</code>```

as it is used in the pkgdown's vignette. When I used that code, I got an error and the vignette did not build.

--smart/-S has been removed.  Use +smart or -smart extension instead. For example: pandoc -f markdown+smart -t markdown-smart. Try
  pandoc.exe --help for more information. Error: pandoc document
  conversion failed with error 2 In addition: Warning message: running
  command '"C:/PROGRA~2/Pandoc/pandoc" +RTS -K512m -RTS
  Introduction.utf8.md --to html --from
  markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash
  --output pandoc23e071f76af6.html --smart --email-obfuscation none --self-contained --standalone --section-divs --template "C:\Users\E\Documents\R\win-library\3.4\rmarkdown\rmd\h\default.html"
  --highlight-style pygments --css "C:\Users\E\Documents\R\win-library\3.4\rmarkdown\rmarkdown\templates\html_vignette\resources\vignette.css"
  --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"'
  had status 2  Execution halted

I changed the header as suggested here to:

```<code>output:
  html_document:
    smart: false
</code>```

This header knits a vignette but I still get the same pandoc error when using build_site().

Pandoc is version 2.0. sessionInfo() returns:

R version 3.4.1 (2017-06-30) Platform: x86_64-w64-mingw32/x64 (64-bit)
  Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:

LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252     LC_MONETARY=English_United Kingdom.1252  LC_NUMERIC=C

  LC_TIME=English_United Kingdom.1252

attached base packages:
  stats     graphics  grDevices utils

  datasets  methods   base

other attached packages:
  pkgdown_0.1.0.9000 devtools_1.13.2

loaded via a namespace (and not attached):  MASS_7.3-47

  compiler_3.4.1   magrittr_1.5     R6_2.2.2         tools_3.4.1

  withr_1.0.2      roxygen2_6.0.1    Rcpp_0.12.12     memoise_1.1.0
  xml2_1.1.1       stringi_1.1.5    stringr_1.2.0    digest_0.6.12

  commonmark_1.2   rlang_0.1.1.9000

Any ideas how to fix it?

EDIT:

I ran the whole thing on Ubuntu and I managed to make it work (see the repo). Still don't know what was causing the issue. Here is the output of sessionInfo():

R version 3.3.3 (2017-03-06) Platform: x86_64-pc-linux-gnu (64-bit)
  Running under: Ubuntu 16.04.2 LTS

locale:

LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C

  LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8

  LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8

  LC_PAPER=en_GB.UTF-8       LC_NAME=C                 LC_ADDRESS=C

  LC_TELEPHONE=C             LC_MEASUREMENT=en_GB.UTF-8
  LC_IDENTIFICATION=C

attached base packages: stats     graphics  grDevices utils

  datasets  methods   base

other attached packages: pkgdown_0.1.0.9000 devtools_1.13.1

loaded via a namespace (and not attached):  MASS_7.3-45

  magrittr_1.5   R6_2.2.2       tools_3.3.3    withr_2.0.0

  roxygen2_6.0.1 Rcpp_0.12.12   memoise_1.1.0   xml2_1.1.1

  stringi_1.1.2  stringr_1.2.0  digest_0.6.12  commonmark_1.2
  rlang_0.1.1

答:
The warning is raised because the argument --smart is being used here: ... running command '"C:/PROGRA~2/Pandoc/pandoc" ...  --smart ... "'. Because --smart/-S has been removed for Pandoc 2.0, that's a problem. So, remove --smart from the caller or command-line to fix this.

In Pandoc 2+, usage of smart is the same as for any other extension. To enable it, you append +smart to either the --to or the --from argument it, or possibly to both. And to disable, append -smart.

For example:

--to html+smart

Or maybe:

--from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-smart

Body:
I'm trying to build a website with pkgdown so I ran pkgdown::build_site().

This throws the following error:

Building article 'index.html'

Error: pandoc document conversion failed with error 2

There was a similar problem on SO but the answer didn't solve my issue.

My guess was that the problem was in the header of my vignette which currently is:

output:
  rmarkdown::html_vignette:
    smart: false
    toc: true

I tried changing it to:

output: rmarkdown::html_vignette

as it is used in the pkgdown's vignette. When I used that code, I got an error and the vignette did not build.

--smart/-S has been removed.  Use +smart or -smart extension instead. For example: pandoc -f markdown+smart -t markdown-smart. Try
  pandoc.exe --help for more information. Error: pandoc document
  conversion failed with error 2 In addition: Warning message: running
  command '"C:/PROGRA~2/Pandoc/pandoc" +RTS -K512m -RTS
  Introduction.utf8.md --to html --from
  markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash
  --output pandoc23e071f76af6.html --smart --email-obfuscation none --self-contained --standalone --section-divs --template "C:\Users\E\Documents\R\win-library\3.4\rmarkdown\rmd\h\default.html"
  --highlight-style pygments --css "C:\Users\E\Documents\R\win-library\3.4\rmarkdown\rmarkdown\templates\html_vignette\resources\vignette.css"
  --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"'
  had status 2  Execution halted

I changed the header as suggested here to:

output:
  html_document:
    smart: false

This header knits a vignette but I still get the same pandoc error when using build_site().

Pandoc is version 2.0. sessionInfo() returns:

R version 3.4.1 (2017-06-30) Platform: x86_64-w64-mingw32/x64 (64-bit)
  Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:

LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252     LC_MONETARY=English_United Kingdom.1252  LC_NUMERIC=C

  LC_TIME=English_United Kingdom.1252

attached base packages:
  stats     graphics  grDevices utils

  datasets  methods   base

other attached packages:
  pkgdown_0.1.0.9000 devtools_1.13.2

loaded via a namespace (and not attached):  MASS_7.3-47

  compiler_3.4.1   magrittr_1.5     R6_2.2.2         tools_3.4.1

  withr_1.0.2      roxygen2_6.0.1    Rcpp_0.12.12     memoise_1.1.0
  xml2_1.1.1       stringi_1.1.5    stringr_1.2.0    digest_0.6.12

  commonmark_1.2   rlang_0.1.1.9000

Any ideas how to fix it?

EDIT:

I ran the whole thing on Ubuntu and I managed to make it work (see the repo). Still don't know what was causing the issue. Here is the output of sessionInfo():

R version 3.3.3 (2017-03-06) Platform: x86_64-pc-linux-gnu (64-bit)
  Running under: Ubuntu 16.04.2 LTS

locale:

LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C

  LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8

  LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8

  LC_PAPER=en_GB.UTF-8       LC_NAME=C                 LC_ADDRESS=C

  LC_TELEPHONE=C             LC_MEASUREMENT=en_GB.UTF-8
  LC_IDENTIFICATION=C

attached base packages: stats     graphics  grDevices utils

  datasets  methods   base

other attached packages: pkgdown_0.1.0.9000 devtools_1.13.1

loaded via a namespace (and not attached):  MASS_7.3-45

  magrittr_1.5   R6_2.2.2       tools_3.3.3    withr_2.0.0

  roxygen2_6.0.1 Rcpp_0.12.12   memoise_1.1.0   xml2_1.1.1

  stringi_1.1.2  stringr_1.2.0  digest_0.6.12  commonmark_1.2
  rlang_0.1.1


问:
How to remove specific character surrounding a string?
I have this string:

```<code>var str = "? this is a ? test ?";
</code>```

Now I want to get this:

```<code>var newstr = "this is a ? test";
</code>```

As you see I want to remove just those ? surrounding (in the beginning and end) that string (not in the middle of string). How can do that using JavaScript?

Here is what I have tried:

var str = "? this is a ? test ?";
var result = str.trim("?");
document.write(result);```

So, as you see it doesn't work. Actually I'm a PHP developer and trim() works well in PHP. Now I want to know if I can use trim() to do that in JS.

It should be noted I can do that using regex, but to be honest I hate regex for this kind of jobs. Anyway is there any better solution?

Edit: As this mentioned in the comment, I need to remove both ? and whitespaces which are around the string.

答:
to keep this question up to date using an ES6 approach:

I liked the bitwise method but when readability is a concern too then here's another approach.

```<code>function trimByChar(string, character) {
  const first = [...string].findIndex(char => char !== character);
  const last = [...string].reverse().findIndex(char => char !== character);
  return string.substring(first, string.length - last);
}
</code>```

Body:
I have this string:

var str = "? this is a ? test ?";

Now I want to get this:

var newstr = "this is a ? test";

As you see I want to remove just those ? surrounding (in the beginning and end) that string (not in the middle of string). How can do that using JavaScript?

Here is what I have tried:

var str = "? this is a ? test ?";
var result = str.trim("?");
document.write(result);

So, as you see it doesn't work. Actually I'm a PHP developer and trim() works well in PHP. Now I want to know if I can use trim() to do that in JS.

It should be noted I can do that using regex, but to be honest I hate regex for this kind of jobs. Anyway is there any better solution?

Edit: As this mentioned in the comment, I need to remove both ? and whitespaces which are around the string.

Body:
to keep this question up to date using an ES6 approach:

I liked the bitwise method but when readability is a concern too then here's another approach.

function trimByChar(string, character) {
  const first = [...string].findIndex(char => char !== character);
  const last = [...string].reverse().findIndex(char => char !== character);
  return string.substring(first, string.length - last);
}


问:
how to remove AWS S3 Bucket with strange name
I accidentally copied data to a bucket named "s3://my-rd-data/Project-0001" so my bucket path looked like:

```<code>s3://my-rd-data/s3://my-rd-data/Project-0001
</code>```

what i really want is

```<code>s3://my-rd-data/Project-0001
</code>```

Now, i cannot remove the wrong bucket"s3://my-rd-data/s3://":

```<code>$ aws s3 rb s3://my-rd-data/s3\:\/\/
Please specify a valid bucket name only. E.g.

$ aws s3 rb s3://my-rd-data/s3://
Please specify a valid bucket name only. E.g.

$ aws s3 rb s3://my-rd-data/s3\://
Please specify a valid bucket name only. E.g.
</code>```

Can someone let me know how to remove this bucket?

Thanks a lot,

Shuoguo

答:
Have you tried removing the bucket from AWS Web Console?

Also, you can do aws s3 ls to see the name of the bucket and delete it that way.

Per AWS Docs Bucket Restrictions and Limitations:

Bucket names can contain lowercase letters, numbers, and hyphens. Each label must start and end with a lowercase letter or a number.

Body:
I accidentally copied data to a bucket named "s3://my-rd-data/Project-0001" so my bucket path looked like:

s3://my-rd-data/s3://my-rd-data/Project-0001

what i really want is

s3://my-rd-data/Project-0001

Now, i cannot remove the wrong bucket"s3://my-rd-data/s3://":

$ aws s3 rb s3://my-rd-data/s3\:\/\/
Please specify a valid bucket name only. E.g.

$ aws s3 rb s3://my-rd-data/s3://
Please specify a valid bucket name only. E.g.

$ aws s3 rb s3://my-rd-data/s3\://
Please specify a valid bucket name only. E.g.

Can someone let me know how to remove this bucket?

Thanks a lot,

Shuoguo


问:
rails - REGEX for email validation
I'm looking for a regex to validate an email to learn if it's valid or not.. I have the following:

```<code>def is_a_valid_email?(email)
    email_regex = %r{
      ^ # Start of string
      [0-9a-z] # First character
      [0-9a-z.+]+ # Middle characters
      [0-9a-z] # Last character
      @ # Separating @ character
      [0-9a-z] # Domain name begin
      [0-9a-z.-]+ # Domain name middle
      [0-9a-z] # Domain name end
      $ # End of string
    }xi # Case insensitive

    (email =~ email_regex)
end
</code>```

Problem with the above is XXX_XXX@Xxx.com does not return as valid when it should be. Any thoughts or suggestions for a better regex?

Thanks

答:
```<code>validates_format_of :email,
  :with => /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i
</code>```

Don't ask me to explain it! That was from a validation plugin that I've since lost track of as all I needed was the email regex.

Title: rails - REGEX for email validation

Body:
I'm looking for a regex to validate an email to learn if it's valid or not.. I have the following:

def is_a_valid_email?(email)
    email_regex = %r{
      ^ # Start of string
      [0-9a-z] # First character
      [0-9a-z.+]+ # Middle characters
      [0-9a-z] # Last character
      @ # Separating @ character
      [0-9a-z] # Domain name begin
      [0-9a-z.-]+ # Domain name middle
      [0-9a-z] # Domain name end
      $ # End of string
    }xi # Case insensitive

    (email =~ email_regex)
end

Problem with the above is XXX_XXX@Xxx.com does not return as valid when it should be. Any thoughts or suggestions for a better regex?

Thanks

Body:
validates_format_of :email,
  :with => /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i

Don't ask me to explain it! That was from a validation plugin that I've since lost track of as all I needed was the email regex.


问:
How do I set state in React when there is no class or constructor?
I'm looking at the default demo React code in https://codesandbox.io/s/new, which comes out like this:

```<code>import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

const App = () => <Hello name="CodeSandbox" />;

render(<App />, document.getElementById('root'));
</code>```

This is different than many of the other examples I've seen, which usually have something more like:

```<code>class Layout extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...};
  }
  render() {...}
}
</code>```

Since the codesandbox example doesn't have a class or a constructor, I don't have a place to put this.state. So how and where would I add a state?

答:
App is a stateless component.

You can just convert App to a class if you want to have state.

For example:

```<code>import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...};
  }
  render() {
    return <Hello name="CodeSandbox" />;
  }
}

render(<App />, document.getElementById('root'));
</code>```

This is an article which might help:
https://code.tutsplus.com/tutorials/stateful-vs-stateless-functional-components-in-react--cms-29541

There is a section titled Class Components vs. Functional Components

Body:
I'm looking at the default demo React code in https://codesandbox.io/s/new, which comes out like this:

import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

const App = () => <Hello name="CodeSandbox" />;

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

This is different than many of the other examples I've seen, which usually have something more like:

class Layout extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...};
  }
  render() {...}
}

Since the codesandbox example doesn't have a class or a constructor, I don't have a place to put this.state. So how and where would I add a state?

Body:
App is a stateless component.

You can just convert App to a class if you want to have state.

For example:

import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...};
  }
  render() {
    return <Hello name="CodeSandbox" />;
  }
}

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

This is an article which might help:
https://code.tutsplus.com/tutorials/stateful-vs-stateless-functional-components-in-react--cms-29541

There is a section titled Class Components vs. Functional Components


问:
THREEJS how do you rotate around an objects local axis
I am having a hard time understanding how the local axis rotation works in ThreeJS. I saw this Rotate around local axis answer and it is not working quite the way I expected.

If I create a a cylinder and rotate it

```<code>const geometry = new THREE.CylinderBufferGeometry( 10, 10, 20 );
geometry.rotateX(Math.PI/2)
</code>```

How do I then rotate the cylinder along its long axis?

I expect this to do the job: geometry.rotateY(Math.PI/5) but that appears to be rotating it around the world axis. I want to just rotate it around the local axis to make it look the same as if I had done

```<code>geometry.rotateY(Math.PI/5)
geometry.rotateX(Math.PI/2)
</code>```

Can anyone help explain how to rotate around the objects internal axis?

What actually happens:
https://jsfiddle.net/h20hnn3n/46/

What I want it to look like:
https://jsfiddle.net/81j6g2ms/1/

My use case requires me to rotate around the X and arbitrary amount first and then I need to rotate around the old Y axis, so it would be great if I could do it in this order

Edit:
It appears that it matters whether you rotate the geometry vs a mesh. Shouldn't it be equivalent to do it either way?

I'm really confused why this doesn't act the same way: https://jsfiddle.net/10L8se71/2/

答:
In case anyone else runs into this I'll post a solution.

Rotating a geometry works differently than rotating a mesh. So you need to add it to a mesh first. The following ends up with the right result:

```<code>const mesh = new THREE.Mesh( geometry, material ) ;
mesh.rotateX(Math.PI/2)
mesh.rotateY(Math.PI/5)
</code>```

Body:
I am having a hard time understanding how the local axis rotation works in ThreeJS. I saw this Rotate around local axis answer and it is not working quite the way I expected.

If I create a a cylinder and rotate it

const geometry = new THREE.CylinderBufferGeometry( 10, 10, 20 );
geometry.rotateX(Math.PI/2)

How do I then rotate the cylinder along its long axis?

I expect this to do the job: geometry.rotateY(Math.PI/5) but that appears to be rotating it around the world axis. I want to just rotate it around the local axis to make it look the same as if I had done

geometry.rotateY(Math.PI/5)
geometry.rotateX(Math.PI/2)

Can anyone help explain how to rotate around the objects internal axis?

What actually happens:
https://jsfiddle.net/h20hnn3n/46/

What I want it to look like:
https://jsfiddle.net/81j6g2ms/1/

My use case requires me to rotate around the X and arbitrary amount first and then I need to rotate around the old Y axis, so it would be great if I could do it in this order

Edit:
It appears that it matters whether you rotate the geometry vs a mesh. Shouldn't it be equivalent to do it either way?

I'm really confused why this doesn't act the same way: https://jsfiddle.net/10L8se71/2/

Body:
In case anyone else runs into this I'll post a solution.

Rotating a geometry works differently than rotating a mesh. So you need to add it to a mesh first. The following ends up with the right result:

const mesh = new THREE.Mesh( geometry, material ) ;
mesh.rotateX(Math.PI/2)
mesh.rotateY(Math.PI/5)


问:
No module named pandas_datareader
I have just installed pandas_datareader using pip install pandas-datareader which ran successfully.

Now I am trying to use it for a tutorial and I am getting this error when I try to import.

```<code>    import pandas_datareader as pdr

ModuleNotFoundError: No module named 'pandas_datareader'
</code>```

This is the link to the tutorial.

https://www.datacamp.com/community/tutorials/finance-python-trading#gs.DgsO1BY

Any ideas?

答: In your Anaconda Prompt, do this : pip install pandas_datareader

Title: No module named pandas_datareader

Body:
I have just installed pandas_datareader using pip install pandas-datareader which ran successfully.

Now I am trying to use it for a tutorial and I am getting this error when I try to import.

    import pandas_datareader as pdr

ModuleNotFoundError: No module named 'pandas_datareader'

This is the link to the tutorial.

https://www.datacamp.com/community/tutorials/finance-python-trading#gs.DgsO1BY

Any ideas?


问:
How do I use Key-Value Coding in Swfit 4.0?
I never used Swift4 before, and dont know how to use KVC in it.

I try to create model with Dictionary, here the code:

```<code>class Person : NSObject {
    var name: String = ""
    var age: Int = 0

    init(dict: [String : Any]) {
        super.init()
        self.setValuesForKeys(dict)
    }
}

let dict: [String : Any] = ["name" : "Leon", "age" : 18]
let p = Person(dict: dict)
print(p.name, p.age)
</code>```

There I get two question:

1. Why dont I using AnyObject? "Leon"and18 was infer to String and Int, does it using in KVC?

2. @objc var name: String = "" , this form is worked, but I can not understand it.

Thanks for all helps.

答:
To implement KVC support for a property in Swift 4, you need two things:

Since the current implementation of KVC is written in Objective-C, you need the @objc annotation on your property so that Objective-C can see it. This also means that the property's type needs to be compatible with Objective-C.

In addition to exposing the property to Objective-C, you will need to set up your notifications in order for observers to be notified when the property changes. There are three ways to do this:

For stored properties, the easiest thing to do is to add the dynamic keyword like so:

```<code>@objc dynamic var foo: String
</code>```

This will allow Cocoa to use Objective-C magic to automagically generate the needed notifications for you, and is usually what you want. However, if you need finer control, you can also write the notification code manually:

```<code>@objc private static let automaticallyNotifiesObserversOfFoo = false
@objc var foo: String {
    willSet { self.willChangeValue(for: \.foo) }
    didSet { self.didChangeValue(for: \.foo) }
}
</code>```

The automaticallyNotifiesObserversOf<property name> property is there to signify to the KVC/KVO system that we are handling the notifications ourselves and that Cocoa shouldn't try to generate them for us.

Finally, if your property is not stored, but rather depends on some other property or properties, you need to implement a keyPathsForValuesAffecting<your property name here> method like so:

```<code>@objc dynamic var foo: Int
@objc dynamic var bar: Int

@objc private static let keyPathsForValuesAffectingBaz: Set<String> = [
    #keyPath(foo), #keyPath(bar)
]
@objc var baz: Int { return self.foo + self.bar }
</code>```

In the example above, an observer of the baz property will be notified when the value for foo or the value for bar changes.

Body:
I never used Swift4 before, and dont know how to use KVC in it.

I try to create model with Dictionary, here the code:

class Person : NSObject {
    var name: String = ""
    var age: Int = 0

    init(dict: [String : Any]) {
        super.init()
        self.setValuesForKeys(dict)
    }
}

let dict: [String : Any] = ["name" : "Leon", "age" : 18]
let p = Person(dict: dict)
print(p.name, p.age)

There I get two question:

1. Why dont I using AnyObject? "Leon"and18 was infer to String and Int, does it using in KVC?

2. @objc var name: String = "" , this form is worked, but I can not understand it.

Thanks for all helps.

Body:
To implement KVC support for a property in Swift 4, you need two things:

Since the current implementation of KVC is written in Objective-C, you need the @objc annotation on your property so that Objective-C can see it. This also means that the property's type needs to be compatible with Objective-C.

In addition to exposing the property to Objective-C, you will need to set up your notifications in order for observers to be notified when the property changes. There are three ways to do this:

For stored properties, the easiest thing to do is to add the dynamic keyword like so:

@objc dynamic var foo: String

This will allow Cocoa to use Objective-C magic to automagically generate the needed notifications for you, and is usually what you want. However, if you need finer control, you can also write the notification code manually:

@objc private static let automaticallyNotifiesObserversOfFoo = false
@objc var foo: String {
    willSet { self.willChangeValue(for: \.foo) }
    didSet { self.didChangeValue(for: \.foo) }
}

The automaticallyNotifiesObserversOf<property name> property is there to signify to the KVC/KVO system that we are handling the notifications ourselves and that Cocoa shouldn't try to generate them for us.

Finally, if your property is not stored, but rather depends on some other property or properties, you need to implement a keyPathsForValuesAffecting<your property name here> method like so:

@objc dynamic var foo: Int
@objc dynamic var bar: Int

@objc private static let keyPathsForValuesAffectingBaz: Set<String> = [
    #keyPath(foo), #keyPath(bar)
]
@objc var baz: Int { return self.foo + self.bar }

In the example above, an observer of the baz property will be notified when the value for foo or the value for bar changes.


问:
Issues with queryset and slicing
I have 2 models, Company and Product, with Product having a ForeignKey to Company

```<code>class Product(Meta):
    company = models.ForeignKey(
        Company,
        related_name='products',
        on_delete=models.CASCADE
    )
</code>```

I do the following filtering:

```<code> company = Company.objects.filter(account=account, pk=company_pk)
        if not company:
            raise Http404
        product = Product.objects.filter(company=company, pk=product_pk)
        if not product:
            raise Http404
        return product
</code>```

And I have the following error:

```<code>The QuerySet value for an exact lookup must be limited to one result using slicing.
</code>```

company_pk and product_pk are just variables.  If I remove the Product filter there is no error.

I presume it happens because company result is a QuerySet and is pushed as argument in Product.objects.filter

答:
Company is a queryset. You might want to do

```<code>Product.objects.filter(company=company[0], pk=product_pk)
</code>```

Or better yet you can use the relations in the ORM to simplify into 1 lookup.

```<code>Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk)
</code>```

Title: Issues with queryset and slicing

Body:
I have 2 models, Company and Product, with Product having a ForeignKey to Company

class Product(Meta):
    company = models.ForeignKey(
        Company,
        related_name='products',
        on_delete=models.CASCADE
    )

I do the following filtering:

 company = Company.objects.filter(account=account, pk=company_pk)
        if not company:
            raise Http404
        product = Product.objects.filter(company=company, pk=product_pk)
        if not product:
            raise Http404
        return product

And I have the following error:

The QuerySet value for an exact lookup must be limited to one result using slicing.

company_pk and product_pk are just variables.  If I remove the Product filter there is no error.

I presume it happens because company result is a QuerySet and is pushed as argument in Product.objects.filter

Body:
Company is a queryset. You might want to do

Product.objects.filter(company=company[0], pk=product_pk)

Or better yet you can use the relations in the ORM to simplify into 1 lookup.

Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk)


问:
Google+ People Search API returns no items
Is google+ people search deprecated?

I'm using the Try this API from their page
https://developers.google.com/+/web/api/rest/latest/people/search

and keep getting no items for different queries

```<code>{
 "kind": "plus#peopleFeed",
 "etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/K-_p8YwZl_F9FBOVSt8JEHLSg9Y\"",
 "selfLink": "https://content.googleapis.com/plus/v1/people?
     query=jane%20smith&key=[mykey]",
 "title": "Google+ People Search Results",
 "nextPageToken": "",
  "items": []
}
</code>```

答: yes, this broke in the past day or two, after working for years. </p>

Body:
Is google+ people search deprecated?

I'm using the Try this API from their page
https://developers.google.com/+/web/api/rest/latest/people/search

and keep getting no items for different queries

{
 "kind": "plus#peopleFeed",
 "etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/K-_p8YwZl_F9FBOVSt8JEHLSg9Y\"",
 "selfLink": "https://content.googleapis.com/plus/v1/people?
     query=jane%20smith&key=[mykey]",
 "title": "Google+ People Search Results",
 "nextPageToken": "",
  "items": []
}


问:
Like button with Ajax
I am trying to create a like button with ajax.

This is my architecture:

models.py

```<code>class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    texto = models.CharField(max_length=200)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    fecha_publicacion = models.DateTimeField(auto_now_add=True)
    tag = models.ManyToManyField(Tags, blank=True)
    slug = models.SlugField(null=True)
    likes = models.ManyToManyField(Perfil, blank=True, related_name="likes")

    def __str__(self):
        return (self.titulo)

    @property
    def total_likes(self):
        return self.likes.count()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.titulo)
        super(Comentario, self).save(*args, **kwargs)
</code>```

views.py

```<code>def like(request):
    if request.method == 'POST':
        perfil = request.user
        slug = request.POST.get('slug', None)
        comentario = get_object_or_404(Comentario, slug=slug)

        if comentario.objects.filter(id=user.id).exists():
            comentario.likes.remove(user)

        else:
            comentario.likes.add(user)

    contexto = {'likes_count': comentario.total_likes }
    return HttpResponse(json.dumps(contexto), content_type='application/json')
</code>```

urls.py

```<code>url(r'^like$', login_required(like), name='like'),
</code>```

html

```<code><input type="button" id="like" name="{{ company_slug }}" value="Like" />
<script>
$('#like').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'home:like' %}",
               data: {'slug': $(this).attr('titulo'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert(' likes count is now ' + response.likes_count);
            },
                error: function(rs, e) {
                       alert(rs.responseText);
            }
      });
})
</script>
</code>```

When I push the button like it does not do anything. The console tells me:

POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found)

and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

What is the problem?

答:
#1

As I can see you use jquery-3.2.1.slim.min.js. This (slim) version excludes ajax module!

https://blog.jquery.com/2017/03/16/jquery-3-2-0-is-out/

Slim build

Sometimes you don’t need ajax, or you prefer to use one of the many
  standalone libraries that focus on ajax requests. And often it is
  simpler to use a combination of CSS and class manipulation for all
  your web animations. Along with the regular version of jQuery that
  includes the ajax and effects modules, we’ve released a “slim” version
  that excludes these modules.

#2

You use wrong url as I can see.
In your html part it's {% url 'home:listar' %}, given urls.py contains only name='like'

Title: Like button with Ajax

Body:
I am trying to create a like button with ajax.

This is my architecture:

models.py

class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    texto = models.CharField(max_length=200)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    fecha_publicacion = models.DateTimeField(auto_now_add=True)
    tag = models.ManyToManyField(Tags, blank=True)
    slug = models.SlugField(null=True)
    likes = models.ManyToManyField(Perfil, blank=True, related_name="likes")

    def __str__(self):
        return (self.titulo)

    @property
    def total_likes(self):
        return self.likes.count()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.titulo)
        super(Comentario, self).save(*args, **kwargs)

views.py

def like(request):
    if request.method == 'POST':
        perfil = request.user
        slug = request.POST.get('slug', None)
        comentario = get_object_or_404(Comentario, slug=slug)

        if comentario.objects.filter(id=user.id).exists():
            comentario.likes.remove(user)

        else:
            comentario.likes.add(user)

    contexto = {'likes_count': comentario.total_likes }
    return HttpResponse(json.dumps(contexto), content_type='application/json')

urls.py

url(r'^like$', login_required(like), name='like'),

html

<input type="button" id="like" name="{{ company_slug }}" value="Like" />

When I push the button like it does not do anything. The console tells me:

POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found)

and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

What is the problem?


问:
What is the animated style on the new imac pro page called?
I would like to create a webpage that replcates the animation that takes place on the apple imac pro page.

What is this type of animation called?
Can this be done using HTML5 and CSS3 only?

https://www.apple.com/uk/imac-pro/?afid=p238%7CsQ4bjRw3L-dc_mtid_20925wi539930_pcrid_198758187038_&cid=wwa-uk-kwgo-mac-bran-imac+pro-e-slid--productid-

答:
The top of the site looks like Image sprites (you can also do something similar with playing a video when you scroll)
see this: https://codepen.io/ollieRogers/pen/lfeLc/

```<code>function scrollPlay(){
  var frameNumber  = window.pageYOffset/playbackConst;
  vid.currentTime  = frameNumber;
  window.requestAnimationFrame(scrollPlay);
}

window.requestAnimationFrame(scrollPlay);
</code>```

I had to add some of the code so I could post the codepen link above...

The rest of the site "style" is similar to parallax scrolling see these:
https://ihatetomatoes.net/demos/simple-parallax-scrolling-tutorial/
https://ihatetomatoes.net/demos/parallax-scroll-effect/

Body:
The top of the site looks like Image sprites (you can also do something similar with playing a video when you scroll)
see this: https://codepen.io/ollieRogers/pen/lfeLc/

function scrollPlay(){
  var frameNumber  = window.pageYOffset/playbackConst;
  vid.currentTime  = frameNumber;
  window.requestAnimationFrame(scrollPlay);
}

window.requestAnimationFrame(scrollPlay);

I had to add some of the code so I could post the codepen link above...

The rest of the site "style" is similar to parallax scrolling see these:
https://ihatetomatoes.net/demos/simple-parallax-scrolling-tutorial/
https://ihatetomatoes.net/demos/parallax-scroll-effect/


答:
My shot at this (see comment and link above):</p>
```<code>^.+@.+$
</code>```

Title: rails - REGEX for email validation

Body:
My shot at this (see comment and link above):

^.+@.+$


问:
how to manipulate string column of numbers separated by dots using t-sql
I have a column of nvarchar(255) type that represents software version
numbers:

```<code>  VersionNumber
 ---------------

    1.0.0.505
    1.0.0.506
    1.0.0.507
    1.0.0.508
    1.0.0.509
    1.0.1.2
</code>```

I need to extract the maximum version number (the min version number in the example above is 1.0.0.505 and the max version number is 1.0.1.2, values arranged from the smallest to the highest).

in order to explain exactly what i need - if i could use imperative programming language i think i would do something like that to detect the max version number:

lets say version number is d.c.b.a.

i would separate each version number to four different variables: a b
c d

that i will sum each series.

a will be summed by tens

b will be summed by hundreds

c will be summed by thousands

d will be summed by milions

than the maximum total sum of each Max(a+b+c+d) will be the max version.

but what is the technic to achieve something like that in sql?

答:
for future readers: based on @AlexK. link that is the solution:

select TOP 1 VersionNumber from Users order by (cast('/' + replace(VersionNumber , '.', '/') + '/' as hierarchyid)) DESC;

Body:
I have a column of nvarchar(255) type that represents software version
numbers:

  VersionNumber
 ---------------

    1.0.0.505
    1.0.0.506
    1.0.0.507
    1.0.0.508
    1.0.0.509
    1.0.1.2

I need to extract the maximum version number (the min version number in the example above is 1.0.0.505 and the max version number is 1.0.1.2, values arranged from the smallest to the highest).

in order to explain exactly what i need - if i could use imperative programming language i think i would do something like that to detect the max version number:

lets say version number is d.c.b.a.

i would separate each version number to four different variables: a b
c d

that i will sum each series.

a will be summed by tens

b will be summed by hundreds

c will be summed by thousands

d will be summed by milions

than the maximum total sum of each Max(a+b+c+d) will be the max version.

but what is the technic to achieve something like that in sql?


问:
Purpose of assert in NodeJS
I'm new to nodejs, I follow all the steps in the documentation. First I study and test the assert function of node, I just want to know what is the purpose of using assert? if no error there's no output, but if you have an error, there's an output saying AssertError etc.

I want to know, when and what is the purpose of using assert?

答:
In any programming language errors are an issue. Whether by human error or poor design. The assert module in node.js is used to test the behavior of a function and reduce the creation of "buggy" code, this also promotes design thinking.

In most cases assertions are used in unit testing. This takes a unit of code, be it a function, method etc and runs multiple tests on it. These test the value that a function generates(actual) vs what we expect the function to provide.

An example of assertions:

```<code>"use strict";

//Run the code and change the values of x and y (to equal 42) to test the assert module.
const x = 18;
const y = 20;

//We have to import our assert module
var assert = require("assert");

//Calculates the anser to life (42)
var life = function(a,b){
    return a + b;
 };

//Overwrite the variable of result to equal the return.
result = life(x,y);

//Change the comments below to see the difference between the two values
assert.deepEqual(result, 42);
//assert.fail(result, 42, "", '<');
</code>```

From a technical point of view, developers should write their tests before they start to write their code. This is a form of top-down development strategy, which allows developers to understand the functional requirements of the software. Therefore when writing your assertions you obtain the parameters you require and what results you expect. Thus making the logic the only hurdle.

Title: Purpose of assert in NodeJS

Body:
In any programming language errors are an issue. Whether by human error or poor design. The assert module in node.js is used to test the behavior of a function and reduce the creation of "buggy" code, this also promotes design thinking.

In most cases assertions are used in unit testing. This takes a unit of code, be it a function, method etc and runs multiple tests on it. These test the value that a function generates(actual) vs what we expect the function to provide.

An example of assertions:

"use strict";

//Run the code and change the values of x and y (to equal 42) to test the assert module.
const x = 18;
const y = 20;

//We have to import our assert module
var assert = require("assert");

//Calculates the anser to life (42)
var life = function(a,b){
    return a + b;
 };

//Overwrite the variable of result to equal the return.
result = life(x,y);

//Change the comments below to see the difference between the two values
assert.deepEqual(result, 42);
//assert.fail(result, 42, "", '<');

From a technical point of view, developers should write their tests before they start to write their code. This is a form of top-down development strategy, which allows developers to understand the functional requirements of the software. Therefore when writing your assertions you obtain the parameters you require and what results you expect. Thus making the logic the only hurdle.


问:
How do i reverse each character in a string?
```<code>class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}
</code>```

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

答:
First, you skip over index 0. Put these lines at the end of your method to avoid this:

```<code>count++;
current = count;
</code>```

You might need a variable to track where the current word began. For example, declare one along with count and current like this:

```<code>int wordStart = 0;
</code>```

Then, when you finish processing a word, set wordStart to point to the first character of the next word. I would put that after the while loop, here:

```<code>build.append(s.charAt(i));
wordStart = count + 1;
</code>```

You will also need to change this: while(current > 0){ to this: while(current >= wordStart)

Also: you don't need count. The variable i is the exact same thing.

Body:
class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

Body:
First, you skip over index 0. Put these lines at the end of your method to avoid this:

count++;
current = count;

You might need a variable to track where the current word began. For example, declare one along with count and current like this:

int wordStart = 0;

Then, when you finish processing a word, set wordStart to point to the first character of the next word. I would put that after the while loop, here:

build.append(s.charAt(i));
wordStart = count + 1;

You will also need to change this: while(current > 0){ to this: while(current >= wordStart)

Also: you don't need count. The variable i is the exact same thing.


问:
Using jQuery, window.resize Event is not triggered?
GOAL: dynamically change height of each division element so that opposing elements in adjacent columns align horizontally -- like UL LI LI, but without the actual list.

If the window is super wide, each item may only have 1 line; but with window shrinkage, each item may have a unique line count; e.g.

```<code>item 1      item 2
  1 line      2 lines

item 3       item 4
  3 lines      1 line
</code>```

My desired result is to adjust all items to 3 lines tall via

```<code>$(window).on('resize', function() { ...});
</code>```

However, this window.resize Event is not triggered?

WHY?

HTML:

```<code><div class="parent">
    <div class="column extraPaddingOnRight">
<a href="links/headstone.pdf">Nancy at Arlington National Cemetery</a><p>
    </div>
</div>
<!-- other DIV links follow -->
</code>```

The CSS:

```<code>.extraPaddingOnRight {
    padding-right: 1.5em;
}

.column {
    float: left;
    /* Theoretically 50%, but less because of extraPaddingOnRight */
    width: 40%;
}
</code>```

JS:

```<code>$(document).ready(function() {

    function resizer() {
        var $maxItemHeight = 0, $thisItemHeight;

        $('div.column a').each(function() {
            $thisItemHeight = $(this).height();
            if ($thisItemHeight > $maxItemHeight)
                $maxItemHeight = $thisItemHeight;
        });

        $('div.column a').each(function() {
            $(this).css( {
                height: $maxItemHeight + 'px';
            });
        });
    }

    $(window).on('resize', function() {
    /*
        alert('ok');   // not triggered?
    */
        resizer;
    });
});
</code>```

答:
Here was my problem ... took too many stupid pills ...

```<code>$(document).ready(function() {

    $(window).resize(function() {
        resizer();
    });

 /*
    $(window).on('resize', function() {   // does not work!
        resizer();
    });
 */

 /*
    $(window).on('resize', resizer);       // does not work either!
 */

})
</code>```

Together with the suggested removal of the semi-colon coupled with a very very dumb error with my HTML Markup ...

Body:
GOAL: dynamically change height of each division element so that opposing elements in adjacent columns align horizontally -- like UL LI LI, but without the actual list.

If the window is super wide, each item may only have 1 line; but with window shrinkage, each item may have a unique line count; e.g.

item 1      item 2
  1 line      2 lines

item 3       item 4
  3 lines      1 line

My desired result is to adjust all items to 3 lines tall via

$(window).on('resize', function() { ...});

However, this window.resize Event is not triggered?

WHY?

HTML:

Nancy at Arlington National Cemetery

The CSS:

.extraPaddingOnRight {
    padding-right: 1.5em;
}

.column {
    float: left;
    /* Theoretically 50%, but less because of extraPaddingOnRight */
    width: 40%;
}

JS:

$(document).ready(function() {

    function resizer() {
        var $maxItemHeight = 0, $thisItemHeight;

        $('div.column a').each(function() {
            $thisItemHeight = $(this).height();
            if ($thisItemHeight > $maxItemHeight)
                $maxItemHeight = $thisItemHeight;
        });

        $('div.column a').each(function() {
            $(this).css( {
                height: $maxItemHeight + 'px';
            });
        });
    }

    $(window).on('resize', function() {
    /*
        alert('ok');   // not triggered?
    */
        resizer;
    });
});

Body:
Here was my problem ... took too many stupid pills ...

$(document).ready(function() {

    $(window).resize(function() {
        resizer();
    });

 /*
    $(window).on('resize', function() {   // does not work!
        resizer();
    });
 */

 /*
    $(window).on('resize', resizer);       // does not work either!
 */

})

Together with the suggested removal of the semi-colon coupled with a very very dumb error with my HTML Markup ...