问:
Python cPickle from a db field TypeError
In my project i save a list as a cPickle object in a byte field of my postgresql db like this:

```<code>my_list = list(self.outhtml)
bitRst = cPickle.dumps(my_list)
cur.execute("INSERT INTO frontend_t_test (test_id, test_data, test_creation, ip_addr) VALUES (%s, %s, %s, %s)",
                    (str(id(self)),
                     psycopg2.Binary(bitRst), dt, test_utils.return_ip()))
</code>```

All done, when i try to retrive my list i do:

```<code>cur = myconn.cursor()

cur.execute("""SELECT test_data FROM frontend_t_test WHERE test_id = %s""",(idTest,))
res = cur.fetchall()
with open(res, 'rb') as f:
    mynewlist = cPickle.load(f)
</code>```

but instead of the original list i get this error:

Traceback (most recent call last):
    File "", line 1, in
      with open(res, 'rb') as f:
  TypeError: coercing to Unicode: need string or buffer, list found

How can i retreive my pickled list from db?

Thanks in advance

答:
You don't need to "open" data returned from cursor. Just use the data and call loads.

```<code>cur.execute("""SELECT test_data FROM frontend_t_test WHERE test_id = %s""",(idTest,))
res = cur.fetchone()
data = str(res[0])  # buffer => str
mynewlist = cPickle.loads(data)
</code>```

Body:
In my project i save a list as a cPickle object in a byte field of my postgresql db like this:

my_list = list(self.outhtml)
bitRst = cPickle.dumps(my_list)
cur.execute("INSERT INTO frontend_t_test (test_id, test_data, test_creation, ip_addr) VALUES (%s, %s, %s, %s)",
                    (str(id(self)),
                     psycopg2.Binary(bitRst), dt, test_utils.return_ip()))

All done, when i try to retrive my list i do:

cur = myconn.cursor()

cur.execute("""SELECT test_data FROM frontend_t_test WHERE test_id = %s""",(idTest,))
res = cur.fetchall()
with open(res, 'rb') as f:
    mynewlist = cPickle.load(f)

but instead of the original list i get this error:

Traceback (most recent call last):
    File "", line 1, in
      with open(res, 'rb') as f:
  TypeError: coercing to Unicode: need string or buffer, list found

How can i retreive my pickled list from db?

Thanks in advance

Body:
You don't need to "open" data returned from cursor. Just use the data and call loads.

cur.execute("""SELECT test_data FROM frontend_t_test WHERE test_id = %s""",(idTest,))
res = cur.fetchone()
data = str(res[0])  # buffer => str
mynewlist = cPickle.loads(data)


来源: stackexchange

问:
jQuery form submit handler doesn't trigger when textField changes by Watin in MVC Asp.net app
I am writing Watin test in MVC Asp.net app. I mvc app, all input are wrpped with form and every time an input or textarea is changed their form gets submitted by jquery like code below:

```<code>$("textarea", context).change(function() {
      $(this).parents('form:first').submit();
  });
</code>```

This is perfect when changes are done by keyboard. However this doesn't trigger the form submit when input/textarea are changed by Watin TypeText() method. I tried to call Change() and Blur() events by Watin and also tried PressTab() with no luck.

Any help would be appreciated.

Regards

Behnam Divsalar

答:
I also encountered this bug in WatiN with the "onchange" event. A workaround is to trigger the event yourself.</p>

```<code>Browser.Eval("$('textarea').change()");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am writing Watin test in MVC Asp.net app. I mvc app, all input are wrpped with form and every time an input or textarea is changed their form gets submitted by jquery like code below:

$("textarea", context).change(function() {
      $(this).parents('form:first').submit();
  });

This is perfect when changes are done by keyboard. However this doesn't trigger the form submit when input/textarea are changed by Watin TypeText() method. I tried to call Change() and Blur() events by Watin and also tried PressTab() with no luck.

Any help would be appreciated.

Regards

Behnam Divsalar

Body:
I also encountered this bug in WatiN with the "onchange" event. A workaround is to trigger the event yourself.

Browser.Eval("$('textarea').change()");


问:
Persistent Menu and Get Started Button Microsoft Bot Framework
I'm getting to the end of the development process of my bot. I'm currently doing it in C# and the end goal of it is to be deployed on messenger. However I've run into a snag when trying to implement a "Get Started" button and a persistent menu.

The following code was from facebook's dev portal on how to add a persistent menu and I have found similar code for a Get Started button, however, starting my code up in VS Code and pasting this into a terminal, I get an error back complaining about compatibility.

Does Microsoft's bot framework automatically put this in when deploying to the messenger channel or is this code not compatible with C# ?

Thanks

```<code>  curl -X POST -H "Content-Type: application/json" -d '{
      "persistent_menu":[
        {
          "locale":"default",
          "composer_input_disabled":true,
          "call_to_actions":[
            {
              "title":"My Account",
              "type":"nested",
              "call_to_actions":[
                {
                  "title":"Pay Bill",
                  "type":"postback",
                  "payload":"PAYBILL_PAYLOAD"
                },
                {
                  "title":"History",
                  "type":"postback",
                  "payload":"HISTORY_PAYLOAD"
                },
                {
                  "title":"Contact Info",
                  "type":"postback",
                  "payload":"CONTACT_INFO_PAYLOAD"
                }
              ]
            },
            {
              "type":"web_url",
              "title":"Latest News",
              "url":"http://petershats.parseapp.com/hat-news",
              "webview_height_ratio":"full"
            }
          ]
        },
        {
          "locale":"zh_CN",
          "composer_input_disabled":false
        }
      ]
    }' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=YOUR_ACCESS_TOKEN_HERE"
</code>```

答:
Creating "persistent menu" and "Get Started button" is specific to Facebook Messenger channel: it is not done through the Bot Framework but they are interesting tools to use in bot framework once they are set up.

This setup must be made with your Facebook development account. All you will have to do after is to handle in your bot code the specific payloads corresponding to your menu or your Get Started action.

So to create your menu and get started button, use your favorite API request tool (in your sample it's made for cURL) to call Facebook's API to setup those items. It has nothing to do with C# or Bot Framework, so nothing is made automatically by the framework.

If you got problems during those calls, please be more explicit about the errors you got.

ContentLicense: CC BY-SA 3.0

Body:
I'm getting to the end of the development process of my bot. I'm currently doing it in C# and the end goal of it is to be deployed on messenger. However I've run into a snag when trying to implement a "Get Started" button and a persistent menu.

The following code was from facebook's dev portal on how to add a persistent menu and I have found similar code for a Get Started button, however, starting my code up in VS Code and pasting this into a terminal, I get an error back complaining about compatibility.

Does Microsoft's bot framework automatically put this in when deploying to the messenger channel or is this code not compatible with C# ?

Thanks

  curl -X POST -H "Content-Type: application/json" -d '{
      "persistent_menu":[
        {
          "locale":"default",
          "composer_input_disabled":true,
          "call_to_actions":[
            {
              "title":"My Account",
              "type":"nested",
              "call_to_actions":[
                {
                  "title":"Pay Bill",
                  "type":"postback",
                  "payload":"PAYBILL_PAYLOAD"
                },
                {
                  "title":"History",
                  "type":"postback",
                  "payload":"HISTORY_PAYLOAD"
                },
                {
                  "title":"Contact Info",
                  "type":"postback",
                  "payload":"CONTACT_INFO_PAYLOAD"
                }
              ]
            },
            {
              "type":"web_url",
              "title":"Latest News",
              "url":"http://petershats.parseapp.com/hat-news",
              "webview_height_ratio":"full"
            }
          ]
        },
        {
          "locale":"zh_CN",
          "composer_input_disabled":false
        }
      ]
    }' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=YOUR_ACCESS_TOKEN_HERE"


问:
Use ssh credentials in jenkins pipeline with ssh, scp or sftp
I want to use scp/ssh to upload some files to a server. I discover that I need to use certificate-based authentication, but the question is how? Really what I want to do is to use the same sort of credentials I use with git - passworded ssh cert stored in Jenkins. However, I can't work out how to - the snippet generator has no obvious option for that.

What do others do? Is there an undocumented feature that would do this?

答: If you install the SSH Agent plugin you can use the ssh-agent pipeline step to run a shell script with an ssh-agent active. The ssh-agent takes a Jenkins credentials ID (a passworded ssh cert, like the one you have for git).


问:
MapStruct : Dealing with HashMap entries as source
Here is my source object:

```<code>public class Record {

    public final long captureTime;
    public final String environnement;
    public final String bundle;
    public final String type;
    public final String id;
    public final Map<String,Object> meta;

}
</code>```

Here is my destination object:

```<code>public class MappedRecord {

    public final long captureTime;
    public final String environnement;
    public final String bundle;
    public final String type;
    public final String id;
    public final String ip;
    public final String server;

}
</code>```

And my mapper looks like the following:

```<code>public interface RecordMapper {

    RecordMapper MAPPER = Mappers.getMapper( RecordMapper.class );

    @Mappings({
        @Mapping(source = "captureTime", target = "captureTime"),
        @Mapping(source = "environnement", target = "environnement"),
        @Mapping(source = "bundle", target = "bundle"),
        @Mapping(source = "type", target = "type"),
        @Mapping(source = "id", target = "id"),
        @Mapping(expression = "java((String) r.meta.get(\"ip\"))", target = "ip"),
        @Mapping(expression = "java((String) r.meta.get(\"server\"))", target = "server"),
    })

    MappedRecord toMappedRecord(Record r);

}
</code>```

For now it works well but I would like to know if there is a more "elegant" way to set Map entries as source. Because with this I did not manage to add transformation functions using the "qualifiedByName" property, it looks like it can only work when a "source" is specified. Did I misunderstand something ?

I tried the following approaches without satisfying results :

Overwrite getter for specific fields in my Record class

Add a transformation function with the "qualifiedByName" property. Something like:

```<code>@Named("metaGetter")
default String dataGetter (String property) {
    return (String) r.meta.get(property);
}
</code>```

But obviously this does not compile as the property name is not valid as a proper source.

Thanks for your time.

答:
Write your own qualifier:

```<code>public class MappingUtil {
    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public @interface Ip {
    }
    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public static @interface Server {
    }
    @Ip
    public String ip(Map<String, Object> in) {

        return (String)in.get("ip");
    }
    @Server
    public String server(Map<String, Object> in) {

        return (String)in.get("server");
    }
}
</code>```

and then just add to the mapping:

```<code>@Mapper( uses = MappingUtil.class )
public interface SourceTargetMapper {

