问:
Method is missing or has incorrect signature
I am making a simple app in which context view changes and then a toast message is displayed as input given by user. I don't understand why the app keeps on crashing when changing the context view.

Also Android studio gives this warning:

Method "Toaster" is missing in "FirstActivity" or has incorrect signature.

Here is my code:

activity_me_clicked.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/welcome"
        android:textSize="36sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:paddingLeft="7dp"
        android:paddingRight="7dp"
        android:text="@string/intro"
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:baselineAligned="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <EditText
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="7dp"
                android:layout_marginEnd="7dp"
                android:layout_marginTop="10dp"
                android:ems="10"
                android:hint="Name"
                android:inputType="textPersonName"
                tools:ignore="HardcodedText" />

            <Button
                android:id="@+id/named"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:paddingBottom="10dp"
                android:paddingTop="10dp"
                android:onClick="MainProcess"
                android:text="@string/done" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal"
            tools:ignore="UselessLeaf"></LinearLayout>

    </LinearLayout>

</LinearLayout>
</code>```

FirstActivity.Java:

```<code>package com.example.nautatvanavlakha.abcd;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class FirstActivity extends AppCompatActivity {
    public static String owner_string;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_clicked);
    }

    public void MainProcess(View view) {

        final String TAG="DEBUG";
        Log.d(TAG,"At least process started");

        EditText owner = (EditText) findViewById(R.id.name);
        owner_string = owner.getText().toString();
        Log.d(TAG,"owner name stored");

        TextView textView = (TextView) findViewById(R.id.welcome);
        textView.setText("Hi " + owner_string + ".");
        Log.d(TAG,"owner name is set");

        setContentView(R.layout.activity_main_screen);
        Log.d(TAG,"content shown");
    }
}
</code>```

activity_main_screen.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/welcome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/what_would_you_like_me_to_do_today"
        android:textSize="18sp" />

    <Button
        android:id="@+id/Cam"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/camera" />

    <Button
        android:id="@+id/Mus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/music" />

    <Button
        android:id="@+id/QR"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/scanQR" />

    <EditText
        android:id="@+id/toastText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/order"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/toaster"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:onClick="toaster"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/toast"
        android:layout_marginEnd="100dp"
        android:layout_gravity="center"/>

</LinearLayout>
</code>```

MainScreen.java:

```<code>package com.example.nautatvanavlakha.abcd;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
    }

    public void toaster(View view){

        EditText toast = (EditText)findViewById(R.id.toastText);
        String final_toast = toast.getText().toString();
        Toast.makeText(getApplicationContext(), final_toast, Toast.LENGTH_SHORT).show();
    }

}
</code>```

EDIT: As suggested, I moved the toaser function to FirstActivity.Java and deleted the MainScreen.java file as it becomes pointless to keep it. But the major problem is when I press the button (id named) the app keeps stopping.

EDIT2: I found that setContentView(R.layout.activity_main_screen) in FirstActivity.Java needs to be above this code

```<code>    TextView textView = (TextView) findViewById(R.id.welcome);
    textView.setText("Hi " + owner_string + ".");
    Log.d(TAG,"owner name is set");
</code>```

so that Activity has access to all the layout components. Thanks solved :)

答:
This is a wrong way to change the contents of your Activity, The main problem here is that you have onClick attribute set to "toaster", And you don't have a function called "toaster" in your FirstActivity.

Beside that, The MainScreen Activity in your code will never be used.

So, Your problem is that you set the FirstActivity contents to "activity_main_screen.xml", And FirstActivity doesn't have "toaster" method in it, When you change the context, the Activity will try to find toaster method and the app will crash because the method doesn't exist in FirstActivity.

You can solve this problem by making a method called "toaster" inside FirstActivity, But
This is a very bad practice, You can use Fragments instead, Or you can use Intent to move to another activity.

Some useful links about Fragments:

https://developer.android.com/guide/components/fragments.html

https://www.tutorialspoint.com/android/android_fragments.htm

https://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/

Why should I use fragment in Android?

Body:
I am making a simple app in which context view changes and then a toast message is displayed as input given by user. I don't understand why the app keeps on crashing when changing the context view.

Also Android studio gives this warning:

Method "Toaster" is missing in "FirstActivity" or has incorrect signature.

Here is my code:

activity_me_clicked.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/welcome"
        android:textSize="36sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:paddingLeft="7dp"
        android:paddingRight="7dp"
        android:text="@string/intro"
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:baselineAligned="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <EditText
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="7dp"
                android:layout_marginEnd="7dp"
                android:layout_marginTop="10dp"
                android:ems="10"
                android:hint="Name"
                android:inputType="textPersonName"
                tools:ignore="HardcodedText" />

            <Button
                android:id="@+id/named"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:paddingBottom="10dp"
                android:paddingTop="10dp"
                android:onClick="MainProcess"
                android:text="@string/done" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal"
            tools:ignore="UselessLeaf"></LinearLayout>

    </LinearLayout>

</LinearLayout>

FirstActivity.Java:

package com.example.nautatvanavlakha.abcd;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class FirstActivity extends AppCompatActivity {
    public static String owner_string;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_clicked);
    }

    public void MainProcess(View view) {

        final String TAG="DEBUG";
        Log.d(TAG,"At least process started");

        EditText owner = (EditText) findViewById(R.id.name);
        owner_string = owner.getText().toString();
        Log.d(TAG,"owner name stored");

        TextView textView = (TextView) findViewById(R.id.welcome);
        textView.setText("Hi " + owner_string + ".");
        Log.d(TAG,"owner name is set");

        setContentView(R.layout.activity_main_screen);
        Log.d(TAG,"content shown");
    }
}

activity_main_screen.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/welcome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/what_would_you_like_me_to_do_today"
        android:textSize="18sp" />

    <Button
        android:id="@+id/Cam"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/camera" />

    <Button
        android:id="@+id/Mus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/music" />

    <Button
        android:id="@+id/QR"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/scanQR" />

    <EditText
        android:id="@+id/toastText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/order"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/toaster"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:onClick="toaster"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/toast"
        android:layout_marginEnd="100dp"
        android:layout_gravity="center"/>

</LinearLayout>

MainScreen.java:

package com.example.nautatvanavlakha.abcd;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
    }

    public void toaster(View view){

        EditText toast = (EditText)findViewById(R.id.toastText);
        String final_toast = toast.getText().toString();
        Toast.makeText(getApplicationContext(), final_toast, Toast.LENGTH_SHORT).show();
    }

}

EDIT: As suggested, I moved the toaser function to FirstActivity.Java and deleted the MainScreen.java file as it becomes pointless to keep it. But the major problem is when I press the button (id named) the app keeps stopping.

EDIT2: I found that setContentView(R.layout.activity_main_screen) in FirstActivity.Java needs to be above this code

    TextView textView = (TextView) findViewById(R.id.welcome);
    textView.setText("Hi " + owner_string + ".");
    Log.d(TAG,"owner name is set");

so that Activity has access to all the layout components. Thanks solved :)


来源: stackexchange

问:
What is wrong with this IF statement in rails?
I am trying to only show comments if there are any comments as when there are no comments the for loop shows this (the hash table at the bottom)

The if statement in my code is

```<code><h2>Comments</h2>
<% if @article.comments.any? %>

<%= @article.comments.each do |comment| %>

<p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
 </p>

 <p>
  <strong>Comment:</strong>
  <%= comment.comment %>
 </p>

 <% end %>
<% end %>
</code>```

What is wrong with my code that it still enters the for loop even when there are no comments?

答: The line that is causing the problem: <%= @article.comments.each do |comment| %>. You don't need to use <%= %> while iterating through the comments of an article. <% %> will do the job.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to only show comments if there are any comments as when there are no comments the for loop shows this (the hash table at the bottom)

The if statement in my code is

Comments

<% if @article.comments.any? %>

<%= @article.comments.each do |comment| %>

  Commenter:
  <%= comment.commenter %>

  Comment:
  <%= comment.comment %>

 <% end %>
<% end %>

What is wrong with my code that it still enters the for loop even when there are no comments?


答:
<%= ... %> will output itself because you specify the equal sign (=) after <%, if you specify the minus sign (-) it will not output itself, or simply no sign, just <%. I personally prefer to specify - as it declares your intention (and SLIM uses - as well)

```<code><%- @article.comments.each do |comment| %>
</code>```

Title: What is wrong with this IF statement in rails?

Body:
<%= ... %> will output itself because you specify the equal sign (=) after <%, if you specify the minus sign (-) it will not output itself, or simply no sign, just <%. I personally prefer to specify - as it declares your intention (and SLIM uses - as well)

<%- @article.comments.each do |comment| %>


问:
Python - Get Result of Google Search

My goal is to create a small sript that find all the result of a google search but in "raw".

I don't speak english very well so i prefer to give an exemple to show you what i would like :

I Type : elephant

The script return

www.elephant.com

www.bluelephant.com

