问:
How to use maven active-profiles on Eclipse with testng execution
On my pom.xml I have created some profiles. On my Eclipse project I have selected the profiles I must use to run with TestNG. The test must doing different things depends on the profile. I try use ${project.activeProfiles[0].id}, but does not work for me.

The Eclipse selected profiles:

The TestNG execution error:

MVN commands:

When I run the mvn help:active-profiles command the result is:

```<code>The following profiles are active:
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

And the mvn help:all-profiles command result is:

```<code>[INFO] Listing Profiles for Project: com.myproject:project:jar:1.0
  Profile Id: UAT-Dev-Mt (Active: false , Source: pom)
  Profile Id: UAT-Dev-Bg (Active: false , Source: pom)
  Profile Id: PROD-Dev-Mt (Active: false , Source: pom)
  Profile Id: PROD-Dev-Bg (Active: false , Source: pom)
  Profile Id: Acceptance (Active: false , Source: pom)
  Profile Id: Regression (Active: false , Source: pom)
  Profile Id: CriticalPath (Active: false , Source: pom)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

Why TestNG on Eclipse does not work, for me, with this selected profiles and with the maven pom variable?

Thank you in advance.

答:
TestNG eclipse plugin does not have well integration with Maven, the limited feature provided by TestNG Eclipse plugin is just ready the system properties (and/or environment variables) defined in the pom.xml of current active profile.
anything else, like profile specific goals won't be executed at all.

so back to your case, if you just want to the profile managed system properties, you can select one active profile then simple run the testng tests, the properties will be injected to the runtime testng process. for anything else, not supported yet.

Body:
On my pom.xml I have created some profiles. On my Eclipse project I have selected the profiles I must use to run with TestNG. The test must doing different things depends on the profile. I try use ${project.activeProfiles[0].id}, but does not work for me.

The Eclipse selected profiles:

The TestNG execution error:

MVN commands:

When I run the mvn help:active-profiles command the result is:

The following profiles are active:
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

And the mvn help:all-profiles command result is:

[INFO] Listing Profiles for Project: com.myproject:project:jar:1.0
  Profile Id: UAT-Dev-Mt (Active: false , Source: pom)
  Profile Id: UAT-Dev-Bg (Active: false , Source: pom)
  Profile Id: PROD-Dev-Mt (Active: false , Source: pom)
  Profile Id: PROD-Dev-Bg (Active: false , Source: pom)
  Profile Id: Acceptance (Active: false , Source: pom)
  Profile Id: Regression (Active: false , Source: pom)
  Profile Id: CriticalPath (Active: false , Source: pom)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Why TestNG on Eclipse does not work, for me, with this selected profiles and with the maven pom variable?

Thank you in advance.


来源: stackexchange

问:
How can we add an external PDF to the current page with PDFsharp?
I get the stream of a PDF file and I am trying to add this to my current PDF.

```<code>        byte[] pdfBytes = interview.Application.CandidateResumeFile.File.FileBinary.ToArray();
        Stream pdfstream = new MemoryStream(imgBytes);
</code>```

This gives me the stream of the PDF file that I want to add to my page.

```<code>        PdfDocument doc = new PdfDocument();
        doc.Info.Title = "Test PDFSharp";
        PdfPage page = doc.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);

        ////////content

        const string filename = "test.pdf";
        doc.Save(filename);
        Process.Start(filename);
</code>```

Here is how my page is set up, and the page loads fine. I just want to add the PDF file to the page.

答:
PDFsharp comes with several samples that solve this task in different ways.

See Concatenate Documents:

http://pdfsharp.net/wiki/ConcatenateDocuments-sample.ashx

See Combine Documents:

http://pdfsharp.net/wiki/CombineDocuments-sample.ashx

Basically there are two options: draw an existing page onto a new page, allowing you to resize and scale it. Or add the page to the new document, creating an exact copy.

ContentLicense: CC BY-SA 3.0

Body:
I get the stream of a PDF file and I am trying to add this to my current PDF.

        byte[] pdfBytes = interview.Application.CandidateResumeFile.File.FileBinary.ToArray();
        Stream pdfstream = new MemoryStream(imgBytes);

This gives me the stream of the PDF file that I want to add to my page.

        PdfDocument doc = new PdfDocument();
        doc.Info.Title = "Test PDFSharp";
        PdfPage page = doc.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);

        ////////content

        const string filename = "test.pdf";
        doc.Save(filename);
        Process.Start(filename);

Here is how my page is set up, and the page loads fine. I just want to add the PDF file to the page.


问:
Angular JS how can i switch filters on checkbox values changed?
I have this code, now I want to create two checkboxes one for "emp_nome" and another for "local" when I check either of them I can search my input only for those checked values, help, please</p>

```<code><input type="text" id="myInput" ng-model="search.SN" placeholder="Search for names..">
<div style="overflow-x:auto;">

  <table id="myTable">
    <tr style="border-bottom:1px solid black;" class="header">
      <td>ID</td>
      <td>Nome Entidade</td>
      <td>Ultima Localização</td>
      <td>Categoria</td>
      <td>Nº de Reclamações contra Entidade</td>
      <td>Data da última reclamação</td>
    </tr>

    <tr ng-repeat="x in myData | filter: {emp_nome: search.SN} || filter: {local: search.SNs}" id="removal">
      <td>{{ x.id }}</td>
      <td style="background:rgba(0, 159, 255, 0.24);font-size:17px;"><u>{{ x.emp_nome }}</u></td>
      <td>{{ x.local }}</td>
      <td>{{ x.tipo }}</td>
      <td>
        <center>{{ x.emp_rec }}</center>
      </td>
      <td>
        <center>{{ x.data }}</center>
      </td>
    </tr>

  </table>

  <br><br>

</div>
</code>```

答:
You can make the filter expression dynamically and manage it in your controller. I mean ng-repeat="x in myData | filter: {emp_nome: search.SN}" could be ng-repeat="x in myData | filter: filterObject"

And you could manage to populate this filterObject to have the object you want to use in filter, by using ng-change (in your input text & checkbox) for example

example in ng-change may be:

```<code>if (checkboxValue === 'local') { //local checked
  $scope.filterObject = {local: $scope.search.SN};
} else if (checkboxValue === 'emp_nome') {//emp_nome checked
  $scope.filterObject = {emp_nome: $scope.search.SN};
} else { //filter by all
  $scope.filterObject = $scope.search.SN;
}
</code>```

it's just an example, I don't know how you manage it

Official doc about filter: https://docs.angularjs.org/api/ng/filter/filter

Body:
I have this code, now I want to create two checkboxes one for "emp_nome" and another for "local" when I check either of them I can search my input only for those checked values, help, please

<input type="text" id="myInput" ng-model="search.SN" placeholder="Search for names..">

      ID
      Nome Entidade
      Ultima Localização
      Categoria
      Nº de Reclamações contra Entidade
      Data da última reclamação

      {{ x.id }}
      {{ x.emp_nome }}
      {{ x.local }}
      {{ x.tipo }}

        {{ x.emp_rec }}

        {{ x.data }}

Body:
You can make the filter expression dynamically and manage it in your controller. I mean ng-repeat="x in myData | filter: {emp_nome: search.SN}" could be ng-repeat="x in myData | filter: filterObject"

And you could manage to populate this filterObject to have the object you want to use in filter, by using ng-change (in your input text & checkbox) for example

example in ng-change may be:

if (checkboxValue === 'local') { //local checked
  $scope.filterObject = {local: $scope.search.SN};
} else if (checkboxValue === 'emp_nome') {//emp_nome checked
  $scope.filterObject = {emp_nome: $scope.search.SN};
} else { //filter by all
  $scope.filterObject = $scope.search.SN;
}

it's just an example, I don't know how you manage it

Official doc about filter: https://docs.angularjs.org/api/ng/filter/filter


问:
Update M2M relationship django rest framework (many=true)
I try to update a channel:

```<code>PUT
content [{'url': 'http://localhost:8000/api/movies/2', 'title': u'Ariel', 'backdrop_path': u'/z2QUexmccqrvw1kDMw3R8TxAh5E.jpg', 'popularity': 0.082, 'poster_path': u'/8ld3BEg8gnynRsfj2AzbLocD8NR.jpg', 'release_date': datetime.date(1988, 10, 21), 'runtime': 69L, 'tagline': u'', 'vote_average': 9.0, 'vote_count': 0L}]
csrfmiddlewaretoken XXXXXXXXXXXXXXXXXXXXXXXXXXx
name    cody private
owner   http://localhost:8000/api/users/1
private 1
</code>```

And I get this error:

```<code>instance should be a queryset or other iterable with many=True
</code>```

And here is the code you need to understand what's going on.