    SourceTargetMapper MAPPER = Mappers.getMapper( SourceTargetMapper.class );

    @Mappings( {
        @Mapping(source = "map", target = "ip", qualifiedBy = MappingUtil.Ip.class ),
        @Mapping(source = "map", target = "server", qualifiedBy = MappingUtil.Server.class ),
    } )
    Target toTarget( Source s );
}
</code>```

Body:
Here is my source object:

public class Record {

    public final long captureTime;
    public final String environnement;
    public final String bundle;
    public final String type;
    public final String id;
    public final Map<String,Object> meta;

}

Here is my destination object:

public class MappedRecord {

    public final long captureTime;
    public final String environnement;
    public final String bundle;
    public final String type;
    public final String id;
    public final String ip;
    public final String server;

}

And my mapper looks like the following:

public interface RecordMapper {

    RecordMapper MAPPER = Mappers.getMapper( RecordMapper.class );

    @Mappings({
        @Mapping(source = "captureTime", target = "captureTime"),
        @Mapping(source = "environnement", target = "environnement"),
        @Mapping(source = "bundle", target = "bundle"),
        @Mapping(source = "type", target = "type"),
        @Mapping(source = "id", target = "id"),
        @Mapping(expression = "java((String) r.meta.get(\"ip\"))", target = "ip"),
        @Mapping(expression = "java((String) r.meta.get(\"server\"))", target = "server"),
    })

    MappedRecord toMappedRecord(Record r);

}

For now it works well but I would like to know if there is a more "elegant" way to set Map entries as source. Because with this I did not manage to add transformation functions using the "qualifiedByName" property, it looks like it can only work when a "source" is specified. Did I misunderstand something ?

I tried the following approaches without satisfying results :

Overwrite getter for specific fields in my Record class

Add a transformation function with the "qualifiedByName" property. Something like:

@Named("metaGetter")
default String dataGetter (String property) {
    return (String) r.meta.get(property);
}

But obviously this does not compile as the property name is not valid as a proper source.

Thanks for your time.

Body:
Write your own qualifier:

public class MappingUtil {
    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public @interface Ip {
    }
    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public static @interface Server {
    }
    @Ip
    public String ip(Map<String, Object> in) {

        return (String)in.get("ip");
    }
    @Server
    public String server(Map<String, Object> in) {

        return (String)in.get("server");
    }
}

and then just add to the mapping:

@Mapper( uses = MappingUtil.class )
public interface SourceTargetMapper {

    SourceTargetMapper MAPPER = Mappers.getMapper( SourceTargetMapper.class );

    @Mappings( {
        @Mapping(source = "map", target = "ip", qualifiedBy = MappingUtil.Ip.class ),
        @Mapping(source = "map", target = "server", qualifiedBy = MappingUtil.Server.class ),
    } )
    Target toTarget( Source s );
}


问:
Android onTouch() method doesn't work (swipe detection)
I'm programming Snake on Android with Android Studio 2.3.2

And in order to move the snake i've made an onTouchListener to detect if the user is swiping and in which direction (North, South, East, West)

In the following is the onTouch method of View.onTouchListener:

```<code>@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            prevX = event.getX();
            prevY = event.getY();

            break;
        case MotionEvent.ACTION_UP:
            float newX = event.getX();
            float newY = event.getY();

            //Calculates where we swiped

            if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
                //LEFT - RiGHT Direction

                if( newX > prevX) {
                    //RIGHT
                    gameEngine.updateDirection(Direction.East);
                } else {
                    //LEFT
                    gameEngine.updateDirection(Direction.West);
                }
            } else {
                // UP-DOWN Direction
                if (newY > prevY) {
                    //DOWN
                    gameEngine.updateDirection(Direction.South);
                } else {
                    //UP
                    gameEngine.updateDirection(Direction.North);
                }
            }

            break;
    }
    return false;
}
</code>```

The problem is that it only detects LEFT and RIGHT (so EAST and WEST).
And i don't know why UP and DOWN doesn't get detected.

答:
You must return "True" after ACTION_DOWN. This tells Android to watch for the ACTION_UP event.</p>

```<code>switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        prevX = event.getX();
        prevY = event.getY();

        return true;
</code>```

Body:
I'm programming Snake on Android with Android Studio 2.3.2

And in order to move the snake i've made an onTouchListener to detect if the user is swiping and in which direction (North, South, East, West)

In the following is the onTouch method of View.onTouchListener:

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            prevX = event.getX();
            prevY = event.getY();

            break;
        case MotionEvent.ACTION_UP:
            float newX = event.getX();
            float newY = event.getY();

            //Calculates where we swiped

            if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
                //LEFT - RiGHT Direction

                if( newX > prevX) {
                    //RIGHT
                    gameEngine.updateDirection(Direction.East);
                } else {
                    //LEFT
                    gameEngine.updateDirection(Direction.West);
                }
            } else {
                // UP-DOWN Direction
                if (newY > prevY) {
                    //DOWN
                    gameEngine.updateDirection(Direction.South);
                } else {
                    //UP
                    gameEngine.updateDirection(Direction.North);
                }
            }

            break;
    }
    return false;
}

The problem is that it only detects LEFT and RIGHT (so EAST and WEST).
And i don't know why UP and DOWN doesn't get detected.

Body:
You must return "True" after ACTION_DOWN. This tells Android to watch for the ACTION_UP event.

switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        prevX = event.getX();
        prevY = event.getY();

        return true;


问:
npm request.post giving error everytime but the same post works with JQuery
I am trying to make a post request from express js to an api, from serverside.

Here is the code for it

```<code>request.post({
                url: $url,
                crossDomain: true,
                data: {id : '392', sid: 'abc'}
                }, function(error, response, body){
                    console.log(response.statusCode);
                    console.log(body);
            });
</code>```

this always returns with a response statusCode 500;

On the other hand, I tried the same post request from server side using Jquery.

Here is the code for it.

```<code>$.ajax({
    url: $url,
    crossDomain:true,
    data: {
        id : $id,
        sid: $sid
    },
    type: "POST",
    // dataType: "json",

    //on success
    success: function(response){
        //do something after something is received data
    },
    //on error
    error: function(jqXHR, exception){
        //bad request
        console.log(jqXHR.status);
        console.log(exception);
    }
});
</code>```

The $url and all the other variables are same in both the cases. Though, I get proper response and status code 200 for the post I do with Jquery, unlike the one I do with npm request module.

Where am I going wrong?

答:
request and $.ajax don't have the same options when being called. You can send the request body using the body property in the options object passed. Additionally, there is the convenience boolean json to add the Content-Type:application/json header to the request, serialize the request body as JSON and to automatically parse the response body as JSON.

```<code>const request = require('request')

request({
  url: $url,
  method: 'POST',
  body: {id: '392', sid: 'abc'},
  json: true
}, (err, res, body) => {
  if (err) {
    // handle error
    console.log(err)
    return
  }

  // handle response
  console.log(response)
})
</code>```

Body:
I am trying to make a post request from express js to an api, from serverside.

Here is the code for it

request.post({
                url: $url,
                crossDomain: true,
                data: {id : '392', sid: 'abc'}
                }, function(error, response, body){
                    console.log(response.statusCode);
                    console.log(body);
            });

this always returns with a response statusCode 500;

On the other hand, I tried the same post request from server side using Jquery.

Here is the code for it.

$.ajax({
    url: $url,
    crossDomain:true,
    data: {
        id : $id,
        sid: $sid
    },
    type: "POST",
    // dataType: "json",

    //on success
    success: function(response){
        //do something after something is received data
    },
    //on error
    error: function(jqXHR, exception){
        //bad request
        console.log(jqXHR.status);
        console.log(exception);
    }
});

The $url and all the other variables are same in both the cases. Though, I get proper response and status code 200 for the post I do with Jquery, unlike the one I do with npm request module.

Where am I going wrong?

Body:
request and $.ajax don't have the same options when being called. You can send the request body using the body property in the options object passed. Additionally, there is the convenience boolean json to add the Content-Type:application/json header to the request, serialize the request body as JSON and to automatically parse the response body as JSON.

const request = require('request')

request({
  url: $url,
  method: 'POST',
  body: {id: '392', sid: 'abc'},
  json: true
}, (err, res, body) => {
  if (err) {
    // handle error
    console.log(err)
    return
  }

  // handle response
  console.log(response)
})


问:
Why the restrictions on protocols with Self or associatedtype?
While designing APIs, I run into this at every corner:

Protocol can only be used as a generic constraint because it has Self or associatedType requirements

What that means is that you basically can not use Self or associatedtype on protocol level if you ever plan to use the protocol type on its own -- otherwise the need for types to be generic themselves cascades out of control.

This is rather annoying (read: makes it next to impossible to design reasonable APIs, e.g. such that expose protocols but hide implementations). For instance, you can not have a simple data container protocol:

```<code>protocol DataContainer: Equatable {
    var id: Int { get }
    var content: Data { get }
}
</code>```

The issue is that Equatable requires static function == which is, of course, expressed using Self. Therefore, you can not have a type like [DataContainer], or any number of other natural things. I first ran into it with groups (arrays) of users (which could be of one of three different types).

The "official" recommended "solution" is to have delegating/wrapper structs that eliminate the type variable, like AnyDataContainer. This feels like a rather silly, hacky workaround, not proper API design.

I honestly don't get why the type system has this restriction. What are the reason? Why can't the compiler implicitly create AnyP for every protocol P to work around it?

答:
Think of it like the documentation says A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.

So the protocol only says what is required to conform to it not how that is to be done.  The job of 'how' is left up to whatever conforms to the protocol itself.

This means:

1) You can't use a protocol on it's own as it has no implementation itself.

2) You cannot design an API that uses protocols to hide implementation.

Basically the protocol is saying to anything that implements it 'here is what you need to do but it's up to you how to do it'.

For an API maybe you would be better off using subclassing.

(Of course there may be ways to bend a protocol to do these kind of things but then you should really think if that's the best way to do it)

Edit:

You can use self within a protocol extension but you can't use it in the way you want.  I could add this to the protocol:

```<code>func doubleID() -> Int
</code>```

and then create an extension like this:

```<code>extension DataContainer {
    func doubleID() -> Int {
        return self.id * 2
    }
}
</code>```

So you can hide some implementation but then that is a default as whatever conforms to the protocol is free to define it's own method for doubleID.

Edit:

This will achieve what you are after though:

```<code>protocol TestProtocol: Equatable {
    var id: Int { get }
    var data: Data { get }
}