www.ebay.com/elephant

.....

I was thinking about urllib.request but the return value will not be usable to that !
I found some tutorials but not adapted at all to my wish !
Like i told you my goal is to have an .txt file as output witch contains alls the website who match with my query !

Thanks all

答:
I just add 2 points to "9th Dimension" answer.

Use this guide to find your Custom Search Engine ID

A small modification should be made in the second line of the code: as the following, the "version" should be added as an argument

service = build('customsearch','v1',developerKey= my_api_key)

Title: Python - Get Result of Google Search


问:
Using javascript regexp to find the first AND longest match
I have a RegExp like the following simplified example:

```<code>var exp = /he|hell/;
</code>```

When I run it on a string it will give me the first match, fx:

```<code>var str = "hello world";
var match = exp.exec(str);
// match contains ["he"];
</code>```

I want the first and longest possible match,
and by that i mean sorted by index, then length.

Since the expression is combined from an array of RegExp's, I am looking for a way to find the longest match without having to rewrite the regular expression.

Is that even possible?

If it isn't, I am looking for a way to easily analyze the expression, and arrange it in the proper order. But I can't figure out how since the expressions could be a lot more complex, fx:

```<code>var exp = /h..|hel*/
</code>```

答:
I don't know if this is what you're looking for (Considering this question is almost 8 years old...), but here's my grain of salt:

(Switching the he for hell will perform the search based on the biggest first)

```<code>var exp = /hell|he/;
var str = "hello world";
var match = exp.exec(str);

if(match)
{
  match.sort(function(a, b){return b.length - a.length;});
  console.log(match[0]);
 }
</code>```

Where match[0] is going to be the longest of all the strings matched.

ContentLicense: CC BY-SA 2.5

Body:
I have a RegExp like the following simplified example:

var exp = /he|hell/;

When I run it on a string it will give me the first match, fx:

var str = "hello world";
var match = exp.exec(str);
// match contains ["he"];

I want the first and longest possible match,
and by that i mean sorted by index, then length.

Since the expression is combined from an array of RegExp's, I am looking for a way to find the longest match without having to rewrite the regular expression.

Is that even possible?

If it isn't, I am looking for a way to easily analyze the expression, and arrange it in the proper order. But I can't figure out how since the expressions could be a lot more complex, fx:

var exp = /h..|hel*/

Body:
I don't know if this is what you're looking for (Considering this question is almost 8 years old...), but here's my grain of salt:

(Switching the he for hell will perform the search based on the biggest first)

var exp = /hell|he/;
var str = "hello world";
var match = exp.exec(str);

if(match)
{
  match.sort(function(a, b){return b.length - a.length;});
  console.log(match[0]);
 }

Where match[0] is going to be the longest of all the strings matched.


问:
jsPDF - Cannot render html to pdf
I need to render a view to pdf but from a jquery get(). It returns a view and I try to insert this returned data in doc jsPDF() but it doesn't work!

The view have the all, metadata, css links, js links and the content.

My jquery function:

```<code>function exportToPdf()
{
  $('#exportToPdf').on('click', function(e)
  {
    var ref = $(this).attr('data-ref');

    $.get("/to-pdf/"+encodeURIComponent(ref), function(data)
    {
      var doc = new jsPDF();
      doc.text(data, 10, 10);
      doc.save('a4.pdf');
    });
  });
}
</code>```

How can I do that?

Thank you.

答:
Try this.</p>

```<code>function onClick() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  pdf.canvas.height = 80 * 11;
  pdf.canvas.width = 80 * 8.5;
  pdf.fromHTML(document.body); //Your HTML content goes here
  pdf.save('test.pdf');
};
</code>```

Title: jsPDF - Cannot render html to pdf

Body:
I need to render a view to pdf but from a jquery get(). It returns a view and I try to insert this returned data in doc jsPDF() but it doesn't work!

The view have the all, metadata, css links, js links and the content.

My jquery function:

function exportToPdf()
{
  $('#exportToPdf').on('click', function(e)
  {
    var ref = $(this).attr('data-ref');

    $.get("/to-pdf/"+encodeURIComponent(ref), function(data)
    {
      var doc = new jsPDF();
      doc.text(data, 10, 10);
      doc.save('a4.pdf');
    });
  });
}

How can I do that?

Thank you.

Body:
Try this.

function onClick() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  pdf.canvas.height = 80 * 11;
  pdf.canvas.width = 80 * 8.5;
  pdf.fromHTML(document.body); //Your HTML content goes here
  pdf.save('test.pdf');
};


问:
Cannot link my page to the router in node.js
Can someone help me out? I am trying to connect my HTML page to the router, so that when I go to a certain link, I can render a certain HTML page. Right now, I am just trying to send something and nothing works. Here is a screenshot of my work:

My ultimate goal is to render movie_info.html.

Thanks in advance!

答:
you don't have to render html pages. You can simply open html as static file.</p>

```<code>var express = require('express');
var server = express(); // better instead
server.use('/', express.static(__dirname + '/your_html_page_folder'));
server.listen(3000);
</code>```

Body:
you don't have to render html pages. You can simply open html as static file.

var express = require('express');
var server = express(); // better instead
server.use('/', express.static(__dirname + '/your_html_page_folder'));
server.listen(3000);


问:
variable is losing its value in c program
This is written in 'c' and compiled with gcc.  I'm not sure what else you need to know.

The smallest complete example I could put together is shown here.  The variable 'numatoms' loses its value when it gets to line 23 (after the scanf()).

I'm stumped. Maybe it has something to do with scanf() overwritting the space for numatoms?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

/*
 *
 */
int main(int argc, char** argv) {
uint8_t numatoms;
uint8_t r;
char a[20];

do {
    printf("NO. OF ATOMS?");
    fflush(stdout);
    scanf("%d", &numatoms);
    printf("\r\n");
    for(;;){
        printf("value of numatoms is %u\r\n", numatoms);
        printf("RAY?");
        fflush(stdout);
        scanf("%u", &r);
        printf("value of numatoms is %u\r\n", numatoms);
        if(r < 1)
            break;
        else {
            printf("value of numatoms is %u\r\n", numatoms);
        }
    }
    printf("CARE TO TRY AGAIN?");
    fflush(stdout);
    scanf("%s", a);
    printf("\r\n");
} while (a[0] == 'y' || a[0] == 'Y');

return (EXIT_SUCCESS);
</code>```

}

答:
You should use macros for format specifiers for integer types defined in the header <inttypes.h>.

From the C Standard (7.8.1 Macros for format specifiers)

1 Each of the following object-like macros expands to a character
  string literal containing a conversion specifier, possibly modified by
  a length modifier, suitable for use within the format argument of a
  formatted input/output function when converting the corresponding
  integer type. These macro names have the general form of PRI
  (character string literals for the fprintf and fwprintf family) or SCN
  (character string literals for the fscanf and fwscanf family),217)
  followed by the conversion specifier, followed by a name corresponding
  to a similar type name in 7.20.1. In these names, N represents the
  width of the type as described in 7.20.1.

The general form of the macro used for unsigned integer types with the conversion specifier u looks like

```<code>SCNuN
</code>```

Here is a demonstrative program

```<code>#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(void)
{
    uint8_t x;

    scanf( "%" SCNu8, &x );

    printf( "x = %u\n", x );

    return 0;
}
</code>```

Body:
This is written in 'c' and compiled with gcc.  I'm not sure what else you need to know.

The smallest complete example I could put together is shown here.  The variable 'numatoms' loses its value when it gets to line 23 (after the scanf()).

I'm stumped. Maybe it has something to do with scanf() overwritting the space for numatoms?

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

/*
 *
 */
int main(int argc, char** argv) {
uint8_t numatoms;
uint8_t r;
char a[20];

do {
    printf("NO. OF ATOMS?");
    fflush(stdout);
    scanf("%d", &numatoms);
    printf("\r\n");
    for(;;){
        printf("value of numatoms is %u\r\n", numatoms);
        printf("RAY?");
        fflush(stdout);
        scanf("%u", &r);
        printf("value of numatoms is %u\r\n", numatoms);
        if(r < 1)
            break;
        else {
            printf("value of numatoms is %u\r\n", numatoms);
        }
    }
    printf("CARE TO TRY AGAIN?");
    fflush(stdout);
    scanf("%s", a);
    printf("\r\n");
} while (a[0] == 'y' || a[0] == 'Y');

return (EXIT_SUCCESS);

}

Body:
You should use macros for format specifiers for integer types defined in the header <inttypes.h>.

From the C Standard (7.8.1 Macros for format specifiers)

1 Each of the following object-like macros expands to a character
  string literal containing a conversion specifier, possibly modified by
  a length modifier, suitable for use within the format argument of a
  formatted input/output function when converting the corresponding
  integer type. These macro names have the general form of PRI
  (character string literals for the fprintf and fwprintf family) or SCN
  (character string literals for the fscanf and fwscanf family),217)
  followed by the conversion specifier, followed by a name corresponding
  to a similar type name in 7.20.1. In these names, N represents the
  width of the type as described in 7.20.1.

The general form of the macro used for unsigned integer types with the conversion specifier u looks like

SCNuN

Here is a demonstrative program

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(void)
{
    uint8_t x;

    scanf( "%" SCNu8, &x );

    printf( "x = %u\n", x );

    return 0;
}


问:
I cannot find the name of a dynamically created javascript object (in jQuery)
I have a page which uses javascript to add some textboxes to the page, and then we try to do some work based on these later.

What I am having a lot of trouble with though is that I cannot return the 'name' value which I am saving with the js.

Full page source (albeit a simplified version) is below.

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="Scripts/jquery-1.4.1-vsdoc.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        //we use live because the inputs havent been created yet.
        $('.myclass').live('blur', function () {

            //debugger;
            alert('textbox selected has ID '+ $(this).attr('id') ); //this returns txtInput
            alert('textbox selected has name '+ $(this).attr('name') ); //this returns null (or an empty string).
        });

    AddInputTextBox("My Label: ", "txtInput", "mydiv", "MyName");

    });

    function AddInputTextBox(LabelValue, Id, divToAddTo, NameKey) {
        //debugger;
        var txtbox = document.createElement('input');
        txtbox.setAttribute("type", "text");
        txtbox.setAttribute("id", Id);
        txtbox.setAttribute("name", NameKey);
        txtbox.setAttribute("class", "myclass");

        alert('Textbox created with name = ' + txtbox.name);

        var foo = document.getElementById(divToAddTo);
        foo.innerHTML += LabelValue;
        foo.appendChild(txtbox);
    }
    </script>
</head>

<body>
    <div id="mydiv">
        <!-- placeholder -->
    </div>
</body>
</html>
</code>```

So as you can see, document.ready runs and creates one textbox.
when the blur fires (box loses focus) - I can access the ID, class, type, etc, but I cannot get a value for the 'name'.

Sure it is something dead simple, but can someone tell me why?

答:
This seems to be working for me.

http://jsfiddle.net/dem5d/

Am I missing something?

Bob

Body:
I have a page which uses javascript to add some textboxes to the page, and then we try to do some work based on these later.

What I am having a lot of trouble with though is that I cannot return the 'name' value which I am saving with the js.

Full page source (albeit a simplified version) is below.

So as you can see, document.ready runs and creates one textbox.
when the blur fires (box loses focus) - I can access the ID, class, type, etc, but I cannot get a value for the 'name'.

Sure it is something dead simple, but can someone tell me why?


问:
ConstraintSet: Listview won't move properly
No Matter what i write inside of Constraintset.connect to change the position, it always just stays where it is (i want it to move from outside the screen into the screen from the left side), at the moment the view is fully inside of the screen and only the left constraint is missing).
Thanks.

