text:
Q: Solr - Facing issue in matching dates I am facing an issue in solr. I am not able to match dates
I am working in solr 5.5
Below is the part of my schema
  <!--Application fields -->
  <fieldType name="long_field" class="solr.TrieLongField"/>
  <fieldType name="timestamp_field" class="solr.TrieDateField"/>
  <fieldType name="string_field" class="solr.StrField"/>
  <fieldType name="text_field" class="solr.TextField"/>

  <field name="tweet_id" type="long_field" indexed="false" stored="false"/>
  <field name="unixtime" type="string_field" indexed="false" stored="false"/>
  <field name="timestamp" type="timestamp_field" indexed="false" stored="true"/>
  <field name="lang" type="string_field" indexed="false" stored="true"/>
  <field name="user" type="text_field" indexed="false" stored="true"/>
  <field name="timezone" type="text_field" indexed="false" stored="true"/>
  <field name="tweet_text" type="text_field" indexed="false" stored="true"/>
  <!--Application fields -->

This is the sample data when I give the query
http://172.28.128.3:8983/solr/tweets_shard1_replica1/select?q=id:75bfb093-033c-41fa-8712-814f17da7c54

<response>
<lst name="responseHeader">
<int name="status">0</int>
<int name="QTime">7</int>
<lst name="params">
<str name="q">id:75bfb093-033c-41fa-8712-814f17da7c54</str>
</lst>
</lst>
<result name="response" numFound="1" start="0">
<doc>
<date name="timestamp">2014-12-31T21:03:06Z</date>
<str name="lang">und</str>
<str name="timezone">Eastern Time (US & Canada)</str>
<str name="user">startup_owner11</str>
<str name="tweet_text">Wow! $GOOG is going down today #BigData</str>
<str name="id">75bfb093-033c-41fa-8712-814f17da7c54</str>
<long name="_version_">1558697655805149184</long>
</doc>
</result>
</response>

Now when I give the below query. I am getting an error
http://172.28.128.3:8983/solr/tweets_shard1_replica1/select?q=*:*&fq=timestamp:2014-12-31T21:03:06Z

Below is the response from solr
<response>
<lst name="responseHeader">
<int name="status">400</int>
<int name="QTime">1</int>
<lst name="params">
<str name="q">*:*</str>
<str name="fq">timestamp:2014-12-31T21:03:06Z</str>
</lst>
</lst>
<lst name="error">
<lst name="metadata">
<str name="error-class">org.apache.solr.common.SolrException</str>
<str name="root-error-class">org.apache.solr.common.SolrException</str>
</lst>
<str name="msg">Invalid Date String:'2014-12-31T21'</str>
<int name="code">400</int>
</lst>
</response>

Please help

A: Two things you missed

*

*you should escape(:) while querying datefield.

timestamp:2014-12-31T21\:03\:06Z

*set index="true" for timestamp field.

<field name="timestamp" type="timestamp_field" indexed="true" stored="true"/>
reindex and run your query
http://172.28.128.3:8983/solr/tweets_shard1_replica1/select?q=*:*&fq=timestamp:2014-12-31T21\:03\:06Z

Hope this Helps,
vinod


text:
Q: How to print the name of checkboxes as they are checked? I'm making a task management tool and my app needs the capability of creating repeating tasks, so I'm trying to emulate Google Calendar's "repeating event" menu. This  one:

As you can see, when you check the boxes for the days of the week you want, the "Summary" field updates automatically with the days you have selected. How would I achieve this using AngularJS or JQuery?
The rest of the "Summary" options I did using ng-if, like this:

Weekly

 '1' && !recurrence_frequency && !recurrence_end">

Every {{recurrence_pattern}} weeks

Weekly, {{recurrence_frequency}} times

 '1' && recurrence_frequency && !recurrence_end">

Every {{recurrence_pattern}} weeks,
                                        {{recurrence_frequency}} times

Weekly, until {{recurrence_end}}

 '1' && !recurrence_frequency && recurrence_end">

Every {{recurrence_pattern}} weeks, until
                                        {{recurrence_end}}

Where:

*

*recurrence_pattern is the number of weeks;

*recurrence_frequency is the number of occurrences;

*recurrence_end is the end date.

I mean, I could do it like I've been doing so far, using ng-if, but I would have to make a ng-if for every single combination of checkboxes and I'd be here all day. I'm betting there's an easier way.
This is my code for the checkboxes:
Repeat on:

    <input type="checkbox" id="monday" title="Monday" value="Monday"> M

    <input type="checkbox" id="tuesday" title="Tuesday" value="Tuesday"> T

    <input type="checkbox" id="wednesday" title="Wednesday" value="Wednesday"> W

    <input type="checkbox" id="thursday" title="Thursday" value="Thursday"> T

    <input type="checkbox" id="friday" title="Friday" value="Friday"> F

    <input type="checkbox" id="saturday" title="Saturday" value="Saturday"> S

    <input type="checkbox" id="sunday" title="Sunday" value="Sunday"> S

Again, the technologies I'm using is JavaScript with AngularJS, but I also have JQuery available since I'm using Bootstrap 3.
Thank you.

A: You can loop through all checked checkboxes using $("input:checked").each() and then you get its value using .val()

var answer = $("#SelectedAnswer").val();
$("input:checked").each(function () {
  var id = $(this).val();
  console.log(id);
});

Repeat on:

    <input type="checkbox" id="monday" title="Monday" value="Monday" checked> M

    <input type="checkbox" id="tuesday" title="Tuesday" value="Tuesday"> T

    <input type="checkbox" id="wednesday" title="Wednesday" value="Wednesday" checked> W

    <input type="checkbox" id="thursday" title="Thursday" value="Thursday"> T

    <input type="checkbox" id="friday" title="Friday" value="Friday" checked> F

    <input type="checkbox" id="saturday" title="Saturday" value="Saturday"> S

    <input type="checkbox" id="sunday" title="Sunday" value="Sunday"> S

A: On click of checkbox you can get title of that checkbox.
<input type="checkbox" id="monday" title="Monday" value="Monday">

$scope.summary = "";
$("input:checked").each(function () {
  var title = $(this).attr("title");
  $scope.summary+= title;
});

A: Please have a look at below code. It uses jquery:

$(document).ready(function() {
  $(".checkbox-inline input[type=checkbox]").click(function() {
    var selectedDays = "";
    var tempArray = []
    $("input:checked").each(function() {
      var name = $(this).val();
      tempArray.push(name);
    });
    selectedDays = tempArray.join(",");

    $(".summary").text(selectedDays);
  });
});

Repeat on:

  <input type="checkbox" id="monday" title="Monday" value="Monday">M

  <input type="checkbox" id="tuesday" title="Tuesday" value="Tuesday">T

  <input type="checkbox" id="wednesday" title="Wednesday" value="Wednesday">W

  <input type="checkbox" id="thursday" title="Thursday" value="Thursday">T

  <input type="checkbox" id="friday" title="Friday" value="Friday">F

  <input type="checkbox" id="saturday" title="Saturday" value="Saturday">S

  <input type="checkbox" id="sunday" title="Sunday" value="Sunday">S

Summary:

A: You could use jQuery DOM selector :checked, but you should not. Because it's not really the "angular way" to do it.
What you want is something like this :

angular.module('app', [])

.controller('ctrl', function($scope) {
  $scope.values = [{
      value: 'test1'
  }, {
      value: 'test2'
  }, {
      value: 'test3'
  }];

  $scope.result = function() {
    return $scope.values.filter(function(el) { return el.checked; }).map(function(el) { return el.value; }).join(', ');
  }
});

<input type="checkbox" ng-model="value.checked">{{ value.value }}

      {{ result() }}

A: Click on checkbox you can get title of that checkbox.
  //in Controller
    $scope.CheckBoxes = [{
        value: 'CheckBox1'
    }, {
        value: 'CheckBox2'
    }, {
        value: 'CheckBox3'
    }];

    $scope.result = function () {
        return $scope.CheckBoxes.filter(function (el) { return el.checked;        }).map(function (el) { return el.value; }).join(', ');
    }

   // in View

<input type="checkbox" ng-model="value.checked">{{ value.value }}

    {{ result() }}

A: Have you thought about replacing your checkboxes with a bootstrap multiselect? http://davidstutz.github.io/bootstrap-multiselect/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Springboot- Error creating bean with name 'defaultValidator' I am creating a springboot program, and it was working earlier until I altered the SQL table and added a column skipMerge.
My entity class:
package com.chansoft.Entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.lang.NonNull;

import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = "files")
@Getter
@Setter
public class FilesEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "fileID")
    private Long fileID;

    @Column(name = "uploaded", columnDefinition = "tinyint(1)")
    @NonNull
    private boolean uploaded;

    @Column(name = "ocrCompleted", columnDefinition = "tinyint(1)")
    @NonNull
    private boolean ocrCompleted;

    @Column(name = "ocrDownloaded", columnDefinition = "tinyint(1)")
    @NonNull
    private boolean ocrDownloaded;

    @Column(name = "ocrIndexed", columnDefinition = "tinyint(1)")
    @NonNull
    private boolean ocrIndexed;

    @Column(name = "ocrJSONFileName", columnDefinition = "json")
    private String ocrJSONFileName;

    @Column(name = "fileDirectory", columnDefinition = "varchar(1000)")
    private String fileDirectory;

    @Column(name = "gcsDirectory", columnDefinition = "varchar(1000)")
    private String gcsDirectory;

    @Column(name = "isCombined", columnDefinition = "tinyint(1)")
    private boolean isCombined;

    @Column(name = "skipMerge", columnDefinition = "tinyint(1)")
    private boolean skipMerge;

}

My repository class:
    package com.chansoft.Repositories;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.chansoft.Entities.FilesEntity;

@RepositoryRestResource(exported = false)
public interface FilesRepository extends CrudRepository<FilesEntity, Long> {

    public List<FilesEntity> findByFileDirectoryIgnoreCase(String FileDirectory);

    public List<FilesEntity> findByUploaded(boolean Uploaded);

    public List<FilesEntity> findByIsCombinedAndSkipMerge(boolean IsCombined, boolean SkipMerge);
}

MySQL table:

Anyone have any clues? Its not missing a dependency since it was working earlier before, without the altered table. I tried commenting out the skipMerge part in the entity, repository, services and controllers to no avail.
Thanks!
Edit: I am getting this as my stacktrace:
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultValidator' defined in class path resource [org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: Receiver class org.hibernate.validator.engine.ConfigurationImpl does not define or inherit an implementation of the resolved method 'abstract javax.validation.ParameterNameProvider getDefaultParameterNameProvider()' of interface javax.validation.Configuration.
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.18.jar:5.3.18]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.18.jar:5.3.18]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.18.jar:5.3.18]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.18.jar:5.3.18]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.18.jar:5.3.18]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.18.jar:5.3.18]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.18.jar:5.3.18]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.18.jar:5.3.18]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.18.jar:5.3.18]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.18.jar:5.3.18]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.6.jar:2.6.6]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.6.jar:2.6.6]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.6.jar:2.6.6]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.6.jar:2.6.6]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.6.jar:2.6.6]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.6.jar:2.6.6]
        at com.chansoft.PdfOcrReaderApplication.main(PdfOcrReaderApplication.java:10) ~[classes/:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.6.6.jar:2.6.6]
    Caused by: java.lang.AbstractMethodError: Receiver class org.hibernate.validator.engine.ConfigurationImpl does not define or inherit an implementation of the resolved method 'abstract javax.validation.ParameterNameProvider getDefaultParameterNameProvider()' of interface javax.validation.Configuration.
        at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.configureParameterNameProvider(LocalValidatorFactoryBean.java:327) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:293) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.18.jar:5.3.18]
    ... 21 common frames omitted

A: The failure is unrelated to the change you made to your entity.
The exception indicates that the version of Hibernate Validator on your classpath is not compatible with the version of the Validation API that is on the classpath. Hibernate Validator is older than the API and does not implement getDefaultParameterNameProvider.
You can correct the problem by changing your build.gradle or pom.xml. With Spring Boot 2.6.6 you should be using Hibernate Validator    6.2.3.Final. If you are using Spring Boot's dependency management, you can remove the version in your build script and it will then use 6.2.3.Final automatically.


text:
Q: How to select the items that have an association with any user in Rails I have a relation between User and Hobby, the relation in User is has_and_belongs_to_many and the one for Hobby is also has_and_belongs_to_many.
I'm trying to get the list of Hobbies that Users have chosen. For example if one user selected Soccer and another selected Basketball, I want to have a query that shows me "Soccer, Basketball".
How can I do this join in a query? Right now I'm grabbing the hobbies for each User via User.find(id).hobbies

A: You could inner join hobbies with users to get all hobbies chosen by all users.
Hobby.joins(:users).uniq


text:
Q: Swapping a string where space is found in php I need to implement the following functionality:
I have a name field which contains both name and surname. This is stored in a database and is in the order 'surname name'.
I am implementing a script which searches through these records. Currently, I managed to check if a string contains a space, if it contains a space it means it is a name and not an ID Card Number for instance. Here is the code:
$query = "John Doe";

$checkIfSpaceExists = strpos($query, " ");

if ($checkIfSpaceExists == "")
{
    //No Space therefore it is not a name
}
else
{
    //Contains space
   $queryExploded = explode(" ", $query);
   foreach ($queryExploded as $q)
   {
      //Here I need the functionality so that if someone entered John Doe
      //2 different strings are saved, which are
      //$string1 = John Doe
      //$string2 = Doe Johns

      //If the name consists of 3 parts, strings for every combination is saved
}

Then I will insert these strings in an SQL statement with the LIKE attribute and there will be a LIKE for both JOHN DOE and DOE JOHN. Hence, if the user can either enter John Doe or Doe John in order to find the result.
Any suggestions on how to do this?
Many thanks
chris

A: Ok, from the start - be sure to read the manual carefully. strpos doesn't do exactly what you think it's doing. Here's how you should check for a space:
if (strpos($query, ' ') === false)  // the triple-equals is important!

After that, it's simply a matter of permutations and combinations. Here's another answer on Stack Overflow which shows you how to do it: algorithm that will take number or words and find all possible combinations

A: What about using these exploded 3 strings in separate AND-combined LIKE-constraints?
Something like
"... WHERE name LIKE '%$name[0]%' AND name LIKE '%$name[1]%' AND name LIKE '%$name[2]%'"

You could build this String in a foreach loop.

A: echo preg_replace('/^(\w+) (\w+)$/', '$2 $1', "John Doe");

Doe John

A: I guess you cannot split this field into name and surname? I suggest creating new table, tags in database. Tags will be any word - might be surname, may be name, may be ID number... Then make a connection record_tags with record_id and tag_id. Then the query will look like
SELECT record.* FROM record
INNER JOIN record_tags rt1 ON rt1.record_id = record.id
INNER JOIN tag t1 ON t1.id = rt1.tag_id
INNER JOIN record_tags rt2 ON rt2.record_id = record.id
INNER JOIN tag t2 ON t2.id = rt2.tag_id
WHERE
t1.name = "John"
AND t2.name = "Doe"

This will be better approach to searching, as you can then use any amount of words/tags. I think the SQL can be even easier. the multiple-like approach is I think much slower, especially as your database grows.

A: With some looping and string manipulation, I managed to implement this script.
Here is what I did:
I checked if the query contains a space using strpos. If it contains a space, then it means its a name with both name and surname so I enter a loop in order to output one string with 'name surname' and the other string with 'surname name'
Here is the code:
   $like = ""; //This is the LIKE sql command.
   foreach ($selectedFields as $field)
   {
            $checkIfSpaceExists = strpos($query," ");

    if ($checkIfSpaceExists != "")
    {
        $query1 = $query; //No space, so query1 is equal ta original query

        $queryExploded = explode(" ", $query);

        for ($i=0; $i<count($queryExploded); $i++) //First loop (name surname)
        {
            $tmp1 = $tmp1 . " " . $queryExploded[$i];
        }

        for ($i=count($queryExploded); $i>=0; $i--) //Second loop (surname name)
        {
            $tmp2 = $tmp2 . " " . $queryExploded[$i];

        }
        $query2 = $tmp2;
        $query2 = trim($query2);

        $like = $like . $field . " LIKE '%" . $query1 . "%' or " . $field . " LIKE '%" . $query2 . "%' or ";

I hope this helps someone else in need :)


text:
Q: How to pass epoch timestamp in each requests of Gatling script dynamically I have to pass current epoch timestamp in below "request_1" and "request_2" dynamically. How can I achieve this. Below are just few requests given, actually there are many requests in scripts.
Here all requests should have current timestamp only. So each requests will have different different timestamp.
Is there any function so that I can replace all timestamp directly without replacing one by one.
  val Transaction_Name_1 = group("Transaction_Name_1")
  {
      exec(http("request_1")
        .get("/abc/details1?_=1590748529401"))
      .pause(5)
      .exec(http("request_2")
        .get("/abc/details1?_=1590748535534"))
  }

A: There's no way to magically do this everywhere. You have to replace each occurrence.
As of Gatling 3.3.1 (current version as of now), the easiest way is to do:
val Transaction_Name_1 = group("Transaction_Name_1") {
  exec(http("request_1")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis()))
  .pause(5)
  .exec(http("request_2")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis()))
}

In Gatling 3.4.0, we'll be introducing a new Gatling EL feature so you will be able to write:
val Transaction_Name_1 = group("Transaction_Name_1") {
  exec(http("request_1")
    .get("/abc/details1?_=${currentTimeMillis()}")
  .pause(5)
  .exec(http("request_2")
    .get("/abc/details1?_=${currentTimeMillis()}"))
}


text:
Q: Rails 3 , help with setting up a config for a controller I have the resource photos
Currently I have this working: /photos
which shows the photos#index controller which is what I want...
But now I want to also have /projects/2/photos
Which should show photos for that project. Problem is that is pointing to the def index, and somehow I need a separate view for this path.
Thoughts? Thanks
routes:
resources :projects do
  resources :photos,do
  collection do
    get 'newjs'
  end
end

A: In the PhotosController#index action you can check to see if params[:project_id] is defined -- if it is then you are using the sub-resource. If it is not, you are using the top-level resource.


text:
Q: Using regexp to validate a date using DD-Mon-YYYY format Hello I am trying to validate a date in the format:
03-Mar-2011 or 12-Dec-2007. I currently have a regexp that fails on the 3 character Month. I probably just need to tweak that to get it to work properly.
    //function isDate(txtDate) {
    function isDate(sender, args) {
        var currVal = document.getElementById('<%=txtChange_Date.ClientID%>').value;

            if (currVal == '')
                return false;

            //Declare Regex
            var rxDatePattern = /^(\d{1,2})(\/|-)[a-zA-Z]{3}(\/|-)(\d{4})$/;

            var dtArray = currVal.match(rxDatePattern); // is format OK?

            if (dtArray == null)
                return false;

            //formerly //Checks for dd/mm/yyyy format.
            //Checks for dd-MMM-yyyy format.
            var dtDay = dtArray[1];
            var dtMonth = dtArray[3];
            var dtYear = dtArray[4];

            switch(dtMonth)
            {
                case 'Jan':
                    dtMonth = '01';
                    break;
                case 'Feb':
                    dtMonth = '02';
                    break;
                case 'Mar':
                    dtMonth = '03';
                    break;
                case 'Apr':
                    dtMonth = '04';
                    break;
                case 'May':
                    dtMonth = '05';
                    break;
                case 'Jun':
                    dtMonth = '06';
                    break;
                case 'Jul':
                    dtMonth = '07';
                    break;
                case 'Aug':
                    dtMonth = '08';
                    break;
                case 'Sep':
                    dtMonth = '09';
                    break;
                case 'Oct':
                    dtMonth = '10';
                    break;
                case 'Nov':
                    dtMonth = '11';
                    break;
                case 'Dec':
                    dtMonth = '12';
                    break;
            }

if (dtMonth < 1 || dtMonth > 12)
                return false;
else if (dtDay < 1 || dtDay > 31)
                return false;
else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31)
                return false;
else if (dtMonth == 2) {
            var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
                if (dtDay > 29 || (dtDay == 29 && !isleap))
                    return false;
            }

            return true;
        }

A: There were a few problems with your code, but your regular expression was fine except that month wasn't being grouped.
Other Changes

*

*The switch that converts the month needed to have dtMonth converted to lower case and the case statements needed to match the case.

*I explicitly converted the date parts to integers with parseInt.  I don't know if it was an issue with dtDay or dtYear, but it was causing an issue with dtMonth.

*With the parseInt change I added a not a number check and dtMonth.

*I also moved the validator out of the event handler.  Just a good practice to follow if the validation isn't trivial.