func ==<T: TestProtocol>(lhs: T, rhs: T) -> Bool {
     return lhs.id == rhs.id
}

func ==<T: TestProtocol, U: TestProtocol>(lhs: T, rhs: U) -> Bool {
    return lhs.id == rhs.id
}

func !=<T: TestProtocol, U: TestProtocol>(lhs: T, rhs: U) -> Bool {
    return lhs.id != rhs.id
}
</code>```

This will provide a default equality implementation for anything that conforms to the TestProtocol however it will not stop anything overriding with its own implementation.

Body:
While designing APIs, I run into this at every corner:

Protocol can only be used as a generic constraint because it has Self or associatedType requirements

What that means is that you basically can not use Self or associatedtype on protocol level if you ever plan to use the protocol type on its own -- otherwise the need for types to be generic themselves cascades out of control.

This is rather annoying (read: makes it next to impossible to design reasonable APIs, e.g. such that expose protocols but hide implementations). For instance, you can not have a simple data container protocol:

protocol DataContainer: Equatable {
    var id: Int { get }
    var content: Data { get }
}

The issue is that Equatable requires static function == which is, of course, expressed using Self. Therefore, you can not have a type like [DataContainer], or any number of other natural things. I first ran into it with groups (arrays) of users (which could be of one of three different types).

The "official" recommended "solution" is to have delegating/wrapper structs that eliminate the type variable, like AnyDataContainer. This feels like a rather silly, hacky workaround, not proper API design.

I honestly don't get why the type system has this restriction. What are the reason? Why can't the compiler implicitly create AnyP for every protocol P to work around it?

Body:
Think of it like the documentation says A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.

So the protocol only says what is required to conform to it not how that is to be done.  The job of 'how' is left up to whatever conforms to the protocol itself.

This means:

1) You can't use a protocol on it's own as it has no implementation itself.

2) You cannot design an API that uses protocols to hide implementation.

Basically the protocol is saying to anything that implements it 'here is what you need to do but it's up to you how to do it'.

For an API maybe you would be better off using subclassing.

(Of course there may be ways to bend a protocol to do these kind of things but then you should really think if that's the best way to do it)

Edit:

You can use self within a protocol extension but you can't use it in the way you want.  I could add this to the protocol:

func doubleID() -> Int

and then create an extension like this:

extension DataContainer {
    func doubleID() -> Int {
        return self.id * 2
    }
}

So you can hide some implementation but then that is a default as whatever conforms to the protocol is free to define it's own method for doubleID.

Edit:

This will achieve what you are after though:

protocol TestProtocol: Equatable {
    var id: Int { get }
    var data: Data { get }
}

func ==<T: TestProtocol>(lhs: T, rhs: T) -> Bool {
     return lhs.id == rhs.id
}

func ==<T: TestProtocol, U: TestProtocol>(lhs: T, rhs: U) -> Bool {
    return lhs.id == rhs.id
}

func !=<T: TestProtocol, U: TestProtocol>(lhs: T, rhs: U) -> Bool {
    return lhs.id != rhs.id
}

This will provide a default equality implementation for anything that conforms to the TestProtocol however it will not stop anything overriding with its own implementation.


问:
laravel eloquent count with a groupby
If I'd have the following table structure

```<code>ID      name   type
1       John   Admin
2       Johan  Admin
3       Sam    User
4       Rick   User
</code>```

How would I use Laravels Eloquent with a groupBy query, but still grab each record, and also sum up per type how many records each type has?

Example result would be as follow

```<code>[
    'type' => 'Admin',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'John'
        ],
        1 => [
            'name' => 'Johan'
        ]
    ]
],
[
    'type' => 'User',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'Sam'
        ],
        1 => [
            'name' => 'Rick'
        ]
    ]
]
</code>```

答:
I think the best way to achieve this is to have a table with types related through hasMany() to your data.

Then you can use standard Eloquent tools without restructuring the data manually:

```<code>$data = Type::with('users')->withCount('users')->get();
</code>```

Title: laravel eloquent count with a groupby

Body:
If I'd have the following table structure

ID      name   type
1       John   Admin
2       Johan  Admin
3       Sam    User
4       Rick   User

How would I use Laravels Eloquent with a groupBy query, but still grab each record, and also sum up per type how many records each type has?

Example result would be as follow

[
    'type' => 'Admin',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'John'
        ],
        1 => [
            'name' => 'Johan'
        ]
    ]
],
[
    'type' => 'User',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'Sam'
        ],
        1 => [
            'name' => 'Rick'
        ]
    ]
]

Body:
I think the best way to achieve this is to have a table with types related through hasMany() to your data.

Then you can use standard Eloquent tools without restructuring the data manually:

$data = Type::with('users')->withCount('users')->get();


问:
Strange issue adding strings together in Jython Sikulix
So I'm writing a program in Jython SikuliX to automatically make labels by taking a three letter input (MAG) and then adding a number to the end (1) and then increment the number by +1 for each label (MAG1 - MAG2 - MAG3 etc.)

However the trick here is that I need the combination of the letters and number to always be 6 characters in length (So MAG001 or MAG010 or MAG100).

I've already got the number concatenation down however I'm running into a strange issue with any number over 100. Going from label 9 to label 10 and above works perfectly (MAG009 - MAG010 - MAG011 and so on) however when I get to MAG99 and then go to MAG100 I receive an error:

```<code>[error] --- Traceback --- error source first line: module ( function )
statement 26: main ( name_change ) name = name
[error] --- Traceback --- end --------------
</code>```

I have no idea why this is... Code is below.

```<code>import time

name1 = str(input("First three letters of product name"))
labels = int(input("At what number do you want the labels to stop?"))

a = int(input("What number should the labels start at?"))
e = "00"
d = "0"

find("1496686601617.png")
doubleClick("1496686607803.png")

def name_change(name1, a):
    a = str(a)
    c = len("%s%s" % (name1, a))

    if c == 4:
        name = ("%s%s" % (name1, e))

    if c == 5:
        name = ("%s%s" % (name1, d))

    if c == 6:
        name = name

    a = int(a)
    return name

def label_make(name, a):
    click("1496688531026.png")
    type("0000")
    rightClick("1496688447045.png")
    click("Select_All.png")
    type("%s%r" % (name, a))
    click("1496686753618.png")
    click("Save As-1.png")
    time.sleep(1)
    type("%s%r" % (name, a))
    click("1496687258684.png")

    a = a + 1
    return a

while labels >= a:
    name = name_change(name1, a)
    a = label_make(name, a)
</code>```

Any help would be greatly appreciated.

答:
Nevermind, I solved my own issue:

I went back to an older version that didn't involve functions and specified the variable for name if it is already 6 characters long and it works. Code below:

```<code>import time

name1 = str(input("First three letters of product name"))
labels = int(input("At what number do you want the labels to stop?"))

a = int(input("What number should the labels start at?"))
e = "00"
d = "0"

find("1496686601617.png")
doubleClick("1496686607803.png")

while labels >= a:
    #a = str(a)
    c = len("%s%s" % (name1, a))

    if c == 4:
        name = ("%s%s" % (name1, e))

    if c == 5:
        name = ("%s%s" % (name1, d))

    if c == 6:
        name = name1

    #a = int(a)

    click("1496688531026.png")
    type("0000")
    rightClick("1496688447045.png")
    click("Select_All.png")
    type("%s%r" % (name, a))
    click("1496686753618.png")
    click("Save As-1.png")
    time.sleep(1)
    type("%s%r" % (name, a))
    click("1496687258684.png")
    #a = int(a)
    a = a + 1
</code>```

Body:
So I'm writing a program in Jython SikuliX to automatically make labels by taking a three letter input (MAG) and then adding a number to the end (1) and then increment the number by +1 for each label (MAG1 - MAG2 - MAG3 etc.)

However the trick here is that I need the combination of the letters and number to always be 6 characters in length (So MAG001 or MAG010 or MAG100).

I've already got the number concatenation down however I'm running into a strange issue with any number over 100. Going from label 9 to label 10 and above works perfectly (MAG009 - MAG010 - MAG011 and so on) however when I get to MAG99 and then go to MAG100 I receive an error:

[error] --- Traceback --- error source first line: module ( function )
statement 26: main ( name_change ) name = name
[error] --- Traceback --- end --------------

I have no idea why this is... Code is below.

import time

name1 = str(input("First three letters of product name"))
labels = int(input("At what number do you want the labels to stop?"))

a = int(input("What number should the labels start at?"))
e = "00"
d = "0"

find("1496686601617.png")
doubleClick("1496686607803.png")

def name_change(name1, a):
    a = str(a)
    c = len("%s%s" % (name1, a))

    if c == 4:
        name = ("%s%s" % (name1, e))

    if c == 5:
        name = ("%s%s" % (name1, d))

    if c == 6:
        name = name

    a = int(a)
    return name

def label_make(name, a):
    click("1496688531026.png")
    type("0000")
    rightClick("1496688447045.png")
    click("Select_All.png")
    type("%s%r" % (name, a))
    click("1496686753618.png")
    click("Save As-1.png")
    time.sleep(1)
    type("%s%r" % (name, a))
    click("1496687258684.png")

    a = a + 1
    return a

while labels >= a:
    name = name_change(name1, a)
    a = label_make(name, a)

Any help would be greatly appreciated.

Body:
Nevermind, I solved my own issue:

I went back to an older version that didn't involve functions and specified the variable for name if it is already 6 characters long and it works. Code below:

import time

name1 = str(input("First three letters of product name"))
labels = int(input("At what number do you want the labels to stop?"))

a = int(input("What number should the labels start at?"))
e = "00"
d = "0"

find("1496686601617.png")
doubleClick("1496686607803.png")

while labels >= a:
    #a = str(a)
    c = len("%s%s" % (name1, a))

    if c == 4:
        name = ("%s%s" % (name1, e))

    if c == 5:
        name = ("%s%s" % (name1, d))

    if c == 6:
        name = name1

    #a = int(a)

    click("1496688531026.png")
    type("0000")
    rightClick("1496688447045.png")
    click("Select_All.png")
    type("%s%r" % (name, a))
    click("1496686753618.png")
    click("Save As-1.png")
    time.sleep(1)
    type("%s%r" % (name, a))
    click("1496687258684.png")
    #a = int(a)
    a = a + 1


问:
Support multiple languages in custom keyboard extension
I want to change language english keyboard to arabic so when i choose arabic language from container app .
Alignment as well as cursor position should change in custom keyboard.

```<code><key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>IsASCIICapable</key>
        <false/>
        <key>PrefersRightToLeft</key>
        <false/>
        <key>PrimaryLanguage</key>
        <string>mul</string>
        <key>RequestsOpenAccess</key>
        <false/>
    </dict>