ListviewItem:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#202020">

    <ImageView
        android:id="@+id/listItemImageView"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="40dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:paddingBottom="16dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/listItemTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/listItemImageView"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="17dp"
        android:layout_marginRight="17dp"
        android:layout_marginTop="8dp"
        android:layout_toLeftOf="@+id/listItemImageView"
        android:layout_toStartOf="@+id/listItemImageView"
        android:fontFamily="casual"
        android:text="This Text will change"
        android:textAlignment="viewStart"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/listItemImageView"
        app:layout_constraintRight_toLeftOf="@+id/listItemImageView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
</android.support.constraint.ConstraintLayout>
</code>```

Main activity.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:id="@+id/urlayout"
    tools:context="com.example.me.gesturelaunchertest.MainActivity">
    <!-- Ab fadeduration sachen für I usw. -->
    <android.gesture.GestureOverlayView
        android:id="@+id/gesOverlay"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_gravity="center_horizontal"

        android:eventsInterceptionEnabled="true"
        android:fadeDuration="300"
        android:gestureStrokeAngleThreshold="0"
        android:gestureStrokeLengthThreshold="300.0"
        android:gestureStrokeSquarenessThreshold="0"
        android:gestureColor="@android:color/white"
        android:gestureStrokeWidth="40.0"
        android:uncertainGestureColor="@android:color/darker_gray"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </android.gesture.GestureOverlayView>

    <ListView
        android:id="@+id/applistview"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:background="@android:color/transparent"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        android:layout_marginRight="113dp"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

MainActivity:

```<code>            TransitionManager.beginDelayedTransition(constraintLayout);
            constraintSet=new ConstraintSet();

            constraintSet.clone(constraintLayout);

            constraintSet.connect(applistview.getId(), ConstraintSet.LEFT, constraintLayout.getId(), ConstraintSet.RIGHT, 110);

            constraintSet.applyTo(constraintLayout);
</code>```

答:
There seems to be an issue with ConstraintSet.LEFT and ConstraintSet.RIGHT not working. See this issue on the bug tracker.

Try using ConstraintSet.START and ConstraintSet.END instead:

```<code>constraintSet.connect(applistview.getId(), ConstraintSet.START,
        constraintLayout.getId(), ConstraintSet.END, 110);
</code>```

I hope this helps.

Body:
No Matter what i write inside of Constraintset.connect to change the position, it always just stays where it is (i want it to move from outside the screen into the screen from the left side), at the moment the view is fully inside of the screen and only the left constraint is missing).
Thanks.

ListviewItem:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#202020">

    <ImageView
        android:id="@+id/listItemImageView"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="40dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:paddingBottom="16dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/listItemTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/listItemImageView"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="17dp"
        android:layout_marginRight="17dp"
        android:layout_marginTop="8dp"
        android:layout_toLeftOf="@+id/listItemImageView"
        android:layout_toStartOf="@+id/listItemImageView"
        android:fontFamily="casual"
        android:text="This Text will change"
        android:textAlignment="viewStart"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/listItemImageView"
        app:layout_constraintRight_toLeftOf="@+id/listItemImageView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
</android.support.constraint.ConstraintLayout>

Main activity.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:id="@+id/urlayout"
    tools:context="com.example.me.gesturelaunchertest.MainActivity">

    <android.gesture.GestureOverlayView
        android:id="@+id/gesOverlay"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_gravity="center_horizontal"

        android:eventsInterceptionEnabled="true"
        android:fadeDuration="300"
        android:gestureStrokeAngleThreshold="0"
        android:gestureStrokeLengthThreshold="300.0"
        android:gestureStrokeSquarenessThreshold="0"
        android:gestureColor="@android:color/white"
        android:gestureStrokeWidth="40.0"
        android:uncertainGestureColor="@android:color/darker_gray"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </android.gesture.GestureOverlayView>

    <ListView
        android:id="@+id/applistview"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:background="@android:color/transparent"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        android:layout_marginRight="113dp"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity:

            TransitionManager.beginDelayedTransition(constraintLayout);
            constraintSet=new ConstraintSet();

            constraintSet.clone(constraintLayout);

            constraintSet.connect(applistview.getId(), ConstraintSet.LEFT, constraintLayout.getId(), ConstraintSet.RIGHT, 110);

            constraintSet.applyTo(constraintLayout);

Body:
There seems to be an issue with ConstraintSet.LEFT and ConstraintSet.RIGHT not working. See this issue on the bug tracker.

Try using ConstraintSet.START and ConstraintSet.END instead:

constraintSet.connect(applistview.getId(), ConstraintSet.START,
        constraintLayout.getId(), ConstraintSet.END, 110);

I hope this helps.


问:
Loop over columns in DF and calculate sum based on condition for every appended column in R or Python
```<code>A B C
1 0 0
0 0 1
0 1 0
1 1 1
</code>```

Here I have 4*3 dataframe (columns A,B,C). I`d like to calculate sum in a combination of columns based on a condition that both rows are 1. In other words, in the output I want to have 1*3 dataframe with A 2 B 1 C 1. So, first I look at column A, it has 2 rows with ones, so the sum is 2, then I look at combination of A and B, there is just one row with BOTH 1, so I get 1. Finally, I get combination of A,B,C and it has one row with all ones, so I get 1 as well. Could you pls help with the best way to do it in R or Python.

答:
Here is another approach which is consecutively multiplying the values in each row from left to right using the Reduce() function. The codes below require that there are only 1's and 0's in the data.frame.

```<code>library(data.table)
setDT(DF)[, Reduce(`*`, .SD, accumulate = TRUE)][, lapply(.SD, sum)]
</code>```

```<code>   V1 V2 V3
1:  2  1  1
</code>```

The result is a data.table. If a vector is required, try

```<code>setDT(DF)[, Reduce(`*`, .SD, accumulate = TRUE)][, unname(sapply(.SD, sum))]
</code>```

```<code>[1] 2 1 1
</code>```

Data

```<code>DF <- structure(list(A = c(1L, 0L, 0L, 1L), B = c(0L, 0L, 1L, 1L),
    C = c(0L, 1L, 0L, 1L)), .Names = c("A", "B", "C"), row.names = c(NA,
-4L), class = "data.frame")
</code>```

