问:
How to use expression-templates for specific types?
When using expression templates, how do I create specializations? From the Wikipedia example, I can make a Vector sum template class like so:

```<code>template <typename E1, typename E2>
class VecSum : public VecExpression<VecSum<E1, E2> > {
    E1 const& _u;
    E2 const& _v;
public:
    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v) {
        assert(u.size() == v.size());
    }
    double operator[](size_t i) const { return _u[i] + _v[i]; }
    size_t size()               const { return _v.size(); }
};

template <typename E1, typename E2>
VecSum<E1,E2> const
operator+(E1 const& u, E2 const& v) {
   return VecSum<E1, E2>(u, v);
}
</code>```

According to Wikipedia, if I have a Vector class that extends VecExpression<Vector> and a constructor from the VecExpression class that uses the [] operator and a loop, this will allow loop merging so statements like the following only use a single loop:

```<code>Vector a = ...;
Vector b = ...;
Vector c = ...;
Vector d = a+b+c;
</code>```

I get why this works, but I'm not sure how to extend it to scalars. I want to be able to add a scalar (int, float, or double) to the entire Vector, but I'm not sure how to do this. My best guess is to create specializations for the VecSum class like:

```<code>template<typename E2> VecSum<int, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, int>{ /*stuff goes here*/ }
template<typename E2> VecSum<float, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, float>{ /*stuff goes here*/ }
template<typename E2> VecSum<double, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, double>{ /*stuff goes here*/ }
</code>```

But this seems like its a lot more work than is necessary, is there another solution?

答:
What about an alternative:

```<code>class AnySize { };
bool operator==(AnySize, AnySize) { return true; }
bool operator==(size_t, AnySize) { return true; }
bool operator==(AnySize, size_t) { return true; }

template <typename T>
class Scalar {
    T _value;

public:
    explicit Scalar(T value) : _value(value) {}
    T operator[](int) { return _value; }
    AnySize size() { return {}; }
}
</code>```

You will also need to change VecExpression::size, to give an appropriate size rather than always the left hand side's

```<code>AnySize size_for(AnySize, AnySize) { return {}; }
size_t size_for(size_t lhs, AnySize) { return lhs; }
size_t size_for(AnySize, size_t rhs) { return rhs; }
size_t size_for(size_t lhs, size_t rhs) { return lhs; }

auto VecExpression<E1,E2>::size() { return size_for(_u.size(), _v.size()); }
</code>```

Body:
When using expression templates, how do I create specializations? From the Wikipedia example, I can make a Vector sum template class like so:

template <typename E1, typename E2>
class VecSum : public VecExpression<VecSum<E1, E2> > {
    E1 const& _u;
    E2 const& _v;
public:
    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v) {
        assert(u.size() == v.size());
    }
    double operator[](size_t i) const { return _u[i] + _v[i]; }
    size_t size()               const { return _v.size(); }
};

template <typename E1, typename E2>
VecSum<E1,E2> const
operator+(E1 const& u, E2 const& v) {
   return VecSum<E1, E2>(u, v);
}

According to Wikipedia, if I have a Vector class that extends VecExpression<Vector> and a constructor from the VecExpression class that uses the [] operator and a loop, this will allow loop merging so statements like the following only use a single loop:

Vector a = ...;
Vector b = ...;
Vector c = ...;
Vector d = a+b+c;

I get why this works, but I'm not sure how to extend it to scalars. I want to be able to add a scalar (int, float, or double) to the entire Vector, but I'm not sure how to do this. My best guess is to create specializations for the VecSum class like:

template<typename E2> VecSum<int, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, int>{ /*stuff goes here*/ }
template<typename E2> VecSum<float, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, float>{ /*stuff goes here*/ }
template<typename E2> VecSum<double, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, double>{ /*stuff goes here*/ }

But this seems like its a lot more work than is necessary, is there another solution?

Body:
What about an alternative:

class AnySize { };
bool operator==(AnySize, AnySize) { return true; }
bool operator==(size_t, AnySize) { return true; }
bool operator==(AnySize, size_t) { return true; }

template <typename T>
class Scalar {
    T _value;

public:
    explicit Scalar(T value) : _value(value) {}
    T operator[](int) { return _value; }
    AnySize size() { return {}; }
}

You will also need to change VecExpression::size, to give an appropriate size rather than always the left hand side's

AnySize size_for(AnySize, AnySize) { return {}; }
size_t size_for(size_t lhs, AnySize) { return lhs; }
size_t size_for(AnySize, size_t rhs) { return rhs; }
size_t size_for(size_t lhs, size_t rhs) { return lhs; }

auto VecExpression<E1,E2>::size() { return size_for(_u.size(), _v.size()); }


来源: stackexchange

问:
Splice from array works only in one order
I have a little problem.
I have a checkbox for showing div. I can choose from 6 different checkboxes to select which div I want to show.

When check checkboxes I show div and send to server checked name of div.

```<code> $scope.savesGraphUserDetail = [];
    $scope.addRemoveUserChart = function(checked, value) {
      if (checked) {
        $scope.savesGraphUserDetail.push(value);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
        .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }else {
        var index = $scope.savesGraphUserDetail.indexOf(value);
        $scope.savesGraphUserDetail.splice(index);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
          .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }
</code>```

And this is ok,
but when I uncheck checkboxes I get a problem, because if I check in this order
first click "A", second "C" and third "D" I push in my array like this

```<code>myArray = ["A", "C", "D"]
</code>```

And if I uncheck in reverse order,
first uncheck "D"

```<code>myArray = ["A", "C"]
</code>```

second uncheck "C"

```<code>myArray = ["A"]
</code>```

and last "A"

```<code>myArray = []
</code>```

and this is perfect, but if I change order when unchecking checkboxes

```<code>myArray = ["A", "C", "D"]
</code>```

if I first uncheck "C", my array remove "C" and "D", i get this

```<code>myArray = ["A"]
</code>```

if I first uncheck "A", my array remove "A" and "C" and "D", I get this

```<code>myArray = []
</code>```

How to remove an only unchecked item?

答:
Your problem is that you are calling .splice() method with the index only, you need to sepecify 1 as second parameter, which is the number of items to be spliced, the deleteCount optional param.

```<code>var index = $scope.savesGraphUserDetail.indexOf(value);
$scope.savesGraphUserDetail.splice(index, 1);
</code>```

Otherwise all of the elements beginning with start index on through the end of the array will be deleted, that's why "C" and "D" were deleted in your second try.

Documentation:

If you take a look at the .splice() MDN specification, you can see that:

ContentLicense: CC BY-SA 3.0

Body:
I have a little problem.
I have a checkbox for showing div. I can choose from 6 different checkboxes to select which div I want to show.