</code>```

If I change in primary language in info.plist to “ar” then its working fine but i want to change at run time so both languages will work.

Or Is there any way to change cursor position in uiinputviewcontroller in keyboard class.

I am also trying to change primary language key by localized string for both languages but its not pick the arabic language localized string file.

Arabic keyboard display textalignment as left to right so this one is the issue.:http://i.stack.imgur.com/RtvDQ.png

Any Suggestion for this.
Thanks.

答:
There is a property " primaryLanguage " of UIInputViewController which you can set runtime.
 e.g. Suppose in your keyboard extension project UIInputViewController subclass is KeyboardViewController then inside it set
 self.primaryLanguage = @"ar"</p>

Body:
I want to change language english keyboard to arabic so when i choose arabic language from container app .
Alignment as well as cursor position should change in custom keyboard.

<key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>IsASCIICapable</key>
        <false/>
        <key>PrefersRightToLeft</key>
        <false/>
        <key>PrimaryLanguage</key>
        <string>mul</string>
        <key>RequestsOpenAccess</key>
        <false/>
    </dict>

If I change in primary language in info.plist to “ar” then its working fine but i want to change at run time so both languages will work.

Or Is there any way to change cursor position in uiinputviewcontroller in keyboard class.

I am also trying to change primary language key by localized string for both languages but its not pick the arabic language localized string file.

Arabic keyboard display textalignment as left to right so this one is the issue.:http://i.stack.imgur.com/RtvDQ.png

Any Suggestion for this.
Thanks.


问:
I got Fatal error: Allowed memory size of 134217728 bytes exhausted when upload a file
I'm currently developping a PHP website and I need to store files in my database.
I'm using a LONGBLOB to store files such as PDF,PPTX,...
The file upload was working fine until i get this error :
Fatal error: Allowed memory size of 134217728 bytes exhausted

Here is my function :

```<code>public function uploadFile() {
    // We upload only pdf for now
    if (isset($_FILES['fichier']['name']) && $_FILES['fichier']['type']=="application/pdf"){
      $tmp_name = $_FILES['fichier']['tmp_name'];
      // Avoid problem with space
      $nom = str_replace(' ','_',$_FILES['fichier']['name']);
      $taille = $_FILES['fichier']['size'];
      $type = $_FILES['fichier']['type'];
      $fp = fopen($tmp_name, 'rb');
      $content = fread($fp, filesize($tmp_name));
      $statement = $this->db->prepare("INSERT INTO document(nomfichier,fichier,typefichier,taillefichier) VALUES (?,?,?,?)");
      $statement->bindParam(1, $nom);
      $statement->bindParam(2, $content, PDO::PARAM_LOB, $taille);
      $statement->bindParam(3, $type);
      $statement->bindParam(4, $taille);
      $statement->execute();
      $statement->closeCursor();
      // Redirect
      header('Location: documentation');
      die('redirect');
</code>```

Edit : Problem comes from the database who choose a blob instead of longblob when regenerated

答:
I think the problem exists in the line below:

```<code>$content = fread($fp, filesize($tmp_name));
</code>```

Here you are trying to read the content of the file, at this point you will get out of memory when the filesize is large.

So, increasing memory limit is not a better solution in this case. It's better to stream the file content rather than keeping hole content in memory.

Remove the above mentioned line, also replace the following line:

```<code>$statement->bindParam(2, $content, PDO::PARAM_LOB, $taille);
</code>```

with

```<code>$stmt->bindColumn(2, $fp, PDO::PARAM_LOB);
</code>```

PDO::PARAM_LOB tells PDO to map the data as a stream

Body:
I'm currently developping a PHP website and I need to store files in my database.
I'm using a LONGBLOB to store files such as PDF,PPTX,...
The file upload was working fine until i get this error :
Fatal error: Allowed memory size of 134217728 bytes exhausted

Here is my function :

public function uploadFile() {
    // We upload only pdf for now
    if (isset($_FILES['fichier']['name']) && $_FILES['fichier']['type']=="application/pdf"){
      $tmp_name = $_FILES['fichier']['tmp_name'];
      // Avoid problem with space
      $nom = str_replace(' ','_',$_FILES['fichier']['name']);
      $taille = $_FILES['fichier']['size'];
      $type = $_FILES['fichier']['type'];
      $fp = fopen($tmp_name, 'rb');
      $content = fread($fp, filesize($tmp_name));
      $statement = $this->db->prepare("INSERT INTO document(nomfichier,fichier,typefichier,taillefichier) VALUES (?,?,?,?)");
      $statement->bindParam(1, $nom);
      $statement->bindParam(2, $content, PDO::PARAM_LOB, $taille);
      $statement->bindParam(3, $type);
      $statement->bindParam(4, $taille);
      $statement->execute();
      $statement->closeCursor();
      // Redirect
      header('Location: documentation');
      die('redirect');

Edit : Problem comes from the database who choose a blob instead of longblob when regenerated

Body:
I think the problem exists in the line below:

$content = fread($fp, filesize($tmp_name));

Here you are trying to read the content of the file, at this point you will get out of memory when the filesize is large.

So, increasing memory limit is not a better solution in this case. It's better to stream the file content rather than keeping hole content in memory.

Remove the above mentioned line, also replace the following line:

$statement->bindParam(2, $content, PDO::PARAM_LOB, $taille);

with

$stmt->bindColumn(2, $fp, PDO::PARAM_LOB);

PDO::PARAM_LOB tells PDO to map the data as a stream


问:
setLayoutParams of a layout inside a Fragment from an Activity
I have an Activity that has many fragment inside. When on a particular fragment I inflate a menu and when clicking on the inflated MenuItem I should call a method of the Fragment class that change the layout params of a Constraint Layout inside the fragment. The problem is that I get a NPE on the Constraint Layout I'm trying to change.

These are the methods I'm trying to call:

```<code>public void searcherOpen() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT));
    searchText.setFocusable(true);
}
public void searcherClose() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(0, 0));
    searchText.setFocusable(false);
}
</code>```

These are the MenuItem that are calling the methods:

```<code>getMenuInflater().inflate(R.menu.patient_fragment_menu, menu);
        final MenuItem search = menu.findItem(R.id.menu_search);
        final MenuItem close_search = menu.findItem(R.id.menu_search_close);
        search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherOpen();
                search.setVisible(false);
                close_search.setVisible(true);
                return true;
            }
        });
        close_search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherClose();
                search.setVisible(true);
                close_search.setVisible(false);
                return true;
            }
        });
</code>```

This is how I define the fragment inside the activity in onCreate:

```<code>patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");
</code>```

And this is the error:

```<code>06-06 14:52:23.314 3682-3682/com.medishare.zeeromed E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.medishare.zeeromed, PID: 3682
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.medishare.zeeromed.fragments.PatientFragment.searcherOpen()' on a null object reference
                                                                      at com.medishare.zeeromed.DrawerActivity$3.onMenuItemClick(DrawerActivity.java:255)
                                                                      at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
                                                                      at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
                                                                      at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22393)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:173)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
</code>```

答: try getSuportFragmentManager() instead of getFragmentManager()</p>

Body:
I have an Activity that has many fragment inside. When on a particular fragment I inflate a menu and when clicking on the inflated MenuItem I should call a method of the Fragment class that change the layout params of a Constraint Layout inside the fragment. The problem is that I get a NPE on the Constraint Layout I'm trying to change.

These are the methods I'm trying to call:

public void searcherOpen() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT));
    searchText.setFocusable(true);
}
public void searcherClose() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(0, 0));
    searchText.setFocusable(false);
}

These are the MenuItem that are calling the methods:

getMenuInflater().inflate(R.menu.patient_fragment_menu, menu);
        final MenuItem search = menu.findItem(R.id.menu_search);
        final MenuItem close_search = menu.findItem(R.id.menu_search_close);
        search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherOpen();
                search.setVisible(false);
                close_search.setVisible(true);
                return true;
            }
        });
        close_search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherClose();
                search.setVisible(true);
                close_search.setVisible(false);
                return true;
            }
        });

This is how I define the fragment inside the activity in onCreate:

patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");

And this is the error:

06-06 14:52:23.314 3682-3682/com.medishare.zeeromed E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.medishare.zeeromed, PID: 3682
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.medishare.zeeromed.fragments.PatientFragment.searcherOpen()' on a null object reference
                                                                      at com.medishare.zeeromed.DrawerActivity$3.onMenuItemClick(DrawerActivity.java:255)
                                                                      at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
                                                                      at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
                                                                      at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22393)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:173)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)


问:
How to get height of div which contains dynamically added image?
I have a little script that add images to some columns. I would like it to add images to the smallest column. But when I try to get the height of the columns it always return 30px (surely because the images are not loaded yet)

Here is some code :

```<code><div id="diaporama-col1" class="col-xs-4">

</div>
<div id="diaporama-col2" class="col-xs-4">

</div>
<div id="diaporama-col3" class="col-xs-4">