Body:
A B C
1 0 0
0 0 1
0 1 0
1 1 1

Here I have 4*3 dataframe (columns A,B,C). I`d like to calculate sum in a combination of columns based on a condition that both rows are 1. In other words, in the output I want to have 1*3 dataframe with A 2 B 1 C 1. So, first I look at column A, it has 2 rows with ones, so the sum is 2, then I look at combination of A and B, there is just one row with BOTH 1, so I get 1. Finally, I get combination of A,B,C and it has one row with all ones, so I get 1 as well. Could you pls help with the best way to do it in R or Python.

Body:
Here is another approach which is consecutively multiplying the values in each row from left to right using the Reduce() function. The codes below require that there are only 1's and 0's in the data.frame.

library(data.table)
setDT(DF)[, Reduce(`*`, .SD, accumulate = TRUE)][, lapply(.SD, sum)]

   V1 V2 V3
1:  2  1  1

The result is a data.table. If a vector is required, try

setDT(DF)[, Reduce(`*`, .SD, accumulate = TRUE)][, unname(sapply(.SD, sum))]

[1] 2 1 1

Data

DF <- structure(list(A = c(1L, 0L, 0L, 1L), B = c(0L, 0L, 1L, 1L),
    C = c(0L, 1L, 0L, 1L)), .Names = c("A", "B", "C"), row.names = c(NA,
-4L), class = "data.frame")


问:
Changing a .click function button to load right away instead?
I'm loading html2canvas which has the following script:

```<code> $(function() {
             $("#btnSave").click(function() {
                                 html2canvas($(".widget"), {
                                             onrendered: function(canvas) {
                                             theCanvas = canvas;
                                             document.body.appendChild(canvas);

                                             // Convert and download as image
                                             Canvas2Image.saveAsPNG(canvas);
                                             $("#img-out").append(canvas);
                                             // Clean up
                                             //document.body.removeChild(canvas);
                                             }
                                             });
                                 });
             });
</code>```

I have a button with the id "btnSave" that when clicked it generates my canvas image. Now, instead of having to click the button I would prefer it to load on the page automatically. Is this possible?

jsFiddle to what I'm working with: https://jsfiddle.net/h5ase09f/

Thanks in advance!

答:
Try doing it after the document loads using the ready callback:</p>

```<code>$(document).ready(function(){
     html2canvas($(".widget"), {
       onrendered: function(canvas) {
         theCanvas = canvas;
         document.body.appendChild(canvas);

         // Convert and download as image
         Canvas2Image.saveAsPNG(canvas);
         $("#img-out").append(canvas);
         // Clean up
         //document.body.removeChild(canvas);
       }
     });
});
</code>```

Body:
I'm loading html2canvas which has the following script:

 $(function() {
             $("#btnSave").click(function() {
                                 html2canvas($(".widget"), {
                                             onrendered: function(canvas) {
                                             theCanvas = canvas;
                                             document.body.appendChild(canvas);

                                             // Convert and download as image
                                             Canvas2Image.saveAsPNG(canvas);
                                             $("#img-out").append(canvas);
                                             // Clean up
                                             //document.body.removeChild(canvas);
                                             }
                                             });
                                 });
             });

I have a button with the id "btnSave" that when clicked it generates my canvas image. Now, instead of having to click the button I would prefer it to load on the page automatically. Is this possible?

jsFiddle to what I'm working with: https://jsfiddle.net/h5ase09f/

Thanks in advance!

Body:
Try doing it after the document loads using the ready callback:

$(document).ready(function(){
     html2canvas($(".widget"), {
       onrendered: function(canvas) {
         theCanvas = canvas;
         document.body.appendChild(canvas);

         // Convert and download as image
         Canvas2Image.saveAsPNG(canvas);
         $("#img-out").append(canvas);
         // Clean up
         //document.body.removeChild(canvas);
       }
     });
});


问:
How to access template value parameter from a debugging helper in Qt Creator?
I have a class, something like

```<code>class FixedPoint<int frac> {
    ...
    private:
        std::uint32_t value;
}
</code>```

I want to write a debugging helper that represents a FixedPoint value as a floating-point number. I could do that if I knew the frac value. Is there a way to access it?

For now I consider parsing value.dynamicTypeName() which seems to contain the full template name including the parameters, but it feels hacky...

答:
Answering my own question: there are methods to access value template parameters. In my case you do it like this:

```<code>def qdump__FixedPoint(d, value):
    frac = int(value.type.template_argument(0))
    d.putValue(value['value'] / float(1 << frac))
</code>```

Source.

Body:
I have a class, something like

class FixedPoint<int frac> {
    ...
    private:
        std::uint32_t value;
}

I want to write a debugging helper that represents a FixedPoint value as a floating-point number. I could do that if I knew the frac value. Is there a way to access it?

For now I consider parsing value.dynamicTypeName() which seems to contain the full template name including the parameters, but it feels hacky...

Body:
Answering my own question: there are methods to access value template parameters. In my case you do it like this:

def qdump__FixedPoint(d, value):
    frac = int(value.type.template_argument(0))
    d.putValue(value['value'] / float(1 << frac))

Source.


问:
Doctrine DBAL get Server Information
I did not find anything about this in the manual of the Doctrine DBAL or the Search here.

So basically my question is, is there a way to get the Database Server Information using Doctrine DBAL.

PHP has things like "mysqli_get_server_info()" and "PDO::getAttribute(PDO::ATTR_SERVER_VERSION)", so I was looking if the Doctrine DBAL supports something like this as well.

答:
An old question, but I needed an answer as well.

so:

```<code>$this->getDoctrine()->getConnection()->getWrappedConnection()->getServerVersion();
</code>```

Title: Doctrine DBAL get Server Information

Body:
An old question, but I needed an answer as well.

so:

$this->getDoctrine()->getConnection()->getWrappedConnection()->getServerVersion();


问:
Storing language dictionaries in database
I'm creating a language app that currently only features Mandarin Chinese and Spanish.

Currently, I have self-created dictionary simply loaded as JSON without storing in the DB, but I've found full downloadable dictionaries, such as CEDICT for Chinese to do the definitions for me. That being said, this file is 115k rows long, with 6 columns per row.

I also need to do this for Spanish, and then every other language I plan on including.

Notes:

MySQL DB

Laravel ORM (PHP)

That being said, what's the best way to store this data?

I'm assuming as separate tables, dictionary_zh, dictionary_es, but I could also store each dictionary in a dictionary table, with an added column for locale and query based on that. This SO answer states that 1m records isn't "too much" for a table to handle, it simply defines on how you index the table.

Btw, anyone have a recommendation for a good downloadable Spanish - English dictionary?

Note: I'm downloading the dictionary and cutting it up into something I can load into a CSV

```<code>Traditional Simplified  Pinyin  Meaning       Level Quest
佟               佟       Tong2   surname Tong    1     2
...
</code>```

I'm translating it by simply passing in the identifying character, in this case佟, and grabbing its Meaning.

答:
I would store each dictionary in a separate table to abstract how I fetch the definition for a word depending on the locale, without the need to know how a dictionary (mapped as Dictionary type in the diagram below) operates its translation. This is useful when you might have dictionaries which don't reside in your DB, such as ones translating via an API.

The method translate() is implemented differently for each type of Dictionary (in your case ChineseDictionary or SpanishDictionary).

Another advantage of this approach from a data management point of view is that you will not have to make a lot of operations on the data when new versions of your dictionary are released, which makes it cheap to maintain.

Body:
I'm creating a language app that currently only features Mandarin Chinese and Spanish.

Currently, I have self-created dictionary simply loaded as JSON without storing in the DB, but I've found full downloadable dictionaries, such as CEDICT for Chinese to do the definitions for me. That being said, this file is 115k rows long, with 6 columns per row.

I also need to do this for Spanish, and then every other language I plan on including.

Notes:

MySQL DB

Laravel ORM (PHP)

That being said, what's the best way to store this data?

I'm assuming as separate tables, dictionary_zh, dictionary_es, but I could also store each dictionary in a dictionary table, with an added column for locale and query based on that. This SO answer states that 1m records isn't "too much" for a table to handle, it simply defines on how you index the table.

Btw, anyone have a recommendation for a good downloadable Spanish - English dictionary?

Note: I'm downloading the dictionary and cutting it up into something I can load into a CSV

Traditional Simplified  Pinyin  Meaning       Level Quest
佟               佟       Tong2   surname Tong    1     2
...

I'm translating it by simply passing in the identifying character, in this case佟, and grabbing its Meaning.


问:
Details View in Asp.net, Set it to NEW
I have a grid view on my page, and a hidden details view.
When the user wants to add a new entry, they will click a button, and the gridview will become hidden and the details view will become visible. The only problem is I want my details view to automatically be set empty in the NEW mode, without them having to click the new in the details view form.</p>

答:
In the RowCommand event of the gridview:</p>

```<code>myDetailsView.Visible = true;
myDetailsView.CurrentMode = DetailsViewMode.Insert;
myGridView.Visible = false;
</code>```

Title: Details View in Asp.net, Set it to NEW

Body:
In the RowCommand event of the gridview:

myDetailsView.Visible = true;
myDetailsView.CurrentMode = DetailsViewMode.Insert;
myGridView.Visible = false;


问:
Apache2 redirecting
I am new to apache2 configuration and as far as I could determine the server setup is correct and it works fine on mydomain.com

The problem is even if I explicitly type the url www.mydomain.com, I get 301 redirect from apache to mydomain.com. I tried rewrite rules only to end up in infinite loop.

We actually want to do reverse - mydomain.com should redirect to www.mydomain.com but as indicated above, I get infinite redirect loop until browser gives up.

I have searched the configuration and could not find any mention of mydomain.com so thinking that there is some external configuration (DNS lookup?) coming into picture which is not configured correctly.

答:
If this is for local PC (testing and development) you need to edit your host file in windows or hosts in linux.

I locally resolved the problem that I had by creating a virtual DNS server for my local network (ubuntu server).

```<code>    install bind
apt-get install bind9 -y