```<code>class Channel(models.Model):
    """
    A channel is a "container" for a users movies and television shows.
    """
    PUBLIC_VISIBILITY, PRIVATE_VISIBILITY = 0, 1
    VISIBILITY_CHOICES = (
        (PUBLIC_VISIBILITY, 'public'),
        (PRIVATE_VISIBILITY, 'private'),
    )
    owner = models.ForeignKey(User, related_name='owned_channels')
    name = models.CharField(max_length=60)
    content = models.ManyToManyField(Movie, db_table='channel_contents',
                                     related_name='channels', null=True, blank=True, default=None)
    subscribers = models.ManyToManyField(User, db_table='channel_subscribers',
                                         related_name='subscribed_channels', null=True, blank=True, default=None)
    created = models.DateTimeField(auto_now_add=True)
    last_mod = models.DateTimeField(auto_now=True)
    query = models.CharField(max_length=255, default='')
    private = models.IntegerField(choices=VISIBILITY_CHOICES, default=PRIVATE_VISIBILITY)

    default = models.BooleanField(default=False)

class Movie(models.Model):
    id = models.BigIntegerField(primary_key=True)
    adult = models.BooleanField()
    backdrop_path = models.ImageField(upload_to='backdrop/')
    budget = models.IntegerField(blank=True, null=True)
    genres = models.ManyToManyField('Genre',
                                    through='MovieGenre',
                                    blank=True, null=True)
    homepage = models.URLField(blank=True, null=True)
    imdb_id = models.CharField(max_length=20, blank=True, null=True)
    original_title = models.CharField(max_length=100)
    overview = models.TextField(blank=True, null=True)
    popularity = models.FloatField(blank=True, null=True)
    poster_path = models.ImageField(upload_to='poster/')
    release_date = models.DateField(blank=True, null=True)
    revenue = models.IntegerField(blank=True, null=True)
    runtime = models.IntegerField(blank=True, null=True)
    tagline = models.CharField(max_length=200, blank=True, null=True)
    title = models.CharField(max_length=100, db_index=True)
    vote_average = models.FloatField(blank=True, null=True)
    vote_count = models.IntegerField(blank=True, null=True)
    actors = models.ManyToManyField('Actor',
                                    through='MovieActor',
                                    blank=True, null=True)
    directors = models.ManyToManyField('Director',
                                       through='MovieDirector',
                                       blank=True, null=True)
    production_companies = models.ManyToManyField(
        'ProductionCompany',
        through='MovieProduction',
        blank=True, null=True)
</code>```

Channel serializing code:

```<code># Routes
url(r'^channels$', ChannelList.as_view(), name='channel-list'),
url(r'^channels/(?P<pk>\d+)$', ChannelDetail.as_view(), name='channel-detail'),

# Views
class ChannelList(generics.ListCreateAPIView):
    """
    API endpoint that represents a list of users.
    """
    model = Channel
    serializer_class = ChannelSerializer

class ChannelDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    API endpoint that represents a single users.
    """
    model = Channel
    serializer_class = ChannelSerializer

# Serializer
class ChannelSerializer(serializers.HyperlinkedModelSerializer):
    content = MovieSerializer(many=True)

    class Meta:
        model = Channel
        fields = ('url', 'owner', 'name', 'content', 'private')
</code>```

答:
If you want to update the nested relation you can do like this,

```<code>      class SchoolSerializer(serializers.HyperlinkedModelSerializer):

                students = StudentSerializer(many=True, read_only=True)
                students_ids = serializers.PrimaryKeyRelatedField(many=True,\
                read_only=False, queryset=Student.objects.all(),\
                source='students')

                class Meta:
                    model = School
                    fields = ('name', 'image', 'address', 'url',\
                    'students', 'students_ids')
</code>```

use PrimaryKeyRelatedField this will allow you to create, update, nested relations (Many-to-Many field) by just passing a list of id's
students will give you nested data,
students_ids can be used for write operations

Body:
I try to update a channel:

PUT
content [{'url': 'http://localhost:8000/api/movies/2', 'title': u'Ariel', 'backdrop_path': u'/z2QUexmccqrvw1kDMw3R8TxAh5E.jpg', 'popularity': 0.082, 'poster_path': u'/8ld3BEg8gnynRsfj2AzbLocD8NR.jpg', 'release_date': datetime.date(1988, 10, 21), 'runtime': 69L, 'tagline': u'', 'vote_average': 9.0, 'vote_count': 0L}]
csrfmiddlewaretoken XXXXXXXXXXXXXXXXXXXXXXXXXXx
name    cody private
owner   http://localhost:8000/api/users/1
private 1

And I get this error:

instance should be a queryset or other iterable with many=True

And here is the code you need to understand what's going on.

class Channel(models.Model):
    """
    A channel is a "container" for a users movies and television shows.
    """
    PUBLIC_VISIBILITY, PRIVATE_VISIBILITY = 0, 1
    VISIBILITY_CHOICES = (
        (PUBLIC_VISIBILITY, 'public'),
        (PRIVATE_VISIBILITY, 'private'),
    )
    owner = models.ForeignKey(User, related_name='owned_channels')
    name = models.CharField(max_length=60)
    content = models.ManyToManyField(Movie, db_table='channel_contents',
                                     related_name='channels', null=True, blank=True, default=None)
    subscribers = models.ManyToManyField(User, db_table='channel_subscribers',
                                         related_name='subscribed_channels', null=True, blank=True, default=None)
    created = models.DateTimeField(auto_now_add=True)
    last_mod = models.DateTimeField(auto_now=True)
    query = models.CharField(max_length=255, default='')
    private = models.IntegerField(choices=VISIBILITY_CHOICES, default=PRIVATE_VISIBILITY)

    default = models.BooleanField(default=False)

class Movie(models.Model):
    id = models.BigIntegerField(primary_key=True)
    adult = models.BooleanField()
    backdrop_path = models.ImageField(upload_to='backdrop/')
    budget = models.IntegerField(blank=True, null=True)
    genres = models.ManyToManyField('Genre',
                                    through='MovieGenre',
                                    blank=True, null=True)
    homepage = models.URLField(blank=True, null=True)
    imdb_id = models.CharField(max_length=20, blank=True, null=True)
    original_title = models.CharField(max_length=100)
    overview = models.TextField(blank=True, null=True)
    popularity = models.FloatField(blank=True, null=True)
    poster_path = models.ImageField(upload_to='poster/')
    release_date = models.DateField(blank=True, null=True)
    revenue = models.IntegerField(blank=True, null=True)
    runtime = models.IntegerField(blank=True, null=True)
    tagline = models.CharField(max_length=200, blank=True, null=True)
    title = models.CharField(max_length=100, db_index=True)
    vote_average = models.FloatField(blank=True, null=True)
    vote_count = models.IntegerField(blank=True, null=True)
    actors = models.ManyToManyField('Actor',
                                    through='MovieActor',
                                    blank=True, null=True)
    directors = models.ManyToManyField('Director',
                                       through='MovieDirector',
                                       blank=True, null=True)
    production_companies = models.ManyToManyField(
        'ProductionCompany',
        through='MovieProduction',
        blank=True, null=True)

Channel serializing code:

# Routes
url(r'^channels$', ChannelList.as_view(), name='channel-list'),
url(r'^channels/(?P<pk>\d+)$', ChannelDetail.as_view(), name='channel-detail'),

# Views
class ChannelList(generics.ListCreateAPIView):
    """
    API endpoint that represents a list of users.
    """
    model = Channel
    serializer_class = ChannelSerializer

class ChannelDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    API endpoint that represents a single users.
    """
    model = Channel
    serializer_class = ChannelSerializer

# Serializer
class ChannelSerializer(serializers.HyperlinkedModelSerializer):
    content = MovieSerializer(many=True)

    class Meta:
        model = Channel
        fields = ('url', 'owner', 'name', 'content', 'private')

Body:
If you want to update the nested relation you can do like this,

      class SchoolSerializer(serializers.HyperlinkedModelSerializer):

                students = StudentSerializer(many=True, read_only=True)
                students_ids = serializers.PrimaryKeyRelatedField(many=True,\
                read_only=False, queryset=Student.objects.all(),\
                source='students')

                class Meta:
                    model = School
                    fields = ('name', 'image', 'address', 'url',\
                    'students', 'students_ids')

use PrimaryKeyRelatedField this will allow you to create, update, nested relations (Many-to-Many field) by just passing a list of id's
students will give you nested data,
students_ids can be used for write operations


问:
checking if word exist in english dictionary r
I'm performing some text analysis on  mutliple resume to generate a wordcloud using wordcloud package along with tm package for preprocessing the corpus of document in R.

The problems i'm facing are :

Checking whether the word in corpus have some meaning ie. it belongs to english dictionary.

How to mine / process multiple resumes together.

Checking for tech terms like r,java,eclipse etc.

Appreciate the help.

答:
I've faced some issues before, so sharing solutions to your problems :

1. There is a package qdapDictionaries which is a collection of dictionaries and word lists for use with the 'qdap' package.

```<code>library(qdapDictionaries)

#create custom function
is.word  <- function(x) x %in% GradyAugmented # or use any dataset from package

#use this function to filter words, df = dataframe from corpus
df <- df[which(is.word(df$terms)),]
</code>```

2. Using VCorpus(DirSource(...)) to create your corpus from directory containing all resumes

```<code>resumeDir <- "path/all_resumes/"
myCorpus <- VCorpus(DirSource(resumeDir))
</code>```

3. Create your custom dictionary file like my_dict.csv containing tech terms.

```<code>#read custom dictionary
tech_dict <- read.csv("path/to/my_dict.csv", stringsAsFactors = FALSE)
#create tech function
is.tech <- function(x) x %in% tech_dict
#filter
tech_df <- df[which(is.tech(df$terms)),]
</code>```

Hope this helps.

Body:
I've faced some issues before, so sharing solutions to your problems :

1. There is a package qdapDictionaries which is a collection of dictionaries and word lists for use with the 'qdap' package.

library(qdapDictionaries)

#create custom function
is.word  <- function(x) x %in% GradyAugmented # or use any dataset from package

#use this function to filter words, df = dataframe from corpus
df <- df[which(is.word(df$terms)),]

2. Using VCorpus(DirSource(...)) to create your corpus from directory containing all resumes

resumeDir <- "path/all_resumes/"
myCorpus <- VCorpus(DirSource(resumeDir))

3. Create your custom dictionary file like my_dict.csv containing tech terms.

#read custom dictionary
tech_dict <- read.csv("path/to/my_dict.csv", stringsAsFactors = FALSE)
#create tech function
is.tech <- function(x) x %in% tech_dict
#filter
tech_df <- df[which(is.tech(df$terms)),]

Hope this helps.


问:
Java unable to find valid certification
I'm having trouble getting a RuntimeException while sending email using Java to Zimbra Mail Server.

Here is my Java class Test.java

```<code>public class Test {

    public static void main(String[] args) {
        sendMail("receiver@domain.com","Test","Test Message",null);
    }

    public static Properties getMailProperties() {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.bevmi.com");
        props.put("mail.smtp.port", "587");
        return props;
    }

    public static boolean sendMail(String to, String subject,String text,String cc)  {
        final String username = "user@domain.com;
        final String password = "password";
        Properties props = getMailProperties();
        Session session = Session.getInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSender(new InternetAddress("sender@domain.com"));
            if ((cc!=null) && (!cc.isEmpty())) {
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }
            message.setSubject(subject);
            message.setText(text,  "UTF-8", "html");
            System.out.println("Sending Message to :" + to);
            Transport.send(message);
            System.out.println("Email Sent");
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
</code>```

And I got the following RuntimeException stacktrace in my "main" thread.

java.lang.RuntimeException: javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at Test.sendMail(Test.java:57) at Test.main(Test.java:13)

答:
Did you take a look at this?
This could be your solutions. It seems that your settings are missing something.

In the link I gave you the same issue is solved by adding this code line.

props.put("mail.smtp.ssl.trust", "smtp.gmail.com");

That in this case should not contain "smtp.gmail.com" but "smtp.benvi.com" if that's your true host.

I hope to be helpful.

Title: Java unable to find valid certification

Body:
I'm having trouble getting a RuntimeException while sending email using Java to Zimbra Mail Server.

Here is my Java class Test.java

public class Test {

    public static void main(String[] args) {
        sendMail("receiver@domain.com","Test","Test Message",null);
    }

    public static Properties getMailProperties() {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.bevmi.com");
        props.put("mail.smtp.port", "587");
        return props;
    }

    public static boolean sendMail(String to, String subject,String text,String cc)  {
        final String username = "user@domain.com;
        final String password = "password";
        Properties props = getMailProperties();
        Session session = Session.getInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSender(new InternetAddress("sender@domain.com"));
            if ((cc!=null) && (!cc.isEmpty())) {
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }
            message.setSubject(subject);
            message.setText(text,  "UTF-8", "html");
            System.out.println("Sending Message to :" + to);
            Transport.send(message);
            System.out.println("Email Sent");
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

And I got the following RuntimeException stacktrace in my "main" thread.

java.lang.RuntimeException: javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at Test.sendMail(Test.java:57) at Test.main(Test.java:13)


问:
Joining two dataframes in Spark
When I'm trying to join two data frames using

DataFrame joindf = dataFrame.join(df, df.col(joinCol)); //.equalTo(dataFrame.col(joinCol)));
```

My program is throwing below exception

org.apache.spark.sql.AnalysisException: join condition 'url' of type
  string is not a boolean.;

Here joinCol value is url
Need inputs as what could possibly cause these exceptions

答:
What that means is that the join condition should evaluate to an expression. Lets say we want to join 2 dataframes based on id, so what we can do is :

With Python:

```<code>df1.join(df2, df['id'] == df['id'], 'left')  # 3rd parameter is type of join which in this case is left join
</code>```

With Scala:

```<code>df1.join(df2, df('id') === df('id'))    // create inner join based on id column
</code>```

ContentLicense: CC BY-SA 4.0

Title: Joining two dataframes in Spark

Body:
When I'm trying to join two data frames using

DataFrame joindf = dataFrame.join(df, df.col(joinCol)); //.equalTo(dataFrame.col(joinCol)));

My program is throwing below exception

org.apache.spark.sql.AnalysisException: join condition 'url' of type
  string is not a boolean.;

Here joinCol value is url
Need inputs as what could possibly cause these exceptions

Body:
What that means is that the join condition should evaluate to an expression. Lets say we want to join 2 dataframes based on id, so what we can do is :

With Python:

df1.join(df2, df['id'] == df['id'], 'left')  # 3rd parameter is type of join which in this case is left join

With Scala:

df1.join(df2, df('id') === df('id'))    // create inner join based on id column


问:
java.lang.OutOfMemoryError at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)?
I am facing this issue in uploading the file to the google drive, i am uploading the recorded audio to the google drive at that time this exception is occurring

The code used for writing the content in the file

```<code>                      OutputStream outputStream = result.getDriveContents().getOutputStream();
                    FileInputStream fis;
                    try {
                        fis = new FileInputStream(file);
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buf = new byte[1024];
                        int n;
                        while (-1 != (n = fis.read(buf)))
                            baos.write(buf, 0, n);
                        byte[] photoBytes = baos.toByteArray();
                        outputStream.write(photoBytes);

                        outputStream.close();
                        outputStream = null;
                        fis.close();
                        fis = null;

                        Log.e("File Size", "Size " + file.length());

                    } catch (FileNotFoundException e) {
                        Log.v("EXCEPTION", "FileNotFoundException: " + e.getMessage());
                    } catch (IOException e1) {
                        Log.v("EXCEPTION", "Unable to write file contents." + e1.getMessage());
                    }
</code>```

The exception occurs in the line `  baos.write(buf, 0, n);

Please help me how to solve this error.`

答:
You are getting OOM because you try to read full file into the memory before writing it to the google drive outputStream. The file may be too large to be stored in the memory. This way you need to write it part by part. It is easy to accomplish using this method:

```<code>  private static final int BUFFER_SIZE = 1024;

  public static long copy(InputStream from, OutputStream to)
      throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    long total = 0;
    while (true) {
      int r = from.read(buffer);
      if (r == -1) {
        break;
      }
      to.write(buffer, 0, r);
      total += r;
    }
    return total;
  }
</code>```

The method will return number of bytes copied.

Body:
I am facing this issue in uploading the file to the google drive, i am uploading the recorded audio to the google drive at that time this exception is occurring

The code used for writing the content in the file

                      OutputStream outputStream = result.getDriveContents().getOutputStream();
                    FileInputStream fis;
                    try {
                        fis = new FileInputStream(file);
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buf = new byte[1024];
                        int n;
                        while (-1 != (n = fis.read(buf)))
                            baos.write(buf, 0, n);
                        byte[] photoBytes = baos.toByteArray();
                        outputStream.write(photoBytes);

                        outputStream.close();
                        outputStream = null;
                        fis.close();
                        fis = null;

                        Log.e("File Size", "Size " + file.length());

                    } catch (FileNotFoundException e) {
                        Log.v("EXCEPTION", "FileNotFoundException: " + e.getMessage());
                    } catch (IOException e1) {
                        Log.v("EXCEPTION", "Unable to write file contents." + e1.getMessage());
                    }

The exception occurs in the line `  baos.write(buf, 0, n);

Please help me how to solve this error.`

Body:
You are getting OOM because you try to read full file into the memory before writing it to the google drive outputStream. The file may be too large to be stored in the memory. This way you need to write it part by part. It is easy to accomplish using this method:

  private static final int BUFFER_SIZE = 1024;

  public static long copy(InputStream from, OutputStream to)
      throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    long total = 0;
    while (true) {
      int r = from.read(buffer);
      if (r == -1) {
        break;
      }
      to.write(buffer, 0, r);
      total += r;
    }
    return total;
  }

The method will return number of bytes copied.


问:
Height not being respected in absolutely positioned table
If an absolutely positioned element with display: table has height explicitly set, if content height is larger than provided height value, then the element will shrink wrap the content and not consider the height value.

#main {
  width: 100px;
  height: 29px;
  position: absolute;
  top: 20px;
  left: 200px;
  border: 1px red dashed;
  display: table;
  table-layout: fixed;
  border-spacing: 0;
  border-collapse: separate;
}

#child {
  display: table-cell;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main">
  <div id="child">Custom Text With Validation:</div>
</div></code>```

答:
It is the table cell that doesn't honor its parent's height for the same reason i doesn't honor max-height, hence pushing the table's size.

Here is 2 ways to make this to work, either set position: absolute on the child

#main {
  width: 100px;
  height: 29px;
  position: absolute;
  top: 20px;
  left: 200px;
  border: 1px red dashed;
  display: table;
  table-layout: fixed;
  border-spacing: 0;
  border-collapse: separate;
}
#child {
  position: absolute;
  display: table-cell;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main">
  <div id="child">Custom Text With Validation:
  </div>
</div></code>```

or add an extra element inside the child and set the height on that.

#main {
  width: 100px;
  height: 29px;
  position: absolute;
  top: 20px;
  left: 200px;
  border: 1px red dashed;
  display: table;
  table-layout: fixed;
  border-spacing: 0;
  border-collapse: separate;
}
#child {
  display: table-cell;
}
#child div {
  height: 29px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main">
  <div id="child">
    <div>Custom Text With Validation:</div>
  </div>
</div></code>```

Adding overflow: hidden on the table will also properly "cut" of the excess.

Body:
If an absolutely positioned element with display: table has height explicitly set, if content height is larger than provided height value, then the element will shrink wrap the content and not consider the height value.

#main {
  width: 100px;
  height: 29px;
  position: absolute;
  top: 20px;
  left: 200px;
  border: 1px red dashed;
  display: table;
  table-layout: fixed;
  border-spacing: 0;
  border-collapse: separate;
}

#child {
  display: table-cell;
}

Custom Text With Validation:

Body:
It is the table cell that doesn't honor its parent's height for the same reason i doesn't honor max-height, hence pushing the table's size.

Here is 2 ways to make this to work, either set position: absolute on the child

#main {
  width: 100px;
  height: 29px;
  position: absolute;
  top: 20px;
  left: 200px;
  border: 1px red dashed;
  display: table;
  table-layout: fixed;
  border-spacing: 0;
  border-collapse: separate;
}
#child {
  position: absolute;
  display: table-cell;
}

<div id="main">
  <div id="child">Custom Text With Validation:
  </div>
</div>

or add an extra element inside the child and set the height on that.

#main {
  width: 100px;
  height: 29px;
  position: absolute;
  top: 20px;
  left: 200px;
  border: 1px red dashed;
  display: table;
  table-layout: fixed;
  border-spacing: 0;
  border-collapse: separate;
}
#child {
  display: table-cell;
}
#child div {
  height: 29px;
}

<div id="main">
  <div id="child">
    <div>Custom Text With Validation:</div>
  </div>
</div>

Adding overflow: hidden on the table will also properly "cut" of the excess.


问:
How can I recursively find and run all Junit 4 tests within Eclipse?
I would like to run all junit 4 tests within my Eclipse project.  The project is setup with /source and /test.  Under /test are various packages, such as:

```<code>com.yaddayadda.test.core.entity
com.yaddayadda.test.core.framework
</code>```

If I right-click at the /test level in Package Explorer and choose Run As; Junit Test I receive the error:

```<code>No tests found with test runner 'JUnit 4'.
</code>```

If I right-click on com.yaddayadda.test.core.entity, then it finds and runs all the tests within that package.  So the @Test annotations are correct (they are also picked up by Ant correctly on the build server).  However, if I try and run all tests within com.yaddayadda.test.core then it finds none.

Basically, it only seems to look within the package rather the recusively at all children.  Is there a way to fix this?

答:
I found that Burt Beckwith's code is great but it will run every test in the project regardless of where you place AllTests.  This modification to one function will allow you to place AllTests in any subdirectory of your project and it will only run tests under that location.</p>

```<code>private static Class<?>[] findClasses() {List<File> classFiles = new ArrayList<File>();
  String packagepath = AllTests.class.getPackage().getName().replace(".", "/");
  File RELATIVE_DIR = new File( CLASSES_DIR.getAbsolutePath() + "\\" + packagepath );
  findClasses(classFiles, RELATIVE_DIR);
  List<Class<?>> classes = convertToClasses(classFiles, CLASSES_DIR);
  return classes.toArray(new Class[classes.size()]);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would like to run all junit 4 tests within my Eclipse project.  The project is setup with /source and /test.  Under /test are various packages, such as:

com.yaddayadda.test.core.entity
com.yaddayadda.test.core.framework

If I right-click at the /test level in Package Explorer and choose Run As; Junit Test I receive the error:

No tests found with test runner 'JUnit 4'.

If I right-click on com.yaddayadda.test.core.entity, then it finds and runs all the tests within that package.  So the @Test annotations are correct (they are also picked up by Ant correctly on the build server).  However, if I try and run all tests within com.yaddayadda.test.core then it finds none.

Basically, it only seems to look within the package rather the recusively at all children.  Is there a way to fix this?

Body:
I found that Burt Beckwith's code is great but it will run every test in the project regardless of where you place AllTests.  This modification to one function will allow you to place AllTests in any subdirectory of your project and it will only run tests under that location.

private static Class<?>[] findClasses() {List<File> classFiles = new ArrayList<File>();
  String packagepath = AllTests.class.getPackage().getName().replace(".", "/");
  File RELATIVE_DIR = new File( CLASSES_DIR.getAbsolutePath() + "\\" + packagepath );
  findClasses(classFiles, RELATIVE_DIR);
  List<Class<?>> classes = convertToClasses(classFiles, CLASSES_DIR);
  return classes.toArray(new Class[classes.size()]);
}


问:
how to send encoded data from python to nodejs
I want to send some string data from Python3 to nodeJs. The string is Korean characters and I am encoding it to utf8.(Cause I don't know other ways sending data safely.) When I send(from python) it is ByteStream and in nodeJs I receive it as Array. I convert this Array to String. But now I cannot decode string back to original Korean characters.
Here are some codes I am using.

python

```<code>input = sys.argv[1]
d = bot.get_response(input)
data = str(d).encode('utf8')

print(data)
</code>```

nodeJs

```<code>var utf = require('utf8');
var python = require('python-shell');

var pyt = path.normalize('path/to/my/python.exe'),
        scrp = path.normalize('path/to/my/scriptsFolder/'),

    var options = {
        mode: 'text',
        pythonPath: pyt,
        pythonOptions: ['-u'],
        scriptPath: scrp,
        encoding: 'utf8',
        args: [message]
    };

    python.run('test.py', options, function (err, results) {

        //here I need to decode 'results'
        var originalString = utf.encode(results.toString());// that code is not working for me

    });
</code>```

I have used several libs like utf8 to decode but didn't help.
Can someone please give some idea how to make it work.

EDIT

I have to edit with some more info.
I have tried @smarx approach but did not work.

I have two cases:

1. if I send data as string from python here is what I get in nodeJs b'\xec\x95\x88\xeb\x85\x95\xed\x95\x98\xec\x8b\xad\xeb\x8b\x88\xea\xb9\x8c? \xec\x9d\xb4\xed\x9a\xa8\xec\xa2\x85 \xea\xb3\xa0\xea\xb0\x9d\xeb\x8b\x98! \xeb\x8f\x99\xec\x96\x91\xeb\xa7\xa4\xec\xa7\x81\xec\x9e\x85\xeb\x8b\x88\xeb\x8b\xa4

2. if I encode data and send. I get �ȳ��Ͻʴϱ�? ��ȿ�� ������! �

答:
I'm still not sure what python.run does, since you won't share that code, but here's my version of the code, which is working fine:

test.py

```<code>print("안녕 세상")
</code>```

app.js

```<code>const { exec } = require('child_process');

exec('python3 test.py', function (err, stdout, stderr) {
    console.log(stdout);
});

// Output:
// 안녕 세상
</code>```

Body:
I want to send some string data from Python3 to nodeJs. The string is Korean characters and I am encoding it to utf8.(Cause I don't know other ways sending data safely.) When I send(from python) it is ByteStream and in nodeJs I receive it as Array. I convert this Array to String. But now I cannot decode string back to original Korean characters.
Here are some codes I am using.

python

input = sys.argv[1]
d = bot.get_response(input)
data = str(d).encode('utf8')

print(data)

nodeJs

var utf = require('utf8');
var python = require('python-shell');

var pyt = path.normalize('path/to/my/python.exe'),
        scrp = path.normalize('path/to/my/scriptsFolder/'),

    var options = {
        mode: 'text',
        pythonPath: pyt,
        pythonOptions: ['-u'],
        scriptPath: scrp,
        encoding: 'utf8',
        args: [message]
    };

    python.run('test.py', options, function (err, results) {

        //here I need to decode 'results'
        var originalString = utf.encode(results.toString());// that code is not working for me

    });

I have used several libs like utf8 to decode but didn't help.
Can someone please give some idea how to make it work.

EDIT

I have to edit with some more info.
I have tried @smarx approach but did not work.

I have two cases:

1. if I send data as string from python here is what I get in nodeJs b'\xec\x95\x88\xeb\x85\x95\xed\x95\x98\xec\x8b\xad\xeb\x8b\x88\xea\xb9\x8c? \xec\x9d\xb4\xed\x9a\xa8\xec\xa2\x85 \xea\xb3\xa0\xea\xb0\x9d\xeb\x8b\x98! \xeb\x8f\x99\xec\x96\x91\xeb\xa7\xa4\xec\xa7\x81\xec\x9e\x85\xeb\x8b\x88\xeb\x8b\xa4

2. if I encode data and send. I get �ȳ��Ͻʴϱ�? ��ȿ�� ������! �

Body:
I'm still not sure what python.run does, since you won't share that code, but here's my version of the code, which is working fine:

test.py

print("안녕 세상")

app.js

const { exec } = require('child_process');

exec('python3 test.py', function (err, stdout, stderr) {
    console.log(stdout);
});

// Output:
// 안녕 세상


问:
How to set data for logistic regression in scala?
I am new to scala and I want to implement a logistic regression model.So initially I load a csv file as below:

```<code>val sqlContext = new org.apache.spark.sql.SQLContext(sc)
 val df = sqlContext.read.format("com.databricks.spark.csv")
    .option("header", "true")
    .option("inferSchema", "true")
    .load("D:/sample.txt")
</code>```

The file is as below:

```<code>P,P,A,A,A,P,NB
N,N,A,A,A,N,NB
A,A,A,A,A,A,NB
P,P,P,P,P,P,NB
N,N,P,P,P,N,NB
A,A,P,P,P,A,NB
P,P,A,P,P,P,NB
P,P,P,A,A,P,NB
P,P,A,P,A,P,NB
P,P,A,A,P,P,NB
P,P,P,P,A,P,NB
P,P,P,A,P,P,NB
N,N,A,P,P,N,NB
N,N,P,A,A,N,NB
N,N,A,P,A,N,NB
N,N,A,P,A,N,NB
N,N,A,A,P,N,NB
N,N,P,P,A,N,NB
N,N,P,A,P,N,NB
A,A,A,P,P,A,NB
A,A,P,A,A,A,NB
A,A,A,P,A,A,NB
A,A,A,A,P,A,NB
A,A,P,P,A,A,NB
A,A,P,A,P,A,NB
P,N,A,A,A,P,NB
N,P,A,A,A,N,NB
P,N,A,A,A,N,NB
P,N,P,P,P,P,NB
N,P,P,P,P,N,NB
</code>```

Then I want to train the model by below code:

```<code>val lr = new LogisticRegression()
      .setMaxIter(10)
      .setRegParam(0.3)
      .setElasticNetParam(0.8)
      .setFeaturesCol("Feature")
      .setLabelCol("Label")
</code>```

Then I fit the model by below:

```<code> val lrModel = lr.fit(df)

println(lrModel.coefficients +"are the coefficients")
println(lrModel.interceptVector+"are the intercerpt vactor")
println(lrModel.summary +"is summary")
</code>```

But it is not printing the results.

Any help is appreciated.

答:
from your code:

```<code>val lr = new LogisticRegression()
      .setMaxIter(10)
      .setRegParam(0.3)
      .setElasticNetParam(0.8)
      .setFeaturesCol("Feature")  <- here
      .setLabelCol("Label") <- here
</code>```

you are setting features column and label column. As you didn't mention column names, i am assuming the column containing NB values is your label and you want to include all others are the columns for prediction.

All predictor variables that you want include in your model, needs to be in form of single vector column, generally called as features column. You need to create it using VectorAssembler as follows:

```<code>import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.linalg.Vectors

//creating features column
val assembler = new VectorAssembler()
  .setInputCols(Array(" insert your column names here "))
  .setOutputCol("Feature")
</code>```

Refer: https://spark.apache.org/docs/latest/ml-features.html#vectorassembler.

Now you can proceed to fit the logistic regression model. pipeline is used to combine multiple transformations beforefitting the data.

```<code>val pipeline = new Pipeline().setStages(Array(assembler,lr))

//fitting the model
val lrModel = pipeline.fit(df)
</code>```

Body:
I am new to scala and I want to implement a logistic regression model.So initially I load a csv file as below:

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
 val df = sqlContext.read.format("com.databricks.spark.csv")
    .option("header", "true")
    .option("inferSchema", "true")
    .load("D:/sample.txt")

The file is as below:

P,P,A,A,A,P,NB
N,N,A,A,A,N,NB
A,A,A,A,A,A,NB
P,P,P,P,P,P,NB
N,N,P,P,P,N,NB
A,A,P,P,P,A,NB
P,P,A,P,P,P,NB
P,P,P,A,A,P,NB
P,P,A,P,A,P,NB
P,P,A,A,P,P,NB
P,P,P,P,A,P,NB
P,P,P,A,P,P,NB
N,N,A,P,P,N,NB
N,N,P,A,A,N,NB
N,N,A,P,A,N,NB
N,N,A,P,A,N,NB
N,N,A,A,P,N,NB
N,N,P,P,A,N,NB
N,N,P,A,P,N,NB
A,A,A,P,P,A,NB
A,A,P,A,A,A,NB
A,A,A,P,A,A,NB
A,A,A,A,P,A,NB
A,A,P,P,A,A,NB
A,A,P,A,P,A,NB
P,N,A,A,A,P,NB
N,P,A,A,A,N,NB
P,N,A,A,A,N,NB
P,N,P,P,P,P,NB
N,P,P,P,P,N,NB

Then I want to train the model by below code:

val lr = new LogisticRegression()
      .setMaxIter(10)
      .setRegParam(0.3)
      .setElasticNetParam(0.8)
      .setFeaturesCol("Feature")
      .setLabelCol("Label")

Then I fit the model by below:

 val lrModel = lr.fit(df)

println(lrModel.coefficients +"are the coefficients")
println(lrModel.interceptVector+"are the intercerpt vactor")
println(lrModel.summary +"is summary")

But it is not printing the results.

Any help is appreciated.

Body:
from your code:

val lr = new LogisticRegression()
      .setMaxIter(10)
      .setRegParam(0.3)
      .setElasticNetParam(0.8)
      .setFeaturesCol("Feature")  <- here
      .setLabelCol("Label") <- here

you are setting features column and label column. As you didn't mention column names, i am assuming the column containing NB values is your label and you want to include all others are the columns for prediction.

All predictor variables that you want include in your model, needs to be in form of single vector column, generally called as features column. You need to create it using VectorAssembler as follows:

import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.linalg.Vectors

//creating features column
val assembler = new VectorAssembler()
  .setInputCols(Array(" insert your column names here "))
  .setOutputCol("Feature")

Refer: https://spark.apache.org/docs/latest/ml-features.html#vectorassembler.

Now you can proceed to fit the logistic regression model. pipeline is used to combine multiple transformations beforefitting the data.

val pipeline = new Pipeline().setStages(Array(assembler,lr))

//fitting the model
val lrModel = pipeline.fit(df)


问:
Ordered associative containers with identity-based equality
I am writing a template function, with template argument X. Inside that function, I want to create std::set<std::pair<int, X>> such that:

objects in that set are sorted by the first (int) field of the pair (I don't care about how ties are broken)

I can add multiple objects with the same .first to the set, as long as their .second are not identical

If I knew that template argument X always has < defined, the most basic std::set<std::pair<int, X> (with the default comparator) would have worked perfectly fine. Unfortunately, I cannot assume anything about X.

I was thinking to "cheat" and use pointer-based comparison for the X field:

```<code>template <typename X>
struct DistCmp {
    bool operator()(const std::pair<int, X>& lhs, const std::pair<int, X>& rhs) const {
        return lhs.first < rhs.first || lhs.first == rhs.first && &lhs.second < &rhs.second;
    }
};

template <typename X>
void f() {
    std::set<std::pair<int, X>, DistCmp<X>> s{};
    // ...
}
</code>```

(After all, I don't really care how the .second is compared, as long as it's not compared equally for non-identical objects.)

Unfortunately, I don't think it's correct. Partly because of the quote from C++ standard here (it suggests that pointer comparison, in general, is unspecified, so I can't rely on them being unequal for non-identical objects). And partly I just feel it's suspicious/hacky.

Is there any clean/portable solution for this issue?

Update:

One approach I thought about was to use == for the comparison of pointers instead of <. However, this is no good because it will cause pair<1, x> < pair<1, y> && pair<1, y> < pair<1, x> to be true. This violates the requirement of strict weak ordering and may cause stuff to break.

答:
I think ::std::map< int, ::std::set< X > > satisfies both of your criteria.

Update: since there might be no < operator to compare X instance you may want to write a template with specialization:

```<code>#include <map>
#include <set>
#include <vector>
#include <type_traits>
#include <algorithm>
#include <utility>

//  Default implementation is used when there is no < operator to compare T instances,
//  but there is == operator.
template< typename T, typename TDummy = void >
t_FancyContainerHelper final
{
    public: using
    t_Values = ::std::vector< T >;

    public: using
    t_IntToValues = ::std::map< int, t_Values >;

    public: static void
    Insert(t_IntToValues & int_to_values, int const key, T const & value)
    {
        auto p_pair{int_to_values.find(key)};
        if(int_to_values.end() != p_pair)
        (
            auto const & values(p_pair->second);
            if(values.end() != ::std::find(values.begin(), values.end(), value))
            {
                return;
            }
        }
        else
        {
            p_pair = int_to_values.emplace
            (
                ::std::piecewise_construct
            ,   ::std::forward_as_tuple(key)
            ,   ::std::forward_as_tuple()
            ).second;
        }
        auto & values(p_pair->second);
        values.emplace(value);
    }
};

//  This specialization is used when there is < operator to compare T instances.
template< typename T > class
t_FancyContainerHelper
<
    T
,   ::std::enable_if_t
    <
        ::std::is_same
        <
            bool
        ,   decltype
            (
                ::std::declval< T const & >()
                <
                ::std::declval< T const & >()
            )
        >
    >
> final
{
    public: using
    t_Values = ::std::set< T >;

    public: using
    t_IntToValues = ::std::map< int, t_Values >;

    public: static void
    Insert(t_IntToValues & int_to_values, int const key, T const & value)
    {
        auto p_pair{int_to_values.find(key)};
        if(int_to_values.end() != p_pair)
        (
            auto const & values(p_pair->second);
            if(values.end() != values.find(value))
            {
                return;
            }
        }
        else
        {
            p_pair = int_to_values.emplace
            (
                ::std::piecewise_construct
            ,   ::std::forward_as_tuple(key)
            ,   ::std::forward_as_tuple()
            ).second;
        }
        auto & values(p_pair->second);
        values.emplace(value);
    }
};
</code>```

Body:
I am writing a template function, with template argument X. Inside that function, I want to create std::set<std::pair<int, X>> such that:

objects in that set are sorted by the first (int) field of the pair (I don't care about how ties are broken)

I can add multiple objects with the same .first to the set, as long as their .second are not identical

If I knew that template argument X always has < defined, the most basic std::set<std::pair<int, X> (with the default comparator) would have worked perfectly fine. Unfortunately, I cannot assume anything about X.

I was thinking to "cheat" and use pointer-based comparison for the X field:

template <typename X>
struct DistCmp {
    bool operator()(const std::pair<int, X>& lhs, const std::pair<int, X>& rhs) const {
        return lhs.first < rhs.first || lhs.first == rhs.first && &lhs.second < &rhs.second;
    }
};

template <typename X>
void f() {
    std::set<std::pair<int, X>, DistCmp<X>> s{};
    // ...
}

(After all, I don't really care how the .second is compared, as long as it's not compared equally for non-identical objects.)

Unfortunately, I don't think it's correct. Partly because of the quote from C++ standard here (it suggests that pointer comparison, in general, is unspecified, so I can't rely on them being unequal for non-identical objects). And partly I just feel it's suspicious/hacky.

Is there any clean/portable solution for this issue?

Update:

One approach I thought about was to use == for the comparison of pointers instead of <. However, this is no good because it will cause pair<1, x> < pair<1, y> && pair<1, y> < pair<1, x> to be true. This violates the requirement of strict weak ordering and may cause stuff to break.

Body:
I think ::std::map< int, ::std::set< X > > satisfies both of your criteria.

Update: since there might be no < operator to compare X instance you may want to write a template with specialization:

#include <map>
#include <set>
#include <vector>
#include <type_traits>
#include <algorithm>
#include <utility>

//  Default implementation is used when there is no < operator to compare T instances,
//  but there is == operator.
template< typename T, typename TDummy = void >
t_FancyContainerHelper final
{
    public: using
    t_Values = ::std::vector< T >;

    public: using
    t_IntToValues = ::std::map< int, t_Values >;

    public: static void
    Insert(t_IntToValues & int_to_values, int const key, T const & value)
    {
        auto p_pair{int_to_values.find(key)};
        if(int_to_values.end() != p_pair)
        (
            auto const & values(p_pair->second);
            if(values.end() != ::std::find(values.begin(), values.end(), value))
            {
                return;
            }
        }
        else
        {
            p_pair = int_to_values.emplace
            (
                ::std::piecewise_construct
            ,   ::std::forward_as_tuple(key)
            ,   ::std::forward_as_tuple()
            ).second;
        }
        auto & values(p_pair->second);
        values.emplace(value);
    }
};

//  This specialization is used when there is < operator to compare T instances.
template< typename T > class
t_FancyContainerHelper
<
    T
,   ::std::enable_if_t
    <
        ::std::is_same
        <
            bool
        ,   decltype
            (
                ::std::declval< T const & >()
                <
                ::std::declval< T const & >()
            )
        >
    >
> final
{
    public: using
    t_Values = ::std::set< T >;

    public: using
    t_IntToValues = ::std::map< int, t_Values >;

    public: static void
    Insert(t_IntToValues & int_to_values, int const key, T const & value)
    {
        auto p_pair{int_to_values.find(key)};
        if(int_to_values.end() != p_pair)
        (
            auto const & values(p_pair->second);
            if(values.end() != values.find(value))
            {
                return;
            }
        }
        else
        {
            p_pair = int_to_values.emplace
            (
                ::std::piecewise_construct
            ,   ::std::forward_as_tuple(key)
            ,   ::std::forward_as_tuple()
            ).second;
        }
        auto & values(p_pair->second);
        values.emplace(value);
    }
};


问:
Non-Lazy Static Initialization Block in C#
I need to run some code to register a type for a factory pattern. I would do this in Java with a static initialization block or in C++ with a static constructor.

How do you do this in C#? That static constructor gets run lazily and since the type will never be referred to in the code, never gets registered.

EDIT: I tried a test to see the registration code work. This doesn't seem to be working though.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[assembly: AssemblyTest.RegisterToFactory("hello, world!")]

namespace AssemblyTest
{
    [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
    sealed class RegisterToFactoryAttribute : Attribute
    {
        public RegisterToFactoryAttribute(string name)
        {
            Console.WriteLine("Registered {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}
</code>```

Nothing gets printed.

答:
How about in a constructor for an assembly level attribute?

Example:

```<code>[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
sealed class RegisterToFactoryAttribute : Attribute
{
    public Type TypeToRegister { get; set; }

    public RegisterToFactoryAttribute(Type typeToRegister)
    {
        TypeToRegister = typeToRegister;

        // Registration code
    }
}
</code>```

Usage:

```<code>[assembly:RegisterToFactory(typeof(MyClass))]
</code>```

--EDIT on Assembly Level Attributes--

After doing some research, I figured it will only load the assembly attributes if they are queried:

Example:

```<code>object[] attributes =
    Assembly.GetExecutingAssembly().GetCustomAttributes(
        typeof(RegisterToFactoryAttribute), false);
</code>```

or

```<code>object[] attributes =
    Assembly.GetExecutingAssembly().GetCustomAttributes(false);
</code>```

Don't know why but putting this code @ the program load should do it.

--EDIT--

I almost forgot:

Have you considered using MEF?? It's a great solution to this problem.

Example:

```<code>class MyFactory
{
    [ImportMany("MyFactoryExport")]
    public List<Object> Registrations { get; set; }

    public MyFactory()
    {
        AssemblyCatalog catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
        CompositionContainer container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }
}

[Export("MyFactoryExport")]
class MyClass1
{ }

[Export("MyFactoryExport")]
class MyClass2
{ }

[Export("MyFactoryExport")]
class MyClass3
{ }
</code>```

Body:
I need to run some code to register a type for a factory pattern. I would do this in Java with a static initialization block or in C++ with a static constructor.

How do you do this in C#? That static constructor gets run lazily and since the type will never be referred to in the code, never gets registered.

EDIT: I tried a test to see the registration code work. This doesn't seem to be working though.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[assembly: AssemblyTest.RegisterToFactory("hello, world!")]

namespace AssemblyTest
{
    [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
    sealed class RegisterToFactoryAttribute : Attribute
    {
        public RegisterToFactoryAttribute(string name)
        {
            Console.WriteLine("Registered {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Nothing gets printed.

Body:
How about in a constructor for an assembly level attribute?

Example:

[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
sealed class RegisterToFactoryAttribute : Attribute
{
    public Type TypeToRegister { get; set; }

    public RegisterToFactoryAttribute(Type typeToRegister)
    {
        TypeToRegister = typeToRegister;

        // Registration code
    }
}

Usage:

[assembly:RegisterToFactory(typeof(MyClass))]

--EDIT on Assembly Level Attributes--

After doing some research, I figured it will only load the assembly attributes if they are queried:

Example:

object[] attributes =
    Assembly.GetExecutingAssembly().GetCustomAttributes(
        typeof(RegisterToFactoryAttribute), false);

or

object[] attributes =
    Assembly.GetExecutingAssembly().GetCustomAttributes(false);

Don't know why but putting this code @ the program load should do it.

--EDIT--

I almost forgot:

Have you considered using MEF?? It's a great solution to this problem.

Example:

class MyFactory
{
    [ImportMany("MyFactoryExport")]
    public List<Object> Registrations { get; set; }

    public MyFactory()
    {
        AssemblyCatalog catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
        CompositionContainer container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }
}

[Export("MyFactoryExport")]
class MyClass1
{ }

[Export("MyFactoryExport")]
class MyClass2
{ }

[Export("MyFactoryExport")]
class MyClass3
{ }


问:
if condition on radio button check/uncheck
I am very new to javascript and i am trying to insert multiple conditions in an if statement.

below my js.

if (($("#chkIs_3").is(":checked")) && ($(document.getElementById("two").checked == false) && $(document.getElementById("four").checked == false)))
            {
                alert("Please check one vehicle type.");
            }```

If and only if the id's(two, four) are unchecked the alert has to be shown, but for me even if one of the radio buttons is checked the alert is shown.

Please help me in rectifying the probelem.

id = chkIs_3 is a checkbox
id = (two & four) are radio buttons.

答:
You are mixing native Javascript with jQuery, for a start. You're also doing

$(document.getElementById("two").checked == false)
```

<p>...which is just weird and not valid. The dollar sign <code>$</code> is just a normal variable name. In this case jQuery is using it as its main function name.</p>

<hr>

<p>This is what you need instead (in case you're not aware, the exclamation mark <code>!</code> means "not" and <em>inverts</em> the result of the <code>$("#two").is(":checked")</code>):</p>

<pre class="lang-js prettyprint-override"><code>if ($("#chkIs_3").is(":checked") && (!$("#two").is(":checked") && !$("#four").is(":checked")))
{
    alert("Please check one vehicle type.");
}
</code>```

Body:
I am very new to javascript and i am trying to insert multiple conditions in an if statement.

below my js.

if (($("#chkIs_3").is(":checked")) && ($(document.getElementById("two").checked == false) && $(document.getElementById("four").checked == false)))
            {
                alert("Please check one vehicle type.");
            }

If and only if the id's(two, four) are unchecked the alert has to be shown, but for me even if one of the radio buttons is checked the alert is shown.

Please help me in rectifying the probelem.

id = chkIs_3 is a checkbox
id = (two & four) are radio buttons.

Body:
You are mixing native Javascript with jQuery, for a start. You're also doing

$(document.getElementById("two").checked == false)

...which is just weird and not valid. The dollar sign $ is just a normal variable name. In this case jQuery is using it as its main function name.

This is what you need instead (in case you're not aware, the exclamation mark ! means "not" and inverts the result of the $("#two").is(":checked")):

if ($("#chkIs_3").is(":checked") && (!$("#two").is(":checked") && !$("#four").is(":checked")))
{
    alert("Please check one vehicle type.");
}


问:
How to download receipt in PDF format in mobile using javascript
I am new to JavaScript, I am building a mobile app with angular and JavaScript. I want to print a receipt in my app. So i want to download receipt in PDF format. I searched and do not get a working code. The receipt is in table tag.
My code is here.</p>

```<code><div id="preview" class="container">
        <h4 class="h4-order">Order Date <span>{{order_time|date:'mediumDate'}}</span></h4>
        <table>
            <tr>
                <th><b>Qty</b></th>
                <th><b>Product</b></th>
                <th><b>From</b></th>
                <th><b>Price</b></th>
                <th><b>Offer</b></th>
                <th><b>Total</b></th>
            </tr>
            <tr ng-repeat="receipt in new_receipts">
                <td>{{receipt.quantity}}</td>
                <td>{{receipt.name}}</td>
                <td>{{receipt.ownname}}</td>
                <td>{{receipt.price}}</td>
                <td ng-if="receipt.offer">{{receipt.offer}}%</td>
                <td ng-if="!receipt.offer">0%</td>
                <td>{{receipt.total}}</td>
            </tr>
        </table>
        <div class="receipt-total">
            <h3>Sub Total : <span><img src="img/mybag/rs.png" class="rs-mybag-total"/> {{total}}</span></h3>
        </div>
        </div>
</code>```

答:
By using

cordova.plugins.printer

I got the PDFto print the receipt.

Body:
I am new to JavaScript, I am building a mobile app with angular and JavaScript. I want to print a receipt in my app. So i want to download receipt in PDF format. I searched and do not get a working code. The receipt is in table tag.
My code is here.

Order Date {{order_time|date:'mediumDate'}}

                Qty
                Product
                From
                Price
                Offer
                Total

                {{receipt.quantity}}
                {{receipt.name}}
                {{receipt.ownname}}
                {{receipt.price}}
                {{receipt.offer}}%
                0%
                {{receipt.total}}

Sub Total :  {{total}}


问:
In the grid layout , what the difference between the followings
```<code>Width="auto"
Width ="*"
Width ="100*"
</code>```

答:
The size can be specified as an absolute amount of logical units, as a percentage value or automatically.

Fixed Fixed size of logical units (1/96 inch)

Auto Takes as much space as needed by the contained control

Star (*) Takes as much space as available, percentally divided over all star-sized columns. Star-sizes are like percentages, except that the sum of all star columns does not have to be 100%. Remember that star-sizing does not work if the grid size is calculated based on its content.

for more

http://www.wpftutorial.net/GridLayout.html

Body:
Width="auto"
Width ="*"
Width ="100*"


问:
Get Row Count of Dbset in DbContext dynamicly
I have a form that pass a instance of my DbContext and a Entity of Table to it as below :

```<code>public frm_foo(DbContext DatabaseContext, DbSet TableEntity)
        {
           InitializeComponent();
           var res =GetRowCount(DatabaseContext,TableEntity);
        }
</code>```

And call form contractor by:

```<code>new frm_foo(dbContext, dbContext.Set<IpRoom>()).ShowDialog();
</code>```

The Context contain a IpRoom table.

I want to get Count of row from in a function that send the DbContext and Dbset instance to it as below :

```<code>public int GetRowCount(DbContext DatabaseContext, DbSet TableEntity)
   {
       var countVal = (from a in DatabaseContext.Set(TableEntity.GetType())
                        select a).Count();
       return countVal;
   }
</code>```

But Got error:

Could not find an implementation of the query pattern for source type
  'DbSet'.  'Select' not found.

While DatabaseContext.Set(TableEntity.GetType()) return a Dbset! Anybody know whats my wrong? Thanks in advance

Ps: I dont want use SqlQuery, Something like:

```<code>var sql = "SELECT COUNT(*) FROM dbo.IpRoom";
var total = context.Database.SqlQuery<int>(sql).Single();
</code>```

答:
Add a class to your project as blow:

```<code>namespace System.Data.Entity
{
  public static class EntityFrameworkExtensions
  {
    public static IEnumerable<object> AsEnumerable(this DbSet set)
    {
      foreach (var entity in set)
        yield return entity;
    }
  }
}
</code>```

This class add a Generic method AsEnumerable to DbSet instance and when you want to use it for example for Count:

```<code> var count = (from a in TableEntity.AsEnumerable() select a).Count();
</code>```

Body:
I have a form that pass a instance of my DbContext and a Entity of Table to it as below :

public frm_foo(DbContext DatabaseContext, DbSet TableEntity)
        {
           InitializeComponent();
           var res =GetRowCount(DatabaseContext,TableEntity);
        }

And call form contractor by:

new frm_foo(dbContext, dbContext.Set<IpRoom>()).ShowDialog();

The Context contain a IpRoom table.

I want to get Count of row from in a function that send the DbContext and Dbset instance to it as below :

public int GetRowCount(DbContext DatabaseContext, DbSet TableEntity)
   {
       var countVal = (from a in DatabaseContext.Set(TableEntity.GetType())
                        select a).Count();
       return countVal;
   }

But Got error:

Could not find an implementation of the query pattern for source type
  'DbSet'.  'Select' not found.

While DatabaseContext.Set(TableEntity.GetType()) return a Dbset! Anybody know whats my wrong? Thanks in advance

Ps: I dont want use SqlQuery, Something like:

var sql = "SELECT COUNT(*) FROM dbo.IpRoom";
var total = context.Database.SqlQuery<int>(sql).Single();

Body:
Add a class to your project as blow:

namespace System.Data.Entity
{
  public static class EntityFrameworkExtensions
  {
    public static IEnumerable<object> AsEnumerable(this DbSet set)
    {
      foreach (var entity in set)
        yield return entity;
    }
  }
}

This class add a Generic method AsEnumerable to DbSet instance and when you want to use it for example for Count:

 var count = (from a in TableEntity.AsEnumerable() select a).Count();


问:
Get Azure Active Directory token from an electron app
What would be the best way to obtain an AAD token from an electron app?

Microsoft has 2 javascript authentication libraries: adal.js and msal.js.
Both are designed for browsers and not native Electron apps (For example - AAD won't allow for file:/// scheme as a reply URL).

Sounds like a long term solution would be native AAD packages (like Microsoft built for Apache Cordova), but since that's probably not going to happen any time soon, what is the best short-term option?

答: The Azure AD doesn't support the file protocol as the reply address. To develop the single page application, you can host it on the server and using the server URL as the reply address.</p>


答:
Writing to a ByteArrayOutputStream first means that the complete file will end up in the JVM's heap. Depending on the file size and heap size this might not be possible, hence the exception. If you don't need the ByteArrayOutputStream for anything else just write directly to outputStream:

```<code>OutputStream outputStream = result.getDriveContents().getOutputStream();
FileInputStream fis;
try {
    fis = new FileInputStream(file);
    byte[] buf = new byte[1024];
    int n;
    while (-1 != (n = fis.read(buf)))
        outputStream.write(buf, 0, n);

} catch (FileNotFoundException e) {
    Log.v("EXCEPTION", "FileNotFoundException: " + e.getMessage());
} catch (IOException e1) {
    Log.v("EXCEPTION", "Unable to write file contents." + e1.getMessage());
} finally {
    outputStream.close();
    fis.close();
    Log.e("File Size", "Size " + file.length());
}
</code>```

P.S.: nulling the references should not be necessary if they go out of scope soon...

Title: java.lang.OutOfMemoryError at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)?

Body:
I am facing this issue in uploading the file to the google drive, i am uploading the recorded audio to the google drive at that time this exception is occurring

The code used for writing the content in the file

                      OutputStream outputStream = result.getDriveContents().getOutputStream();
                    FileInputStream fis;
                    try {
                        fis = new FileInputStream(file);
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buf = new byte[1024];
                        int n;
                        while (-1 != (n = fis.read(buf)))
                            baos.write(buf, 0, n);
                        byte[] photoBytes = baos.toByteArray();
                        outputStream.write(photoBytes);

                        outputStream.close();
                        outputStream = null;
                        fis.close();
                        fis = null;

                        Log.e("File Size", "Size " + file.length());

                    } catch (FileNotFoundException e) {
                        Log.v("EXCEPTION", "FileNotFoundException: " + e.getMessage());
                    } catch (IOException e1) {
                        Log.v("EXCEPTION", "Unable to write file contents." + e1.getMessage());
                    }

The exception occurs in the line `  baos.write(buf, 0, n);

Please help me how to solve this error.`

Body:
Writing to a ByteArrayOutputStream first means that the complete file will end up in the JVM's heap. Depending on the file size and heap size this might not be possible, hence the exception. If you don't need the ByteArrayOutputStream for anything else just write directly to outputStream:

OutputStream outputStream = result.getDriveContents().getOutputStream();
FileInputStream fis;
try {
    fis = new FileInputStream(file);
    byte[] buf = new byte[1024];
    int n;
    while (-1 != (n = fis.read(buf)))
        outputStream.write(buf, 0, n);

} catch (FileNotFoundException e) {
    Log.v("EXCEPTION", "FileNotFoundException: " + e.getMessage());
} catch (IOException e1) {
    Log.v("EXCEPTION", "Unable to write file contents." + e1.getMessage());
} finally {
    outputStream.close();
    fis.close();
    Log.e("File Size", "Size " + file.length());
}

P.S.: nulling the references should not be necessary if they go out of scope soon...


问:
selecting 2 different option values and sending data to php using ajax
I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.

This is my jQuery code:

```<code>$(document).ready(function() {
  $("#updateStatus").change(function() {
    var opt = $("#updateStatus").val();

    $("#updateStatus1").change(function() {
      var sta = $("#updateStatus1").val();

      $.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
      });
    });
  });
});
</code>```

This is my PHP code:

```<code>$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
  echo json_encode("fail");
} else {
  echo json_encode("sucess");
}
</code>```

答:
Thanks every one looks like i just had to change some code in ajax this is my new code which is working fine
This is my PHP code I got rid of if(!$row)

```<code>                mysql_select_db("dts_db",$con);
            $id=$_POST['opt'];

            $status=$_POST['sta'];

            $query="UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
            $result=mysql_query($query);if(!$result){    die("My sql query result ".mysql_error());}
</code>```

else {

echo json_encode("success");

}

and this is my ajax

```<code>$.ajax({
url: 'updatecode.php',
type: 'POST',
data:  {opt:opt,sta:sta},
dataType: 'json',
success: function(data) {
  alert(data + "hello");
}
</code>```

});

Body:
I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.

This is my jQuery code:

$(document).ready(function() {
  $("#updateStatus").change(function() {
    var opt = $("#updateStatus").val();

    $("#updateStatus1").change(function() {
      var sta = $("#updateStatus1").val();

      $.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
      });
    });
  });
});

This is my PHP code:

$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
  echo json_encode("fail");
} else {
  echo json_encode("sucess");
}

Body:
Thanks every one looks like i just had to change some code in ajax this is my new code which is working fine
This is my PHP code I got rid of if(!$row)

                mysql_select_db("dts_db",$con);
            $id=$_POST['opt'];

            $status=$_POST['sta'];

            $query="UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
            $result=mysql_query($query);if(!$result){    die("My sql query result ".mysql_error());}

else {

echo json_encode("success");

}

and this is my ajax

$.ajax({
url: 'updatecode.php',
type: 'POST',
data:  {opt:opt,sta:sta},
dataType: 'json',
success: function(data) {
  alert(data + "hello");
}

});


问:
Adding a “switch to desktop site” button on mobile with bootstrap Drupal 7
I need a swith to desktop button that will be display it just on mobile, and has to display the desktop version on mobile once I push it, the same like "request desktop site" on chrome but inside of my Drupal 7 site.

My site includes bootstrap for responsive, I don't want to disable bootstrap, I just need inside of my responsive site on mobile display the button to make the switch.

Any idea how to do this? please help!

答:
In case that you want to display that link depending on user browser use PHP to detect mobile browser, i.e. use Mobile Detect class for it.

http://mobiledetect.net/

Or if you don't want to use 3rd party classes:

```<code>    <?php

    $useragent=$_SERVER['HTTP_USER_AGENT'];

    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) {
      echo 'mobile link';
    }else{
      echo 'desktop link';
    }
</code>```

On other hand, if you want to allow visitors to change view on their own store site version (desktop/mobile) in PHP session and depending on that variable version display one or other link...but also desktop/mobile theme.

Body:
In case that you want to display that link depending on user browser use PHP to detect mobile browser, i.e. use Mobile Detect class for it.

http://mobiledetect.net/

Or if you don't want to use 3rd party classes:

    <?php

    $useragent=$_SERVER['HTTP_USER_AGENT'];

    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) {
      echo 'mobile link';
    }else{
      echo 'desktop link';
    }

On other hand, if you want to allow visitors to change view on their own store site version (desktop/mobile) in PHP session and depending on that variable version display one or other link...but also desktop/mobile theme.


问:
In IE6, and using divs, how to split entire page into two columns, left div with static width and right with elastic width?
I don't know if what am asking for is even possible in IE6, but here goes:  I am working on a page layout and want to split the body into two container divs. I want to give the left div a fixed width of 200px; while making the right div elastic along the page's width.  The right div's left border must be touching the left div's right border to make things clearer i made a diagram:

答:
```<code><html style="height:100%">
<body style="height:100%;margin:0px;">
  <div style="position:absolute;left:0;right:0;z-index:1000;height:100%;width:200px;background-color:red;">
    Sidebar
  </div>
  <div style="height:100%;width:100%;">
    <div style="padding-left:200px;background-color:blue;height:100%">
      Content
    </div>
  </div>

</body>
</html>
</code>```

here it is online: http://milkish.com/test/ie6.html
check it with netrender: http://ipinfo.info/netrenderer/index.php

Body:
<html style="height:100%">
<body style="height:100%;margin:0px;">
  <div style="position:absolute;left:0;right:0;z-index:1000;height:100%;width:200px;background-color:red;">
    Sidebar
  </div>
  <div style="height:100%;width:100%;">
    <div style="padding-left:200px;background-color:blue;height:100%">
      Content
    </div>
  </div>

</body>
</html>

here it is online: http://milkish.com/test/ie6.html
check it with netrender: http://ipinfo.info/netrenderer/index.php


问:
With() vs Compact() in Laravel
Is there any difference between with() and compact() ?

Which one is more efficient ?

答:
with() is a method made available by method from one of their classes while compact() is a method that is available by default in PHP The with() cannot be used outside laravel but the compact() can be used anywhere in the PHP script.

The compact() function is used to convert given variable to to array in which the key of the array will be the name of the variable and the value of the array will be the value of the variable.

Title: With() vs Compact() in Laravel


答:
with() is a Laravel function and compact() is a PHP function and have totally different purposes.

with() allows you to pass variables to a view and compact() creates an array from existing variables given as string arguments to it.

See compact() for more info on this matter.

Title: With() vs Compact() in Laravel

Body:
Is there any difference between with() and compact() ?

Which one is more efficient ?


问:
AutoCompleteTextView item selection programmatically
I have an AutoCompleteTextView that is filled with cities from an sqlite database that calls an AsyncTask on item click, recently I added an option to detect my location using the gps, so the problem is I can detect the city (i.e Beirut) and set the text for the AutoCompleteTextView but the thing is that the dropdown filter opens showing Beirut (which is correct) but I still need to click on the list item to invoke the listener, how to do so programmatically

How to:

Enter the Activity (DONE)

Detect location (DONE)

set text of text view (DONE)

show textview dropdown list(DONE)

choose the item that will be returned, since it will only return one city (NOT DONE)

答:
Try with adding below after setText() in AutoCompleteTextview:-

```<code>autoCompleteTV.setSelection(position);
</code>```

Updated:

This will work in Spinner and AutoCompleteTextView which has dropdown feature, but it will not work with EditText.

Here you can check docs for AbsSpinner in this link:
https://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int)

Body:
Try with adding below after setText() in AutoCompleteTextview:-

autoCompleteTV.setSelection(position);

Updated:

This will work in Spinner and AutoCompleteTextView which has dropdown feature, but it will not work with EditText.

Here you can check docs for AbsSpinner in this link:
https://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int)


问:
How to add number of views in database in php mysql
How do we add number of views ( eg  most viewed articles) in php mysql database. How to add numbers when a person click to database? </p>

答:
Simplest solution:

Let's pretend your pages table is called "pages", and the number of views column is called "views".

Every page should trigger the following query:

```<code>UPDATE pages SET views=views+1 WHERE ID=19
</code>```

(19 is the visited page ID)

Body:
Simplest solution:

Let's pretend your pages table is called "pages", and the number of views column is called "views".

Every page should trigger the following query:

UPDATE pages SET views=views+1 WHERE ID=19

(19 is the visited page ID)


问:
Cordova to Android studio error malformed \uxxxx encoding
I want to import my Cordova project to Android Studio.
But when on Grandle Sync, this error is shown -

```<code>malformed \uxxxx encoding
</code>```

The error part is:

```<code>def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader) //this line is the error (line 290)
    }
</code>```

The entire Gradle file is available here: https://pastebin.com/66vVKHzG

How to solve this ?

答:
The error is caused in android build when we use \usr\<blah> i.e a \(backslash) instead of /(forward slash) in directory structure. The parser will see it as an escape character!!

I still don't know from where that \ is getting used from your Cordova Project. You need to figure that out based on what functionalities you are doing and where you are using file system.

According to your code propsFilePath might be having a \ which is causing this error.

Reference - https://coderanch.com/t/107014/Malformed-uxxxx-encoding-error

Body:
I want to import my Cordova project to Android Studio.
But when on Grandle Sync, this error is shown -

malformed \uxxxx encoding

The error part is:

def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader) //this line is the error (line 290)
    }

The entire Gradle file is available here: https://pastebin.com/66vVKHzG

How to solve this ?