Code
function isDate(currVal) {
    if (currVal == '') return false;

    //Declare Regex
    var rxDatePattern = /^(\d{1,2})(\/|-)([a-zA-Z]{3})(\/|-)(\d{4})$/;

    var dtArray = currVal.match(rxDatePattern); // is format OK?

    if (dtArray == null) return false;

    var dtDay = parseInt(dtArray[1]);
    var dtMonth = dtArray[3];
    var dtYear = parseInt(dtArray[4]);

    // need to change to lowerCase because switch is
    // case sensitive
    switch (dtMonth.toLowerCase()) {
        case 'jan':
            dtMonth = '01';
            break;
        case 'feb':
            dtMonth = '02';
            break;
        case 'mar':
            dtMonth = '03';
            break;
        case 'apr':
            dtMonth = '04';
            break;
        case 'may':
            dtMonth = '05';
            break;
        case 'jun':
            dtMonth = '06';
            break;
        case 'jul':
            dtMonth = '07';
            break;
        case 'aug':
            dtMonth = '08';
            break;
        case 'sep':
            dtMonth = '09';
            break;
        case 'oct':
            dtMonth = '10';
            break;
        case 'nov':
            dtMonth = '11';
            break;
        case 'dec':
            dtMonth = '12';
            break;
    }

    // convert date to number
    dtMonth = parseInt(dtMonth);

    if (isNaN(dtMonth)) return false;
    else if (dtMonth < 1 || dtMonth > 12) return false;
    else if (dtDay < 1 || dtDay > 31) return false;
    else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) return false;
    else if (dtMonth == 2) {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay > 29 || (dtDay == 29 && !isleap)) return false;
    }

    return true;
}

jsFiddle
Alternate Solution
You might not like a really complicated regex, but you can really reduce your code by handling the switching in the regex itself.  The following gets the matched month by looping through the matched group into an undefined one is not encountered and then offsetting the value.
function isDate(currVal) {

    if (currVal == '') return false;

    //Declare Regex
    var rxDatePattern = /^(\d{1,2})(\/|-)(?:(\d{1,2})|(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec))(\/|-)(\d{4})$/i;

    var dtArray = currVal.match(rxDatePattern);

    if (dtArray == null) return false;

    var dtDay = parseInt(dtArray[1]);
    var dtMonth = parseInt(dtArray[3]);
    var dtYear = parseInt(dtArray[17]);

    if (isNaN(dtMonth)) {
        for (var i = 4; i <= 15; i++) {
            if ((dtArray[i])) {
                dtMonth = i - 3;
                break;
            }
        }
    }

    if (dtMonth < 1 || dtMonth > 12) return false;
    else if (dtDay < 1 || dtDay > 31) return false;
    else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) return false;
    else if (dtMonth == 2) {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay > 29 || (dtDay == 29 && !isleap)) return false;
    }

    return true;
}

jsFiddle

A: your regex is ok, you haven't enclosed the month subpattern with parentheses so you haven't defined a capture group. consequently, your switch statement fails:
try
var rxDatePattern = /^(\d{1,2})(\/|-)([a-zA-Z]{3})(\/|-)(\d{4})$/;

and
var dtYear = dtArray[5];  // now 5 instead of 4

A: You need parentheses around the month to capture it:
/^(\d{1,2})(\/|-)([a-zA-Z]{3})(\/|-)(\d{4})$/

Which will mean you then need to adjust the index of your year:
var dtYear = dtArray[5];  // now 5 instead of 4

A: It looks like there's just brackets missing around the month section to make it a separate group.
        /^(\d{1,2})(\/|-)([a-zA-Z]{3})(\/|-)(\d{4})$/

        var dtDay = dtArray[1];
        var dtMonth = dtArray[3];
        var dtYear = dtArray[5];

A: Here is the code, no regexp required and use of javascript build in date parsing.
var isDate = (function() {
    var MONTHS = [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec"
    ];

    return function (date) {
        var v = new Date(date);
        var day = v.getDate();
        if(day < 10) {
            day = "0" + day;
        }
        var month = MONTHS[v.getMonth()];
        var year = v.getFullYear();
        var total = day + "-" + month + "-" + year;
        return date.toUpperCase() == total.toUpperCase();
    }
}());

THE FIDDLE


text:
Q: How to get an array of images? I want to make a Battery app which should notify the battery percentage to user in form of image. Now for battery percentage 0-100, I need 101 images in all. What I want to do is that is it possible to insert all these images in an array and use them accordingly. For instance, if my battery percentage is 47%, the image in array at position 47 should be the resource.
That is, suppose I have ImageView named Battery, and I have an array named batteryimage(containing all the 101 images) then I should be able to do this,
Battery.setBackgroundResource(R.drawable.batteryimage[p])

where p will be the current percentage of battery, which I will get by code.
Hope you all understood what I want.. Thanx in advance..

A: define a array of image id like this
int[] p = {R.drawable.image1, R.drawable.image2....}

now for different condition use member of this array like
Battery.setBackgroundResource(p[0])  // or p[1]

or you can use ENUM to make it more readable..
But.. I think you should think in another way. instead of using 100 different image create a custom progressbar to show different state of your battery.
To know the basics of Progress bar see doc here
and to create custom progressbar you can check this so question


text:
Q: Binding silverlight UI property to source I have a checkbox which i need to bind to a bool in the source and also disable or enable a container.
My source is as follows for the binding but it does not work:
private bool isMapEditOn = false;

OnLoadFunction()
{
    //Bindings
    Binding mapEditBind = new Binding("IsChecked") { Source = isMapEditOn, Mode = BindingMode.TwoWay };

    //Bind to check or uncheck the mapEdit Checkbox
    ChckEditMap.SetBinding(ToggleButton.IsCheckedProperty, mapEditBind);
    //Bind to disable children (point and area buttons).
    EditBtnContainer.SetBinding(IsEnabledProperty, mapEditBind);
}

When I test this by checking and unchecking the checkbox, it does not altar isMapEditOn.

A: Try using the type bool? instead of bool.  The IsChecked property is defined as:
public bool? IsChecked { get; set; }

A: The easiest way to do this is to wrap the isMapEditOn in a property. If you want change notification from the source you'll need to implement INotifyPropertyChanged (not shown here. See this page for info on implementing this interface ):
private bool _isMapEditOn = false;

public bool IsMapEditOn
{
    get
    {
        return _isMapEditOn;
    }
    set
    {
        _isMapEditOn = value;
    }
}

OnLoadFunction()
{
    //Bindings
    Binding mapEditBind = new Binding("IsMapEditOn") { Source = this, Mode = BindingMode.TwoWay };

    //Bind to check or uncheck the mapEdit Checkbox
    ChckEditMap.SetBinding(ToggleButton.IsCheckedProperty, mapEditBind);
    //Bind to disable children (point and area buttons).
    EditBtnContainer.SetBinding(IsEnabledProperty, mapEditBind);
}


text:
Q: What does the `<` operator do in shell? I was reading this question, in which someone is trying to get the number of lines in a file from the shell. From the comments, I saw and implemented that the following:
$ wc -l myfile.txt
30213 myfile.txt

$ wc -l < <filename>
30213

What I don't understand is, what the < operator is doing here. Can someone explain why the < operator chops off the file name from the output in this case?

A: In the first case, the filename is supplied as an argument when calling wc, this causes wc to include it in the output.
In the second case, stdin is redirected from filename, this makes wc "unaware" of the file and thus not able to print its name. This is equivalent to calling cat filename | wc -l.
So to answer your question, operator < redirects input file descriptor to read from a given file. If descriptor number is not explicitly specified, then it defaults to standard input (fd 0). See here for a formal reference and here for a convenient description.

A: wc outputs the file name as part of the output when it reads from a file.
The < redirects input and output between files/programs, following the direction of the "arrow". For more information on I/O redirection, this is a pretty handy link. The reason that the file name is "chopped off" is because wc is technically no longer reading from a file.


text:
Q: Codeigniter 3 Redis session driver garage collection with sess_expiration = 0 I was reading the source code for Redis session driver. In the gc function it return true and says Redis handles this.
How does redis decide when to evict data with a sess_expiration = 0? I don't want redis to fill up when these sessions can be deleted.

A: I'm not very familiar with the topic, but I think:
redis follows a specific strategy to manage your session by default. Accordingly: GC saves a default expire time after the session information for use in the next entry. In doing so, it looks at its configuration (Did you create a table to store Session? When should you save it?).
It made it possible to customize this part. So you can manage your session by writing your own handlers. If you want, you can store the session information in any place without taking it to the database side (like cookie). Also you can set up your own web service and manage the remember me information from there, is another option.
My understanding is that if you set sess_expiration to 0 than it will manage itself. Otherwise you can set a short time like 40 minutes and you can use like sintakonte's corn job. (I think no way to write your own GC, You can customize your session handler like that PK_Session)

A: Basically said, you don't.
We had the same problem - a possible approach would be to define a max expiration time (e.g. 3, 6, 12 months).
Additionally you can track the time where the session was accessed last, and delete all inactive sessions after a defined period.
For this you have to write your own GC. (We installed a cron job which runs every 24 hours).


text:
Q: Visual Studio 2022 and .net update issues for Azure Function App I have been using Visual Studio 2019 for my Azure Function App. I recently updated to version 2022, I then uninstalled 2019.
I am getting the following errors now:
 1>CodeaApi -> G:\AVR_Project\Codea App\Codea Azure Function App\bin\Debug\netcoreapp3.1\bin\CodeaApi.dll
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error : It was not possible to find any compatible framework version
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error : The framework 'Microsoft.NETCore.App', version '3.0.0' (x64) was not found.
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error :   - The following frameworks were found:
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error :       6.0.1 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error :
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error : You can resolve the problem by installing the specified framework and/or SDK.
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error :
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error : The specified framework can be found at:
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error :   - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=3.0.0&arch=x64&rid=win10-x64
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error :
    1>C:\Users\asf\.nuget\packages\microsoft.net.sdk.functions\3.0.6\build\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error : Metadata generation failed.
    1>Done building project "CodeaApi.csproj" -- FAILED.

Do I need to install version 3.0.1 to make it compatible with Azure Function Apps?

A: Yes you can resolve this by installing .NET Core 3.1 SDK,

When targeting Azure Functions 3.0, by default, the .NET Core 3.1 SDK
is required on the machine building the project.