cd /etc/bind

vim named.conf.options

And uncomment forwarders and two rows bellow and instead of 0.0.0.0 enter google's dns IP (8.8.8.8).

service bind9 restart

vim named.conf.options

zone "YOURDOMAIN NAME" {
        type master;
        file "db.site.com";
        notify yes;
        };

cp db.local /var/cache/bind/db.site.com
cd /var/cache/bind/
vim db.sajt1.rs

$TTL    604800
@       IN      SOA     admin. admin.itlink.edu. (
                              2         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
        IN NS ns.YOURDOMAINNAMEHERE.
        IN      A       192.168.1.10 replace this with the IP of your PC that has apache installed
ns      A       192.168.1.10 replace this with the IP of your PC that has apache installed
www     A       192.168.1.10 replace this with the IP of your PC that has

service bind9 restart
</code>```

If you put the IP of the ubuntu server as your dns everything will function properly (since all sites that cant be resolved will be sent to google DNS and it will do it for you).
But this is for local network only.

Title: Apache2 redirecting

Body:
If this is for local PC (testing and development) you need to edit your host file in windows or hosts in linux.

I locally resolved the problem that I had by creating a virtual DNS server for my local network (ubuntu server).

    install bind
apt-get install bind9 -y

cd /etc/bind

vim named.conf.options

And uncomment forwarders and two rows bellow and instead of 0.0.0.0 enter google's dns IP (8.8.8.8).

service bind9 restart

vim named.conf.options

zone "YOURDOMAIN NAME" {
        type master;
        file "db.site.com";
        notify yes;
        };

cp db.local /var/cache/bind/db.site.com
cd /var/cache/bind/
vim db.sajt1.rs

$TTL    604800
@       IN      SOA     admin. admin.itlink.edu. (
                              2         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
        IN NS ns.YOURDOMAINNAMEHERE.
        IN      A       192.168.1.10 replace this with the IP of your PC that has apache installed
ns      A       192.168.1.10 replace this with the IP of your PC that has apache installed
www     A       192.168.1.10 replace this with the IP of your PC that has

service bind9 restart

If you put the IP of the ubuntu server as your dns everything will function properly (since all sites that cant be resolved will be sent to google DNS and it will do it for you).
But this is for local network only.


问:
How can I access an object's property in Ruby
My user object has a boolean property that I want to check as a user logs in.

This is what I'm trying to do, but I am getting a 500 error:

```<code>user = User.find_by_email(params['email'])
if user.is_mentor
    #do something
end
</code>```

答:
You need to check to see if there was actually a user that was found with the email params['email']:

```<code>user = User.find_by_email params['email']

if user.present? && user.is_mentor?
    # do something
end
</code>```

Here, user.present? checks to see if user is not equal to nil, which is what it would be if no user was found.

Also, the ? at the end of a method call indicates that the method is returning a boolean value. You should include the question mark in the method call as well if the method is user defined:

```<code>def is_mentor?
    # do something
end
</code>```

Body:
My user object has a boolean property that I want to check as a user logs in.

This is what I'm trying to do, but I am getting a 500 error:

user = User.find_by_email(params['email'])
if user.is_mentor
    #do something
end

Body:
You need to check to see if there was actually a user that was found with the email params['email']:

user = User.find_by_email params['email']

if user.present? && user.is_mentor?
    # do something
end

Here, user.present? checks to see if user is not equal to nil, which is what it would be if no user was found.

Also, the ? at the end of a method call indicates that the method is returning a boolean value. You should include the question mark in the method call as well if the method is user defined:

def is_mentor?
    # do something
end


答:
Use $(document).ready instead of $(id).click and it will load automatically.

$(document).ready(function() {
  var widget = $(".widget")[0]
  var result = html2canvas(widget).then(function(canvas) {
    console.log('rendered');
    theCanvas = canvas;
    document.body.appendChild(canvas);

    // Convert and download as image
    Canvas2Image.saveAsPNG(canvas);
    $("#img-out").append(img);
  }).catch(
    // Log the rejection reason
    (reason) => {
      console.log('Handle rejected promise (' + reason + ') here.');
    });

  console.log('running');
  console.log(result);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* ------- BLACK BOX ------- */

.template2,
.template3,
.template4 {
  background: rgba(0, 0, 0, 0.6);
  background-size: cover;
  width: 50%;
  position: relative;
  left: 25%;
  top: 25%;
  max-height: 50%;
}

/* ------- ADDRESS POSITIONING ------- */

.template2 .data {
  position: absolute;
  z-index: 111;
  text-align: center;
  color: #fff;
  font-family: Lato;
  padding-left: 20%;
  padding-top: 14%;
}

.template3 .data {
  position: absolute;
  z-index: 111;
  text-align: center;
  color: #fff;
  font-family: Lato;
  padding-left: 12%!important;
  padding-top: 14%!important;
}

.template4 .data {
  position: absolute;
  z-index: 111;
  text-align: center;
  color: #fff;
  font-family: Lato;
  padding-left: 9%!important;
  padding-top: 14%!important;
}

/* ------- TITLE TEXT ------- */

.template2 .data h2 {
  font-family: Montserrat;
  font-size: 5.6rem;
  line-height: 1;
}

.template3 .data h2 {
  font-family: Montserrat;
  font-size: 5.6rem;
  line-height: 1;
}

.template4 .data h2 {
  font-family: Montserrat;
  font-size: 5.6rem;
  line-height: 1;
}

/* ------- ADDRESS TEXT ------- */

.template2 .data p {
  margin: 0;
  text-transform: uppercase;
  font-family: arial;
  letter-spacing: 1.5px;
  font-weight: regular;
  font-size: 18px;
}

.template3 .data p {
  margin: 0;
  text-transform: uppercase;
  font-family: lato;
  letter-spacing: 1.5px;
  font-weight: bold;
}

.template4 .data p {
  margin: 0;
  text-transform: uppercase;
  font-family: lato;
  letter-spacing: 1.5px;
  font-weight: bold;
}

.line {
  border-bottom: 2px solid #fff;
  width: 45px;
}

</style></code>```

<link href="https://cotala.com/social/profile/css/script.css" rel="stylesheet" />

    <input type="button" id="btnSave" value="Save" />

JUST
SOLD

1234 Address Avenue
Langley
Walnut Grove

```

Note Snippet may not work here. Was getting cross domain security errors. Working fiddle is here: https://jsfiddle.net/q04quu74/

Title: Changing a .click function button to load right away instead?

Body:
Use $(document).ready instead of $(id).click and it will load automatically.

$(document).ready(function() {
  var widget = $(".widget")[0]
  var result = html2canvas(widget).then(function(canvas) {
    console.log('rendered');
    theCanvas = canvas;
    document.body.appendChild(canvas);

    // Convert and download as image
    Canvas2Image.saveAsPNG(canvas);
    $("#img-out").append(img);
  }).catch(
    // Log the rejection reason
    (reason) => {
      console.log('Handle rejected promise (' + reason + ') here.');
    });

  console.log('running');
  console.log(result);

});

/* ------- BLACK BOX ------- */

.template2,
.template3,
.template4 {
  background: rgba(0, 0, 0, 0.6);
  background-size: cover;
  width: 50%;
  position: relative;
  left: 25%;
  top: 25%;
  max-height: 50%;
}

/* ------- ADDRESS POSITIONING ------- */

.template2 .data {
  position: absolute;
  z-index: 111;
  text-align: center;
  color: #fff;
  font-family: Lato;
  padding-left: 20%;
  padding-top: 14%;
}

.template3 .data {
  position: absolute;
  z-index: 111;
  text-align: center;
  color: #fff;
  font-family: Lato;
  padding-left: 12%!important;
  padding-top: 14%!important;
}

.template4 .data {
  position: absolute;
  z-index: 111;
  text-align: center;
  color: #fff;
  font-family: Lato;
  padding-left: 9%!important;
  padding-top: 14%!important;
}

/* ------- TITLE TEXT ------- */

.template2 .data h2 {
  font-family: Montserrat;
  font-size: 5.6rem;
  line-height: 1;
}

.template3 .data h2 {
  font-family: Montserrat;
  font-size: 5.6rem;
  line-height: 1;
}

.template4 .data h2 {
  font-family: Montserrat;
  font-size: 5.6rem;
  line-height: 1;
}

/* ------- ADDRESS TEXT ------- */

.template2 .data p {
  margin: 0;
  text-transform: uppercase;
  font-family: arial;
  letter-spacing: 1.5px;
  font-weight: regular;
  font-size: 18px;
}

.template3 .data p {
  margin: 0;
  text-transform: uppercase;
  font-family: lato;
  letter-spacing: 1.5px;
  font-weight: bold;
}

.template4 .data p {
  margin: 0;
  text-transform: uppercase;
  font-family: lato;
  letter-spacing: 1.5px;
  font-weight: bold;
}

.line {
  border-bottom: 2px solid #fff;
  width: 45px;
}

</style>

<script src="https://cdn.jsdelivr.net/canvas2image/0.1/canvas2image.min.js"></script>
<link href="https://cotala.com/social/profile/css/script.css" rel="stylesheet" />
<script src="https://cotala.com/social/profile/js/html2canvas.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="off-canvas-wrapper">
  <div class="off-canvas-wrapper-inner" data-off-canvas-wrapper>

    <center><input type="button" id="btnSave" value="Save" />
      <div id="img-out"></div>
    </center>

    <div class="column">
      <div id="html2canvas">
        <div class="widget thumbnail">

          <div class="template2">
            <div class="absolute">
              <div class="data">
                <h2>JUST<br>SOLD</h2>
                <hr class="line">
                <p>1234&nbsp;Address&nbsp;Avenue<br>Langley<br>Walnut&nbsp;Grove</p>

              </div>
            </div>
            <img src="http://cotala.com/social/profile/images/templates/blank.png">
          </div>

        </div>
      </div>

    </div>

Note Snippet may not work here. Was getting cross domain security errors. Working fiddle is here: https://jsfiddle.net/q04quu74/


问:
JSON, PHP and REST Web services
I'm new with this, so please be patient... (I'll write it just like the code was given to me)... I'm working on PHP files with .js files attached (if somehow this could be helpfull), this is a CRM insertion.

I need to consume a REST web service from:

```<code>http://example.com:8080/path/to/folder
</code>```

From a PHP (POST method) form, I need to send a JSON with the data (this could be also be send with jQuery):

```<code>{
"name": "Name",
"lastname": "Last Name",
"email": "name@example.com", (need to be validated on PHP)
"phone": "19283764", (need to be validated on PHP)
"source": "eCommerce",
"credential": "no"
}
</code>```

And get this response:

```<code>{
"response":[X]{
"result":[X]{
"message": "Record(s) added successfully",
"recorddetail":[X]{
"FL":[ ][{"content": 5646542168321358, "val": "Id" }, {"content": "2017-06-30 11:25:17",…]
}
},
"uri": "/crm/private/xml/Leads/insertRecords"
}
}
</code>```

If someone could please give me an example of how to achive this, that would be awesome. Or instruction where and what to write in every file would be appreciated too.

Thanks for the help!

答:
Sending a JSON to server and parsing output from server:

```<code>var data={name:"Oliver",last_name:"Schael",phone:2445}
$.post("http://example.com:8080/path/to/folder",data,function(response){
  var json_output=JSON.parse(response);
});
</code>```

Title: JSON, PHP and REST Web services

Body:
I'm new with this, so please be patient... (I'll write it just like the code was given to me)... I'm working on PHP files with .js files attached (if somehow this could be helpfull), this is a CRM insertion.

I need to consume a REST web service from:

http://example.com:8080/path/to/folder

From a PHP (POST method) form, I need to send a JSON with the data (this could be also be send with jQuery):

{
"name": "Name",
"lastname": "Last Name",
"email": "name@example.com", (need to be validated on PHP)
"phone": "19283764", (need to be validated on PHP)
"source": "eCommerce",
"credential": "no"
}

And get this response:

{
"response":[X]{
"result":[X]{
"message": "Record(s) added successfully",
"recorddetail":[X]{
"FL":[ ][{"content": 5646542168321358, "val": "Id" }, {"content": "2017-06-30 11:25:17",…]
}
},
"uri": "/crm/private/xml/Leads/insertRecords"
}
}

If someone could please give me an example of how to achive this, that would be awesome. Or instruction where and what to write in every file would be appreciated too.

Thanks for the help!

Body:
Sending a JSON to server and parsing output from server:

var data={name:"Oliver",last_name:"Schael",phone:2445}
$.post("http://example.com:8080/path/to/folder",data,function(response){
  var json_output=JSON.parse(response);
});


问:
String not displaying properly on mobile?
I'm new here so forgive me if I've made a stupid mistake. I'm trying to edit this website (http://www.fountfornations.org/) and it looks the way I want it to on desktop, but when I look on mobile the line saying "empowerment without limitation" goes to the top and off the screen. How would I fix this issue? I've tried using a media query and moving the string down if screen size is <600px, but it makes no difference on the positioning of the string. Here is my code:

HTML:

CSS:

    .motto{
 text-align: center;
 padding-left: 60px;
 position: relative;
 right: 155px;

    }
    @media screen and (max-width: 600px) {
    ...
    #words{
 text-align: left;
    }
    .motto{
 position: relative;
 top: 250px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="motto">
    <h1>EMPOWERMENT <span style="color: #ffcc00;">WITHOUT LIMITATION</span></h1>
    </div></code>```

Thanks in advance!

答:
Your text is jumping to the top because you are specifying a top value in the media query. Simply remove this to have it stay where it is vertically on the page.

You're using right to align your content by default, and left to align it in your media query. When you reach the snap-point, the .motto will have both attributes applied to it.

You shouldn't really need to use either left or right with position: relative, as you're already using padding-left on .motto. I'd recommend using margin-left instead of padding-left (so that the whole .motto moves, not just the
, and change this on the snap-point to reach the desired indentation:

.motto {
  text-align: center;
  margin-left: 60px;
  position: relative;
}

@media screen and (max-width: 600px) {
  .motto {
    margin-left: 80px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="motto">
  <h1>EMPOWERMENT
    <span style="color: #ffcc00;">WITHOUT LIMITATION</span>
  </h1>
</div></code>```

Also note that you don't need to re-declare position: relative in the @media query, as elements within media queries will automatically inherit any non-media-query rules, so the element already has position: relative applied.

Hope this helps! :)

Body:
I'm new here so forgive me if I've made a stupid mistake. I'm trying to edit this website (http://www.fountfornations.org/) and it looks the way I want it to on desktop, but when I look on mobile the line saying "empowerment without limitation" goes to the top and off the screen. How would I fix this issue? I've tried using a media query and moving the string down if screen size is <600px, but it makes no difference on the positioning of the string. Here is my code:

HTML:

CSS:

    .motto{
 text-align: center;
 padding-left: 60px;
 position: relative;
 right: 155px;

    }
    @media screen and (max-width: 600px) {
    ...
    #words{
 text-align: left;
    }
    .motto{
 position: relative;
 top: 250px;
    }

EMPOWERMENT WITHOUT LIMITATION

Thanks in advance!

Body:
Your text is jumping to the top because you are specifying a top value in the media query. Simply remove this to have it stay where it is vertically on the page.

You're using right to align your content by default, and left to align it in your media query. When you reach the snap-point, the .motto will have both attributes applied to it.

You shouldn't really need to use either left or right with position: relative, as you're already using padding-left on .motto. I'd recommend using margin-left instead of padding-left (so that the whole .motto moves, not just the <h1>, and change this on the snap-point to reach the desired indentation:

.motto {
  text-align: center;
  margin-left: 60px;
  position: relative;
}

@media screen and (max-width: 600px) {
  .motto {
    margin-left: 80px;
  }
}

<div class="motto">
  <h1>EMPOWERMENT
    <span style="color: #ffcc00;">WITHOUT LIMITATION</span>
  </h1>
</div>

Also note that you don't need to re-declare position: relative in the @media query, as elements within media queries will automatically inherit any non-media-query rules, so the element already has position: relative applied.

Hope this helps! :)


问:
SQL Server 2014 : how to get records that have rows of different values of only particular column
Our customers have accounts with us for their vehicles. Some customers have multiple vehicles, hence multiple licence plates. Sometimes, some customers have different Insurance Accounts for their vehicles too.

I need a list of accounts that have:

More than 1 licence plate and

More than 1 insurance account ID

I'm using 3 tables:

Account table A for account info

Plate table P for licence plate info

EventLog table E for info when notice letter was sent

Relationship:

```<code>A.AccountId = P.AccountId = E.AccountId
</code>```

My code so far:

```<code>SELECT
    A.AccountNumber, A.AccountId, A.CurrentBalance,
    E.NotificationDt,
    P.LicPlateNo, A.RegistrationTypeId, P.InsuranceAccountId
FROM
    Account A
INNER JOIN
    Plate P ON A.AccountId = P.AccountId
INNER JOIN
    EventLog E ON A.AccountId = E.AccountId
WHERE
    A.RegistrationTypeId = 3
    AND P.EndDate IS NULL
    AND A.AccountStatusId = 1
    AND A.DelinquencyStatusId = 11
    AND E.EventId = 64
    AND P.PlateStatusId = 1
ORDER BY
    AccountNumber, A.AccountId, P.LicPlateNo
</code>```

My sample data looks like this:

```<code>+---------+---------+---------+-------------+----------+---+--------+
|AccNo    | AccId   |CurrBal  |NotifDt      |LicPlateNo|RTI|InsAccId|
+---------+---------+---------+-------------+----------+---+--------+
|21234561 |123456   |    56.79|   2017-01-01|ABC123    |  3|1234ABC |
|21234572 |123457   |    83.25|   2017-01-03|DEF345    |  3|345DEF  |
|22345672 |234567   |   104.38|   2017-01-03|GHI345    |  3|567GHI  |
|22345672 |234568   |   104.38|   2017-01-03|JKL678    |  3|789MNO  |
+---------+---------+---------+-------------+----------+---+--------+
</code>```

In my sample data, the last two columns are for the same AccountNumber which has different LicencePlateNos and different Insurance AccountIds.

I would like my data to look like this:

```<code>+---------+---------+---------+-------------+----------+---+--------+
|22345672 |234567   |   104.38|   2017-01-03|GHI345    |  3|567GHI  |
|22345672 |234568   |   104.38|   2017-01-03|JKL678    |  3|789MNO  |
+---------+---------+---------+-------------+----------+---+--------+
</code>```

What would the code be that would give me that data?

I tried using a GROUP BY... HAVING clause but that gives me only the unique AccountNumbers that have multiple licence plates. I would like to show the different licence plate nos and the different InsuranceAccountIDs as well.

答:
A simple way is to use your query as a base and count the values with more than one row:</p>

```<code>SELECT a.*
FROM (SELECT A.AccountNumber, A.AccountId, A.CurrentBalance, E.NotificationDt,
             P.LicPlateNo, A.RegistrationTypeId, P.InsuranceAccountId,
             COUNT(*) OVER (PARTITION BY A.AccountNumber) as cnt
      FROM Account A INNER JOIN
           Plate P
           ON A.AccountId = P.AccountId INNER JOIN
           EventLog E
           ON A.AccountId = E.AccountId
      WHERE A.RegistrationTypeId = 3 AND
            P.EndDate IS NULL AND
            A.AccountStatusId = 1 AND
            A.DelinquencyStatusId = 11 AND
            E.EventId = 64 AND
            P.PlateStatusId = 1
     ) a
WHERE cnt > 1;
ORDER BY AccountNumber, AccountId, LicPlateNo;
</code>```

Body:
Our customers have accounts with us for their vehicles. Some customers have multiple vehicles, hence multiple licence plates. Sometimes, some customers have different Insurance Accounts for their vehicles too.

I need a list of accounts that have:

More than 1 licence plate and

More than 1 insurance account ID

I'm using 3 tables:

Account table A for account info

Plate table P for licence plate info

EventLog table E for info when notice letter was sent

Relationship:

A.AccountId = P.AccountId = E.AccountId

My code so far:

SELECT
    A.AccountNumber, A.AccountId, A.CurrentBalance,
    E.NotificationDt,
    P.LicPlateNo, A.RegistrationTypeId, P.InsuranceAccountId
FROM
    Account A
INNER JOIN
    Plate P ON A.AccountId = P.AccountId
INNER JOIN
    EventLog E ON A.AccountId = E.AccountId
WHERE
    A.RegistrationTypeId = 3
    AND P.EndDate IS NULL
    AND A.AccountStatusId = 1
    AND A.DelinquencyStatusId = 11
    AND E.EventId = 64
    AND P.PlateStatusId = 1
ORDER BY
    AccountNumber, A.AccountId, P.LicPlateNo

My sample data looks like this:

+---------+---------+---------+-------------+----------+---+--------+
|AccNo    | AccId   |CurrBal  |NotifDt      |LicPlateNo|RTI|InsAccId|
+---------+---------+---------+-------------+----------+---+--------+
|21234561 |123456   |    56.79|   2017-01-01|ABC123    |  3|1234ABC |
|21234572 |123457   |    83.25|   2017-01-03|DEF345    |  3|345DEF  |
|22345672 |234567   |   104.38|   2017-01-03|GHI345    |  3|567GHI  |
|22345672 |234568   |   104.38|   2017-01-03|JKL678    |  3|789MNO  |
+---------+---------+---------+-------------+----------+---+--------+

In my sample data, the last two columns are for the same AccountNumber which has different LicencePlateNos and different Insurance AccountIds.

I would like my data to look like this:

+---------+---------+---------+-------------+----------+---+--------+
|22345672 |234567   |   104.38|   2017-01-03|GHI345    |  3|567GHI  |
|22345672 |234568   |   104.38|   2017-01-03|JKL678    |  3|789MNO  |
+---------+---------+---------+-------------+----------+---+--------+

What would the code be that would give me that data?

I tried using a GROUP BY... HAVING clause but that gives me only the unique AccountNumbers that have multiple licence plates. I would like to show the different licence plate nos and the different InsuranceAccountIDs as well.

Body:
A simple way is to use your query as a base and count the values with more than one row:

SELECT a.*
FROM (SELECT A.AccountNumber, A.AccountId, A.CurrentBalance, E.NotificationDt,
             P.LicPlateNo, A.RegistrationTypeId, P.InsuranceAccountId,
             COUNT(*) OVER (PARTITION BY A.AccountNumber) as cnt
      FROM Account A INNER JOIN
           Plate P
           ON A.AccountId = P.AccountId INNER JOIN
           EventLog E
           ON A.AccountId = E.AccountId
      WHERE A.RegistrationTypeId = 3 AND
            P.EndDate IS NULL AND
            A.AccountStatusId = 1 AND
            A.DelinquencyStatusId = 11 AND
            E.EventId = 64 AND
            P.PlateStatusId = 1
     ) a
WHERE cnt > 1;
ORDER BY AccountNumber, AccountId, LicPlateNo;


问:
Is the S3 Protocol encrypted in transmission when using the SDK?
if I'm using the AmazonS3Client to put and fetch files, is my connection encrypted? This seems basic, but my googling seems to return things about encrypting the S3 storage and not whether the transmission from this client is secure. If it's not secure is there a setting to make it secure?</p>

答:
Amazon S3 endpoints support both HTTP and HTTPS. It is recommended that you communicate via HTTPS to ensure your data is encrypted in transit.

You can also create a Bucket Policy that enforces communication via HTTPS. See:

Stackoverflow: Force SSL on Amazon S3

Sample policy: s3BucketPolicyEncryptionSSL.json


问:
iOS Swift - CollectionView INSIDE UIView XIB INSIDE UIViewController
I can't seem to find any information on how to achieve this, and what I'm trying to achieve is kind of hard to explain, but here it is:

I have a UIViewController that loads a "stack" of reusable UIViews that I've created with a XIB. Within each reusable UIView is a CollectionView, that creates a custom CollectionViewCell for each string in an array.

I have no idea how to accomplish this. No clue whatsoever, and nothing online covers this exact situation. It seems to be one level deeper than any other explanation provides. Every time I try to create the cells for the CollectionView I get a "Must register a nib or a class for the identifier or connect a prototype cell in a storyboard" error.

答:
You can register a nib for a collection cell something like this:

```<code>let cellNib = UINib(nibName: "MyCellAsNib", bundle: nil)
collectionView?.registerNib(cellNib, forCellWithReuseIdentifier: "myCell")
</code>```

It seems to me, however, it would be a lot easier to use one CollectionViewController with sections and prototype cells, instead of a custom UIView 'stack' of multiple CollectionViews. This is exactly what CollectionViewController was designed for.

Body:
You can register a nib for a collection cell something like this:

let cellNib = UINib(nibName: "MyCellAsNib", bundle: nil)
collectionView?.registerNib(cellNib, forCellWithReuseIdentifier: "myCell")

It seems to me, however, it would be a lot easier to use one CollectionViewController with sections and prototype cells, instead of a custom UIView 'stack' of multiple CollectionViews. This is exactly what CollectionViewController was designed for.


问:
Rails 5.0.4 No route matches {:action=>"update_status", :controller=>"tasks"}
I've got the followed code:

tasks_controller.rb

```<code>class TasksController < ApplicationController
 before_action :set_task, only: [:show, :edit, :update, :destroy]

 def index
 end

 def show
 end

 def new
  @task = Task.new
 end

 def edit
 end

 def create
  @task = Task.new(task_params)
end

 def update
 end

 def destroy
  @task.destroy
 end

 def update_status
  @task = Task.find(params[:id])
  @task.status = "Progres"
  format.js
end

private
def set_task
  @task = Task.find(params[:id])
end

def task_params
  params.require(:task).permit(:title, :content, :datetime, :status)
end
end
</code>```

_task.html.erb:

```<code><%= form_tag({:action=>'update_status', :controller=>'tasks'},:method=>:post,:id=>"update_status",:name=>'taskstatus_form',:remote=>true) do %>
    <div class="btn btn-info"><%= submit_tag 'Progres' %></div>
<%end%>
</code>```

and the config/routes.rb

```<code>Rails.application.routes.draw do

  root "tasks#index"
  put '/tasks/update_status'  => 'tasks#index'

  resources :tasks
end
</code>```

This error appears:

No route matches {:action=>"update_status", :controller=>"tasks"}

See anyone the problem? Thanx for help

答:
The error is because your are not routing correctly, both your routes go to index, none to update_status.

Change this:

```<code>put '/tasks/update_status'  => 'tasks#index'
</code>```

to this:

```<code>post '/tasks/update_status'  => 'tasks#update_status'
</code>```

Body:
I've got the followed code:

tasks_controller.rb

class TasksController < ApplicationController
 before_action :set_task, only: [:show, :edit, :update, :destroy]

 def index
 end

 def show
 end

 def new
  @task = Task.new
 end

 def edit
 end

 def create
  @task = Task.new(task_params)
end

 def update
 end

 def destroy
  @task.destroy
 end

 def update_status
  @task = Task.find(params[:id])
  @task.status = "Progres"
  format.js
end

private
def set_task
  @task = Task.find(params[:id])
end

def task_params
  params.require(:task).permit(:title, :content, :datetime, :status)
end
end

_task.html.erb:

<%= form_tag({:action=>'update_status', :controller=>'tasks'},:method=>:post,:id=>"update_status",:name=>'taskstatus_form',:remote=>true) do %>

<%= submit_tag 'Progres' %>

<%end%>

and the config/routes.rb

Rails.application.routes.draw do

  root "tasks#index"
  put '/tasks/update_status'  => 'tasks#index'

  resources :tasks
end

This error appears:

No route matches {:action=>"update_status", :controller=>"tasks"}

See anyone the problem? Thanx for help

Body:
The error is because your are not routing correctly, both your routes go to index, none to update_status.

Change this:

put '/tasks/update_status'  => 'tasks#index'

to this:

post '/tasks/update_status'  => 'tasks#update_status'


答:
An easy way to do this would be to JOIN a result set that would allow you for checking for either or both conditions.  Just include the appropriate filter clause:</p>

```<code>...
INNER JOIN EventLog E ON A.AccountId = E.AccountId

INNER JOIN
(
    SELECT
        Plate.AccountId,
        LicensePlateCount = COUNT(DISTINCT Plate.LicPlateNo),
        InsuranceAccountCount = COUNT(DISTINCT Plate.InsuranceAccountId)
    FROM
        Plate
    WHERE
        Plate.EndDate IS NULL
        AND Plate.PlateStatusId = 1
    GROUP BY
        Plate.AccountId
) PlateAccounts ON A.AccountId = PlateAccounts.AccountId
    -- 1) More than 1 License Plate:
    AND PlateAccounts.LicensePlateCount > 1
    -- 2) More than 1 Insurance Account IDs:
    AND PlateAccounts.InsuranceAccountCount > 1

WHERE A.RegistrationTypeId = 3
...
</code>```

Title: SQL Server 2014 : how to get records that have rows of different values of only particular column

Body:
An easy way to do this would be to JOIN a result set that would allow you for checking for either or both conditions.  Just include the appropriate filter clause:

...
INNER JOIN EventLog E ON A.AccountId = E.AccountId

INNER JOIN
(
    SELECT
        Plate.AccountId,
        LicensePlateCount = COUNT(DISTINCT Plate.LicPlateNo),
        InsuranceAccountCount = COUNT(DISTINCT Plate.InsuranceAccountId)
    FROM
        Plate
    WHERE
        Plate.EndDate IS NULL
        AND Plate.PlateStatusId = 1
    GROUP BY
        Plate.AccountId
) PlateAccounts ON A.AccountId = PlateAccounts.AccountId
    -- 1) More than 1 License Plate:
    AND PlateAccounts.LicensePlateCount > 1
    -- 2) More than 1 Insurance Account IDs:
    AND PlateAccounts.InsuranceAccountCount > 1

WHERE A.RegistrationTypeId = 3
...


问:
SPA + WebAPI authenticate using Azure AD B2C and Azure AD
My customer wants to use AZURE AD B2C to authenticate external users, and Azure AD for employees of his company. I've been looking on github and googling about it, but there's a lack of examples over there.

Does anybody had the same requirement to give some hints?

Besides that, it seems that MSAL.js / hello.js has some bugs (X-Frame-Options issue when renewing the token).

Is there any other JS library that I'm not familiar?

答:
My customer wants to use AZURE AD B2C to authenticate external users, and Azure AD for employees of his company.

Azure B2C supports this from custom policies. You can easily configure this by referring Azure Active Directory B2C: Get started with custom policies and Azure Active Directory B2C: Sign in by using Azure AD accounts

Besides that, it seems that MSAL.js / hello.js has some bugs (X-Frame-Options issue when renewing the token).

Microsoft was written a sample application using hello.js library. But as you said it has x-frame options issue but that is only for Social IDPs. So, you can still use SPA app written from Microsoft for your use-case.

Is there any other JS library that I'm not familiar?

Yes, there is another JS library out there similar to hello.js that is oidc-client.js. It is easy to configure and use in SPA application.


问:
Highlight first character of every line using css or JS
I have requirement to highlight first character in each and every line, as example image below, all the content is in single paragraph, based on resolution change also it should behave same,

I have tried with flex box, and first child using script also, I could not able to find solution

Any help will be appreciated.

答:
try this approach (probably not the best but it works just fine):

var content = document.getElementById('content').innerHTML
var doYourThing = function(){
  var formattedContent = content.replace(/(\w)/g,'$1')
  document.getElementById('formatted').innerHTML = formattedContent

  var characters = document.getElementsByTagName('span')
  var refPosition = characters[0].getBoundingClientRect().left

  for (character of characters){
    if(character.getBoundingClientRect().left <= refPosition){
      character.style.textTransform = "capitalize"
      character.style.color = "red"
    }
  }
}
doYourThing()
window.onresize = doYourThing```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque nisi minima veritatis ipsa magnam culpa ipsam dolores. Deserunt rerum, quod unde consequatur consectetur harum omnis sequi, voluptatum quaerat quasi illo?
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, esse, repellendus sed voluptate facere magni quis beatae corrupti odio id! Labore voluptatem soluta harum esse, at atque deserunt nesciunt ipsa.
</p>
<p id="formatted" style="background-color:#fee"></p></code>```

Customize it to meet your needs. Good luck.
JSFiddle

Body:
try this approach (probably not the best but it works just fine):

var content = document.getElementById('content').innerHTML
var doYourThing = function(){
  var formattedContent = content.replace(/(\w)/g,'<span>$1</span>')
  document.getElementById('formatted').innerHTML = formattedContent

  var characters = document.getElementsByTagName('span')
  var refPosition = characters[0].getBoundingClientRect().left

  for (character of characters){
    if(character.getBoundingClientRect().left <= refPosition){
      character.style.textTransform = "capitalize"
      character.style.color = "red"
    }
  }
}
doYourThing()
window.onresize = doYourThing

<p id="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque nisi minima veritatis ipsa magnam culpa ipsam dolores. Deserunt rerum, quod unde consequatur consectetur harum omnis sequi, voluptatum quaerat quasi illo?
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, esse, repellendus sed voluptate facere magni quis beatae corrupti odio id! Labore voluptatem soluta harum esse, at atque deserunt nesciunt ipsa.
</p>
<p id="formatted" style="background-color:#fee"></p>

Customize it to meet your needs. Good luck.
JSFiddle


问:
Is Autofac ContainerBuilder.Build an expensive operation?
I'm starting to use Autofac and I can't seem to find an answer to this question.

Also, when should I call ContainerBuilder.Build() ?

After I call the ContainerBuilder.Build() is it possible to register another type or instance?

答:
In my web apps I use a base HttpApplication class that calls the Build on the Application_Start event.
I then use a mix of Modules (placed on each assembly that require registration), a assembly "scanner" and MVC integration.

For later registration you could use, for instance, the MEF integration, or, as Jonathan stated, use the Build overload.

Hope it helps :)