</div>
</code>```

.

```<code>var listImgDiaporama=["resources/img/img-1.jpg", "resources/img/img-2.jpg", "resources/img/img-3.jpg", "resources/img/img-4.jpg", "resources/img/img-5.jpg", "resources/img/img-6.jpg", "resources/img/img-7.jpg", "resources/img/img-8.jpg", "resources/img/img-9.jpg", "resources/img/img-10.jpg", "resources/img/img-11.jpg"];
function addImgToDiaporama() {

    for (i = 0; i < listImgDiaporama.length; i++) {

        var col1Height = $("#diaporama-col1").height();
        var col2Height = $("#diaporama-col2").height();
        var col3Height = $("#diaporama-col3").height();

        if (col1Height <= col2Height && col1Height <= col3Height) {
            $("#diaporama-col1").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        } else if (col2Height <= col1Height && col2Height <= col3Height) {
            $("#diaporama-col2").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        } else {
            $("#diaporama-col3").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        }
    }
}
</code>```

Is there a way to make this work ?

答:
You could do something like this, where we compare the height of the columns, figure out the shortest and append the image to it.

Hope this is helpful (helps to view in fullscreen or at https://jsfiddle.net/j9v5uwf2/1/

$('#addImage').click(function(){

  $shortest_column = getShortestColumn();
  $image = getRandImage();

  $($shortest_column).append($image);

});

function getShortestColumn(){

  var shortest_column = null;
  var shortest = 999999999;
  $(".column").each(function(){
    var height = $(this).height();
    if(height < shortest){
       shortest = height;
       shortest_column = $(this);
    }
  });

  return shortest_column;
}

function getRandImage(){
 $rn = Math.floor(Math.random() * 50) + 1
  if ($rn = 1){$image = "";}
  else {$image = "";}

  return $image;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.column {
  width:30%;
  margin-left:1%;
  margin-right:1%;
  float:left;
  background: #222;
  text-align: center;
}
img {
  max-width:100%;
}</code>```

  <button id="addImage">Add Image</button>

```

Body:
I have a little script that add images to some columns. I would like it to add images to the smallest column. But when I try to get the height of the columns it always return 30px (surely because the images are not loaded yet)

Here is some code :

.

var listImgDiaporama=["resources/img/img-1.jpg", "resources/img/img-2.jpg", "resources/img/img-3.jpg", "resources/img/img-4.jpg", "resources/img/img-5.jpg", "resources/img/img-6.jpg", "resources/img/img-7.jpg", "resources/img/img-8.jpg", "resources/img/img-9.jpg", "resources/img/img-10.jpg", "resources/img/img-11.jpg"];
function addImgToDiaporama() {

    for (i = 0; i < listImgDiaporama.length; i++) {

        var col1Height = $("#diaporama-col1").height();
        var col2Height = $("#diaporama-col2").height();
        var col3Height = $("#diaporama-col3").height();

        if (col1Height <= col2Height && col1Height <= col3Height) {
            $("#diaporama-col1").append("")
        } else if (col2Height <= col1Height && col2Height <= col3Height) {
            $("#diaporama-col2").append("")
        } else {
            $("#diaporama-col3").append("")
        }
    }
}

Is there a way to make this work ?

Body:
You could do something like this, where we compare the height of the columns, figure out the shortest and append the image to it.

Hope this is helpful (helps to view in fullscreen or at https://jsfiddle.net/j9v5uwf2/1/

$('#addImage').click(function(){

  $shortest_column = getShortestColumn();
  $image = getRandImage();

  $($shortest_column).append($image);

});

function getShortestColumn(){

  var shortest_column = null;
  var shortest = 999999999;
  $(".column").each(function(){
    var height = $(this).height();
    if(height < shortest){
       shortest = height;
       shortest_column = $(this);
    }
  });

  return shortest_column;
}

function getRandImage(){
 $rn = Math.floor(Math.random() * 50) + 1
  if ($rn = 1){$image = "<img src='http://lorempixel.com/200/100/'>";}
  else {$image = "<img src='http://lorempixel.com/200/150/'>";}

  return $image;
}

.column {
  width:30%;
  margin-left:1%;
  margin-right:1%;
  float:left;
  background: #222;
  text-align: center;
}
img {
  max-width:100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div>
  <center><button id="addImage">Add Image</button></center>
</div>
<hr>
<div class="column" id="column1">
  <img src="http://lorempixel.com/200/100/">
  <img src="http://lorempixel.com/200/150/">
</div>
<div class="column" id="column2">
  <img src="http://lorempixel.com/200/150/">
  <img src="http://lorempixel.com/200/150/">
</div>
<div class="column" id="column3">
  <img src="http://lorempixel.com/200/150/" alt="">
  <img src="http://lorempixel.com/200/100/" alt="">
</div>


问:
Samsung Galaxy S7 Edge ignores datePickerMode
I am setting the datePickerMode in my styles file to spinner like this:

```<code><style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:dialogTheme">@style/MyDialogTheme</item>
    <item name="android:datePickerStyle">@style/MyDatePicker</item>
</style>

<style name="ItvDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePicker</item>
</style>

<style name="MyDatePicker" parent="android:Widget.Material.Light.DatePicker">
    <item name="android:datePickerMode">spinner</item>
</style>
</code>```

and then create a DatePicker

```<code>DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
        //handle result
        }
    };

DatePickerDialog dialog = new DatePickerDialog(this, onDateSetListener, dob.getYear(), dob.getMonth() - 1,
            dob.getDay());

dialog.show();
</code>```

This worked fine across a lot of devices including the Samsung Galaxy S7 Edge on Android 6, but since updating the device to Android 7 it ignores the mode spinner and shows the calendar.

The spinner works fine on an One Plus 3 on Android 7.1.1.

Any ideas?

答:
You can try this.

datePicker.setCalendarViewShown(false);

Body:
I am setting the datePickerMode in my styles file to spinner like this:

and then create a DatePicker

DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
        //handle result
        }
    };

DatePickerDialog dialog = new DatePickerDialog(this, onDateSetListener, dob.getYear(), dob.getMonth() - 1,
            dob.getDay());

dialog.show();

This worked fine across a lot of devices including the Samsung Galaxy S7 Edge on Android 6, but since updating the device to Android 7 it ignores the mode spinner and shows the calendar.

The spinner works fine on an One Plus 3 on Android 7.1.1.

Any ideas?


问:
Firebase Google sign in: get user location
Is it possible to access a Google user's location once they've signed in (using GIDSignIn)?

I have no trouble accessing a user's name, email, and photo.

答:
I believe it is possible,
you can set it as profile properties.

so you get user location normally and set it to users profile in your database


问:
check if variable empty
```<code>if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
    $user_id = '-1';
    $user_name = NULL;
    $user_logged = NULL;
}
if ($user_admin == NULL) {
    $user_admin = NULL;
}
</code>```

Is there any shortest way to do it ?

And if i right, it should be tested with is_null?

It's possible $user_id, $user_name and $user_logged write in one line (maybe array?) without repeating NULL ?

答:
Felt compelled to answer this because of the other responses. Use empty() if you can because it covers more bases. Future you will thank me.

For example  you will have to do things like isset() && strlen()  where instead you could use empty(). Think of it like this empty is like !isset($var) || $var==false

Title: check if variable empty

Body:
if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
    $user_id = '-1';
    $user_name = NULL;
    $user_logged = NULL;
}
if ($user_admin == NULL) {
    $user_admin = NULL;
}

Is there any shortest way to do it ?

And if i right, it should be tested with is_null?

It's possible $user_id, $user_name and $user_logged write in one line (maybe array?) without repeating NULL ?


问:
'automaticallyAdjustsScrollViewInsets' was deprecated in iOS 11.0
I just started compiling up to iOS 11 and noticed that Apple now declared the property

```<code>var automaticallyAdjustsScrollViewInsets: Bool { get set }
</code>```

as being deprecated:

https://developer.apple.com/documentation/uikit/uiviewcontroller/1621372-automaticallyadjustsscrollviewin

Is there another property to fix this warning in iOS 11?

Will the default value stay true or how will this be handled in future?

答:
The default for this property is now true. If you need to set this, you will need to set it in the scrollview that would host the viewController and set its property contentInsetAdjustmentBehavior. Below is an example:</p>

```<code>scrollView.contentInsetAdjustmentBehavior = .automatic
</code>```

Body:
I just started compiling up to iOS 11 and noticed that Apple now declared the property

var automaticallyAdjustsScrollViewInsets: Bool { get set }

as being deprecated:

https://developer.apple.com/documentation/uikit/uiviewcontroller/1621372-automaticallyadjustsscrollviewin

Is there another property to fix this warning in iOS 11?

Will the default value stay true or how will this be handled in future?

Body:
The default for this property is now true. If you need to set this, you will need to set it in the scrollview that would host the viewController and set its property contentInsetAdjustmentBehavior. Below is an example:

scrollView.contentInsetAdjustmentBehavior = .automatic


问:
Does Java automatically save an 'evaluate' statement in a predefined Java variable?
Say I perform a simple add/concatenation statement:

```<code>variable + newInput
</code>```

Without setting the calculated value to a new variable, as in:

```<code>variable = variable + newInput
</code>```

or

```<code>variable += newInput
</code>```

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

```<code>Print(_)
</code>```

Is there anything like this in Java?

答:
No. It does not have anything like this. You have to assign the computed value to a variable, otherwise it will be lost and consequently collected by the garbage collector.

The best option is to use a special operator so not to use an extra variable but assign the result to an old one. This is a Shorthand operator.

```<code>Variable += NewInput
</code>```

Body:
Say I perform a simple add/concatenation statement:

variable + newInput

Without setting the calculated value to a new variable, as in:

variable = variable + newInput

or

variable += newInput

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

Print(_)

Is there anything like this in Java?

Body:
No. It does not have anything like this. You have to assign the computed value to a variable, otherwise it will be lost and consequently collected by the garbage collector.

The best option is to use a special operator so not to use an extra variable but assign the result to an old one. This is a Shorthand operator.

Variable += NewInput


问:
How to create a customized text area in Java for Java code
I want to add GUI to my software and I'm trying to create a text area designed for java code.

In other words, I want to create a small java editor area. How can I do that?
I'm using IntelliJ and SWING if it matters.

答:
As was mentioned, the standard JTextArea doesn't support stylized code, so you'll want to use another component. One possibility is a JEditorPane, which allows for HTML input. Here's the link to the documentation for that:

https://docs.oracle.com/javase/7/docs/api/javax/swing/JEditorPane.html

You'll have to specify the content to take text/html.
Then, you can use the HTML  tag for built-in HTML code display support. Or, you could create your own stylesheet or in-line styles within your HTML to display it however works for you. Either way, this gives you the flexibility to customize how you want your code to be displayed.

Body:
As was mentioned, the standard JTextArea doesn't support stylized code, so you'll want to use another component. One possibility is a JEditorPane, which allows for HTML input. Here's the link to the documentation for that:

https://docs.oracle.com/javase/7/docs/api/javax/swing/JEditorPane.html

You'll have to specify the content to take text/html.
Then, you can use the HTML <code> tag for built-in HTML code display support. Or, you could create your own stylesheet or in-line styles within your HTML to display it however works for you. Either way, this gives you the flexibility to customize how you want your code to be displayed.


问:
Google analytics code not working on Opera
I have following code on my MyBB based website forum. Strangely it works fine on Chrome but I'm not receiving any events (in realtime view) when using Opera 45 (v45.0.2552.888).

Code is copied in footer template, in script tags as provided by Google, UA-XXXXXXXXX-X has replaced the actual Id.

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXXXXX-X', 'auto');
  ga('send', 'pageview');

答:
After spending hours looking into JS code and Google console, I found that new Opera browser has built-in Ad/Content blocker, which was also hindering Google Analytics to send events. So, only solution is disable content blocker.

So unless you whitelist your website, you don't get any events. This means you will not get any analytic events from users of new Opera by default.

Hope that helps.


问:
How do I insert a newline/linebreak after a line using sed
It took me a while to figure out how to do this, so posting in case anyone else is looking for the same.</p>

答:
```<code>sed '/pattern/a\\r' file name
</code>```

It will add a return after the pattern while g will replace the pattern with a blank line.

If a new line (blank) has to be added at end of the file use this:

```<code>sed '$a\\r' file name
</code>```

Body:
sed '/pattern/a\\r' file name

It will add a return after the pattern while g will replace the pattern with a blank line.

If a new line (blank) has to be added at end of the file use this:

sed '$a\\r' file name


问:
T-SQL query to select values with closer timestamp
I'm trying to make a query that based on an ID from table A to display the closest row from table P that has the same TimestampLocal column ad table A.

What I've managed to do:

```<code> IF(A.Generated - P.Local) >= 0 THEN
       select P.Location where P.Local = A.Generated + MIN(A.Generated - P.Local)
    ELSE
       select P.Location where P.Local = A.Generated + MAX(A.Generated - P.Local)