When check checkboxes I show div and send to server checked name of div.

 $scope.savesGraphUserDetail = [];
    $scope.addRemoveUserChart = function(checked, value) {
      if (checked) {
        $scope.savesGraphUserDetail.push(value);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
        .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }else {
        var index = $scope.savesGraphUserDetail.indexOf(value);
        $scope.savesGraphUserDetail.splice(index);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
          .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }

And this is ok,
but when I uncheck checkboxes I get a problem, because if I check in this order
first click "A", second "C" and third "D" I push in my array like this

myArray = ["A", "C", "D"]

And if I uncheck in reverse order,
first uncheck "D"

myArray = ["A", "C"]

second uncheck "C"

myArray = ["A"]

and last "A"

myArray = []

and this is perfect, but if I change order when unchecking checkboxes

myArray = ["A", "C", "D"]

if I first uncheck "C", my array remove "C" and "D", i get this

myArray = ["A"]

if I first uncheck "A", my array remove "A" and "C" and "D", I get this

myArray = []

How to remove an only unchecked item?

Body:
Your problem is that you are calling .splice() method with the index only, you need to sepecify 1 as second parameter, which is the number of items to be spliced, the deleteCount optional param.

var index = $scope.savesGraphUserDetail.indexOf(value);
$scope.savesGraphUserDetail.splice(index, 1);

Otherwise all of the elements beginning with start index on through the end of the array will be deleted, that's why "C" and "D" were deleted in your second try.

Documentation:

If you take a look at the .splice() MDN specification, you can see that:


问:
Android Crash in PlayStore Console
We found lot's of crash logs in PlayStore Console, but don't have any idea what is this about and can't reproduce it.

```<code>java.lang.SecurityException:
  at android.os.Parcel.readException (Parcel.java:1689)
  at android.database.DatabaseUtils.readExceptionFromParcel (DatabaseUtils.java:183)
  at android.database.DatabaseUtils.readExceptionFromParcel (DatabaseUtils.java:135)
  at android.content.ContentProviderProxy.insert (ContentProviderNative.java:482)
  at android.content.ContentResolver.insert (ContentResolver.java:1279)
  at android.content.AsyncQueryHandler$WorkerHandler.handleMessage (AsyncQueryHandler.java:96)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:241)
  at android.os.HandlerThread.run (HandlerThread.java:61)
</code>```

Looks like the exception doesn't depend on any Android version ( at least it happened for 7.1, 7.0, 6.0, 5.1 versions), but as you can see from the screenshot all listed devices are Sony devices

Do you have any guess what this can be related to?

答:
We found a cause of exception.

The exception indeed was Sony specific and was related to notifications.

Here is full stacktrace.

```<code>java.lang.SecurityException: Missing permission to insert badges
11-14 19:41:50.414: E/DatabaseUtils(1389):  at com.sonymobile.home.resourceprovider.HomeResourceProvider.insertBadge(HomeResourceProvider.java:113)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at com.sonymobile.home.resourceprovider.HomeResourceProvider.insert(HomeResourceProvider.java:58)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at android.content.ContentProvider$Transport.insert(ContentProvider.java:220)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:167)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at android.os.Binder.execTransact(Binder.java:404)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at dalvik.system.NativeStart.run(Native Method)
11-14 19:41:50.414: W/dalvikvm(28623): threadid=20: thread exiting with uncaught exception (group=0x415b8d88)
11-14 19:41:50.414: E/AndroidRuntime(28623): FATAL EXCEPTION: AsyncQueryWorker
11-14 19:41:50.414: E/AndroidRuntime(28623): Process: air.com.plexonic.meln2, PID: 28623
11-14 19:41:50.414: E/AndroidRuntime(28623): java.lang.SecurityException: Missing permission to insert badges
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.os.Parcel.readException(Parcel.java:1474)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.content.ContentProviderProxy.insert(ContentProviderNative.java:479)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.content.ContentResolver.insert(ContentResolver.java:1196)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.content.AsyncQueryHandler$WorkerHandler.handleMessage(AsyncQueryHandler.java:96)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.os.Looper.loop(Looper.java:212)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

Solution was to add specific Sony permissions to the AndroidManifest.

```<code><uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE"/>
<uses-permission android:name="com.sonymobile.home.permission.PROVIDER_INSERT_BADGE"/>
</code>```

Title: Android Crash in PlayStore Console

Body:
We found lot's of crash logs in PlayStore Console, but don't have any idea what is this about and can't reproduce it.

java.lang.SecurityException:
  at android.os.Parcel.readException (Parcel.java:1689)
  at android.database.DatabaseUtils.readExceptionFromParcel (DatabaseUtils.java:183)
  at android.database.DatabaseUtils.readExceptionFromParcel (DatabaseUtils.java:135)
  at android.content.ContentProviderProxy.insert (ContentProviderNative.java:482)
  at android.content.ContentResolver.insert (ContentResolver.java:1279)
  at android.content.AsyncQueryHandler$WorkerHandler.handleMessage (AsyncQueryHandler.java:96)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:241)
  at android.os.HandlerThread.run (HandlerThread.java:61)

Looks like the exception doesn't depend on any Android version ( at least it happened for 7.1, 7.0, 6.0, 5.1 versions), but as you can see from the screenshot all listed devices are Sony devices

Do you have any guess what this can be related to?

Body:
We found a cause of exception.

The exception indeed was Sony specific and was related to notifications.

Here is full stacktrace.

java.lang.SecurityException: Missing permission to insert badges
11-14 19:41:50.414: E/DatabaseUtils(1389):  at com.sonymobile.home.resourceprovider.HomeResourceProvider.insertBadge(HomeResourceProvider.java:113)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at com.sonymobile.home.resourceprovider.HomeResourceProvider.insert(HomeResourceProvider.java:58)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at android.content.ContentProvider$Transport.insert(ContentProvider.java:220)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:167)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at android.os.Binder.execTransact(Binder.java:404)
11-14 19:41:50.414: E/DatabaseUtils(1389):  at dalvik.system.NativeStart.run(Native Method)
11-14 19:41:50.414: W/dalvikvm(28623): threadid=20: thread exiting with uncaught exception (group=0x415b8d88)
11-14 19:41:50.414: E/AndroidRuntime(28623): FATAL EXCEPTION: AsyncQueryWorker
11-14 19:41:50.414: E/AndroidRuntime(28623): Process: air.com.plexonic.meln2, PID: 28623
11-14 19:41:50.414: E/AndroidRuntime(28623): java.lang.SecurityException: Missing permission to insert badges
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.os.Parcel.readException(Parcel.java:1474)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.content.ContentProviderProxy.insert(ContentProviderNative.java:479)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.content.ContentResolver.insert(ContentResolver.java:1196)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.content.AsyncQueryHandler$WorkerHandler.handleMessage(AsyncQueryHandler.java:96)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.os.Looper.loop(Looper.java:212)
11-14 19:41:50.414: E/AndroidRuntime(28623):    at android.os.HandlerThread.run(HandlerThread.java:61)

Solution was to add specific Sony permissions to the AndroidManifest.

<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE"/>
<uses-permission android:name="com.sonymobile.home.permission.PROVIDER_INSERT_BADGE"/>


问:
Java How to get start and end of an element in an ArrayList
I have some dynamic values in an ArrayList

```<code>ClassnameOne <!----Begin---->
Classnametwo <!----Begin---->
Classnamethree <!----Begin---->
Classnamethree <!----End---->
Classnametwo <!----End--->
ClassnameOne <!----End---->
</code>```

What I want to do is to get the beginning occurrence of an element and when it ends. So for example ClassnameOne would be 5, Classnametwo would be 3.
This is what I have done so far:

```<code>ArrayList<String> one = new ArrayList<String>();
for (int i = 0; i < one.size(); i++) {
    if(one.get(i).contains("<!----End---->") && one.get(i).equals(one.get(i+1))) {
        break;
    } else {
        count++;
        System.out.println(one.get(i));
    }
    System.out.println(count);
}
</code>```

This doesn't give the right answer. Can you please help?

答:
```<code>ArrayList<String> one = new ArrayList<String>();
for (int starti = 0; starti < one.size(); ++starti) {
    String[] words = one.get(starti).split(" ", 2);
    if (words[1].equals("<!----Begin---->")) {
        int n = 0;
        String sought = words[0] + " " + "<!----End---->";
        for (int endi = starti + 1; endi < one.size(); ++endi) {
            if (one.get(endi).equals(sought) {
                n = endi - starti;
                break;
            }
        }
        System.out.printf("%s at %d covers %d lines.%n", words[0], starti, n);
    }
}
</code>```

Assuming that the names do not repeat, otherwise a stack (or such) would to be needed.

Body:
I have some dynamic values in an ArrayList

ClassnameOne
Classnametwo
Classnamethree
Classnamethree
Classnametwo
ClassnameOne

What I want to do is to get the beginning occurrence of an element and when it ends. So for example ClassnameOne would be 5, Classnametwo would be 3.
This is what I have done so far:

ArrayList<String> one = new ArrayList<String>();
for (int i = 0; i < one.size(); i++) {
    if(one.get(i).contains("") && one.get(i).equals(one.get(i+1))) {
        break;
    } else {
        count++;
        System.out.println(one.get(i));
    }
    System.out.println(count);
}

This doesn't give the right answer. Can you please help?

Body:
ArrayList<String> one = new ArrayList<String>();
for (int starti = 0; starti < one.size(); ++starti) {
    String[] words = one.get(starti).split(" ", 2);
    if (words[1].equals("<!----Begin---->")) {
        int n = 0;
        String sought = words[0] + " " + "<!----End---->";
        for (int endi = starti + 1; endi < one.size(); ++endi) {
            if (one.get(endi).equals(sought) {
                n = endi - starti;
                break;
            }
        }
        System.out.printf("%s at %d covers %d lines.%n", words[0], starti, n);
    }
}

Assuming that the names do not repeat, otherwise a stack (or such) would to be needed.


问:
RegExp URL validation
```<code>var re = /^(https?:\/\/)?([0-9a-z\.-]+)[^-]\.([a-z]{2,9}\.?)([\/#].\S*)*$/i;

re.test("http://zcontest.ru/dir%201/dir_2/program.ext?var1=x&var2=my%20value");
re.test("http://zcontest.ru/dir%201/dir_2/program.ext&var1=x&var2=my%20value");
</code>```

Hi guys. What i must add or change, so that parametres in URL cant start with &(ampersand), like in second example ?

答:
I tried to modify your initial regex as little as possible, since it was unclear exactly what your goal was. Here is the regex as you asked:

^(https?:\/\/)?([0-9a-z\.-]+)[^-]\.([a-z]{2,9}\.?)([\/#].[^?\s]*)*\?([^\t \n]*)*$

Also if you are not having a multiline string being checked, then the \n is unnecessary. Additionally note that it will not match strings which do not contain a ?, such as:

http://zcontest.ru/dir%201/dir_2/program.ext

Title: RegExp URL validation

Body:
var re = /^(https?:\/\/)?([0-9a-z\.-]+)[^-]\.([a-z]{2,9}\.?)([\/#].\S*)*$/i;

re.test("http://zcontest.ru/dir%201/dir_2/program.ext?var1=x&var2=my%20value");
re.test("http://zcontest.ru/dir%201/dir_2/program.ext&var1=x&var2=my%20value");

Hi guys. What i must add or change, so that parametres in URL cant start with &(ampersand), like in second example ?


问:
How can I prevent the debugger from entering my method when Exception is thrown?
How can I prevent the debugger from entering my method when an exception is thrown, instead show the exception at the method's call site?

For example, if one's code causes an exception to be thrown from mscorlib, the debugger (obviously) does not take them into the non-user code to show the exception's source, only shows the exception at the call site.

In other words, this the default behavior:

and this is my desired behavior:

I have tried adding [DebuggerNonUserCode] and [DebuggerStepThrough] attributes to my Fail() method, but no luck.

答:
You need to decorate your method with DebuggerHiddenAttribute:</p>

```<code>[DebuggerHidden]
public static void Fail() {
    throw new Exception("Fail");
}
</code>```

Body:
You need to decorate your method with DebuggerHiddenAttribute:

[DebuggerHidden]
public static void Fail() {
    throw new Exception("Fail");
}


问:
Split rdd and Select elements
I am trying to capture a stream, transform the data, and then save it locally.

So far, streaming, and writing works fine. However, the transformation only works halfway.
The stream I receive consists out of 9 columns separated by "|". So I want to split it, and let's say select column 1,3, and 5. What I have tried looks like this, but nothing really let to a result

```<code>val indices =  List(1,3,5)
linesFilter.window(Seconds(EVENT_PERIOD_SECONDS*WRITE_EVERY_N_SECONDS), Seconds(EVENT_PERIOD_SECONDS*WRITE_EVERY_N_SECONDS)).foreachRDD { (rdd, time) =>
            if (rdd.count() > 0) {
          rdd
          .map(_.split("\\|").slice(1,2))
            //.map(arr => (arr(0), arr(2))))
            //filter(x=> indices.contains(_(x)))) //selec(indices)
            //.zipWithIndex
           .coalesce(1,true)

//the replacement is is used so that I get a csv file at the end
            //.map(_.replace(DELIMITER_STREAM, DELIMITER_OUTPUT))
            //.map{_.mkString(DELIMITER_OUTPUT) }
            .saveAsTextFile(CHECKPOINT_DIR + "/output/o_" + sdf.format(System.currentTimeMillis()))
}
</code>```

Has anyone a tip how do I split a rdd and then only grab specific elements out of it?

Edit Input:

```<code>val lines = streamingContext.socketTextStream(HOST, PORT)
val linesFilter = lines
          .map(_.toLowerCase)
          .filter(_.split(DELIMITER_STREAM).length == 9)
</code>```

Input stream is that:

```<code>536365|71053|white metal lantern|6|01-12-10 8:26|3,39|17850|united kingdom|2017-11-17 14:52:22
</code>```

答:
Thank you very much everyone.

As you recommended, I modified my code like that:

```<code>private val DELIMITER_STREAM = "\\|"

val linesFilter = lines
          .map(_.toLowerCase)
          .filter(_.split(DELIMITER_STREAM).length == 9)
          .map(x =>{
            val y = x.split(DELIMITER_STREAM)
            (y(0),y(1),y(3),y(4),y(5),y(6),y(7))})
</code>```

and then in the RDD

```<code>if (rdd.count() > 0) {

  rdd
    .map(_.productIterator.mkString(DELIMITER_OUTPUT))
    .coalesce(1,true)
    .saveAsTextFile(CHECKPOINT_DIR + "/output/o_" + sdf.format(System.currentTimeMillis()))

  }
</code>```

Title: Split rdd and Select elements

Body:
I am trying to capture a stream, transform the data, and then save it locally.

So far, streaming, and writing works fine. However, the transformation only works halfway.
The stream I receive consists out of 9 columns separated by "|". So I want to split it, and let's say select column 1,3, and 5. What I have tried looks like this, but nothing really let to a result

val indices =  List(1,3,5)
linesFilter.window(Seconds(EVENT_PERIOD_SECONDS*WRITE_EVERY_N_SECONDS), Seconds(EVENT_PERIOD_SECONDS*WRITE_EVERY_N_SECONDS)).foreachRDD { (rdd, time) =>
            if (rdd.count() > 0) {
          rdd
          .map(_.split("\\|").slice(1,2))
            //.map(arr => (arr(0), arr(2))))
            //filter(x=> indices.contains(_(x)))) //selec(indices)
            //.zipWithIndex
           .coalesce(1,true)

//the replacement is is used so that I get a csv file at the end
            //.map(_.replace(DELIMITER_STREAM, DELIMITER_OUTPUT))
            //.map{_.mkString(DELIMITER_OUTPUT) }
            .saveAsTextFile(CHECKPOINT_DIR + "/output/o_" + sdf.format(System.currentTimeMillis()))
}

Has anyone a tip how do I split a rdd and then only grab specific elements out of it?

Edit Input:

val lines = streamingContext.socketTextStream(HOST, PORT)
val linesFilter = lines
          .map(_.toLowerCase)
          .filter(_.split(DELIMITER_STREAM).length == 9)

Input stream is that:

536365|71053|white metal lantern|6|01-12-10 8:26|3,39|17850|united kingdom|2017-11-17 14:52:22

Body:
Thank you very much everyone.

As you recommended, I modified my code like that:

private val DELIMITER_STREAM = "\\|"

val linesFilter = lines
          .map(_.toLowerCase)
          .filter(_.split(DELIMITER_STREAM).length == 9)
          .map(x =>{
            val y = x.split(DELIMITER_STREAM)
            (y(0),y(1),y(3),y(4),y(5),y(6),y(7))})

and then in the RDD

if (rdd.count() > 0) {

  rdd
    .map(_.productIterator.mkString(DELIMITER_OUTPUT))
    .coalesce(1,true)
    .saveAsTextFile(CHECKPOINT_DIR + "/output/o_" + sdf.format(System.currentTimeMillis()))

  }


问:
Voice control script that works offline (localhost with no internet connection)
I'm looking for a voice control script for my website (it's like an app) working offline running on localhost with no internet access. I used talater.com/annyang, it super simple to use and works perfectly, but needs internet access to work. My question is: Do you know any voice control scripts that I can use offline (localhost, no internet access)? Thanks!</p>

答:
Firstly, this isn't the right place for such a question. Secondly, it's already been asked here: Software Recommendations/StackExchange

There they suggested PocketSphinx JS. Also, some browsers now have a Web Speech API which you could implement or if you have Node.js at your disposal then there's a number of speech recognition packages (first brief npm search gave me this one: Speech Tree).


问:
catch the response return in MVP with repository pattern
I'm facing problems: I have been creating a login process that will return a response. If the login is true, it will give response like this.

```<code>{
    "error": false,   "message": "Logged In Successfully",
    "user": {
        "username": "administrator",
        "email": "admin@admin.com",
        "first_name": "USER",
        "last_name": "ADMIN"
    },
    "menu": [
       {
         "name": "MENU A",
         "module": "menu_a",
         "controller": "",
         "parent_module": "",
         "status": ""
       },
       {
          "name": "MENU B",
          "module": "menu_b",
          "controller": " ",
          "parent_module": "",
          "status": ""
       }
    ],
    "privilege": [
       {
           "module": "menu_a"
       },
       {
           "module": "menu_b"
       }
    ]
}
</code>```

Then when it false, it will return response like this.

```<code>{   "error": true,   "message": "Incorrect Login",   "user": {
    "username": "none",
    "email": "none",
    "first_name": "none",
    "last_name": "none",
    "company": "none",
    "phone": "none",
    "gender": "none",
    "place_of_birth": "none",
    "date_of_birth": "none",
    "religion": "none",
    "photo": "none"   },   "menu": "none",   "privilege": "none" }
</code>```

This is my code:

```<code>public interface AppDataSource {

     Single<LoginResponse> attemptLogin(Login login);

     Single<LoginResponse> saveUserData(LoginResponse response);

}

public class AppRemoteDataSource implements AppDataSource {

    private final Retrofit retrofit;

    @Inject
    public AppRemoteDataSource(@NonNull Retrofit retrofit) {
        this.retrofit = retrofit;
    }

    @Override
    public Single<LoginResponse> attemptLogin(Login login) {
        return retrofit.create(OmrService.class).loginUser(login);
    }

    @Override
    public Single<Boolean> checkLogin() {
        throw new UnsupportedOperationException();
    }
}

public class AppLocalDataSource implements AppDataSource {

    @NonNull
    private final SharedPreferences sharedPreferences;

    @NonNull
    private final Realm realm;

    @Inject
    public AppLocalDataSource(@NonNull SharedPreferences sharedPreferences, @NonNull Realm realm) {
        this.sharedPreferences = sharedPreferences;
        this.realm = realm;
    }
    @Override
    public Single<Boolean> checkLogin() {
       return Single.create(s -> {
           Boolean stsLogin = sharedPreferences.getBoolean("IS_USER_LOGIN", >false);
           s.onSuccess(stsLogin);
       });
    }
    @Override
    public Single<LoginResponse> saveUserData(LoginResponse response) {
       return Single.create(e -> {
           if(!response.isError()) {
               savePreference(response.getUser());
               saveMenuPrivilege(response.getMenu(), >response.getPrivilege());
           }
           e.onSuccess(response);
       });
    }

}

public class AppRepository implements AppDataSource {

    @NonNull
    private final AppDataSource localDataSource;

    @NonNull
    private final AppDataSource remoteDataSource;

    @Inject
    public AppRepository(@NonNull @Local AppDataSource localDataSource,
                         @NonNull @Remote AppDataSource remoteDataSource) {
        this.localDataSource = localDataSource;
        this.remoteDataSource = remoteDataSource;
    }

    @Override
    public Single<LoginResponse> attemptLogin(Login login) {
        return remoteDataSource.attemptLogin(login)
                .compose(RxUtils.applySingleSchedulers())
                .flatMap(localDataSource::saveUserData);
    }

    @Override
    public Single<Boolean> checkLogin() {
        return localDataSource.checkLogin();
    }

}

public class LoginPresenter implements LoginContract.Presenter {

    private LoginContract.View view;

    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    private AppRepository repository;

    @Inject
    public LoginPresenter(AppRepository repository, LoginContract.View view) {
        this.repository = repository;
        this.view = view;

    }

    private void attemptLogin(Login login) {
        view.showProgressIndicator(true);
        compositeDisposable.add(repository.attemptLogin(login)
                .subscribe(
                        response -> {
                            if(response.isError()) {
                                Log.d("CHECK RESPONSE ", response.getMessage());
                                view.makeSnack(response.getMessage().toString().replace("<p>","").replace("</p>",""));
                            } else {
                                view.showProgressIndicator(false);
                                view.startMainActivity();
                            }
                        } , e -> {
                            Log.d("CHECK RESPONSE ERROR", e.getMessage());
                            view.makeSnack(e.getMessage().toString());
                            view.showProgressIndicator(false);
                        }
                ));
    }
}
</code>```

The problem is, when I'm testing it false username the response that show in Toast is not "Incorrect Login", instead "com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 268 path $.menu"

I know the menu and privilege is empty when the login is false. But how i can catch the response message "Incorrect login"?, Is there any part of the code that I need to change?

Thanks in advance

答:
The problem is your privilege key.

On success it is an array: "privilege": [ { "module": "menu_a" }, { "module": "menu_b" } ]

In failure it is a string: "privilege": "none"

A simple way to make it work would be to change "none" to []

The problem is in your JSON deserializer (GSON?) which obviously cannot represent both a String and an Array the same way.

So if you cannot change the server response, you most likely need to create a custom deserializer that can do the conversion for you. How to do that depends on what is being used to convert the JSON to Java.

Body:
I'm facing problems: I have been creating a login process that will return a response. If the login is true, it will give response like this.

{
    "error": false,   "message": "Logged In Successfully",
    "user": {
        "username": "administrator",
        "email": "admin@admin.com",
        "first_name": "USER",
        "last_name": "ADMIN"
    },
    "menu": [
       {
         "name": "MENU A",
         "module": "menu_a",
         "controller": "",
         "parent_module": "",
         "status": ""
       },
       {
          "name": "MENU B",
          "module": "menu_b",
          "controller": " ",
          "parent_module": "",
          "status": ""
       }
    ],
    "privilege": [
       {
           "module": "menu_a"
       },
       {
           "module": "menu_b"
       }
    ]
}

Then when it false, it will return response like this.

{   "error": true,   "message": "Incorrect Login",   "user": {
    "username": "none",
    "email": "none",
    "first_name": "none",
    "last_name": "none",
    "company": "none",
    "phone": "none",
    "gender": "none",
    "place_of_birth": "none",
    "date_of_birth": "none",
    "religion": "none",
    "photo": "none"   },   "menu": "none",   "privilege": "none" }

This is my code:

public interface AppDataSource {

     Single<LoginResponse> attemptLogin(Login login);

     Single<LoginResponse> saveUserData(LoginResponse response);

}

public class AppRemoteDataSource implements AppDataSource {

    private final Retrofit retrofit;

    @Inject
    public AppRemoteDataSource(@NonNull Retrofit retrofit) {
        this.retrofit = retrofit;
    }

    @Override
    public Single<LoginResponse> attemptLogin(Login login) {
        return retrofit.create(OmrService.class).loginUser(login);
    }

    @Override
    public Single<Boolean> checkLogin() {
        throw new UnsupportedOperationException();
    }
}

public class AppLocalDataSource implements AppDataSource {

    @NonNull
    private final SharedPreferences sharedPreferences;

    @NonNull
    private final Realm realm;

    @Inject
    public AppLocalDataSource(@NonNull SharedPreferences sharedPreferences, @NonNull Realm realm) {
        this.sharedPreferences = sharedPreferences;
        this.realm = realm;
    }
    @Override
    public Single<Boolean> checkLogin() {
       return Single.create(s -> {
           Boolean stsLogin = sharedPreferences.getBoolean("IS_USER_LOGIN", >false);
           s.onSuccess(stsLogin);
       });
    }
    @Override
    public Single<LoginResponse> saveUserData(LoginResponse response) {
       return Single.create(e -> {
           if(!response.isError()) {
               savePreference(response.getUser());
               saveMenuPrivilege(response.getMenu(), >response.getPrivilege());
           }
           e.onSuccess(response);
       });
    }

}

public class AppRepository implements AppDataSource {

    @NonNull
    private final AppDataSource localDataSource;

    @NonNull
    private final AppDataSource remoteDataSource;

    @Inject
    public AppRepository(@NonNull @Local AppDataSource localDataSource,
                         @NonNull @Remote AppDataSource remoteDataSource) {
        this.localDataSource = localDataSource;
        this.remoteDataSource = remoteDataSource;
    }

    @Override
    public Single<LoginResponse> attemptLogin(Login login) {
        return remoteDataSource.attemptLogin(login)
                .compose(RxUtils.applySingleSchedulers())
                .flatMap(localDataSource::saveUserData);
    }

    @Override
    public Single<Boolean> checkLogin() {
        return localDataSource.checkLogin();
    }

}

public class LoginPresenter implements LoginContract.Presenter {

    private LoginContract.View view;

    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    private AppRepository repository;

    @Inject
    public LoginPresenter(AppRepository repository, LoginContract.View view) {
        this.repository = repository;
        this.view = view;

    }

    private void attemptLogin(Login login) {
        view.showProgressIndicator(true);
        compositeDisposable.add(repository.attemptLogin(login)
                .subscribe(
                        response -> {
                            if(response.isError()) {
                                Log.d("CHECK RESPONSE ", response.getMessage());
                                view.makeSnack(response.getMessage().toString().replace("
","").replace("
",""));
                            } else {
                                view.showProgressIndicator(false);
                                view.startMainActivity();
                            }
                        } , e -> {
                            Log.d("CHECK RESPONSE ERROR", e.getMessage());
                            view.makeSnack(e.getMessage().toString());
                            view.showProgressIndicator(false);
                        }
                ));
    }
}

The problem is, when I'm testing it false username the response that show in Toast is not "Incorrect Login", instead "com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 268 path $.menu"

I know the menu and privilege is empty when the login is false. But how i can catch the response message "Incorrect login"?, Is there any part of the code that I need to change?

Thanks in advance


问:
How to simulate position tracking of an iot thing?
I need to simulate the position tracking for my 'IoT thing' in my IoT platform Thingworx. For eg: If I have a car as a Thing, and it has two modes moving and stopped. I need to simulate the changing latitude and longitude for the car when it is in 'moving' state and store the generated coordinates so that they can be later displayed on the Google map widget in the mashup. Similarly, if the car is stopped then it should display the location where it was last stopped. I have the following questions:

How do I achieve this? As in, should I create and use a service or a subscription (with speed values as the trigger)?

What sort of code snippet will be required for such a functionality?

Should I employ the Google api?

Also how do you store the changing values of the lat/long in the variable which has a datatype 'Location'?

Thanks!

答:
A part of the logic to simulate movement, which can be as complex as you want or a simple as adding Randomly movements to the Latitude / Longitude.

You should use a Timer Thing which for instance triggers every second  ( or any other frequency ) and you subscribe to "Timer" event and there you write the code to move the car.

You need to have a property on the Car Thing that we can call it "location" which of baseType LOCATION, and this property should be set as "logged" then you just need to update location property with the new location ( if it moved since last location - on your simulator code - ). Of course you also must set car Thing's ValueStream property in order to get storage for location changes.

You can use TW Marketplace Google Maps extension in order to show Location and Paths on Google Maps from the recorded simulation.

Setting a location property in TW it's something like:

me.location = {
   latittude: latitude_value,
   longitude: longitude_value,
  elevation: elevation_value,
  units: "WGS84"
}

Hope it helps.


问:
Python Riemann Sum does not yield zero for equal positive and negative areas
I wrote a program to approximate an integral using a Riemann sum and graph it using matplotlib in Python. For functions with equal areas above and below the x-axis, the resulting area should be zero, but my program outputs a very small number instead.

The following code graphs the odd function f(x) = x^3 from -1 to 1, so the area should be zero. My code instead approximates it to be 1.68065561477562 e^-15.

What is causing this? Is it a rounding error in delta_x, x, or y? I know I could just round the value to zero, but I'm wondering if there is another problem or way to solve this.

I have tried using the Decimal.decimal class for delta_x, but I just got an even smaller number.

The Python code:

```<code>import matplotlib.pyplot as plt
import numpy as np

# Approximates and graphs integral using Riemann Sum

# example function: f(x) = x^3
def f_x(x):
    return x**3

# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000

# calculate delta x, list of x-values, list of y-values, and approximate area under curve
delta_x = (b - a) / n

x = np.arange(a, b+delta_x, delta_x)

y = [f_x(i) for i in x]

area = sum(y) * delta_x

# graph using matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.bar(x, y, delta_x, alpha=.5)
plt.title('a={}, b={}, n={}'.format(a, b, n))
plt.xlabel('A = {}'.format(area))
plt.show()
</code>```

答:
Yes, this is just due to floating point inaccuracy.

For constructing the partition, np.linspace() may be more appropriate since np.arange() may or may not include the endpoint depending on how it's rounded when using non-integer step sizes.

From numpy.arange() documentation:

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.

Body:
I wrote a program to approximate an integral using a Riemann sum and graph it using matplotlib in Python. For functions with equal areas above and below the x-axis, the resulting area should be zero, but my program outputs a very small number instead.

The following code graphs the odd function f(x) = x^3 from -1 to 1, so the area should be zero. My code instead approximates it to be 1.68065561477562 e^-15.

What is causing this? Is it a rounding error in delta_x, x, or y? I know I could just round the value to zero, but I'm wondering if there is another problem or way to solve this.

I have tried using the Decimal.decimal class for delta_x, but I just got an even smaller number.

The Python code:

import matplotlib.pyplot as plt
import numpy as np

# Approximates and graphs integral using Riemann Sum

# example function: f(x) = x^3
def f_x(x):
    return x**3

# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000

# calculate delta x, list of x-values, list of y-values, and approximate area under curve
delta_x = (b - a) / n

x = np.arange(a, b+delta_x, delta_x)

y = [f_x(i) for i in x]

area = sum(y) * delta_x

# graph using matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.bar(x, y, delta_x, alpha=.5)
plt.title('a={}, b={}, n={}'.format(a, b, n))
plt.xlabel('A = {}'.format(area))
plt.show()


问:
Bad screen redrawing in Oracle SQL Developer
I have a problem with Oracle SQL Developer.  When I use it on a Windows Server 2003 machine, it works fine.  When I use it on my Windows 7 desktop, I get a lot of redraw problems in the query results grid when I scroll either horizontally or vertically, like so:

Edit: ImageShack was the original image host for my screenshot, and it's no longer a valid url. Since my problem is fixed now, I can't repro this. The gist is that the client area of the result grids was repainted as gibberish during scrolling.

This makes it tricky to assess the results of your queries.  Clicking on the header and on individual cells causes it to then redraw properly, but it's goofy to not be able to just scroll normally.  Is there any way to fix this?  I am using the current version of SQL Developer 1.5.5 with the included JVM.

答:
I made this step after solved

Add or replace the attribute of the following config file.

```<code>..\sqldeveloper\bin\sqldeveloper.conf

AddVMOption -Dsun.java2d.noddraw=true
</code>```

Turkish developer can see this site

Body:
I made this step after solved

Add or replace the attribute of the following config file.

..\sqldeveloper\bin\sqldeveloper.conf

AddVMOption -Dsun.java2d.noddraw=true

Turkish developer can see this site


问:
SQL Server displaying query output in certain format
Question:

How can I display the student name, the department name and the course name of every course that the student has not taken?

I have tried using generating a cartesian product like this:

```<code>SELECT
    NAME, student.dept_name, title
FROM
    student
JOIN
    (SELECT
         id, title
     FROM
         takes, course
     WHERE
         takes.course_id <> course.course_id) a ON student.id = a.id
ORDER BY
    NAME ASC, title ASC
</code>```

And it works fine as long as the student only takes 1 course, but not if he attends to more than one

Can you guys provide a solution ? Thanks in advance

Database relations

The desired output is a connection of the values in this format

```<code>| name | dept_name | title (course name) |
</code>```

答:
```<code>select
    s.*, c.*
from students s
cross join courses c
left join takes t on s.student_id = t.id -- naming looks weird
                 and c.course_id = t.course_id
where t.student_id IS NULL
order by
  s.name, c.title -- or similar
</code>```

A cross join forms a Cartesian product that forms all combinations of student + course. Outer join that large potential set to the actual set of students enrolled to courses. Then, the un-joined rows constitute the courses that have not been taken by (each) student.

If the questions has a small "twist" and that all you need is the list of un-taken courses then:

```<code>select distinct
    c.*
from students s
cross join courses c
left join takes t on s.student_id = t.id -- naming looks weird
                 and c.course_id = t.course_id
where t.student_id IS NULL
order by
  c.title -- or similar
</code>```

Will simplify the result to just the untaken courses.

Body:
Question:

How can I display the student name, the department name and the course name of every course that the student has not taken?

I have tried using generating a cartesian product like this:

SELECT
    NAME, student.dept_name, title
FROM
    student
JOIN
    (SELECT
         id, title
     FROM
         takes, course
     WHERE
         takes.course_id <> course.course_id) a ON student.id = a.id
ORDER BY
    NAME ASC, title ASC

And it works fine as long as the student only takes 1 course, but not if he attends to more than one

Can you guys provide a solution ? Thanks in advance

Database relations

The desired output is a connection of the values in this format

| name | dept_name | title (course name) |

Body:
select
    s.*, c.*
from students s
cross join courses c
left join takes t on s.student_id = t.id -- naming looks weird
                 and c.course_id = t.course_id
where t.student_id IS NULL
order by
  s.name, c.title -- or similar

A cross join forms a Cartesian product that forms all combinations of student + course. Outer join that large potential set to the actual set of students enrolled to courses. Then, the un-joined rows constitute the courses that have not been taken by (each) student.

If the questions has a small "twist" and that all you need is the list of un-taken courses then:

select distinct
    c.*
from students s
cross join courses c
left join takes t on s.student_id = t.id -- naming looks weird
                 and c.course_id = t.course_id
where t.student_id IS NULL
order by
  c.title -- or similar

Will simplify the result to just the untaken courses.


问:
How to create the mongodb schema for below Json?
```<code>{
    "_id" : ObjectId("5a0e77f4b7368f14c088f542"),
    "folderName" : "team 4",
    "tag" : "search",
    "ismainFolder" : true,
    "innerFolder" : [
                    {
                       parentfolderId" : null,
                      "ismainFolder" : false,
                      "foldername" : "Onkar 11"
                        "subinnerFolder" : [
                                        {
                                            "parentfolderId" : null,
                                            "ismainFolder" : false,
                                            "foldername" : "Onkar 11"
                                            "thirdSubFolder" : [
                                                        {
                                                            "parentfolderId" : null,
                                                            "ismainFolder" : false,
                                                           "foldername" : "Onkar 11"
                                                        },
                                                        {
                                                             "parentfolderId" : null,
                                                             "ismainFolder" : false,
                                                             "foldername" : "Onkar 11"
                                                        }
                                                    ]
                                        },

                                   ]
                    },
                ]
}
</code>```

I need to create the mongodb schema for below json format so that innerFolder, subinnerFolder, etc (inner folder structure goes nested) so please help me in this ?

答:
Below is a json schema generated by https://jsonschema.net/#/. You can edit it as required. For Mongoose schema, take a look at https://github.com/topliceanu/mongoose-gen  </p>

```<code>{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://example.com/example.json",
  "type": "object",
  "properties": {
    "folderName": {
      "$id": "/properties/folderName",
      "type": "string",
      "title": "The Foldername Schema.",
      "description": "An explanation about the purpose of this instance.",
      "default": "",
      "examples": [
        "team 4"
      ]
    },
    "tag": {
      "$id": "/properties/tag",
      "type": "string",
      "title": "The Tag Schema.",
      "description": "An explanation about the purpose of this instance.",
      "default": "",
      "examples": [
        "search"
      ]
    },
    "ismainFolder": {
      "$id": "/properties/ismainFolder",
      "type": "boolean",
      "title": "The Ismainfolder Schema.",
      "description": "An explanation about the purpose of this instance.",
      "default": false,
      "examples": [
        true
      ]
    },
    "innerFolder": {
      "$id": "/properties/innerFolder",
      "type": "array",
      "items": {
        "$id": "/properties/innerFolder/items",
        "type": "object",
        "properties": {
          "parentfolderId": {
            "$id": "/properties/innerFolder/items/properties/parentfolderId",
            "type": "null",
            "title": "The Parentfolderid Schema.",
            "description": "An explanation about the purpose of this instance.",
            "default": null,
            "examples": [
              null
            ]
          },
          "ismainFolder": {
            "$id": "/properties/innerFolder/items/properties/ismainFolder",
            "type": "boolean",
            "title": "The Ismainfolder Schema.",
            "description": "An explanation about the purpose of this instance.",
            "default": false,
            "examples": [
              false
            ]
          },
          "foldername": {
            "$id": "/properties/innerFolder/items/properties/foldername",
            "type": "string",
            "title": "The Foldername Schema.",
            "description": "An explanation about the purpose of this instance.",
            "default": "",
            "examples": [
              "Onkar 11"
            ]
          },
          "subinnerFolder": {
            "$id": "/properties/innerFolder/items/properties/subinnerFolder",
            "type": "array",
            "items": {
              "$id": "/properties/innerFolder/items/properties/subinnerFolder/items",
              "type": "object",
              "properties": {
                "parentfolderId": {
                  "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/parentfolderId",
                  "type": "null",
                  "title": "The Parentfolderid Schema.",
                  "description": "An explanation about the purpose of this instance.",
                  "default": null,
                  "examples": [
                    null
                  ]
                },
                "ismainFolder": {
                  "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/ismainFolder",
                  "type": "boolean",
                  "title": "The Ismainfolder Schema.",
                  "description": "An explanation about the purpose of this instance.",
                  "default": false,
                  "examples": [
                    false
                  ]
                },
                "foldername": {
                  "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/foldername",
                  "type": "string",
                  "title": "The Foldername Schema.",
                  "description": "An explanation about the purpose of this instance.",
                  "default": "",
                  "examples": [
                    "Onkar 11"
                  ]
                },
                "thirdSubFolder": {
                  "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder",
                  "type": "array",
                  "items": {
                    "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder/items",
                    "type": "object",
                    "properties": {
                      "parentfolderId": {
                        "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder/items/properties/parentfolderId",
                        "type": "null",
                        "title": "The Parentfolderid Schema.",
                        "description": "An explanation about the purpose of this instance.",
                        "default": null,
                        "examples": [
                          null
                        ]
                      },
                      "ismainFolder": {
                        "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder/items/properties/ismainFolder",
                        "type": "boolean",
                        "title": "The Ismainfolder Schema.",
                        "description": "An explanation about the purpose of this instance.",
                        "default": false,
                        "examples": [
                          false
                        ]
                      },
                      "foldername": {
                        "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder/items/properties/foldername",
                        "type": "string",
                        "title": "The Foldername Schema.",
                        "description": "An explanation about the purpose of this instance.",
                        "default": "",
                        "examples": [
                          "Onkar 11"
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Body:
{
    "_id" : ObjectId("5a0e77f4b7368f14c088f542"),
    "folderName" : "team 4",
    "tag" : "search",
    "ismainFolder" : true,
    "innerFolder" : [
                    {
                       parentfolderId" : null,
                      "ismainFolder" : false,
                      "foldername" : "Onkar 11"
                        "subinnerFolder" : [
                                        {
                                            "parentfolderId" : null,
                                            "ismainFolder" : false,
                                            "foldername" : "Onkar 11"
                                            "thirdSubFolder" : [
                                                        {
                                                            "parentfolderId" : null,
                                                            "ismainFolder" : false,
                                                           "foldername" : "Onkar 11"
                                                        },
                                                        {
                                                             "parentfolderId" : null,
                                                             "ismainFolder" : false,
                                                             "foldername" : "Onkar 11"
                                                        }
                                                    ]
                                        },

                                   ]
                    },
                ]
}

I need to create the mongodb schema for below json format so that innerFolder, subinnerFolder, etc (inner folder structure goes nested) so please help me in this ?

Body:
Below is a json schema generated by https://jsonschema.net/#/. You can edit it as required. For Mongoose schema, take a look at https://github.com/topliceanu/mongoose-gen

{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://example.com/example.json",
  "type": "object",
  "properties": {
    "folderName": {
      "$id": "/properties/folderName",
      "type": "string",
      "title": "The Foldername Schema.",
      "description": "An explanation about the purpose of this instance.",
      "default": "",
      "examples": [
        "team 4"
      ]
    },
    "tag": {
      "$id": "/properties/tag",
      "type": "string",
      "title": "The Tag Schema.",
      "description": "An explanation about the purpose of this instance.",
      "default": "",
      "examples": [
        "search"
      ]
    },
    "ismainFolder": {
      "$id": "/properties/ismainFolder",
      "type": "boolean",
      "title": "The Ismainfolder Schema.",
      "description": "An explanation about the purpose of this instance.",
      "default": false,
      "examples": [
        true
      ]
    },
    "innerFolder": {
      "$id": "/properties/innerFolder",
      "type": "array",
      "items": {
        "$id": "/properties/innerFolder/items",
        "type": "object",
        "properties": {
          "parentfolderId": {
            "$id": "/properties/innerFolder/items/properties/parentfolderId",
            "type": "null",
            "title": "The Parentfolderid Schema.",
            "description": "An explanation about the purpose of this instance.",
            "default": null,
            "examples": [
              null
            ]
          },
          "ismainFolder": {
            "$id": "/properties/innerFolder/items/properties/ismainFolder",
            "type": "boolean",
            "title": "The Ismainfolder Schema.",
            "description": "An explanation about the purpose of this instance.",
            "default": false,
            "examples": [
              false
            ]
          },
          "foldername": {
            "$id": "/properties/innerFolder/items/properties/foldername",
            "type": "string",
            "title": "The Foldername Schema.",
            "description": "An explanation about the purpose of this instance.",
            "default": "",
            "examples": [
              "Onkar 11"
            ]
          },
          "subinnerFolder": {
            "$id": "/properties/innerFolder/items/properties/subinnerFolder",
            "type": "array",
            "items": {
              "$id": "/properties/innerFolder/items/properties/subinnerFolder/items",
              "type": "object",
              "properties": {
                "parentfolderId": {
                  "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/parentfolderId",
                  "type": "null",
                  "title": "The Parentfolderid Schema.",
                  "description": "An explanation about the purpose of this instance.",
                  "default": null,
                  "examples": [
                    null
                  ]
                },
                "ismainFolder": {
                  "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/ismainFolder",
                  "type": "boolean",
                  "title": "The Ismainfolder Schema.",
                  "description": "An explanation about the purpose of this instance.",
                  "default": false,
                  "examples": [
                    false
                  ]
                },
                "foldername": {
                  "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/foldername",
                  "type": "string",
                  "title": "The Foldername Schema.",
                  "description": "An explanation about the purpose of this instance.",
                  "default": "",
                  "examples": [
                    "Onkar 11"
                  ]
                },
                "thirdSubFolder": {
                  "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder",
                  "type": "array",
                  "items": {
                    "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder/items",
                    "type": "object",
                    "properties": {
                      "parentfolderId": {
                        "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder/items/properties/parentfolderId",
                        "type": "null",
                        "title": "The Parentfolderid Schema.",
                        "description": "An explanation about the purpose of this instance.",
                        "default": null,
                        "examples": [
                          null
                        ]
                      },
                      "ismainFolder": {
                        "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder/items/properties/ismainFolder",
                        "type": "boolean",
                        "title": "The Ismainfolder Schema.",
                        "description": "An explanation about the purpose of this instance.",
                        "default": false,
                        "examples": [
                          false
                        ]
                      },
                      "foldername": {
                        "$id": "/properties/innerFolder/items/properties/subinnerFolder/items/properties/thirdSubFolder/items/properties/foldername",
                        "type": "string",
                        "title": "The Foldername Schema.",
                        "description": "An explanation about the purpose of this instance.",
                        "default": "",
                        "examples": [
                          "Onkar 11"
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}


问:
PyQt5 - How to add a scrollbar to a QMessageBox
I have a list which is generated based on user-input.

I am trying to display this list in a QMessageBox. But, I have no way of knowing the length of this list. The list could be long.

Thus, I need to add a scrollbar to the QMessageBox.

Interestingly, I looked everywhere, but I haven’t found any solutions for this.

Below is, what I hope to be a “Minimal, Complete and Verifiable Example”, of course without the user input; I just created a list as an example.

I appreciate any advice.

```<code>import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class W(QWidget):

   def __init__(self):
      super().__init__()

      self.initUi()

   def initUi(self):
      self.btn = QPushButton('Show Message', self)
      self.btn.setGeometry(10, 10, 100, 100)
      self.btn.clicked.connect(self.buttonClicked)
      self.lst = list(range(2000))
      self.show()

   def buttonClicked(self):
      result = QMessageBox(self)
      result.setText('%s' % self.lst)
      result.exec_()

if __name__ == "__main__":
   app = QApplication(sys.argv)
   gui = W()
   sys.exit(app.exec_())
</code>```

答:
You can not add a scrollbar directly since the widget in charge of displaying the text is a QLabel. The solution is to add a QScrollArea. The size may be inadequate so a stylesheet has to be used to set minimum values.

```<code>class ScrollMessageBox(QMessageBox):
   def __init__(self, l, *args, **kwargs):
      QMessageBox.__init__(self, *args, **kwargs)
      scroll = QScrollArea(self)
      scroll.setWidgetResizable(True)
      self.content = QWidget()
      scroll.setWidget(self.content)
      lay = QVBoxLayout(self.content)
      for item in l:
         lay.addWidget(QLabel(item, self))
      self.layout().addWidget(scroll, 0, 0, 1, self.layout().columnCount())
      self.setStyleSheet("QScrollArea{min-width:300 px; min-height: 400px}")

class W(QWidget):
   def __init__(self):
      super().__init__()
      self.btn = QPushButton('Show Message', self)
      self.btn.setGeometry(10, 10, 100, 100)
      self.btn.clicked.connect(self.buttonClicked)
      self.lst = [str(i) for i in range(2000)]
      self.show()

   def buttonClicked(self):
      result = ScrollMessageBox(self.lst, None)
      result.exec_()

if __name__ == "__main__":
   app = QApplication(sys.argv)
   gui = W()
   sys.exit(app.exec_())
</code>```

Output:

Body:
I have a list which is generated based on user-input.

I am trying to display this list in a QMessageBox. But, I have no way of knowing the length of this list. The list could be long.

Thus, I need to add a scrollbar to the QMessageBox.

Interestingly, I looked everywhere, but I haven’t found any solutions for this.

Below is, what I hope to be a “Minimal, Complete and Verifiable Example”, of course without the user input; I just created a list as an example.

I appreciate any advice.

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class W(QWidget):

   def __init__(self):
      super().__init__()

      self.initUi()

   def initUi(self):
      self.btn = QPushButton('Show Message', self)
      self.btn.setGeometry(10, 10, 100, 100)
      self.btn.clicked.connect(self.buttonClicked)
      self.lst = list(range(2000))
      self.show()

   def buttonClicked(self):
      result = QMessageBox(self)
      result.setText('%s' % self.lst)
      result.exec_()

if __name__ == "__main__":
   app = QApplication(sys.argv)
   gui = W()
   sys.exit(app.exec_())

Body:
You can not add a scrollbar directly since the widget in charge of displaying the text is a QLabel. The solution is to add a QScrollArea. The size may be inadequate so a stylesheet has to be used to set minimum values.

class ScrollMessageBox(QMessageBox):
   def __init__(self, l, *args, **kwargs):
      QMessageBox.__init__(self, *args, **kwargs)
      scroll = QScrollArea(self)
      scroll.setWidgetResizable(True)
      self.content = QWidget()
      scroll.setWidget(self.content)
      lay = QVBoxLayout(self.content)
      for item in l:
         lay.addWidget(QLabel(item, self))
      self.layout().addWidget(scroll, 0, 0, 1, self.layout().columnCount())
      self.setStyleSheet("QScrollArea{min-width:300 px; min-height: 400px}")

class W(QWidget):
   def __init__(self):
      super().__init__()
      self.btn = QPushButton('Show Message', self)
      self.btn.setGeometry(10, 10, 100, 100)
      self.btn.clicked.connect(self.buttonClicked)
      self.lst = [str(i) for i in range(2000)]
      self.show()

   def buttonClicked(self):
      result = ScrollMessageBox(self.lst, None)
      result.exec_()

if __name__ == "__main__":
   app = QApplication(sys.argv)
   gui = W()
   sys.exit(app.exec_())

Output:

ContentLicense: CC BY-SA 4.0


问:
Data not inserting in database when submitted
I've set up a form to insert data into a database. It's connected to it fine and can display records with no issues. However, when I want to insert data I click the submit button it removes it from the form but doesn't insert it into the db. I've tried rewriting it about 3 times now using 2 different databases but just can't figure out where I'm going on.</p>

```<code><html>
<head>
</head>

<body>
<form action="input.php" meathod="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>

<?php
if( isset($_POST['submit'])){

//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);

if($conn){
        echo 'connected';
    }
    else {
        die('failed to connect');
    }

$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";

mysql_query($sql,$conn);

mysqli_close($conn);
};
?>
</body>
</html>
</code>```

答:
I think problem is here

```<code>mysql_query($sql,$conn);
</code>```

Replace with

```<code>mysqli_query($conn,$sql);
</code>```

Body:
I've set up a form to insert data into a database. It's connected to it fine and can display records with no issues. However, when I want to insert data I click the submit button it removes it from the form but doesn't insert it into the db. I've tried rewriting it about 3 times now using 2 different databases but just can't figure out where I'm going on.

<form action="input.php" meathod="post">
Username: <input type="text" name="username">

Password: <input type="text" name="password">

<input type="submit" name="submit">
</form>

<?php
if( isset($_POST['submit'])){

//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);

if($conn){
        echo 'connected';
    }
    else {
        die('failed to connect');
    }

$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";

mysql_query($sql,$conn);

mysqli_close($conn);
};
?>

Body:
I think problem is here

mysql_query($sql,$conn);

Replace with

mysqli_query($conn,$sql);


问:
Gridview, Update function affecting all rows instead of single row
For my programming class, I just started using GridView for a movie database table and now I am implementing a edit, update and delete function. I got the edit and update to work but the Update is giving me trouble.

When I click update all my rows are updated to the same thing (Example: I edit movie title and all rows are changed to the same movie title). I'm unsure if I got my labeling mixed up somewhere.

My Database Table:

Note: I am also the code I am using is an example from class and the one from class works but for some reason mine doesn't.

Below is my code sample.

```<code><asp:GridView runat="server" ID="MovieResults" Wrap="true" Visible="false" AutoGenerateColumns="false"
        OnRowEditing="btnSubmit_Click_one" OnRowUpdating="btnSubmit_update_record"
        DataKeyNames="MovieID" OnRowDeleting="btnSubmit_delete_record">
        <Columns>

            <asp:BoundField DataField="MovieTitle" HeaderText="Movie" />
            <asp:BoundField DataField="DateChecked" HeaderText="Date Checked" />
            <asp:BoundField DataField="CheckedOut" HeaderText="Checked Out" />
            <asp:BoundField DataField="MovieDescription" HeaderText="Description" />
            <asp:ImageField DataImageUrlField="ImageLocation" ControlStyle-Width="50"
                ControlStyle-Height = "50" HeaderText = "Movie Image" />
            <asp:CommandField ShowEditButton="true" ShowDeleteButton="true" />
        </Columns>
    </asp:GridView>
</code>```

cs file

```<code>public void btnSubmit_update_record(Object Src, GridViewUpdateEventArgs e)
    {
        get_connection();
        try
        {
            int id = int.Parse(MovieResults.DataKeys[e.RowIndex].Value.ToString());
            connection.Open();

            command = new SqlCommand("UPDATE content SET MovieTitle=@MovieTitle, MovieDescription=@MovieDescription WHERE TRUE", connection);

            //command.Parameters.AddWithValue("@MovieID",
                          //((TextBox)MovieResults.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString());
            command.Parameters.AddWithValue("@MovieTitle",
                ((TextBox)MovieResults.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString());
            command.Parameters.AddWithValue("@MovieDescription",
                ((TextBox)MovieResults.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());

            command.ExecuteNonQuery();
        }
        catch (Exception err)
        {
            // Handle an error by displaying the information.
            lblInfo.Text = "Error reading the database. ";
            lblInfo.Text += err.Message;
        }
        finally
        {
            // Either way, make sure the connection is properly closed.
            // (Even if the connection wasn't opened successfully,
            //  calling Close() won't cause an error.)
            connection.Close();
            lblInfo.Text += "<br /><b>Update was successfull</b> ";
            lblInfo.Text += connection.State.ToString();

        }
    }
</code>```

答:
You are missing some code in your RowUpdating event. You must databind the grid after an update or delete or edit operation else your grid will not show the correct data.

So, let us assume you have a method that gets the data for your gridview and it's called GetMoviesData(). Then, at the end of your btnSubmit_update_record method you will have to include following code.

```<code>MovieResults.EditIndex = -1;
MovieResults.DataSource = GetMoviesData();
MovieResults.DataBind();
</code>```

Body:
For my programming class, I just started using GridView for a movie database table and now I am implementing a edit, update and delete function. I got the edit and update to work but the Update is giving me trouble.

When I click update all my rows are updated to the same thing (Example: I edit movie title and all rows are changed to the same movie title). I'm unsure if I got my labeling mixed up somewhere.

My Database Table:

Note: I am also the code I am using is an example from class and the one from class works but for some reason mine doesn't.

Below is my code sample.

<asp:GridView runat="server" ID="MovieResults" Wrap="true" Visible="false" AutoGenerateColumns="false"
        OnRowEditing="btnSubmit_Click_one" OnRowUpdating="btnSubmit_update_record"
        DataKeyNames="MovieID" OnRowDeleting="btnSubmit_delete_record">
        <Columns>

            <asp:BoundField DataField="MovieTitle" HeaderText="Movie" />
            <asp:BoundField DataField="DateChecked" HeaderText="Date Checked" />
            <asp:BoundField DataField="CheckedOut" HeaderText="Checked Out" />
            <asp:BoundField DataField="MovieDescription" HeaderText="Description" />
            <asp:ImageField DataImageUrlField="ImageLocation" ControlStyle-Width="50"
                ControlStyle-Height = "50" HeaderText = "Movie Image" />
            <asp:CommandField ShowEditButton="true" ShowDeleteButton="true" />
        </Columns>
    </asp:GridView>

cs file

public void btnSubmit_update_record(Object Src, GridViewUpdateEventArgs e)
    {
        get_connection();
        try
        {
            int id = int.Parse(MovieResults.DataKeys[e.RowIndex].Value.ToString());
            connection.Open();

            command = new SqlCommand("UPDATE content SET MovieTitle=@MovieTitle, MovieDescription=@MovieDescription WHERE TRUE", connection);

            //command.Parameters.AddWithValue("@MovieID",
                          //((TextBox)MovieResults.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString());
            command.Parameters.AddWithValue("@MovieTitle",
                ((TextBox)MovieResults.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString());
            command.Parameters.AddWithValue("@MovieDescription",
                ((TextBox)MovieResults.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());

            command.ExecuteNonQuery();
        }
        catch (Exception err)
        {
            // Handle an error by displaying the information.
            lblInfo.Text = "Error reading the database. ";
            lblInfo.Text += err.Message;
        }
        finally
        {
            // Either way, make sure the connection is properly closed.
            // (Even if the connection wasn't opened successfully,
            //  calling Close() won't cause an error.)
            connection.Close();
            lblInfo.Text += "
Update was successfull ";
            lblInfo.Text += connection.State.ToString();

        }
    }

Body:
You are missing some code in your RowUpdating event. You must databind the grid after an update or delete or edit operation else your grid will not show the correct data.

So, let us assume you have a method that gets the data for your gridview and it's called GetMoviesData(). Then, at the end of your btnSubmit_update_record method you will have to include following code.

MovieResults.EditIndex = -1;
MovieResults.DataSource = GetMoviesData();
MovieResults.DataBind();


问:
add class img-responsive to all attached post images in wordpress
i want to add class=img-reponsive & img-shadow to all the attached post thumbnail
i used following function which works fine but it removes the original classes of thubmails

```<code>function add_responsive_class($content){

        $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
        $document = new DOMDocument();
        libxml_use_internal_errors(true);
        $document->loadHTML(utf8_decode($content));

        $imgs = $document->getElementsByTagName('img');
        foreach ($imgs as $img) {
           $img->setAttribute('class','img-responsive img-shadow');
        }

        $html = $document->saveHTML();
        return $html;
}
</code>```

But i want to merge my classes not just overwrite them
So i used jquery

```<code> jQuery(function() {
jQuery(img).addClass('img-responsive img-shadow ');
});
</code>```

But its giving error jquery not defined

Please help me out

答: If you are using the DOMDocument method mentioned above, this can cause issues with utf encoding, especially when using special characters through your content editor, for example: £ being convered to ? or other strange characters. You can loop through $img and then use str_replace on $content, but using "terminators" method worked far better for me.</p>

Body:
i want to add class=img-reponsive & img-shadow to all the attached post thumbnail
i used following function which works fine but it removes the original classes of thubmails

function add_responsive_class($content){

        $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
        $document = new DOMDocument();
        libxml_use_internal_errors(true);
        $document->loadHTML(utf8_decode($content));

        $imgs = $document->getElementsByTagName('img');
        foreach ($imgs as $img) {
           $img->setAttribute('class','img-responsive img-shadow');
        }

        $html = $document->saveHTML();
        return $html;
}

But i want to merge my classes not just overwrite them
So i used jquery

 jQuery(function() {
jQuery(img).addClass('img-responsive img-shadow ');
});

But its giving error jquery not defined

Please help me out


问:
Is there a way to jump pages with a tweepy cursor?
I'm trying to get followers from a big account using tweepy.
When the job was half done, something gone wrong and I had to start again.

I'd like to know if there is a way to jump directly to page X and avoid reiterating all the pages?

答:
I found a way to do this though I am not sure it is the optimal one. If you use tweepy.Cursor class to get followers, you can first define a cursor instance:

```<code>my_cursor = tweepy.Cursor(api.followers, count=200)
</code>```

Then launch the streaming by looping on:

```<code>my_cursor.items()
</code>```

You can access the current page cursor value at any moment by doing:

```<code>my_cursor.next_cursor
</code>```

If you want to restart from approximately the same point where streaming stopped, just do:

```<code>my_new_cursor = tweepy.Cursor(api.followers, count=200,
                              cursor=my_cursor.next_cursor)
</code>```

Body:
I found a way to do this though I am not sure it is the optimal one. If you use tweepy.Cursor class to get followers, you can first define a cursor instance:

my_cursor = tweepy.Cursor(api.followers, count=200)

Then launch the streaming by looping on:

my_cursor.items()

You can access the current page cursor value at any moment by doing:

my_cursor.next_cursor

If you want to restart from approximately the same point where streaming stopped, just do:

my_new_cursor = tweepy.Cursor(api.followers, count=200,
                              cursor=my_cursor.next_cursor)


问:
How to build a C++ make project using specific LDFLAGS (Mac OSX)
I have a project that needs to be built using cmake and make. However, I want the project to use libc++ (since its written in C++11) so I need to set the right linker flags. Is there a way I can pass the following flags via command line?

```<code> LDFLAGS="-L/usr/local/opt/llvm/lib -Wl,-rpath,/usr/local/opt/llvm/lib"
</code>```

Or do I need to edit my CMakeLists.txt file? If so how can I add this to the file?

答:
For the more complex linker flags use

```<code>set (CMAKE_SHARED_LINKER_FLAGS -Wl,-rpath,/usr/local/opt/llvm/lib)
</code>```

To add a library search directory (-L) simply add

```<code>link_directories(/usr/local/opt/llvm/lib)
</code>```

See also this and that answer

Body:
I have a project that needs to be built using cmake and make. However, I want the project to use libc++ (since its written in C++11) so I need to set the right linker flags. Is there a way I can pass the following flags via command line?

 LDFLAGS="-L/usr/local/opt/llvm/lib -Wl,-rpath,/usr/local/opt/llvm/lib"

Or do I need to edit my CMakeLists.txt file? If so how can I add this to the file?

Body:
For the more complex linker flags use

set (CMAKE_SHARED_LINKER_FLAGS -Wl,-rpath,/usr/local/opt/llvm/lib)

To add a library search directory (-L) simply add

link_directories(/usr/local/opt/llvm/lib)

See also this and that answer


问:
UIActionSheet Customization

Can we change the order in which the destructive button and Other buttons appear in an UIActionSheet. By default the destructive button (red colored) appears above other buttons, in my app I would like the other buttons to appear above the destructive button.

答:
You can make any button in the UIActionSheet as destruction button by using the UIActionSheet property destructiveButtonIndex like,</p>

```<code>actionSheet.destructiveButtonIndex = 1;
</code>```

ContentLicense: CC BY-SA 2.5

Title: UIActionSheet Customization

Body:
You can make any button in the UIActionSheet as destruction button by using the UIActionSheet property destructiveButtonIndex like,

actionSheet.destructiveButtonIndex = 1;


答:
You have few typos "meathod=post" should be method="post",mysql_query($sql,$conn) should be mysqli_query($conn,$sql) and mysqli_select_db("test",$conn) should be mysqli_select_db($conn,"test")

```<code> <html>
    <head>
    </head>
    <body>
    <form action="input.php" method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="text" name="password"><br>
    <input type="submit" name="submit">
    </form>
    <?php
    if( isset($_POST['submit'])){
    //connecting to a databse
    $conn = mysqli_connect("localhost","root","");
    mysqli_select_db($conn,"test");
    if($conn){
            echo 'connected';
        }
        else {
            die('failed to connect');
        }
    $sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
    mysqli_query($conn,$sql);
    mysqli_close($conn);
    };
    ?>
    </body>
    </html>
</code>```

Title: Data not inserting in database when submitted

Body:
You have few typos "meathod=post" should be method="post",mysql_query($sql,$conn) should be mysqli_query($conn,$sql) and mysqli_select_db("test",$conn) should be mysqli_select_db($conn,"test")

 <html>
    <head>
    </head>
    <body>
    <form action="input.php" method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="text" name="password"><br>
    <input type="submit" name="submit">
    </form>
    <?php
    if( isset($_POST['submit'])){
    //connecting to a databse
    $conn = mysqli_connect("localhost","root","");
    mysqli_select_db($conn,"test");
    if($conn){
            echo 'connected';
        }
        else {
            die('failed to connect');
        }
    $sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
    mysqli_query($conn,$sql);
    mysqli_close($conn);
    };
    ?>
    </body>
    </html>


问:
Adding Foreign keys from multiple tables, how to ensure sequence
So this is basically my current task.

2 Tables have received a certain number of auto-generated data.

```<code>Table_1 id number, identitynumber number, name varchar2, sex varchar2, birthday date;

Table_2 id number, identification number, manufacturer varchar2, typ varchar2;
</code>```

The ID values on both tables are the primary keys of each table. Now I gotta insert the data from these 2 tables into a 3rd table, that'll use these ids as foreign keys. This table should also receive some auto-generated data.

```<code>Table_3 id number, plate varchar2, id_table1 number, id_table2 number, from date, until date;
</code>```

I planned on using a insert with a select to query the required data:

```<code>insert into table_3 (id, plate, id_table1, id_table2, from, until)
   select function_randomID as id,
      generate_randomPlate as plate,
      (select t1.id
      from table_1) as id_table1,
      (select t2.od
      from table_2) as id_table2,
      generate_date as from,
      gemerate_date as until
   from dual;
</code>```

Now, I know the selects for both IDs are incorrect, and this is precisely the question.

I don't know what condition I need to put into those selects, in order to get a single row and add that into the third table.

Sorry if I didn't ask it in a more succinct way. Hopefully it's clear enough now to be understood.

答:
Now I gotta insert the data from these 2 tables into a 3rd table,
  that'll use these ids as foreign keys. This table should also receive
  some auto-generated data.

Assuming you autogenerated number are coming from a function, you can try this:

```<code>INSERT INTO table_3 (id,
                     plate,
                     id_table1,
                     id_table2,
                     fm,--From is a reserve keyword
                     until)
   SELECT function_randomID AS id,
          generate_randomPlate AS plate,
          tb1.id,
          tb2.id,
          generate_date AS fm,
          gemerate_date AS untl
     FROM table_1 tb1
    CROSS JOIN table_2 tb2 ;
   --ON tb1.id = tb2.id;
</code>```

Body:
So this is basically my current task.

2 Tables have received a certain number of auto-generated data.

Table_1 id number, identitynumber number, name varchar2, sex varchar2, birthday date;

Table_2 id number, identification number, manufacturer varchar2, typ varchar2;

The ID values on both tables are the primary keys of each table. Now I gotta insert the data from these 2 tables into a 3rd table, that'll use these ids as foreign keys. This table should also receive some auto-generated data.

Table_3 id number, plate varchar2, id_table1 number, id_table2 number, from date, until date;

I planned on using a insert with a select to query the required data:

insert into table_3 (id, plate, id_table1, id_table2, from, until)
   select function_randomID as id,
      generate_randomPlate as plate,
      (select t1.id
      from table_1) as id_table1,
      (select t2.od
      from table_2) as id_table2,
      generate_date as from,
      gemerate_date as until
   from dual;

Now, I know the selects for both IDs are incorrect, and this is precisely the question.

I don't know what condition I need to put into those selects, in order to get a single row and add that into the third table.

Sorry if I didn't ask it in a more succinct way. Hopefully it's clear enough now to be understood.

Body:
Now I gotta insert the data from these 2 tables into a 3rd table,
  that'll use these ids as foreign keys. This table should also receive
  some auto-generated data.

Assuming you autogenerated number are coming from a function, you can try this:

INSERT INTO table_3 (id,
                     plate,
                     id_table1,
                     id_table2,
                     fm,--From is a reserve keyword
                     until)
   SELECT function_randomID AS id,
          generate_randomPlate AS plate,
          tb1.id,
          tb2.id,
          generate_date AS fm,
          gemerate_date AS untl
     FROM table_1 tb1
    CROSS JOIN table_2 tb2 ;
   --ON tb1.id = tb2.id;


问:
React + Firebase deploy needs a cache clear
I just deployed a very basic react application that I created using create-react-app and then I built the app and deployed it through the Firebase CLI. When I changed something in the app and then built and deployed it again, I couldn't see the changes on the website when I refreshed the page. After some troubleshooting I figured out that this a cache issue and the browser just uses the older version of the file instead of reloading the new one. Which made sense because when I cleared the cache (or opened the window in incognito mode) I saw the changes I made.

My question is how would this work in a real world application? You can't expect or depend on the users to clear their cache.

答: This question has been answered here Firebase Hosting: cache busting scripts on deploy You need to set the cache headers in firebase.json</p>


问:
Center the login form in the middle of the screen with bootstrap
I am trying to get my login form in the middle of the screen and the company logo on the right above.

In the picture this is what I want to make in bootstrap.

This is my HTML code:

```<code><div class="row">
    <div class="col-sm-3">
        .col-sm-3
    </div>

    <div class="col-sm-6">
        <div class="panel panel-info">
            <div class="panel-heading">
                <div class="panel-title">
                    Sign In
                </div>
                <div class="forgot-password">
                    <a href="#">Forgot password?</a>
                </div>
            </div>
            <div class="panel-body body-panel-styling">
                <form class="form-horizontal" id="loginform"></form>
            </div>
        </div>
    </div>

    <div class="col-sm-3">
        <img alt="Cerrix" class="img-responsive" src="~/Images/Cerrix-Logo.gif">
    </div>
</div>
</code>```

I already try this website but no luck

https://css-tricks.com/centering-css-complete-guide/

How can I center the login form in the middle of the screen and the company logo on the right above side of the screen?

Kind regards

UPDATE: jsfiddle

https://jsfiddle.net/fok6f2fc/

答:
use flexbox to align the login form to the center of the parent container:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

you'll need to extend the height of the your parent div
 for the centered field to work. assuming you want this container to fill the whole page, you can use viewport units to achieve it:

https://www.sitepoint.com/css-viewport-units-quick-start/

Body:
I am trying to get my login form in the middle of the screen and the company logo on the right above.

In the picture this is what I want to make in bootstrap.

This is my HTML code:

        .col-sm-3

                    Sign In

                    Forgot password?

                <form class="form-horizontal" id="loginform"></form>

I already try this website but no luck

https://css-tricks.com/centering-css-complete-guide/

How can I center the login form in the middle of the screen and the company logo on the right above side of the screen?

Kind regards

UPDATE: jsfiddle

https://jsfiddle.net/fok6f2fc/

Body:
use flexbox to align the login form to the center of the parent container:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

you'll need to extend the height of the your parent div <div class="row"> for the centered field to work. assuming you want this container to fill the whole page, you can use viewport units to achieve it:

https://www.sitepoint.com/css-viewport-units-quick-start/