text:
Q: RDS replication from a remote master outside of my VPC I'm attempting to replicate from an external MySQL master to an RDS instance. I don't really want to be sending data in the clear over the Internet, so I have an EC2 instance that I have set up an ssh tunnel on. The tunnel opens port 3307 on the EC2 instance, and connects to the external instance that is running the target master MySQL DB. From that EC2 instance I can run
mysql -u <user> -p -h 127.0.0.1 -P3307

and connect to the target remote DB. All is well there. Furthermore, I can connect to the RDS DB from this instance without problems.
The problem I'm having is that when I set up the replication parameters on my RDS instance, I cannot connect to the remote instance. I'm doing something along the lines of (from the EC2 instance that has access to both DB's):
mysql.rds_set_external_master('<host>', 3307, 'repl_user', '<repl_pass>', 'mysql-bin.000001', 107, 0);

... where  has been 'localhost', '127.0.0.1', the private DNS name of the EC2 instance, the private IP, the public IP and the public DNS. On each try, running SHOW SLAVE STATUS\G displays an error along the lines of:
Last_IO_Error: error connecting to master 'repl_user@<host>:3307'

My question is: When running the rds_set_external_master call, is the host relative to the client that's sending the call or relative to the RDS instance? If the latter, how can I tunnel to my remote instance?

A: OK, let this be a lesson to anyone in my position. When you set up your tunnel, if you don;t specify the IP of the machine (or 0.0.0.0), it'll bind to loopback, and so will be private to the instance that spawned it.
Do this:
ssh -N -f -L *:3307:<external IP>:3306 user@remote


text:
Q: Converting an ArrayAdapter to a List I have an array adapter(string), and would like to convert it to a List<String>, but after a little googling and a few attempts, I am no closer to figuring out how to do this.
I have tried the following;
for(int i = 0; i < adapter./*what?*/; i++){
     //get each item and add it to the list
}

but this doesn't work because there appears to be no adapter.length or adapter.size() method or variable.
I then tried this type of for loop
for (String s: adapter){
    //add s to the list
}

but adapter can't be used in a foreach loop.
Then I did some googling for a method (in Arrays) that converts from an adapter to a list, but found nothing.
What is the best way to do this? Is it even possible?

A: for(int i = 0; i < adapter.getCount(); i++){
     String str = (String)adapter.getItem(i);
}

A: Try this
// Note to the clown who attempted to edit this code.
// this is an input parameter to this code.
ArrayAdapter blammo;
List<String> kapow = new LinkedList<String>(); // ArrayList if you prefer.

for (int index = 0; index < blammo.getCount(); ++index)
{
    String value = (String)blammo.getItem(index);
    // Option 2: String value = (blammo.getItem(index)).toString();
    kapow.add(value);
}

// kapow is a List<String> that contains each element in the blammo ArrayAdapter.

Use option 2 if the elements of the ArrayAdapter are not Strings.


text:
Q: Getting Notifed of Fail Reporting Services Failed Subscriptions We have quite a few reports that run on schedules, and invariably sometimes they fail. I would like to pre-empt these issues and get a notification when ever a failure happens on the server.
Has anyone got a way of doing this?
Cheers
Luke


text:
Q: Find and remove from linked lists using head_return and tail_return I'm working through a linked list example. I am at the find and remove function which traverses the list to find a particular element. The find_remove function does not work. All other functions within the application work (head_return, tail_return, etc.)
I would be grateful if someone could point out where I am going wrong with find_remove.
#include <iostream>
using namespace std;

struct node_ll
{
    int payload;
    node_ll* next;//Pointer to the next node
};

void head_insert(node_ll** list, int pload)
{
    node_ll* temp = new node_ll;//Create a new node, and let temp be the address of that node.
    temp->payload = pload;//Set the payload of the struct whose address is temp to pload.
    temp->next = *list;//Set the next of the struct whose address is temp to the address of the old head of the list.
    *list = temp;//The address of the old head of the list is changed to the address of the struct temp.
};

void tail_insert(node_ll** list, int pload)
{
    if (*list == NULL)
    {
        head_insert(list, pload);
    }
    else
    {
        node_ll* temp = new node_ll;
        for (temp = *list; temp->next; temp = temp->next);
        temp->next = new node_ll;
        temp->next->payload = pload;
        temp->next->next = NULL;
    }
}

int head_return (node_ll** list)
{
    if (*list != NULL)
    {
    int temp = (*list)->payload;
      node_ll* trash = *list;
      *list = (*list)->next;
      delete trash;
      return temp;
    }
    else
    {
        return 0;
    }
}

int tail_return (node_ll** list)
{
    if (*list != NULL)
    {
      if ((*list)->next == NULL)
        {
            return head_return(list);
        }
        else
        {
      node_ll* trash;
            for (trash = *list; trash->next->next; trash = trash->next);
            int temp = trash->next->payload;
            delete trash->next;
            trash->next = NULL;
            return temp;
        }
    }
    else
    {
        return 0;
    }
}

void find_remove (node_ll** list, int pload)
{
    if (*list != NULL)
    {
        node_ll* temp;//Declared before loop for use after loop.
        for (temp = *list; temp->next; temp = temp->next)
        {
            if (temp->payload == pload)
            {
                int trash = head_return(&temp);
            }
        }
        if (temp->payload == pload)
        {
            int trash = tail_return(list);
        }
    }
}

void print_ll (node_ll** list)
{
  node_ll* temp = *list;//Let temp be the address of the node that is the head of the list.
    while(temp)// != NULL
    {
        cout << temp->payload << endl;//Print out payload of the struct whose address is temp.
        temp = temp->next;//Set the address of temp equal to the address stored in next of the struct whose address is temp.
    }
}

int main()
{
    node_ll *blist = NULL;
    tail_insert(&blist, 2);
    tail_insert(&blist, 4);
    tail_insert(&blist, 6);
    find_remove(&blist, 4);
    print_ll(&blist);
    cout << '\n';

    system("PAUSE");
    return 0;
}

EDIT:
Here is my attempt at rewriting your code.
void find_remove (node_ll** list, int pload)
{
    if (*list != NULL)
    {
        while (*list && (*list)->payload == pload)
        {
            head_return(list);
        }
        if (*list != NULL)
        {
            node_ll* temp;
            for (temp = *list; temp->next->next; temp = temp->next)
            {
                if (temp->next->payload == pload)
                {
                    node_ll* trash = temp->next;
                    temp->next = temp->next->next;
                    head_return(&trash);
                }
            }
        }
    }
}

EDIT 2:
Thank you! This new solution works if there are multiple matchine nodes at the start, multiple matching nodes in the middle or multiple matching nodes at the end.
void find_remove (node_ll** list, int pload)
{
    if (*list != NULL)
    {
        while (*list && (*list)->payload == pload)
        {
            head_return(list);
        }
        if (*list != NULL)
        {
            node_ll* temp;
            for (temp = *list; temp->next; temp = temp->next)
            {
                while (temp->next->next != NULL && temp->next->payload == pload)
                {
                    node_ll* trash = temp->next;
                    temp->next = temp->next->next;
                    head_return(&trash);
                }
            }
            if (temp->next == NULL && temp->payload == pload)
            {
                tail_return(list);
            }
        }
    }
}

A: The crash is due to the fact that your loop logic is not correct, also you are not keeping track of the previous node which means you are not correctly resetting the linked list, this is the simplest fix:
void find_remove (node_ll** list, int pload)
{
    if (*list != NULL)
    {
        node_ll* temp, *prev=NULL;//Declared before loop for use after loop.
        for (temp = *list; temp != NULL; temp = temp->next)
        {
            if (temp->payload == pload)
            {
               if( NULL != prev )
               {
                  prev->next = temp->next ;
               }
                int trash = head_return(&temp);
            }

            prev=temp ;
         }
   }
}

Although honestly the code has a lot of style issues and is a lot more like C-style code than C++ style code. You may want to consider checking out Code Review.
update:
If you change this in your modified code it works:
for (temp = *list; temp->next != NULL; temp = temp->next)
                   ^^^^^^^^^^^^^^^^^^

At the top of the loop you never know if temp->next is NULL so doing temp->next->next is never valid.


text:
Q: Laravel 5.5 - where access relationship In Laravel 5.5 I am trying to get all members where member->user->membership->id is user->membership->id. For example:
$members = Member::where($member->user->membership->id,$user->membership->id)->get();

Obviously $member is not set yet. So, how can I access this relationship?
Functions already defined in Models:
Member
public function user() {
    return $this->belongsTo('App\User', 'account_id');
}

Membership
public function user() {
    return $this->hasMany('App\User');
}

User
public function membership() {
    return $this->belongsTo('App\Membership');
}

public function member() {
    return $this->hasMany('App\Member','account_id');
}

A: You can use whereHas to do this:
Member::whereHas('user', function($q) use ($user) {
    $q->where('membership_id', $user->membership_id);
})->get();

I'm supposing you have membership_id in User model, since you are calling user->membership->id.
And you need the relation between Member and User to be defined. Something like this (in Member Model), but considering that you are following the naming convention:
public function user() {
    return $this->belongsTo(User::class);
}


text:
Q: Firefox, Selenium IDE - wait for popup to load before automatically closing I have a popup that loads after being submitted then auto-closes, and then the parent window loads. My issue is having making sure Selenium waits until the popup has finished loading, closed and the parent window has finished loading.
On slow speed the following code works to make sure we wait until the popup loads:

    click
    name=_action

    waitForFrameToLoad
    null

On fast speed, the following code works because it goes to the next command so need to tell it to wait for the popup to finish loading:

    click
    name=_action

    waitForElementNotPresent
    id=head_check

    waitForFrameToLoad
    null

My issue is I cannot control if the user will run the script in slow or fast speed, and the slow speed results in an error if I try to waitForElementNotPresent:
[error] modifyWindow: Window was closed!

A: Since slow speed works, we can "slow down" fast speed at the only step it breaks by adding a pause:

    pause
    5000


text:
Q: Excerpt from question body missing in tag filters The excerpt from the question body that is usually shown in question lists is suddenly missing from tag filters on stackexchange.com:

This bug happened just now, so probably the latest build broke something there.

A: Apologies for that - I missed that reuse of the view for the filtered tags page when working on the hot questions/homepage redesign.
Fixing and building out shortly.


text:
Q: Entity Framework Migrations don't include DefaultValue data annotation (EF5RC) I have a class that looks like this:
[Table("Subscribers", Schema = "gligoran")]
public class Subscriber
{
    [Key]
    public string Email { get; set; }

    [Required]
    [DefaultValue(true)]
    public bool Enabled { get; set; }
}

When creating a migration to include this class I get:
public partial class AddSubscriberClass : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "gligoran.Subscribers",
            c => new
                {
                    Email = c.String(nullable: false, maxLength: 128),
                    Enabled = c.Boolean(nullable: false),
                })
            .PrimaryKey(t => t.Email);

    }

    public override void Down()
    {
        DropTable("gligoran.Subscribers");
    }
}