</code>```

I'm trying to get the Value from table P.

```<code>IF (select datediff(second, a.Generated,p.Local) from A a inner join P p on a.VId=p.VId where a.Id = 830566) >=0
select Location from P where Local = dateadd(millisecond,(select Min(datediff(second, a.Generated,p.Local)) from A a inner join P p on a.VId=p.VId where a.Id=830566),
(select Generated from A where Id=830566))

ELSE

select Location from P where Local =dateadd(second,(select Max(datediff(millisecond, a.Generated,p.Local)) from A a inner join P p on a.VId=p.VId where a.Id=830566),
(select Generated from A where Id=830566))
</code>```

But I got the error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

and

The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.

But I don't know why :( It is possible to get just the closest row from table P based on table A Id? And if there are more than one rows from P with the same TimeStampLocal to get just the first one?

UPDATE

Table A:

```<code>Id       Generated                            VId
830566 | 2017-06-04 10:38:22.2000000 -07:00 | 5635
830567 | 2017-06-04 10:38:45.1000000 -07:00 | 5634
830568 | 2017-06-04 10:31:59.6000000 -07:00 | 5638
</code>```

Table P:

```<code>VId    Local                                Location
5638 | 2017-06-04 10:26:17.9000000 -07:00 | 0xE6
5638 | 2017-06-04 10:31:48.6000000 -07:00 | 0X7F
5638 | 2017-06-04 10:32:48.7000000 -07:00 | 0x3C
5634 | 2017-06-04 10:31:48.6000000 -07:00 | 0xA6
</code>```

As example: For Id 830568 from Table A (received as a parameter) - VId 5638, I should get the closest row from table P with the closest Local time and same VId, in this case the second one 2017-06-04 10:31:48.6000000 -07:00, and for this row from P I'll need to get the Location: 0X7F

答:
This should do it. If you want the closest time without "going over" then remove the ABS() around the datediff() function and uncomment out the join condition.

```<code>declare @TableA table (Id int, [Generated] datetime2, VId int)

declare @TableB table (VId int, [Local] datetime2, [Location] varchar(64))

insert into @TableA
values
(830566,'2017-06-04 10:38:22.2000000 -07:00',5635),
(830567,'2017-06-04 10:38:45.1000000 -07:00',5634),
(830568,'2017-06-04 10:31:59.6000000 -07:00 ',5638)

insert into @TableB values

(5638,'2017-06-04 10:26:17.9000000 -07:00','0xE6'),
(5638,'2017-06-04 10:31:48.6000000 -07:00','0X7F'),
(5638,'2017-06-04 10:32:48.7000000 -07:00','0x3C'),
(5634,'2017-06-04 10:31:48.6000000 -07:00','0xA6')

;with cte as(
select
    a.Id
    ,a.VId
    ,a.Generated
    ,b.Local
    ,b.Location
    ,ABS(DATEDIFF(second,a.Generated,b.Local)) as TD
from
    @TableA a
inner join
    @TableB b on
    b.VId = a.VId)
    --and b.local < a.Generated

select
    c.Id
    ,c.VId
    ,c.Location
from
    cte c
    inner join
        (select ID, min(TD) TD
         from cte
         group by ID) c2 on c2.Id = c.Id and c2.TD = c.TD
</code>```

Body:
I'm trying to make a query that based on an ID from table A to display the closest row from table P that has the same TimestampLocal column ad table A.

What I've managed to do:

 IF(A.Generated - P.Local) >= 0 THEN
       select P.Location where P.Local = A.Generated + MIN(A.Generated - P.Local)
    ELSE
       select P.Location where P.Local = A.Generated + MAX(A.Generated - P.Local)

I'm trying to get the Value from table P.

IF (select datediff(second, a.Generated,p.Local) from A a inner join P p on a.VId=p.VId where a.Id = 830566) >=0
select Location from P where Local = dateadd(millisecond,(select Min(datediff(second, a.Generated,p.Local)) from A a inner join P p on a.VId=p.VId where a.Id=830566),
(select Generated from A where Id=830566))

ELSE

select Location from P where Local =dateadd(second,(select Max(datediff(millisecond, a.Generated,p.Local)) from A a inner join P p on a.VId=p.VId where a.Id=830566),
(select Generated from A where Id=830566))

But I got the error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

and

The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.

But I don't know why :( It is possible to get just the closest row from table P based on table A Id? And if there are more than one rows from P with the same TimeStampLocal to get just the first one?

UPDATE

Table A:

Id       Generated                            VId
830566 | 2017-06-04 10:38:22.2000000 -07:00 | 5635
830567 | 2017-06-04 10:38:45.1000000 -07:00 | 5634
830568 | 2017-06-04 10:31:59.6000000 -07:00 | 5638

Table P:

VId    Local                                Location
5638 | 2017-06-04 10:26:17.9000000 -07:00 | 0xE6
5638 | 2017-06-04 10:31:48.6000000 -07:00 | 0X7F
5638 | 2017-06-04 10:32:48.7000000 -07:00 | 0x3C
5634 | 2017-06-04 10:31:48.6000000 -07:00 | 0xA6

As example: For Id 830568 from Table A (received as a parameter) - VId 5638, I should get the closest row from table P with the closest Local time and same VId, in this case the second one 2017-06-04 10:31:48.6000000 -07:00, and for this row from P I'll need to get the Location: 0X7F

Body:
This should do it. If you want the closest time without "going over" then remove the ABS() around the datediff() function and uncomment out the join condition.

declare @TableA table (Id int, [Generated] datetime2, VId int)

declare @TableB table (VId int, [Local] datetime2, [Location] varchar(64))

insert into @TableA
values
(830566,'2017-06-04 10:38:22.2000000 -07:00',5635),
(830567,'2017-06-04 10:38:45.1000000 -07:00',5634),
(830568,'2017-06-04 10:31:59.6000000 -07:00 ',5638)

insert into @TableB values

(5638,'2017-06-04 10:26:17.9000000 -07:00','0xE6'),
(5638,'2017-06-04 10:31:48.6000000 -07:00','0X7F'),
(5638,'2017-06-04 10:32:48.7000000 -07:00','0x3C'),
(5634,'2017-06-04 10:31:48.6000000 -07:00','0xA6')

;with cte as(
select
    a.Id
    ,a.VId
    ,a.Generated
    ,b.Local
    ,b.Location
    ,ABS(DATEDIFF(second,a.Generated,b.Local)) as TD
from
    @TableA a
inner join
    @TableB b on
    b.VId = a.VId)
    --and b.local < a.Generated

select
    c.Id
    ,c.VId
    ,c.Location
from
    cte c
    inner join
        (select ID, min(TD) TD
         from cte
         group by ID) c2 on c2.Id = c.Id and c2.TD = c.TD


问:
Securely delete file in php
I would like to securely delete a file in PHP. I thought of the following options

Use shredthrough a system call. (exec, shell_exec, ....), but in most shared hostings, those functions are disabled and are forbidden if safe mode is on.

Open it through fopenand overwriting it with random data and unlinkit. Correct me if I'm wrong, but doing my research I found it was disabled on some servers.

The best option I thought of, is using file_put_contentto overwrite its data with zeros, and then deleting it.

Question is: is file_put_content guaranteed to overwrite the file ? I wrote a simplistic approach in the following example: would this code delete a file securely ? Would there be a considerable performance hit ? How do I make it more "large file friendly" ?

```<code>function secure_delete($file_path)
{
    $file_size = filesize($file_path);
    $new_content = str_repeat('0', $file_size);
    file_put_contents($file_path, $new_content);
    unlink($file_path);
}
</code>```

UPDATE: The code I posted is more about demonstrating the overwriting of a file: the actual code would be an implementation of DoD 5220.22-M

答:
It's not so simply. If you erase file with '0' values it can be still posible to restore. You should use any of algorihms for really secure deletion. For example: Gutmann method

It use 35 consecutive writes per file.

Title: Securely delete file in php

Body:
I would like to securely delete a file in PHP. I thought of the following options

Use shredthrough a system call. (exec, shell_exec, ....), but in most shared hostings, those functions are disabled and are forbidden if safe mode is on.

Open it through fopenand overwriting it with random data and unlinkit. Correct me if I'm wrong, but doing my research I found it was disabled on some servers.

The best option I thought of, is using file_put_contentto overwrite its data with zeros, and then deleting it.

Question is: is file_put_content guaranteed to overwrite the file ? I wrote a simplistic approach in the following example: would this code delete a file securely ? Would there be a considerable performance hit ? How do I make it more "large file friendly" ?

function secure_delete($file_path)
{
    $file_size = filesize($file_path);
    $new_content = str_repeat('0', $file_size);
    file_put_contents($file_path, $new_content);
    unlink($file_path);
}

UPDATE: The code I posted is more about demonstrating the overwriting of a file: the actual code would be an implementation of DoD 5220.22-M


问:
MySQL JOIN and GROUP BY
I should get 1 as a result, because object 3 has one attribute (a3) which is over zero. Because of the groupref join (which is needed) i get 3.
I tried to group but didn't get it working.

Reduced statement

```<code>SELECT COUNT(IF(a3 > 0, TRUE, NULL)) AS a3
FROM objects AS o
LEFT JOIN attribs AS a ON o.id=a.oid
LEFT JOIN group_ref AS gx ON gx.oid = o.id
</code>```

Reduced tables

```<code>attribs
------------
oid |   attrib  |   value
------------------------
1   |   a1  |   3
2   |   a2  |   0
3   |   a3  |   1

objects
------------
id  |   title
------------
1   |   obj1
2   |   obj2
3   |   obj3

groups
------------
id  |   title
------------
1   |   g1
2   |   g2
3   |   g3

group_ref
------------
gid |   oid
------------
1   |   1
1   |   2
2   |   1
3   |   3
3   |   2
3   |   1
</code>```

答:
Perhaps this

```<code>drop table if exists a1,o1,g1,gr1;

create table a1(oid int,   attribute varchar(20),    value int);
insert into a1 values
(1   ,   'a1'  ,   3),
(2   ,   'a2'  ,   0),
(3   ,   'a3'  ,   1);

create table o1(id  int,   title varchar(10));
insert into o1 values
(1   ,   'obj1'),
(2   ,   'obj2'),
(3   ,   'obj3');

create table g1(id  int,    title varchar(20));
insert into g1 values
(1   ,   'g1'),
(2   ,   'g2'),
(3   ,   'g3');

create table gr1(gid int,   oid int);
insert into gr1 values
(1   ,   1),
(1   ,   4),
(2   ,   1),
(3   ,   3),
(3   ,   4),
(3   ,   1);

SELECT o1.id,a1.attribute,
         max(case when gr1.oid is not null then 1 else 0 end) as obs
FROM o1
LEFT JOIN a1 ON o1.id=a1.oid
LEFT JOIN gr1 ON gr1.oid = o1.id
group by o1.id,a1.attribute;
</code>```

Result

```<code>+------+-----------+------+
| id   | attribute | obs  |
+------+-----------+------+
|    1 | a1        |    1 |
|    2 | a2        |    0 |
|    3 | a3        |    1 |
+------+-----------+------+
3 rows in set (0.00 sec)
</code>```

Title: MySQL JOIN and GROUP BY

Body:
I should get 1 as a result, because object 3 has one attribute (a3) which is over zero. Because of the groupref join (which is needed) i get 3.
I tried to group but didn't get it working.

Reduced statement

SELECT COUNT(IF(a3 > 0, TRUE, NULL)) AS a3
FROM objects AS o
LEFT JOIN attribs AS a ON o.id=a.oid
LEFT JOIN group_ref AS gx ON gx.oid = o.id

Reduced tables

attribs
------------
oid |   attrib  |   value
------------------------
1   |   a1  |   3
2   |   a2  |   0
3   |   a3  |   1

objects
------------
id  |   title
------------
1   |   obj1
2   |   obj2
3   |   obj3

groups
------------
id  |   title
------------
1   |   g1
2   |   g2
3   |   g3

group_ref
------------
gid |   oid
------------
1   |   1
1   |   2
2   |   1
3   |   3
3   |   2
3   |   1

Body:
Perhaps this

drop table if exists a1,o1,g1,gr1;

create table a1(oid int,   attribute varchar(20),    value int);
insert into a1 values
(1   ,   'a1'  ,   3),
(2   ,   'a2'  ,   0),
(3   ,   'a3'  ,   1);

create table o1(id  int,   title varchar(10));
insert into o1 values
(1   ,   'obj1'),
(2   ,   'obj2'),
(3   ,   'obj3');

create table g1(id  int,    title varchar(20));
insert into g1 values
(1   ,   'g1'),
(2   ,   'g2'),
(3   ,   'g3');

create table gr1(gid int,   oid int);
insert into gr1 values
(1   ,   1),
(1   ,   4),
(2   ,   1),
(3   ,   3),
(3   ,   4),
(3   ,   1);

SELECT o1.id,a1.attribute,
         max(case when gr1.oid is not null then 1 else 0 end) as obs
FROM o1
LEFT JOIN a1 ON o1.id=a1.oid
LEFT JOIN gr1 ON gr1.oid = o1.id
group by o1.id,a1.attribute;

Result

+------+-----------+------+
| id   | attribute | obs  |
+------+-----------+------+
|    1 | a1        |    1 |
|    2 | a2        |    0 |
|    3 | a3        |    1 |
+------+-----------+------+
3 rows in set (0.00 sec)


问:
How to replace escape character in Netezza column
I am trying to replace escape character in Netezza column, but it is not properly replacing.
Please help me some one on this.

```<code>select replace('replaces\tring','\','\\\\');
</code>```

I need output as replaces\\\\tring. Below is the error message i am getting...

ERROR [42S02] ERROR:  Function 'REPLACE(UNKNOWN, UNKNOWN, UNKNOWN)'
  does not exist    Unable to identify a function that satisfies the given
  argument types    You may need to add explicit typecasts

Thanks in advance.

答:
This is because REPLACE function needs to be installed (which is not by default). There is another function which is called TRANSLATE which can be used in a limited way instead of REPLACE but unfortunately won't fit in your situation.

You can use the below query instead:

```<code>SELECT SUBSTRING(x, 1, INSTR(x, '\') - 1) || '\\\\' || SUBSTRING(x, INSTR(x, '\') + LENGTH('\')) FROM
(SELECT 'replaces\tring' AS x) t
</code>```

\ passed to INSTR and LENGTH is the string to be replaced. Note that they occur in three positions.

\\\\ in the middle is the replacement string.

replaces\tring is the string to search in.

Check the below example for replace love with like in I love Netezza:

```<code>SELECT SUBSTRING(x, 1, INSTR(x, 'love') - 1) || 'like' || SUBSTRING(x, INSTR(x, 'love') + LENGTH('love')) FROM
(SELECT 'I love Netezza' AS x) t
</code>```

Body:
I am trying to replace escape character in Netezza column, but it is not properly replacing.
Please help me some one on this.

select replace('replaces\tring','\','\\\\');

I need output as replaces\\\\tring. Below is the error message i am getting...

ERROR [42S02] ERROR:  Function 'REPLACE(UNKNOWN, UNKNOWN, UNKNOWN)'
  does not exist    Unable to identify a function that satisfies the given
  argument types    You may need to add explicit typecasts

Thanks in advance.

Body:
This is because REPLACE function needs to be installed (which is not by default). There is another function which is called TRANSLATE which can be used in a limited way instead of REPLACE but unfortunately won't fit in your situation.

You can use the below query instead:

SELECT SUBSTRING(x, 1, INSTR(x, '\') - 1) || '\\\\' || SUBSTRING(x, INSTR(x, '\') + LENGTH('\')) FROM
(SELECT 'replaces\tring' AS x) t

\ passed to INSTR and LENGTH is the string to be replaced. Note that they occur in three positions.

\\\\ in the middle is the replacement string.

replaces\tring is the string to search in.

Check the below example for replace love with like in I love Netezza:

SELECT SUBSTRING(x, 1, INSTR(x, 'love') - 1) || 'like' || SUBSTRING(x, INSTR(x, 'love') + LENGTH('love')) FROM
(SELECT 'I love Netezza' AS x) t


问:
How do I make pyodbc output more readable/nicer?
I'm currently making a discord bot, and one of it's commands involves pulling data from a SQL table, for this I'm using the AioOdbc module, which almost exactly the same as Pyodbc, with the only real difference being that it doesn't block in asynchronous functions.

Which outputs in this format.

```<code>[('Item1',),('Item2',)]
</code>```

How can I have it output something which is a bit nicer to read? Possibly something like

```<code>Item1, Item2
</code>```

Any help is appreciated!

答:
You can turn it into a string where every item is separated by a comma and space with this code:

```<code>itemString = ', '.join((item[0] for item in items))
</code>```

Where items is the name of this: [('Item1',),('Item2',)]

If you need it to be able to take items out from nested lists with arbitrary depth, such as in this list: [('Item1', 'Item2', ('Item3')), ('Item4', 'Item5')], you can use this code:

```<code>from collections import Iterable

def flatten(nested):
    for element in nested:
        if isinstance(element, Iterable) and not isinstance(element, (str, bytes)):
            yield from flatten(element)
        else:
            yield element
</code>```

Body:
I'm currently making a discord bot, and one of it's commands involves pulling data from a SQL table, for this I'm using the AioOdbc module, which almost exactly the same as Pyodbc, with the only real difference being that it doesn't block in asynchronous functions.

Which outputs in this format.

[('Item1',),('Item2',)]

How can I have it output something which is a bit nicer to read? Possibly something like

Item1, Item2

Any help is appreciated!

Body:
You can turn it into a string where every item is separated by a comma and space with this code:

itemString = ', '.join((item[0] for item in items))

Where items is the name of this: [('Item1',),('Item2',)]

If you need it to be able to take items out from nested lists with arbitrary depth, such as in this list: [('Item1', 'Item2', ('Item3')), ('Item4', 'Item5')], you can use this code:

from collections import Iterable

def flatten(nested):
    for element in nested:
        if isinstance(element, Iterable) and not isinstance(element, (str, bytes)):
            yield from flatten(element)
        else:
            yield element

ContentLicense: CC BY-SA 4.0


问:
How to change working directory in Julia Jupyter?
How to change working directory in Julia Jupyter?

I tried and read everything, still have no idea how to do that. It only allows me to select directories under my home ~/ dir. I can't find any button to go up to /.

答:
I'm pretty sure once you have started the server you cannot then go up directories, I may be wrong though.

So best thing to do is start the jupyter notebook server somewhere that contains all of the folders you might need -i.e. the root dir if you want to make sure you have access to everything.

You can use the --notebook-dir flag for this. Or you can set defaults in the config.


问:
Pandas stacked area chart with zero values
I am creating a stacked area chart using pandas df.plot(kind = area). Some of my data values are zero at some times. I would like to not have the line show where the value is zero. Is it possible to hide the line while still showing the area?

Here is basic code that makes a simple graph. I don't want the red line to show between 3 and 4 because the values are 0.

```<code>import numpy as np
import pandas as pd
data = np.array([np.arange(10)]*3).T
df = pd.DataFrame(data, columns = ['A','B','C'])
df['C']=np.where(df.index==4,0,df['C'])
df['C']=np.where(df.index==3,0,df['C'])
df.plot(kind='area')
</code>```

答:
I have finally worked out the solution to this. Other places suggested edgecolor etc but it didn't solve the problem. linewidth, however, does.

```<code>linewidth=0
</code>```

or, in your case, use the line of code:

```<code>df.plot(kind='area', linewidth=0)
</code>```

Body:
I am creating a stacked area chart using pandas df.plot(kind = area). Some of my data values are zero at some times. I would like to not have the line show where the value is zero. Is it possible to hide the line while still showing the area?

Here is basic code that makes a simple graph. I don't want the red line to show between 3 and 4 because the values are 0.

import numpy as np
import pandas as pd
data = np.array([np.arange(10)]*3).T
df = pd.DataFrame(data, columns = ['A','B','C'])
df['C']=np.where(df.index==4,0,df['C'])
df['C']=np.where(df.index==3,0,df['C'])
df.plot(kind='area')

Body:
I have finally worked out the solution to this. Other places suggested edgecolor etc but it didn't solve the problem. linewidth, however, does.

linewidth=0

or, in your case, use the line of code:

df.plot(kind='area', linewidth=0)


问:
BAD_ACCESS with strcpy in shared memory (C)
I'm very new here and German, so please excuse my bad English here.
As a part of a school exercise we are supposed to implement a socket server with a shared memory for a key-value-store, running on an UNIX-based system. The server, the shared memory and the fork() are working. We use an array of structs and we made functions for this (put, get, delete). In the put-method we get this BAD_ACCESS, when we copy two strings.
Code of the method is below, the link to our repository is here: Github Repo

```<code>int put(int key, char *value, char *resp){
int emptyIndex = -1;
//strcpy(resp, "");
resp = "";
for(int i = 0; i < STORELENGTH; i++){
    // If the key exists, overwrite it, give back previous value, and return true
    if(kv[i].key == key) {
        resp = kv[i].value;
        kv[i].value = value;
        return 1;
    }
    // If the key doesn't exist, remember the empty index
    if(kv[i].key == NULL){
        emptyIndex = i;
    }
}

// If there was an empty index, just reuse it
if(emptyIndex > -1) {
    kv[emptyIndex].key = key;
    resp = "";
    kv[emptyIndex].value = value;
    return 1;
}

*resp = (char) "Error: Put was not successful.";
return -1;
}
</code>```

As you see, the strcpy-Function is a comment, because the programm immediatly stopped working.
Thanks for your help,
Alex

答:
Assuming, that resp should be a string in your main.c you are initializing the it incorrectly:

```<code>char *resp = ""; <- This one is bad
//char resp[BUFSIZ]; <-- This one is good but commented.
</code>```

As a result you have a resp being an char* with allocated size of 1. While strcpy needs at least size of 2 - one for "" you copy one for "\0" - the string termination character. That's why your app crashes when you try put the length of 2 in the resp whose length is 1 - you are trying to write to the memory you don't own.

Also instead of:

```<code>*resp = (char) "Error: Put was not successful.";
</code>```

You should use the strcpy also. I would suggest following:

1. Read about the arrays and pointers to understand it better

2. Read documentation for functions you are using if they are new to you, like strcpy. It contains some valuable info like:

To avoid overflows, the size of the array pointed by destination shall
  be long enough to contain the same C string as source (including the
  terminating null character), and should not overlap in memory with
  source.

3. Learn about debugging - imho, it's one of the most important things!
For example this link describes some points of memory allocation and debugging techniques.

All this could make your life easier in future :)

Body:
I'm very new here and German, so please excuse my bad English here.
As a part of a school exercise we are supposed to implement a socket server with a shared memory for a key-value-store, running on an UNIX-based system. The server, the shared memory and the fork() are working. We use an array of structs and we made functions for this (put, get, delete). In the put-method we get this BAD_ACCESS, when we copy two strings.
Code of the method is below, the link to our repository is here: Github Repo

int put(int key, char *value, char *resp){
int emptyIndex = -1;
//strcpy(resp, "");
resp = "";
for(int i = 0; i < STORELENGTH; i++){
    // If the key exists, overwrite it, give back previous value, and return true
    if(kv[i].key == key) {
        resp = kv[i].value;
        kv[i].value = value;
        return 1;
    }
    // If the key doesn't exist, remember the empty index
    if(kv[i].key == NULL){
        emptyIndex = i;
    }
}

// If there was an empty index, just reuse it
if(emptyIndex > -1) {
    kv[emptyIndex].key = key;
    resp = "";
    kv[emptyIndex].value = value;
    return 1;
}

*resp = (char) "Error: Put was not successful.";
return -1;
}

As you see, the strcpy-Function is a comment, because the programm immediatly stopped working.
Thanks for your help,
Alex

Body:
Assuming, that resp should be a string in your main.c you are initializing the it incorrectly:

char *resp = ""; <- This one is bad
//char resp[BUFSIZ]; <-- This one is good but commented.

As a result you have a resp being an char* with allocated size of 1. While strcpy needs at least size of 2 - one for "" you copy one for "\0" - the string termination character. That's why your app crashes when you try put the length of 2 in the resp whose length is 1 - you are trying to write to the memory you don't own.

Also instead of:

*resp = (char) "Error: Put was not successful.";

You should use the strcpy also. I would suggest following:

1. Read about the arrays and pointers to understand it better

2. Read documentation for functions you are using if they are new to you, like strcpy. It contains some valuable info like:

To avoid overflows, the size of the array pointed by destination shall
  be long enough to contain the same C string as source (including the
  terminating null character), and should not overlap in memory with
  source.

3. Learn about debugging - imho, it's one of the most important things!
For example this link describes some points of memory allocation and debugging techniques.

All this could make your life easier in future :)


问:
why isn't this javascript regex split function working?
I'm trying to split a string by either three or more pound signs or three or more spaces.

I'm using a function that looks like this:

```<code>     var produktDaten = dataMatch[0].replace(/\x03/g, '').trim().split('/[#\s]/{3,}');
     console.log(produktDaten + ' is the data');
</code>```

I need to clean the data up a bit, hence the replace and trim.

The output I'm getting looks like this:

```<code>##########################################################################MA-KF6###Beckhoff###EL1808    BECK.EL1808###MA-KF7###Beckhoff###EL1808    BECK.EL1808###MA-KF12###Beckhoff###EL1808    BECK.EL1808###MA-KF13###Beckhoff###EL1808    BECK.EL1808###MA-KF14###Beckhoff###EL1808    BECK.EL1808###MA-KF15###Beckhoff###EL1808    BECK.EL1808###MA-KF16###Beckhoff###EL1808    BECK.EL1808###MA-KF19###Beckhoff###EL1808    BECK.EL1808 is the data
</code>```

How is this possible?  Irrespective of the input, shouldn't the pound and multiple spaces be deleted by the split?

答:
You passed a string to the split, the input string does not contain that string. I think you wanted to use

```<code>/[#\s]{3,}/
</code>```

like here:

var produktDaten = "##########################################################################MA-KF6###Beckhoff###EL1808    BECK.EL1808###MA-KF7###Beckhoff###EL1808    BECK.EL1808###MA-KF12###Beckhoff###EL1808    BECK.EL1808###MA-KF13###Beckhoff###EL1808    BECK.EL1808###MA-KF14###Beckhoff###EL1808    BECK.EL1808###MA-KF15###Beckhoff###EL1808    BECK.EL1808###MA-KF16###Beckhoff###EL1808    BECK.EL1808###MA-KF19###Beckhoff###EL1808    BECK.EL1808";
console.log(produktDaten.replace(/\x03/g, '').trim().split(/[#\s]{3,}/));```

This /[#\s]{3,}/ regex matches 3 or more chars that are either # or whitespace.

NOTE: just removing ' around it won't fix the issue since you are using an unescaped / and quantify it. You actually need to quantify the character class, [#\s].

Body:
I'm trying to split a string by either three or more pound signs or three or more spaces.

I'm using a function that looks like this:

     var produktDaten = dataMatch[0].replace(/\x03/g, '').trim().split('/[#\s]/{3,}');
     console.log(produktDaten + ' is the data');

I need to clean the data up a bit, hence the replace and trim.

The output I'm getting looks like this:

##########################################################################MA-KF6###Beckhoff###EL1808    BECK.EL1808###MA-KF7###Beckhoff###EL1808    BECK.EL1808###MA-KF12###Beckhoff###EL1808    BECK.EL1808###MA-KF13###Beckhoff###EL1808    BECK.EL1808###MA-KF14###Beckhoff###EL1808    BECK.EL1808###MA-KF15###Beckhoff###EL1808    BECK.EL1808###MA-KF16###Beckhoff###EL1808    BECK.EL1808###MA-KF19###Beckhoff###EL1808    BECK.EL1808 is the data

How is this possible?  Irrespective of the input, shouldn't the pound and multiple spaces be deleted by the split?

Body:
You passed a string to the split, the input string does not contain that string. I think you wanted to use

/[#\s]{3,}/

like here:

var produktDaten = "##########################################################################MA-KF6###Beckhoff###EL1808    BECK.EL1808###MA-KF7###Beckhoff###EL1808    BECK.EL1808###MA-KF12###Beckhoff###EL1808    BECK.EL1808###MA-KF13###Beckhoff###EL1808    BECK.EL1808###MA-KF14###Beckhoff###EL1808    BECK.EL1808###MA-KF15###Beckhoff###EL1808    BECK.EL1808###MA-KF16###Beckhoff###EL1808    BECK.EL1808###MA-KF19###Beckhoff###EL1808    BECK.EL1808";
console.log(produktDaten.replace(/\x03/g, '').trim().split(/[#\s]{3,}/));

This /[#\s]{3,}/ regex matches 3 or more chars that are either # or whitespace.

NOTE: just removing ' around it won't fix the issue since you are using an unescaped / and quantify it. You actually need to quantify the character class, [#\s].