I'd like the Enabled line to look like this:
Enabled = c.Boolean(nullable: false, defaultValue: true),

Of course I can do this myself, but I'm just asking if there's a way to make Entity Framework do it automatically.
I'm using the latest Entity Framework 5 RC (5.0.0-rc.net40).

A: As an Extra to Ladislav's Comment. Which is correct. you cant do it in the model. IF you wanted to use code based migrations.  Ie using PM commandlet Add-Migration / Update Database,   then this approach introduces a generated class into the process.  Then you can have defaults .  See the classes that Derive from DBMigrations.  see http://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigration.addcolumn%28v=vs.103%29.aspx
You can specific Column builder Lamda expressions. This allows defaults.
namespace MigrationsDemo.Migrations
{
  using System;
  using System.Data.Entity.Migrations;

public partial class SomeClassThatisATable : DbMigration
{
    public override void Up()
    {
        AddColumn("MyTable", "MyColumn", c => c.String( defaultvalue:"Mydefault"  ));
    }

A: EF doesn't use DefaultValue attribute at all = it is not part of the model so migrations don't see it. You can propose support of this annotation on Data UserVoice.


text:
Q: Why is it when you call toString() on a function using quokka, it returns a string with extra variables added? I am teaching myself to use prototypes to extend the functionality of objects. I have hit a roadblock when it comes to functions though, when I log a function to string it returns something I don't understand. For example, given:
function foo() {
    var a = 1
    var b = 2
    return a + b
}
console.log( foo.toString() )

you get:
`function foo() {
    var $_$c = $_$wf(1);
    var a = ($_$w(1, 130, $_$c), 1);
    var b = ($_$w(1, 131, $_$c), 2);
    return $_$w(1, 132, $_$c), a + b;
}`

I would expect to get:
`function foo() {
    var a = 1
    var b = 2
    return a + b
}`

Why?
Edit

A: try this:
function foo() {
    var a = 1
    var b = 2
    return a + b
}

console.log(foo);

let x = foo.toString();
console.log(typeof x) // This should return a string

When you print 'x' it should give you the code as a string too.

A: I try  this example it return

`function foo() {
    var $_$c = $_$wf(1);
    var a = ($_$w(1, 130, $_$c), 1);
    var b = ($_$w(1, 131, $_$c), 2);
    return $_$w(1, 132, $_$c), a + b;
}`

and then I made an object and put the function to it and try to return it as toString and also it work correctly


text:
Q: Have ran tasksel to remove some stuff on fresh 18.10, got "update-initramfs: failed for..." error Have ran tasksel to remove some unneeded stuff on fresh Ubuntu 18.10 VM and got the following errors:
$ sudo apt-get install -f
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up initramfs-tools (0.131ubuntu15) ...
update-initramfs: deferring update (trigger activated)
Processing triggers for initramfs-tools (0.131ubuntu15) ...
update-initramfs: Generating /boot/initrd.img-4.18.0-10-generic
W: plymouth module (/usr/lib/x86_64-linux-gnu/plymouth//.so) missing, skipping that theme.
E: /usr/share/initramfs-tools/hooks/plymouth failed with return 1.
update-initramfs: failed for /boot/initrd.img-4.18.0-10-generic with 1.
dpkg: error processing package initramfs-tools (--configure):
 installed initramfs-tools package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 initramfs-tools
E: Sub-process /usr/bin/dpkg returned an error code (1)

What should I do to fix the issue?

A: We need to determine which plymouth-related packages were installed
$ dpkg -l | grep plymouth
ii  libplymouth4:amd64                    0.9.3-1ubuntu10                    amd64        graphical boot animation and logger - shared libraries
ii  plymouth                              0.9.3-1ubuntu10                    amd64        boot animation, logger and I/O multiplexer
rc  plymouth-theme-ubuntu-mate-logo       18.10.1                            all          graphical boot animation and logger - ubuntu-mate-logo theme
rc  plymouth-theme-ubuntu-mate-text       18.10.1                            all          graphical boot animation and logger - ubuntu-mate-text theme
ii  plymouth-theme-ubuntu-text            0.9.3-1ubuntu10                    amd64        boot animation, logger and I/O multiplexer - ubuntu text theme

and then reinstall them:
sudo apt-get install --reinstall $(dpkg -l | grep plymouth | awk '{print $2}')

And voila, problem fixed:
$ sudo apt-get install -f
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

So this example again demonstrates that tasksel should not be used for removing packages on all modern Ubuntu versions!


text:
Q: Build and use a docker image without involving docker.io I'm using docker build -t myimage:latest . and then have a separate Dockerfile using that base image:
FROM myimage:latest
...

But when I try to docker build . for that second Dockerfile, I'm getting an error as its trying to pull from docker.io
------
 > [internal] load metadata for docker.io/library/myimage:latest:
------
failed to solve with frontend dockerfile.v0: failed to create LLB definition: pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed

Is there a way to build and tag images intended only for local use? I can see myImage when I search for it locally: docker image ls | grep myimage

A: This is probably due to the latest tag.
You could try another tag:
echo 'FROM busybox' > Dockerfile
docker build -t myimage:dev .

echo 'FROM myimage:dev' > Dockerfile
docker build .


text:
Q: Can AppFabric be the session state provider and use local cache? I am using AppFabric as the session state provider in my ASP.Net MVC2 app, and I would like it to also use the local cache. I have the following entry in my web.config right after the configSections node:
<dataCacheClient>
    <localCache
         isEnabled="true"
         sync="TimeoutBased"
         objectCount="100000"
         ttlValue="300" />
    <hosts>
        <host name="127.0.0.1" cachePort="22233"/>
    </hosts>
</dataCacheClient>

I also have the following entry in web.config as a child of the system.web node:
<sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
    <providers>
        <add name="AppFabricCacheSessionStoreProvider" type="Microsoft.ApplicationServer.Caching.DataCacheSessionStoreProvider" cacheName="Default" sharedId="DefaultId"/>
    </providers>
</sessionState>

Unfortunately if I add something to session then run the following two commands in the AppFabric powershell, anything I added to my session data is no longer there which leaves me to believe it was not using local cache:
Stop-CacheCluster
Start-CacheCluster

I also try caching objects with AppFabric using the following code and after I start and stop the CacheCluster the once cached object is no longer cached:
var factory = new DataCacheFactory();
var cache = factory.GetCache("Default");
cache.Put("Key", "Test");

However if I instantiate AppFabric using the following code where I explicitly tell it to use local cache rather than relying on the web.config entry it works:
var servers = new List<DataCacheServerEndpoint>(1) { new DataCacheServerEndpoint("127.0.0.1", 22233) };
var configuration = new DataCacheFactoryConfiguration {
                Servers = servers,
                LocalCacheProperties = new DataCacheLocalCacheProperties(100000, new TimeSpan(0, 30, 0), DataCacheLocalCacheInvalidationPolicy.TimeoutBased)
            };
var factory = new DataCacheFactory(configuration);
var cache factory.GetCache("StpWebSession");
cache.Put("Key", "Test");

What am I doing wrong, why doesn't my web.config entry work in telling AppFabric to use local cache? Can you use AppFabric as your session state provider and also have it use local cache?

A: I found a little ditty at http://social.msdn.microsoft.com/Forums/en-US/velocity/thread/24e72dab-bb20-47ec-aae2-77423b1d296b.
Basically, "enableSessionState" is "true" by default meaning you need to go remote for all requests.  If you set the property to "ReadOnly" the session state object will be retrieved from the Local Cache.  Then if local cache is invalidated it will go to remote store again.


text:
Q: Replace Name Attribute with Variable - JQUERY I am using a select element to change the search type on a media site (i.e. search by genre, search by artist).
I have created the dropdown and can get the selected option via a variable but now I need to replace the name attribute on the input element with the variable/selected option.  I have seen the below code to change the "value", is there anything like this for changing the name attribute on an input element.
$("input[name$='letter']").val("a letter");

A: .attr('name', 'blah')


text:
Q: Joining an Active Directory domain in the middle of a sysprep auditing? Is it possible to sysprep a Windows 7 image by installing it on a reference machine, then after entering audit mode, joining the computer to the domain. Then after I finish sysprepping, it will generalize and all specific services I've assigned to run under domain accounts will be configured correctly?
Basically one of the software packages I want to image on a standard Windows 7 install asks for service accounts. I want to assign that to a domain account, but I can't simply type in DOMAIN\user in the set up when it's not joined.

A: Yes you can.
You can join the reference machine to the domain, and assing the accounts of your service.
After you join your machine again when the image is applied everything should works because the SID of the service account is exactly the same.


text:
Q: AJAX using JQuery I am using the following code in index.html

<title>Ajax check</title>

<form action="page.html">
<input type="button" id="ibutton" value="click here"/>

</form>

In page.html, the only content is 'working...'
when I click the click here button... nothing happens.. what is wrong in the code?

A: The bug is the val function. I think that you want to use text function instead of val:
$("#message").text('ajax working..');


text:
Q: Limiting HTTP verbs on every action Is it a good practice to limit the available HTTP verbs for every action?  My code is cleaner without [HttpGet], [HttpPost], [HttpPut], or [HttpDelete] decorating every action, but it might also be less robust or secure.  I don't see this done in many tutorials or example code, unless the verb is explicitly required, like having two "Create" actions where the GET version returns a new form and the POST version inserts a new record.

A: Personally I try to respect RESTful conventions and specify the HTTP verb except for the GET actions which don't modify any state on the server thus allowing them to be invoked with any HTTP verb.

A: Yes, I believe it's a good practice to limit your actions only to the appropriate HTTP method it's supposed to handle, this will keep bad requests out of your system, reduce the effectiveness of possible attacks, improve the documentation of your code, enforce a RESTful design, etc.
Yes, using the [HttpGet], [HttpPost] .. attributes can make your code harder to read, specially if you also use other attributes like [OutputCache], [Authorize], etc.
I use a little trick with a custom IActionInvoker, instead of using attributes I prepend the HTTP method to the action method name, e.g.:
public class AccountController : Controller {

   protected override IActionInvoker CreateActionInvoker() {
      return new HttpMethodPrefixedActionInvoker();
   }

   public ActionResult GetLogOn() {
      ...
   }

   public ActionResult PostLogOn(LogOnModel model, string returnUrl) {
      ...
   }

   public ActionResult GetLogOff() {
      ...
   }

   public ActionResult GetRegister() {
      ...
   }

   public ActionResult PostRegister(RegisterModel model) {
      ...
   }

   [Authorize]
   public ActionResult GetChangePassword() {
      ...
   }

   [Authorize]
   public ActionResult PostChangePassword(ChangePasswordModel model) {
      ...
   }

   public ActionResult GetChangePasswordSuccess() {
      ...
   }
}

Note that this doesn't change the action names, which are still LogOn, LogOff, Register, etc.
Here's the code:
using System;
using System.Collections.Generic;
using System.Web.Mvc;

public class HttpMethodPrefixedActionInvoker : ControllerActionInvoker {

   protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName) {

      var request = controllerContext.HttpContext.Request;

      string httpMethod = request.GetHttpMethodOverride()
         ?? request.HttpMethod;

      // Implicit support for HEAD method.
      // Decorate action with [HttpGet] if HEAD support is not wanted (e.g. action has side effects)

      if (String.Equals(httpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
         httpMethod = "GET";

      string httpMethodAndActionName = httpMethod + actionName;

      ActionDescriptor adescr = base.FindAction(controllerContext, controllerDescriptor, httpMethodAndActionName);

      if (adescr != null)
         adescr = new ActionDescriptorWrapper(adescr, actionName);

      return adescr;
   }

   class ActionDescriptorWrapper : ActionDescriptor {

      readonly ActionDescriptor wrapped;
      readonly string realActionName;

      public override string ActionName {
         get { return realActionName; }
      }

      public override ControllerDescriptor ControllerDescriptor {
         get { return wrapped.ControllerDescriptor; }
      }

      public override string UniqueId {
         get { return wrapped.UniqueId; }
      }

      public ActionDescriptorWrapper(ActionDescriptor wrapped, string realActionName) {

         this.wrapped = wrapped;
         this.realActionName = realActionName;
      }

      public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters) {
         return wrapped.Execute(controllerContext, parameters);
      }

      public override ParameterDescriptor[] GetParameters() {
         return wrapped.GetParameters();
      }

      public override object[] GetCustomAttributes(bool inherit) {
         return wrapped.GetCustomAttributes(inherit);
      }

      public override object[] GetCustomAttributes(Type attributeType, bool inherit) {
         return wrapped.GetCustomAttributes(attributeType, inherit);
      }

      public override bool Equals(object obj) {
         return wrapped.Equals(obj);
      }

      public override int GetHashCode() {
         return wrapped.GetHashCode();
      }

      public override ICollection<ActionSelector> GetSelectors() {
         return wrapped.GetSelectors();
      }

      public override bool IsDefined(Type attributeType, bool inherit) {
         return wrapped.IsDefined(attributeType, inherit);
      }

      public override string ToString() {
         return wrapped.ToString();
      }
   }
}

A: You don't need to specify the HttpGet, all others you do need


text:
Q: Nslookup cannot find name servers without www Our site is responding to nslookup if it is fully written.
nslookup www.example.com - it responds and shows name servers.
But if we write without www,  like nslookup example.com - it cannot find name servers.
What may be the problem?
I have these records:
@ IN NS ns1.example.com.
localhost.example.com. IN A 127.0.0.1
ns1.example.com. IN A ip_add_of_www
What else should I add?

A: DNS is similar to a database of names.
If you do not put there a record, it won't answer to it when being consulted /read.
So, if you have not created two A records, and only created www.example.com, it will only give an address to www.example.com
As CNAMEs pointing to  a domain are not allowed per DNS rfcs/"papers", you have to define not an alias, but an address.
Using bind syntax, where @ is shorthand for your domain:
@       IN A   192.0.2.1

Where 192.0.2.0 is the same address of the A RR attributed to www.
As in:
$TTL 86400
@   IN  SOA     startech60serve root.startech60serve.com (
    2018110201  ;Serial
    3600        ;Refresh
    1800        ;Retry
    604800      ;Expire
    86400       ;Minimum TTL
)

 IN  NS      x.x.x.x

 www      IN A 192.0.2.1
 @        IN A 192.0.2.1

After changing, you need to restart increase the serial.
After increasing, you either restart the service or do a
rndc reload


text:
Q: Finding a minimum area rectangle of a convex polygon I am looking for a efficient way to find a minimum area rectangle of a convex polygon.
running time should be O(n) where n is the number of vertices.
there is a complex algorithm for finind a bounding box of a general polygon, but there should be a easier algorithm for a convex polygon.
How can one do it easily for a convex polygon?
thanks.

A: Rotating calipers are your best friends.
The tightest bounding rectangle is such that one of its sides coincides with a side of the polygon. So,

*

*starting from an arbitrary side, rotate the polygon to make this side horizontal, at the bottom;

*find the three vertices that maximize Y, -X and X respectively (on the figure, 4, 6, and 3). This way, you obtain a bounding box;

*then move to the next side, clockwise, and adjust the rotation;

*find the next three vertices by updating the maxima (follow the outline and stop before Y decreases; same with -X and X; on the figure, 4->5, 6->6 and 3->3);

*for every position, compute the area and keep the best. Stop after a full turn.

It is important to realize that you don't apply the rotations to all vertices, but only when needed. To obtain the initial bounding box, you process O(N) vertices, but the N-1 updates only take O(N) additional work (amortized), and you don't have to compute both coordinates.


text:
Q: Cannot iterate through CSV columns I'm building a stock screener that applies a calculation through each column of a csv file. However, when I run the for loop, I only get one result back.
    String path = "C:/Users/0/Desktop/Git/Finance/Data/NQ100.csv";
    Reader buf = Files.newBufferedReader(Paths.get(path));
    CSVParser parsed = new CSVParser(buf, CSVFormat.DEFAULT.withFirstRecordAsHeader()
            .withIgnoreHeaderCase().withTrim());

    // Parse tickers
    Map<String, Integer> header = parsed.getHeaderMap();
    List<String> tickerList = new ArrayList<>(header.keySet());

    for (int x=1; x < tickerList.size(); x++) { <----------------------- PROBLEM

        // Accessing closing price by Header names
        List<Double> closeList = new ArrayList<>();
        for (CSVRecord record : parsed) {
            String stringClose = record.get(x);
            Double close = Double.valueOf(stringClose);
            closeList.add(close);
        }

        // Percentage Change
        List<Double> pctList = new ArrayList<>();
        for (int i=1; i < closeList.size(); i++) {
            Double pct = closeList.get(i) / closeList.get(i-1) - 1;
            pctList.add(pct);
        }

        // Statistics
        Double sum = 0.0, var = 0.0, mean, sd, rfr, sr;
        // Mean
        for (Double num : pctList) sum += num;
        mean = sum/pctList.size();
        // Standard Deviation
        for (Double num: pctList) var += Math.pow(num - mean, 2);
        sd = Math.sqrt(var/pctList.size());
        // Risk Free Rate
        rfr = Math.pow((1+0.03),(1/252.0))-1;
        // Sharpe Ratio
        sr = Math.sqrt(252) * ((mean-rfr)/sd);

        System.out.println(tickerList.get(x) + " " + sr);
    }

My data looks like this:
,AAL,AAPL,ADBE
2007-10-25,26.311651,23.141403,47.200001
2007-10-26,26.273216,23.384495,47.0
2007-10-29,26.004248,23.43387,47.0

So I was expecting:
AAL XXX
AAPL XXX
ADBE XXX

But I got just:
AAL 0.3604941921663456

Would be grateful if you guys can help me find the problem!

A: So here's a block of the code that work for me, if i understand your question, you only want to "read" each column and row from a csv file, hope helps.
        br = new BufferedReader(new InputStreamReader(new FileInputStream(archivo), "UTF8"));
        while ((line = br.readLine()) != null) {
            if(a!=0){
                String[] datos = line.split(cvsSplitBy);
                System.out.println(datos[0] + " - " + datos[1] + " - " + datos[2]);
            }
            a++;
        }

A: You can iterate through Iterable in Java only once, in your case CSVParser parsed implements Iterable<CSVRecord>.
So you iterate through it only for the first time when you calculate statistics for AAL, during analyzing data for AAPL and ADBE it will be handled as an empty one.
You can handle this by introducing helper list init by the parsed, add next code (it is a one line solution of course e.g. in Java 8, but this option will work for earlier versions too) before the for cycle:
    List<CSVRecord> records = new ArrayList<>();
    for (CSVRecord record : parsed) {
        records.add(record);
    }

And change next line:
for (CSVRecord record : records) {

with:
for (CSVRecord record : parsed) {

For the CSV you've provided you will have next output then:
AAL -21.583101145880306
AAPL 23.417753561072438
ADBE -16.75343297000953


text:
Q: android app fully work in debug but crashes in release [ react native ] I built the app as android react native. when I was working on debug it worked just fine but now on release build it doesn't and the app crashes on start. I checked the E logcat and the issue seems to be this :  TypeError: undefined is not an object (evaluating 'u.getState')
Can somebody help me to solve this issue?
Here is the complete logcat
3-31 01:54:14.659 25416 25419 E nightwatch-watcher: Failed to read from logcat: Success
03-31 01:54:14.698  3302  5239 E BufferQueueProducer: [com.shopertino/com.shopertino.MainActivity[18706]#0] disconnect: not connected (req=1)
03-31 01:54:14.715 18706 18706 E ViewRootImpl: sendUserActionEvent() returned.
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: TypeError: undefined is not an object (evaluating 'u.getState')
03-31 01:54:14.732 18706 18763 E unknown:ReactNative:
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: This error is located at:
03-31 01:54:14.732 18706 18763 E unknown:ReactNative:     in s
03-31 01:54:14.732 18706 18763 E unknown:ReactNative:     in l
03-31 01:54:14.732 18706 18763 E unknown:ReactNative:     in RCTView
03-31 01:54:14.732 18706 18763 E unknown:ReactNative:     in RCTView
03-31 01:54:14.732 18706 18763 E unknown:ReactNative:     in c, stack:
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: s@367:429
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: Sn@90:30120
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: Or@90:45887
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: na@90:72881
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: ra@90:73371
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: Oa@90:80972
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: Wa@90:80310
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: Aa@90:79323
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: sa@90:78013
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: Ba@90:82505
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: render@90:85076
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: exports@338:592
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: run@334:615
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: runApplication@334:2017
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: value@28:3311
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: <unknown>@28:822
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: value@28:2565
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: value@28:794
03-31 01:54:14.732 18706 18763 E unknown:ReactNative: value@-1
03-31 01:54:14.738 18706 18763 E AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
03-31 01:54:14.738 18706 18763 E AndroidRuntime: Process: com.shopertino, PID: 18706
03-31 01:54:14.738 18706 18763 E AndroidRuntime: com.facebook.react.common.JavascriptException: TypeError: undefined is not an object (evaluating 'u.getState')
03-31 01:54:14.738 18706 18763 E AndroidRuntime:
03-31 01:54:14.738 18706 18763 E AndroidRuntime: This error is located at:
03-31 01:54:14.738 18706 18763 E AndroidRuntime:     in s
03-31 01:54:14.738 18706 18763 E AndroidRuntime:     in l
03-31 01:54:14.738 18706 18763 E AndroidRuntime:     in RCTView
03-31 01:54:14.738 18706 18763 E AndroidRuntime:     in RCTView
03-31 01:54:14.738 18706 18763 E AndroidRuntime:     in c, stack:
03-31 01:54:14.738 18706 18763 E AndroidRuntime: s@367:429
03-31 01:54:14.738 18706 18763 E AndroidRuntime: Sn@90:30120
03-31 01:54:14.738 18706 18763 E AndroidRuntime: Or@90:45887
03-31 01:54:14.738 18706 18763 E AndroidRuntime: na@90:72881
03-31 01:54:14.738 18706 18763 E AndroidRuntime: ra@90:73371
03-31 01:54:14.738 18706 18763 E AndroidRuntime: Oa@90:80972
03-31 01:54:14.738 18706 18763 E AndroidRuntime: Wa@90:80310
03-31 01:54:14.738 18706 18763 E AndroidRuntime: Aa@90:79323
03-31 01:54:14.738 18706 18763 E AndroidRuntime: sa@90:78013
03-31 01:54:14.738 18706 18763 E AndroidRuntime: Ba@90:82505
03-31 01:54:14.738 18706 18763 E AndroidRuntime: render@90:85076
03-31 01:54:14.738 18706 18763 E AndroidRuntime: exports@338:592
03-31 01:54:14.738 18706 18763 E AndroidRuntime: run@334:615
03-31 01:54:14.738 18706 18763 E AndroidRuntime: runApplication@334:2017
03-31 01:54:14.738 18706 18763 E AndroidRuntime: value@28:3311
03-31 01:54:14.738 18706 18763 E AndroidRuntime: <unknown>@28:822
03-31 01:54:14.738 18706 18763 E AndroidRuntime: value@28:2565
03-31 01:54:14.738 18706 18763 E AndroidRuntime: value@28:794
03-31 01:54:14.738 18706 18763 E AndroidRuntime: value@-1
03-31 01:54:14.738 18706 18763 E AndroidRuntime:
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at com.facebook.react.modules.core.ExceptionsManagerModule.showOrThrowError(ExceptionsManagerModule.java:54)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at com.facebook.react.modules.core.ExceptionsManagerModule.reportFatalException(ExceptionsManagerModule.java:38)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at android.os.Handler.handleCallback(Handler.java:873)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:99)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:214)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:232)
03-31 01:54:14.738 18706 18763 E AndroidRuntime:    at java.lang.Thread.run(Thread.java:764)
03-31 01:54:14.809  3856  3856 E SDAgentPackageStateReceiver: Not going to handle 'com.shopertino'!
03-31 01:54:14.843  3301  3301 E lmkd    : Error writing /proc/18706/oom_score_adj; errno=22
03-31 01:54:14.850  3856  3912 E WindowManager: RemoteException occurs on reporting focusChanged, w=Window{f32745d u0 com.shopertino/com.shopertino.MainActivity}
03-31 01:54:14.850  3856  3912 E WindowManager: android.os.DeadObjectException
03-31 01:54:14.850  3856  3912 E WindowManager:     at android.os.BinderProxy.transactNative(Native Method)
03-31 01:54:14.850  3856  3912 E WindowManager:     at android.os.BinderProxy.transact(Binder.java:1145)
03-31 01:54:14.850  3856  3912 E WindowManager:     at android.view.IWindow$Stub$Proxy.windowFocusChanged(IWindow.java:500)
03-31 01:54:14.850  3856  3912 E WindowManager:     at com.android.server.wm.WindowState.reportFocusChangedSerialized(WindowState.java:3920)
03-31 01:54:14.850  3856  3912 E WindowManager:     at com.android.server.wm.WindowManagerService$H.handleMessage(WindowManagerService.java:5456)
03-31 01:54:14.850  3856  3912 E WindowManager:     at android.os.Handler.dispatchMessage(Handler.java:106)
03-31 01:54:14.850  3856  3912 E WindowManager:     at android.os.Looper.loop(Looper.java:214)
03-31 01:54:14.850  3856  3912 E WindowManager:     at android.os.HandlerThread.run(HandlerThread.java:65)
03-31 01:54:14.850  3856  3912 E WindowManager:     at com.android.server.ServiceThread.run(ServiceThread.java:44)

A: Proguard was causing the app to crash, i temporarily disabled it and it worked like a charm.
buildTypes {
        release {
           // minifyEnabled enableProguardInReleaseBuilds <--- commented this line
           // proguardFiles getDefaultProguardFile("proguard-android.txt"),  "proguard-rules.pro" and this
            signingConfig signingConfigs.release
            debuggable true

        }


text:
Q: How to save plot drawn using with(plot()) to a variable in R? I get the code for plotting with two y-axis from the following website:
https://www.r-bloggers.com/2015/04/r-single-plot-with-two-different-y-axes/
Here is my code after referencing the code in the link:
    par(mar = c(5,5,2,5))
    with(df, plot(Date, get(element), type="l", col="red3", ylab="beta_mkt"))
    par(new = T)
    with(df, plot(Date, NBER, type="l", axes=F, xlab=NA, ylab=NA, cex=1.2))
    axis(side = 4)
    mtext(side = 4, line = 3, "NBER")

This code prints out a plot, but I wanted to save this plot in a variable so I can reference it later. Anyone know how to achieve it?
Thanks.
Gin


text:
Q: Remove authorisation required for script on Google sheets I run a few bound scripts on Google Sheets I create for users, due to the script functions all require authorisation.
The scripts run from buttons inserted on the spreadsheet itself. I want to remove the authorisation procces so that anonymous users can run the script - I have tried deploying the script as a web app but this hasn't worked.
Has anyone got any ideas what I can do to create these scripts so that anyone can run the script without having to authorise through a Google account please?
Many thanks
P.S. don't suggest that I get all users to create Google accounts as that just isn't going to happen! :-)

A: *

*You want to make users, who don't login to Google, run the container-bound script of Spreadsheet by clicking a button on Spreadsheet.

*You want to make users run the script without the authorization.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Issue and workaround:
Unfortunately, in the current stage, users as anyone who don't login to Google cannot run the script by the clicking a button put on Spreadsheet. This has already mentioned in your question. This situation is the same with the custom menu.
So in this answer, I would like to propose a workaround.
In this workaround, the OnEdit event trigger is used. From your question, I thought that your script might include the methods for requiring to authorize the scopes. So here, the OnEdit event trigger is used as the installable trigger. When the script is run by the OnEdit event trigger, the script is run as the owner. When you install the OnEdit event trigger as the installable trigger, the authorization process is run. So when users use this script, the authorization process is not required.
Usage:
In order to use this sample script, please do the following flow.

*

*Copy and paste the following script by including your script to the script editor.

*Install the OnEdit event trigger to installedOnEdit as the installable trigger.

*A checkbox is used as the button for executing the script. In order to execute the script, as a test case, please put a checkbox to the cell "A1".
Sample script:
function installedOnEdit(e) {
  var lock = LockService.getScriptLock();
  if (lock.tryLock(10000)) {
    var range = e.range;
    try {
      if (range.getA1Notation() == "A1" && e.value == "TRUE") {

        // Please put your script here.

      }
    } catch(err) {
      throw new Error(err)
    } finally {
      range.uncheck();
      lock.releaseLock();
    }
  }
}

*

*In this script, when you check the checkbox, the script in the if statement is run. And when the script is finished, the checkbox is unchecked by e.range.uncheck(). By this, the checkbox is back to standby.

*By LockService, the exclusive processing of the script is run.

*If the process time of your script is over 10 seconds, please modify lock.tryLock(10000).

References:

*

*Installable Triggers

*Event Objects

*Lock Service
If I misunderstood your question and this was not the direction you want, I apologize.


text:
Q: Expected BEGIN_OBJECT but was String at line 1 column 5 I am not able to upload an image to my server from android application. My json seems right.
Here is my code.
private boolean uploadprofilePic(String user_id)
    {
        final Boolean[] imageresponse = new Boolean[1];
        if(imageadded) { //get the image
            Bitmap bitmap = ((BitmapDrawable) profileImage.getDrawable()).getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageInByte = baos.toByteArray();

            //set data
            //String user_id =sharedpreferences.getString("user_id","");
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), imageInByte);
            MultipartBody.Part body = MultipartBody.Part.createFormData("image", "image_" + user_id + ".jpg", requestFile);
            //assert user_id != null;
            RequestBody userId = RequestBody.create(MediaType.parse("text/plain"), user_id);

            //call the api
            loginApiInterface = ApiClient.getApiClient().create(LoginApiInterface.class);

            final ProgressDialog progressDialog = ProgressDialogPopup.showProgressDialog(this,
                    getResources().getString(R.string.loading), "");
            Call<ProfilePicUploadResponse> call = loginApiInterface.uploadprofilePic(body, userId);

            imageresponse[0] = false;
            call.enqueue(new Callback<ProfilePicUploadResponse>() {
                @Override
                public void onResponse(@NonNull Call<ProfilePicUploadResponse> call, @NonNull Response<ProfilePicUploadResponse> response) {
                    //Toast.makeText(EditProfileActivity.this, "Here i m", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                    //AlertPopup.alertDialogShow(EditProfileActivity.this, response.message(), "");
                    ProfilePicUploadResponse profilePicUploadResponse = response.body();
                    if (profilePicUploadResponse.getError() != null){
                        imageresponse[0] = true;
                        assert response.body() != null;
                        setResult(1);
                        finish();
                        Toast.makeText(EditProfileActivity.this, "Success", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(EditProfileActivity.this, "Here i m", Toast.LENGTH_SHORT).show();
                    }

                    if (response.isSuccessful()) {
                        //Toast.makeText(EditProfileActivity.this, "it is successfull", Toast.LENGTH_SHORT).show();

                        //AlertPopup.alertDialogShow(EditProfileActivity.this, response.body().getMessage().toString(), "");
                    } else {
                        //Toast.makeText(EditProfileActivity.this, "Not success", Toast.LENGTH_SHORT).show();
                        imageresponse[0] = false;
                        AlertPopup.alertDialogShow(EditProfileActivity.this, "Some error occurred", "");
                    /*setResult(1);
                    finish();*/
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ProfilePicUploadResponse> call, @NonNull Throwable t) { progressDialog.dismiss();
                    imageresponse[0] = false;
                    AlertPopup.alertDialogShow(EditProfileActivity.this, t.getMessage(), "");
                /*setResult(1);
                finish();*/
                }
            });
            return imageresponse[0];
        }
        else {
            setResult(1);
            finish();
            return imageresponse[0];
        }

    }

I have Pojo class named ProfilePicUploadResponse.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class ProfilePicUploadResponse {

    @SerializedName("error")
    @Expose
    private Boolean error;
    @SerializedName("message")
    @Expose
    private String message;

    public Boolean getError() {
        return error;
    }

    public void setError(Boolean error) {
        this.error = error;
    }

    public ProfilePicUploadResponse withError(Boolean error) {
        this.error = error;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public ProfilePicUploadResponse withMessage(String message) {
        this.message = message;
        return this;
    }
}

I have passed gson as well to retrofit builder
public class ApiClient {

    public static Retrofit retrofit=null;
    private static Gson gson = new GsonBuilder().setLenient().create();

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(7, TimeUnit.MINUTES)
            .readTimeout(7, TimeUnit.MINUTES)
            .writeTimeout(7, TimeUnit.MINUTES)
            .build();

    public static Retrofit getApiClient()
    {
        if(retrofit==null)
        {
            //scalar is for text and gson for json obect and arrays
            retrofit=new Retrofit.Builder().baseUrl(base_url)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return  retrofit;
    }
}

Every time I upload a new image it goes into OnFailure(). The call is asynchronous as it is calling .enqueue method.
Here is the my json response.
{"file_name":"CONSOLATION_Instagram.jpg","user_id":"3461","task_id":"6875","message":"Your Art is uploaded successfully!","error":false,"file_path":"https:\/\/yourmasterpieces.s3.ap-south-1.amazonaws.com\/media\/artworks\/v3\/image_3461_6875.jpg"}

Please help.

A: {"file_name":"CONSOLATION_Instagram.jpg","user_id":"3461","task_id":"6875","message":"Your Art is uploaded successfully!","error":false,"file_path":"https:\/\/yourmasterpieces.s3.ap-south-1.amazonaws.com\/media\/artworks\/v3\/image_3461_6875.jpg"}

line 1 column 5 in your json response is "error":false.
You are trying to use boxed data type (i.e. Boolean) instead of using primitive data type (boolean) which is not supported during parsing.
So in your response class, use boolean instead of Boolean.
public class ProfilePicUploadResponse {

    @SerializedName("error")
    @Expose
    private boolean error;
    @SerializedName("message")
    @Expose
    private String message;

    ....


text:
Q: preRenderView is called on every ajax request I am implementing infinite scrolling using jquery waypoints and jsf following link .
I have prerender for one of the xhtml on which infinite scrolling is required .
Now, as waypoint sends ajax request so why for every scroll it is calling prerender that means whole page is getting refeshed.
Please let me know how to solve this.

A: You seem to think that the preRenderView event is invoked only once during the construction of the view and not invoked on subsequent requests on the same view. This is untrue. The preRenderView event is invoked right before rendering of the view. The view is rendered on every request. This also includes ajax requests (how else should it produce the necessary HTML output for ajax requests?). So the behavior which you're seeing is fully expected. You was simply using the wrong tool for the job.
You should either be using the @PostConstruct method of a @ViewScoped bean,
@ManagedBean
@ViewScoped
public class Bean {

    @PostConstruct
    public void init() {
        // Do here your thing during construction of the view.
    }

    // ...
}

or be adding a negation check on FacesContext#isPostback() in the pre render view event listener
public void preRender() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // Do here your thing which should run on initial (GET) request only.
    }
}

See also:

*

*When to use f:viewAction / preRenderView versus PostConstruct?


text:
Q: Display a 3D image with vtk python I want to Display a 3D image with the vtk module python. The image was saved in .vti format. I wrote the following simple code but it does not work correctly. How i can fix that?
import vtk

file_name = 'Vug.vti'

# Read the source file.
reader = vtk.vtkNrrdReader()
reader.SetFileName(file_name)
reader.Update()

# Map the image through the lookup table
color = vtk.vtkImageMapToColors()
#color.SetLookupTable(table)
color.SetInputConnection(reader.GetOutputPort())

# Display the image
actor = vtk.vtkImageActor()
actor.GetMapper().SetInputConnection(color.GetOutputPort())

renderer = vtk.vtkRenderer()
renderer.AddActor(actor)

window = vtk.vtkRenderWindow()
window.AddRenderer(renderer)

# Set up the interaction
interactor = vtk.vtkRenderWindowInteractor()
window.SetInteractor(interactor)
window.Render()

# Start interaction
interactor.Start()

A: A vtkImageActor displays an image as a 2d object.  If you want to render a 3d volume, you need to use a vtkVolume object.
This example shows how to volume render in VTK:
https://github.com/Kitware/VTK/blob/master/Examples/VolumeRendering/Python/SimpleRayCast.py

A: With vtkplotter this is simply:
from vtkplotter import load, datadir, show
vol = load(datadir + 'vase.vti') # returns vtkVolume
# set color and trasparency transfer functions along the scalar range
vol.color(["green", "pink", "blue"]).alpha([0, 0, 0.2, 0.5, 0.9])
show(vol)


text:
Q: Append div to specific element I am trying to show a message below a list-group-item when a icon is clicked. This is the code i have to show my list

Feed dog

Email work

Icon click is detected with this code
 $("li").on("click", ".edit", function() {
    var id = $(this).data("id");
     //do something
 })

The code I want to use is below but i dont know how to select the right element
$(".list-group data1").append("
To be appended
");

So if id = 1 then show below first li, if id = 2 show below second etc.
How can i make sure that the message is inserted below the correct li?

A: You can do like this:
$('.edit').click(function(){

        $(this).parent().after('
To be appended
')

});

A: How can i make sure that the message is inserted below the correct li?
the clicked li and where you want to post the result must have the same id, see the following example, add id field to li for example:

Feed dog

    // append whatever you want to the div with same id as the  clicked div


text:
Q: Creating custom social icons I'm new to using AddThis, or any form of social media toolbars etc, however I have the following image:
http://songhype.com/wp-content/themes/song/images/social/twitter.png
I need to code this into a social icon, along with a Facebook version.
My initial idea was to just add that in as an image, and then position the text for the number of followers/tweets to be over the top of the grey portion, however I've found this to not work, is there any other method I could use?

A: With Twitter, you need to get a site key and use their API. Facebook provides a pretty simple copy/paste functionality and has the basic instructions for how to do it on their page.
If you check the HTML for the  you can replace the image with your own.
https://dev.twitter.com/docs/follow-button
https://developers.facebook.com/docs/reference/plugins/like/


text:
Q: create an array without entering the size in the new[] statement By mistake i forgot to enter the size of the array and wrote something like
int* ptr = new int[];

I was surprised when the code compiled. So, now since it compiled; could anyone let me know what is the meaning of this? it is creating an array of size?

A: As far as I can tell from looking at the disassembly, this is just a non-standard way of saying int* ptr = new int[0]; (see here for what that means).


text:
Q: Is there a way to set 'jump points' in VSCode? Very similar to this question:
Is there a way to jump to mark in Sublime Text?
But I'm asking for VSCode.
Say I'm in a file:
const a = {
   a: "1",
   b: "2",
   // <-- I'm editing here
}

const processThing = (thing) => {

  if (thing.a) {

  }
  // <-- I'm also editing here

}

I'm constantly between two parts of the file. Is there a keyboard-only way to jump between these two points?

A: There are extensions to do this.
See this Stack Overflow answer:
https://stackoverflow.com/questions/30179571/are-there-bookmarks-in-visual-studio-code#:~:text=%E2%80%93%20Edit%3A%20Found%20out%20how%20to,J%20to%20jump%20to%20it.
I'm finding this one pretty good.
https://github.com/alefragnani/vscode-bookmarks/blob/master/README.md

A: Look at the section Side by Side Editing in VSCode documentation
It seems perfect for your case.

*

*Split the editor with Ctrl + \

*Jump between editors using Ctrl + 1, Ctrl + 2

*It remembers the cursor position in both editors


text:
Q: Read API response in Angular2 & ionic I have successfully get it work to request data from API with http.get in Angular2. This is my http.get
this.http.get('http://localhost:8001/v1/recent', {
      headers: headers
  })
  .map(res => res.text())
  .subscribe(
    data => console.log(data.total),
    () => console.log('API request complete')
  );

The API is based on Laravel, it will return data as follows
{
   "total": 8,
   "per_page": 50,
   "current_page": 1,
   "last_page": 1,
   "next_page_url": null,
   "prev_page_url": null,
   "from": 1,
   "to": 8,
   "data": [
      {
         "id": 1,
         "name": "John Doe",
         "author": {
            "isBlocked": "0",
         }
      },
      {
         "id": 1,
         "name": "John Doe",
         "author": {
            "isBlocked": "0",
         }
      }
    ]
}

How can I retrieve the JSON object above in Angular2? and all of it's nested array?
console.log(data.total) above is return undefined

A: The json in your question is not properly formatted, you have an extra comma after "isBlocked":"0" (in line 15 and in line 22)
"author": {
   "isBlocked": "0",
}

which will make it a invalid JSON. Preventing Angular from parsing it correctly.
The other issue, you are calling .map(res => res.text()) which will convert your response body to a string not an object. If you want it as a javascript object do .map(res => res.json()) instead.
Here is a working plunker