问:
Date deserializer with local time zome
I'm trying to deserialize a Date object and setting the local Time Zone. I'm getting the date from the server in UTC and my website hosting is in the same time zone, but when I receive the date the time zone from server and my website. However, client can be in another time zone so I need to set the time in client time zone. In order to change the time zone, I saved it in session in a previous request, but when I'm going to deserialize it, the session is null.

I have a Date paramenter in an object

```<code>public class WorkDay implements Serializable {
 private static final long serialVersionUID = 1L;
 private int id;
 @JsonDeserialize(using = CustomJsonDateDeserializer.class)
 private Date date;
</code>```

Then, my deserializer method

```<code>public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Autowired
private HttpSession session;

@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException, JsonProcessingException {

    String dateString = jsonparser.getText();

    @SuppressWarnings("resource")
    long createdate = new Scanner(dateString).useDelimiter("[^0-9]+").nextLong();

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(createdate);

    TimeZone tz = (TimeZone)session.getAttribute("timezone");
    cal.setTimeZone(tz);

    return cal.getTime();
}
</code>```

}

I saved the time zone in session

```<code>@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(TimeZone timezone, Model model) {

    UserAuth user = (UserAuth)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if(user!= null)
    {

        try{
            session.setAttribute("timezone", timezone);
</code>```

I saved before the timezone in session in a previous request, but in this class, session is null. Is there any way I could get data from session in this class?

Thanks!

答:
@Autowired does not work inside the Custom Deserializer class as the instance of that class is created by Jackson and not Spring.

As far as getting the TimeZone is concerned, session is stored on server side and hence, will have server's timezone. So, unless you are setting the "timezone" attribute explicitly with any other value, you can get the default timezone with the below:

```<code>TimeZone defaultTimeZone = TimeZone.getDefault();
</code>```

Title: Date deserializer with local time zome

Body:
I'm trying to deserialize a Date object and setting the local Time Zone. I'm getting the date from the server in UTC and my website hosting is in the same time zone, but when I receive the date the time zone from server and my website. However, client can be in another time zone so I need to set the time in client time zone. In order to change the time zone, I saved it in session in a previous request, but when I'm going to deserialize it, the session is null.

I have a Date paramenter in an object

public class WorkDay implements Serializable {
 private static final long serialVersionUID = 1L;
 private int id;
 @JsonDeserialize(using = CustomJsonDateDeserializer.class)
 private Date date;

Then, my deserializer method

public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Autowired
private HttpSession session;

@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException, JsonProcessingException {

    String dateString = jsonparser.getText();

    @SuppressWarnings("resource")
    long createdate = new Scanner(dateString).useDelimiter("[^0-9]+").nextLong();

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(createdate);

    TimeZone tz = (TimeZone)session.getAttribute("timezone");
    cal.setTimeZone(tz);

    return cal.getTime();
}

}

I saved the time zone in session

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(TimeZone timezone, Model model) {

    UserAuth user = (UserAuth)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if(user!= null)
    {

        try{
            session.setAttribute("timezone", timezone);

I saved before the timezone in session in a previous request, but in this class, session is null. Is there any way I could get data from session in this class?

Thanks!

Body:
@Autowired does not work inside the Custom Deserializer class as the instance of that class is created by Jackson and not Spring.

As far as getting the TimeZone is concerned, session is stored on server side and hence, will have server's timezone. So, unless you are setting the "timezone" attribute explicitly with any other value, you can get the default timezone with the below:

TimeZone defaultTimeZone = TimeZone.getDefault();


来源: stackexchange

问:
Visual bug? Excel-vba AllowEditRange with many areas
When I run this code:

```<code>Sub AerTest()
'aer = allow edit range
Dim c, aerMain As Range

Set aerMain = Range("A1")

For Each c In Range("A1:AI23")
    If c.Value = 1 Then
        Set aerMain = Union(c, aerMain)
    End If
Next c

ActiveSheet.Protection.AllowEditRanges.Add Title:="Test", Range:=aerMain

End Sub
</code>```

I expect under review -> Allow Edit Ranges to find something call "Test" which contains all the cells with a 1 in them, in the relevant range (A1:AI23).

In terms of functionality it seems to work. All cells containing a 1 can be altered when the sheet is locked.

However, as shown below, it does not the correct thing is happening, i.e. it only shows a few areas of the range it should. It appears that the field "Refers to cells" only contains something like

```<code>=$AI$23;$AG$23;$AE$23;$AC$23;$AA$23;$Y$23;$W$23;$U$23;$S$23;$Q$23;$O$23;$M$23;$K$23;$I$23;$G$23;$E$23;$C$23;$A$23;$AI$21;$AG$21;$AE$21;$AC$21;$AA$21;$Y$21;$W$21;$U$21;$S$21;$Q$21;$O$21;$M$21;$K$21;$I$21;$G$21;$E$21;$C$21;$A$21;$AI$19;$AG$19;$AE$19;$AC$19
</code>```

which clearly does not contain all the relevant cells (such as "A1").

If i go the the menu shown below and press OK rather then Cancel, I lose the functionality of having all cells containing a 1 editable when the sheet is locked, and then I will in fact only be able to edit the fields in the this in the field "Refers to cell".

Is this purely a visual bug, or are there other approaches to allow edit ranges that avoid these quirks when dealing with a range with many areas?

答:
I found some documentation from Microsoft re Define and use names in formulas.  The important part says:

Name length    A name can contain up to 255 characters.

As far as Excel is concerned, =$AI$23;$AG$23;$AE$23;$AC$23;$AA$23;$Y$23... is just another range name, and thus is limited to the 255 characters.

Your AllowEditRanges.Add will work, because that is actually working with the range itself and not via the range name, but the name being added will be truncated to the 255 characters.

ContentLicense: CC BY-SA 3.0

Body:
When I run this code:

Sub AerTest()
'aer = allow edit range
Dim c, aerMain As Range

Set aerMain = Range("A1")

For Each c In Range("A1:AI23")
    If c.Value = 1 Then
        Set aerMain = Union(c, aerMain)
    End If
Next c

ActiveSheet.Protection.AllowEditRanges.Add Title:="Test", Range:=aerMain

End Sub

I expect under review -> Allow Edit Ranges to find something call "Test" which contains all the cells with a 1 in them, in the relevant range (A1:AI23).

In terms of functionality it seems to work. All cells containing a 1 can be altered when the sheet is locked.

However, as shown below, it does not the correct thing is happening, i.e. it only shows a few areas of the range it should. It appears that the field "Refers to cells" only contains something like

=$AI$23;$AG$23;$AE$23;$AC$23;$AA$23;$Y$23;$W$23;$U$23;$S$23;$Q$23;$O$23;$M$23;$K$23;$I$23;$G$23;$E$23;$C$23;$A$23;$AI$21;$AG$21;$AE$21;$AC$21;$AA$21;$Y$21;$W$21;$U$21;$S$21;$Q$21;$O$21;$M$21;$K$21;$I$21;$G$21;$E$21;$C$21;$A$21;$AI$19;$AG$19;$AE$19;$AC$19

which clearly does not contain all the relevant cells (such as "A1").

If i go the the menu shown below and press OK rather then Cancel, I lose the functionality of having all cells containing a 1 editable when the sheet is locked, and then I will in fact only be able to edit the fields in the this in the field "Refers to cell".

Is this purely a visual bug, or are there other approaches to allow edit ranges that avoid these quirks when dealing with a range with many areas?


问:
What function receives push notifications in iOS from Firebase Messaging?
A day ago the iPhones I'm using to test out push notifications were receiving push notifications but for some reason today they are not.

When it was working I would call the completion handler to present the notification in this function:

```<code>@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        completionHandler([.alert, .badge, .sound])
    }
</code>```

However, that function doesn't seem to be getting called anymore. The only function I see anything getting printed from is this one:

```<code>extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices while app is in the foreground.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        print(remoteMessage.appData)
    }
}
</code>```

I got all of these functions from the Firebase Send a Notification to an iOS Device docs. All I really want is to be able to receive push notifications from Apples APNs server. I'm getting this line in my console APNs token retrieved: 32 bytes and also the push notifications were working yesterday so I'm not sure why it stopped.

The only thing I suspect made it stop working was that I deleted and reinstalled the app onto the iPhones, other than that I haven't messed with the code in the AppDelegate at all. Can anybody please help me figure out why my push notifications might have stopped being sent?

Note I'm using Firebase Messaging topics to send these out from my cloud function, which I can confirm is sending out the messages correctly as I'm receiving them in the 2nd function above, just not in the first one like it was received in yesterday. I'm using admin.messaging().sendToTopic(pet_Id, payload, options); to send out the notifications.

Here's my full AppDelegate.swift file, if anybody could help me figure it out I'd greatly appreciate it!

答:
I had something similar,

Here is my answer here - Firebase Push Notifs Problem

Here is what could be the problem,

I turned push off and deleted the certs from apple dev center and created them all over again and this made everything work as it should.

"I also had this line of code set to,

```<code>FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.sandbox)
</code>```

I will change it to .prod when I push to the app store."

Body:
A day ago the iPhones I'm using to test out push notifications were receiving push notifications but for some reason today they are not.

When it was working I would call the completion handler to present the notification in this function:

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        completionHandler([.alert, .badge, .sound])
    }

However, that function doesn't seem to be getting called anymore. The only function I see anything getting printed from is this one:

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices while app is in the foreground.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        print(remoteMessage.appData)
    }
}

I got all of these functions from the Firebase Send a Notification to an iOS Device docs. All I really want is to be able to receive push notifications from Apples APNs server. I'm getting this line in my console APNs token retrieved: 32 bytes and also the push notifications were working yesterday so I'm not sure why it stopped.

The only thing I suspect made it stop working was that I deleted and reinstalled the app onto the iPhones, other than that I haven't messed with the code in the AppDelegate at all. Can anybody please help me figure out why my push notifications might have stopped being sent?

Note I'm using Firebase Messaging topics to send these out from my cloud function, which I can confirm is sending out the messages correctly as I'm receiving them in the 2nd function above, just not in the first one like it was received in yesterday. I'm using admin.messaging().sendToTopic(pet_Id, payload, options); to send out the notifications.

Here's my full AppDelegate.swift file, if anybody could help me figure it out I'd greatly appreciate it!

Body:
I had something similar,

Here is my answer here - Firebase Push Notifs Problem

Here is what could be the problem,

I turned push off and deleted the certs from apple dev center and created them all over again and this made everything work as it should.

"I also had this line of code set to,

FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.sandbox)

I will change it to .prod when I push to the app store."


问:
How to run a shell command in a specific folder
I can use this out, err := exec.Command("git", "log").Output() to get an output of the command which will run in the same path as the executable  location.

How do I specify in which folder I want to run the command?

答:
exec.Command() returns you a value of type *exec.Cmd. Cmd is a struct and has a Dir field:

```<code>// Dir specifies the working directory of the command.
// If Dir is the empty string, Run runs the command in the
// calling process's current directory.
Dir string
</code>```

So simply set it before calling Cmd.Output():

```<code>cmd:= exec.Command("git", "log")
cmd.Dir = "your/intended/working/directory"
out, err := cmd.Output()
</code>```

Also note that this is specific to git command; git allows you to pass the path using the -C flag, so you may also do what you want like this:

```<code>out, err := exec.Command("git", "-C", "your/intended/working/directory", "log").
    Output()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
exec.Command() returns you a value of type *exec.Cmd. Cmd is a struct and has a Dir field:

// Dir specifies the working directory of the command.
// If Dir is the empty string, Run runs the command in the
// calling process's current directory.
Dir string

So simply set it before calling Cmd.Output():

cmd:= exec.Command("git", "log")
cmd.Dir = "your/intended/working/directory"
out, err := cmd.Output()

Also note that this is specific to git command; git allows you to pass the path using the -C flag, so you may also do what you want like this:

out, err := exec.Command("git", "-C", "your/intended/working/directory", "log").
    Output()


问:
mysql btree index on InnoDB tables?
Do InnoDB  tables already contain a b tree? Or was i reading something wrong?</p>

答:
innodb tables have a special kind of primary key index called a clustered b-tree index which can make well a well designed innodb table very fast to query.

following resources may be of interest:

http://dev.mysql.com/doc/refman/5.0/en/innodb-index-types.html

http://www.xaprb.com/blog/2006/07/04/how-to-exploit-mysql-index-optimizations/

ContentLicense: CC BY-SA 2.5

Title: mysql btree index on InnoDB tables?


问:
running python code in an external shell using sublimetext?
First of all, I am new to programming.
To run python code in an external shell window, I followed the instructions given on this page
link

My problem is that if I save the python file in any path that contains a folder name with a space, it gives me this error:

C:\Python34\python.exe: can't open file 'C:\Program': [Errno 2] No such file or directory

Does not work:

C:\Program Files\Python Code

Works:

C:\ProgramFiles\PythonCode

could someone help me fix the problem???

Here is the code:

```<code>    import sublime
import sublime_plugin
import subprocess
class PythonRunCommand(sublime_plugin.WindowCommand):
    def run(self):
        command = 'cmd /k "C:\Python34\python.exe" %s' % sublime.active_window().active_view().file_name()
        subprocess.Popen(command)
</code>```

答:
subprocess methods accept a string or a list. Passing as a string is the lazy way: just copy/paste your command line and it works. That is for hardcoded commands, but things get complicated when you introduce parameters known at run-time only, which may contain spaces, etc...

Passing a list is better because you don't need to compose your command and escape spaces by yourself. Pass the parameters as a list so it's done automatically and better that you could do:

```<code>command = ['cmd','/k',r"C:\Python34\python.exe",sublime.active_window().active_view().file_name()]
</code>```

And always use raw strings (r prefix) when passing literal windows paths or you may have some surprises with escape sequences meaning something (linefeed, tab, unicode...)

In this particular case, if file associations are properly set, you only need to pass the python script without any other command prefix:

```<code>command = [sublime.active_window().active_view().file_name()]
</code>```

(you'll need shell=True added to the subprocess command but it's worth it because it avoids to hardcode python path, and makes your plugin portable)

Body:
First of all, I am new to programming.
To run python code in an external shell window, I followed the instructions given on this page
link

My problem is that if I save the python file in any path that contains a folder name with a space, it gives me this error:

C:\Python34\python.exe: can't open file 'C:\Program': [Errno 2] No such file or directory

Does not work:

C:\Program Files\Python Code

Works:

C:\ProgramFiles\PythonCode

could someone help me fix the problem???

Here is the code:

    import sublime
import sublime_plugin
import subprocess
class PythonRunCommand(sublime_plugin.WindowCommand):
    def run(self):
        command = 'cmd /k "C:\Python34\python.exe" %s' % sublime.active_window().active_view().file_name()
        subprocess.Popen(command)

Body:
subprocess methods accept a string or a list. Passing as a string is the lazy way: just copy/paste your command line and it works. That is for hardcoded commands, but things get complicated when you introduce parameters known at run-time only, which may contain spaces, etc...

Passing a list is better because you don't need to compose your command and escape spaces by yourself. Pass the parameters as a list so it's done automatically and better that you could do:

command = ['cmd','/k',r"C:\Python34\python.exe",sublime.active_window().active_view().file_name()]

And always use raw strings (r prefix) when passing literal windows paths or you may have some surprises with escape sequences meaning something (linefeed, tab, unicode...)

In this particular case, if file associations are properly set, you only need to pass the python script without any other command prefix:

command = [sublime.active_window().active_view().file_name()]

(you'll need shell=True added to the subprocess command but it's worth it because it avoids to hardcode python path, and makes your plugin portable)


问:
Django Rest Framework - POST request, "This list may not be empty" when list is not empty?
I'm using Django rest framework to set up my own API and having trouble getting the POST method to work correctly. I use the curl command:

```<code> curl --form "fileupload=@exampleteam.json" 127.0.0.1:8000/teams/ > error.html
</code>```

to hit my api with the json file exampleteam.json formatted like such:

```<code>[{"id":3,"name":"newTeam","members":["mem1", "mem2"],"services_used":["service1"]}]
</code>```

So basically, what I want is to create a new team that has the members mem1 and mem2 and utilizes service 1. newTeam, mem1, mem2, and service1 all exist in my database already.

What I get back is this strange html that tells me there isn't any info in my list, and the database does not reflect that I ever made the request. This is what is piped into error.html:

```<code>{"members":["This list may not be empty."],"services_used":["This list may not be empty."]}
</code>```

This is strange to me, the members list is clearly not empty and neither is the services_used list in my request. I'm reasonably confident that the error is either where I defined my POST method, or is a problem with my models, though after messing with those I still cannot find the issue. Below are both files.

views.py

```<code>@api_view(['GET', 'POST'])
def team_list(request):
    if request.method == 'GET':
        teams = Team.objects.all()
        serializer = TeamSerializer(teams, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        serializer = TeamSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

and the associated models from models.py

```<code>class Team(models.Model):
    name = models.CharField(max_length=32, default="")
    members = models.ManyToManyField('Member')
    services_used = models.ManyToManyField('Service')

    def __str__(self):
        return str(self.name)

class Member(models.Model):
    name = models.CharField(max_length=32, default="")
    services_used = models.ManyToManyField('Service')

    def __str__(self):
        return str(self.name)

class Service(models.Model):
    name = models.CharField(max_length=64, default="")

    def __str__(self):
        return(self.name)
</code>```

and the TeamSerializer class:

```<code>class TeamSerializer(serializers.ModelSerializer):
    class Meta:
        model = Team
        fields = ('id', 'name', 'members','services_used')
</code>```

Why is the POST request not updating the database correctly?

答:
If you're not working with instances as specified by Muj Gabriel's answer you can specify the serializer in your class' serializer with the many=True option, for example (classes might not really make sense, but it's just for example purposes):

```<code>class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book

class ChapterSerializer(serializers.ModelSerializer):
    books = BookSerializer(many=True)  # Allows us to create chapters without specifying book(s) straight away

    class Meta:
        model = Chapter
</code>```

Body:
I'm using Django rest framework to set up my own API and having trouble getting the POST method to work correctly. I use the curl command:

 curl --form "fileupload=@exampleteam.json" 127.0.0.1:8000/teams/ > error.html

to hit my api with the json file exampleteam.json formatted like such:

[{"id":3,"name":"newTeam","members":["mem1", "mem2"],"services_used":["service1"]}]

So basically, what I want is to create a new team that has the members mem1 and mem2 and utilizes service 1. newTeam, mem1, mem2, and service1 all exist in my database already.

What I get back is this strange html that tells me there isn't any info in my list, and the database does not reflect that I ever made the request. This is what is piped into error.html:

{"members":["This list may not be empty."],"services_used":["This list may not be empty."]}

This is strange to me, the members list is clearly not empty and neither is the services_used list in my request. I'm reasonably confident that the error is either where I defined my POST method, or is a problem with my models, though after messing with those I still cannot find the issue. Below are both files.

views.py

@api_view(['GET', 'POST'])
def team_list(request):
    if request.method == 'GET':
        teams = Team.objects.all()
        serializer = TeamSerializer(teams, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        serializer = TeamSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

and the associated models from models.py

class Team(models.Model):
    name = models.CharField(max_length=32, default="")
    members = models.ManyToManyField('Member')
    services_used = models.ManyToManyField('Service')

    def __str__(self):
        return str(self.name)

class Member(models.Model):
    name = models.CharField(max_length=32, default="")
    services_used = models.ManyToManyField('Service')

    def __str__(self):
        return str(self.name)

class Service(models.Model):
    name = models.CharField(max_length=64, default="")

    def __str__(self):
        return(self.name)

and the TeamSerializer class:

class TeamSerializer(serializers.ModelSerializer):
    class Meta:
        model = Team
        fields = ('id', 'name', 'members','services_used')

Why is the POST request not updating the database correctly?

Body:
If you're not working with instances as specified by Muj Gabriel's answer you can specify the serializer in your class' serializer with the many=True option, for example (classes might not really make sense, but it's just for example purposes):

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book

class ChapterSerializer(serializers.ModelSerializer):
    books = BookSerializer(many=True)  # Allows us to create chapters without specifying book(s) straight away

    class Meta:
        model = Chapter


问:
IOS Swift3 card stack overlay
I am using swift3 with Xcode8 to develop an iPhone app. I want to achieve the following effect: There are a set of cards and I can scroll and tap a card to select the card, then the selected card will be will be displayed by itself.

I am quite new in IOS development, what I am thinking is using the collection view, but how to achieve this kind of card overlay effect with collection view?

Or should I use something else? Can anyone give some clue? Thanks!

答:
Have a look at MMCardView, currently supporting Swift 3.

In terms of implementing this, a collection view would be a start - looking deeper into libraries this is the common way of implementation. If you don't want to implement a library, take a look at the libraries files and see how they were implemented and adapt it to the way that you want.

Title: IOS Swift3 card stack overlay


问:
How to change image and text on hover
I am trying to change the image and text on hover and I have got this in codepen but it doesnt seem to be working?

$(".service_1").hover(function() {
  $(".hello").hide();

  $(".text").append("Appended text");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.service_item img {
  position: absolute;
}

.service_item {
  height: 307px;
  width: 700px;
  background-size: cover;
  transition: background-image 0.5s linear;
  -webkit-transition: background-image 0.5s linear;
  float: left;
  position: relative;
}

.service_item:hover {
  transition: background-image 0.5s linear;
  -webkit-transition: background-image 0.5s linear;
}

.serviceimg {
  margin-top: 66px;
  height: 949px;
}

.service_item a {
  height: 50%;
  display: block;
  text-align: center;
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  position: relative;
}

.service_item img {
  position: absolute;
  left: 0px;
  width: 100%;
  height: 300px;
  transition: opacity .5s ease;
}

.service_item img:hover {
  opacity: 0;
}

.service_item span {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  text-align: center;
}</code>```

Hello there

```

Can someone point me to where im going wrong please?

Title: How to change image and text on hover

Body:
I am trying to change the image and text on hover and I have got this in codepen but it doesnt seem to be working?

$(".service_1").hover(function() {
  $(".hello").hide();

  $(".text").append("Appended text");
});

.service_item img {
  position: absolute;
}

.service_item {
  height: 307px;
  width: 700px;
  background-size: cover;
  transition: background-image 0.5s linear;
  -webkit-transition: background-image 0.5s linear;
  float: left;
  position: relative;
}

.service_item:hover {
  transition: background-image 0.5s linear;
  -webkit-transition: background-image 0.5s linear;
}

.serviceimg {
  margin-top: 66px;
  height: 949px;
}

.service_item a {
  height: 50%;
  display: block;
  text-align: center;
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  position: relative;
}

.service_item img {
  position: absolute;
  left: 0px;
  width: 100%;
  height: 300px;
  transition: opacity .5s ease;
}

.service_item img:hover {
  opacity: 0;
}

.service_item span {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  text-align: center;
}

Hello there

Can someone point me to where im going wrong please?

Body:
<a href="#">
<img src="http://www.dummy.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png"
onmouseover="this.src='http://www.dummy.com/icons/fasticon/angry-birds/128/red-bird-icon.png'"
onmouseout="this.src='http://www.dummy.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png'"
border="0" alt=""/></a>


问:
Javascript:: export to text file
```<code><!DOCTYPE html>
<html>

<head>
    <title> </title>
    <meta charset=utf-8>
</head>

<body>

    <table>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
        </tr>
        <tr>
            <td>Line #1</td>
            <td>SLTD</td>
            <td>32</td>
        </tr>
        <tr>
            <td>Line #2</td>
            <td>MKTD</td>
            <td>68</td>
        </tr>
        <tr>
            <td>Line #3</td>
            <td>LRTD</td>
            <td>55</td>
        </tr>
        <tr>
            <td>Line #4</td>
            <td>HAD</td>
            <td>47</td>
        </tr>
    </table>

    <button>Export to text file</button>

    <script>
        var theFirstChilds = document.querySelectorAll('table tr td:first-of-type'), text, i;

        text = "";

        for (i = 0; i < theFirstChilds.length; ++i) {
            text = text + theFirstChilds[i].innerText;
        }

        console.log(text);

        var button = document.getElementsByTagName("button")[0];

        button.addEventListener("click", function() {
            //alert("I want to export the variable text [console.log(text)] to text file");
        });
    </script>

</body>

</html>
</code>```

Everything is working properly... The only thing that left is to export it to a text file...

iow... everything in the variable text would be saved to text file...

Single line solution would be perfect :)

Thanks !

答:
one way would be :

```<code>var saveData = (function () {
var a = document.createElement("a");
// document.body.appendChild(a);
// a.style = "display: none";
return function (data, fileName) {
    var json = JSON.stringify(data),
        blob = new Blob([json], {type: "octet/stream"}),
        url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
};
}());

var data = { x: 42, s: "hello, world", d: new Date() },
    fileName = "my-download.json";

saveData(data, fileName);
</code>```

another would be to use download element

```<code>var download = document.getElementById('download');
download.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(VALUE));
download.setAttribute('download', 'filename.csv');
</code>```

but there are other ways too with difference in browser compatibility.

How to export JavaScript array info to csv (on client side)?

JavaScript: Create and save file

Using a library

Make libraries, not the war. FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it.

If you need to save really large files bigger then the blob's size limitation or don't have enough RAM, then have a look at the more advanced StreamSaver.js that can save data directly to the hard drive asynchronously with the power of the new streams API. That will have support for progress, cancelation and knowing when it's done writing.

The following snippet allow you to generate a file (with any extension) and download it without contact any server :

```<code>var content = "What's up , hello world";
// any kind of extension (.txt,.cpp,.cs,.bat)
var filename = "hello.txt";

var blob = new Blob([content], {
 type: "text/plain;charset=utf-8"
});

saveAs(blob, filename);
</code>```

Title: Javascript:: export to text file

Body:
<!DOCTYPE html>

    <title> </title>
    <meta charset=utf-8>

            A
            B
            C

            Line #1
            SLTD
            32

            Line #2
            MKTD
            68

            Line #3
            LRTD
            55

            Line #4
            HAD
            47

    <button>Export to text file</button>

Everything is working properly... The only thing that left is to export it to a text file...

iow... everything in the variable text would be saved to text file...

Single line solution would be perfect :)

Thanks !

Body:
one way would be :

var saveData = (function () {
var a = document.createElement("a");
// document.body.appendChild(a);
// a.style = "display: none";
return function (data, fileName) {
    var json = JSON.stringify(data),
        blob = new Blob([json], {type: "octet/stream"}),
        url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
};
}());

var data = { x: 42, s: "hello, world", d: new Date() },
    fileName = "my-download.json";

saveData(data, fileName);

another would be to use download element

var download = document.getElementById('download');
download.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(VALUE));
download.setAttribute('download', 'filename.csv');

but there are other ways too with difference in browser compatibility.

How to export JavaScript array info to csv (on client side)?

JavaScript: Create and save file

Using a library

Make libraries, not the war. FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it.

If you need to save really large files bigger then the blob's size limitation or don't have enough RAM, then have a look at the more advanced StreamSaver.js that can save data directly to the hard drive asynchronously with the power of the new streams API. That will have support for progress, cancelation and knowing when it's done writing.

The following snippet allow you to generate a file (with any extension) and download it without contact any server :

var content = "What's up , hello world";
// any kind of extension (.txt,.cpp,.cs,.bat)
var filename = "hello.txt";

var blob = new Blob([content], {
 type: "text/plain;charset=utf-8"
});

saveAs(blob, filename);


问:
Hosting WCF service on azure
I got a wcf service which I'd like to run on azure, but I got several problems:

First: do I choose a web role or a worker role for running the wcf service?

Second: The client uses a call to log into the service, afterwards the service should remember who is logged in (sessions). The problem is, for firewall reasons I probably should use some http-binding. But these seem not to support sessions??

Or do I need AppFabric for sessions (what is AppFabric anyway?)?

Is there a good complete tutorial how to host wcf service?

答:
If you host your WCF service in a Web role, you'll then have all the benefits of IIS (pooling, caching, logging, etc.). You can rely on the WCF Web Role template and simply add a WCF service (which manifests itself as an svc) - and with the new SDK 1.3, you should be able to host a WCF service alongside your website in the same role.

You can also new up a ServiceHost in a worker role. With the worker role, you'll have complete control, but you'll lose the benefits of IIS.

For WCF labs, start with the Azure Platform Training Kit. You'll see labs for:

Hosting WCF in a worker role

Using identity management for WCF security

Using WCF with the service bus

Title: Hosting WCF service on azure


问:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema 2 in Angular V4.0.0
I have updated the webpack package to latest version 2.3.2 and i am using Angular V4.0.0, typescript V2.2.2. While runing 'npm run build' command throwing the following error. And it worked fine for angular2 after updating it is throwing the error</p>

```<code>Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration has an unknown property 'htmlLoader'. These properties are valid:
   object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
   For typos: please correct them.
   For loader options: webpack 2 no longer allows custom properties in configuration.
     Loaders should be updated to allow passing options via loader options in module.rules.
     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
     plugins: [
       new webpack.LoaderOptionsPlugin({
         // test: /\.xxx$/, // may apply this only for some modules
         options: {
           htmlLoader: ...
         }
       })
     ]
</code>```

答:
You should move the html loader

```<code> htmlLoader: {
        minimize: false
    },

plugins: [
  new webpack.LoaderOptionsPlugin({
    options: {
      htmlLoader: {
       minimize: true
      }
    }
  })
]
</code>```

Check out this link

In webpack 2.0 they have stopped support directly loading custom loader.

Body:
I have updated the webpack package to latest version 2.3.2 and i am using Angular V4.0.0, typescript V2.2.2. While runing 'npm run build' command throwing the following error. And it worked fine for angular2 after updating it is throwing the error

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration has an unknown property 'htmlLoader'. These properties are valid:
   object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
   For typos: please correct them.
   For loader options: webpack 2 no longer allows custom properties in configuration.
     Loaders should be updated to allow passing options via loader options in module.rules.
     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
     plugins: [
       new webpack.LoaderOptionsPlugin({
         // test: /\.xxx$/, // may apply this only for some modules
         options: {
           htmlLoader: ...
         }
       })
     ]

Body:
You should move the html loader

 htmlLoader: {
        minimize: false
    },

plugins: [
  new webpack.LoaderOptionsPlugin({
    options: {
      htmlLoader: {
       minimize: true
      }
    }
  })
]

Check out this link

In webpack 2.0 they have stopped support directly loading custom loader.


问:
SQL Duplicates remove
I've a problem of duplicates in tsql. How can I remove?
This is my output:

```<code>  id          name       ref
----------- ---------- --------------
1           John       null
1           John       RE
2           Smith      null
2           Smith      DOS
3           Van        null
4           Sam        CR
5           Bob        null
</code>```

Code:

```<code> SELECT DISTINCT
    u.id,
    u.name,
    c.ref
    FROM users u
    LEFT JOIN con c on c.id=u.id
</code>```

I would like the output to be like this:

```<code>  id          name       ref
----------- ---------- --------------
1           John       RE
2           Smith      DOS
3           Van        null
4           Sam        CR
5           Bob        null
</code>```

This is just an example, I've few of them.

thanks

答:
Please make use of below query:

```<code>    DECLARE @TABLE TABLE
    (id INT, name VARCHAR(10),ref VARCHAR(10))

    INSERT INTO @TABLE VALUES
    (1,'John',null),
    (1,'John','RE'),
    (2,'Smith',null),
    (2,'Smith','DOS'),
    (3,'Van',null),
    (4,'Sam','CR'),
    (5,'Bob',null)

    SELECT id,name,ref FROM
    (
     SELECT
        id,name,ref,RN = ROW_NUMBER() OVER (PARTITION BY id,name ORDER BY ref DESC)
     FROM
        @TABLE
    ) AS A
    WHERE RN < 2
</code>```

You can use this too:

```<code>     SELECT
        u.id,
        u.name,
        MAX(u.ref) as Ref
     FROM
        @TABLE u
     GROUP BY
        u.id,
        u.name
</code>```

Title: SQL Duplicates remove

Body:
I've a problem of duplicates in tsql. How can I remove?
This is my output:

  id          name       ref
----------- ---------- --------------
1           John       null
1           John       RE
2           Smith      null
2           Smith      DOS
3           Van        null
4           Sam        CR
5           Bob        null

Code:

 SELECT DISTINCT
    u.id,
    u.name,
    c.ref
    FROM users u
    LEFT JOIN con c on c.id=u.id

I would like the output to be like this:

  id          name       ref
----------- ---------- --------------
1           John       RE
2           Smith      DOS
3           Van        null
4           Sam        CR
5           Bob        null

This is just an example, I've few of them.

thanks

Body:
Please make use of below query:

    DECLARE @TABLE TABLE
    (id INT, name VARCHAR(10),ref VARCHAR(10))

    INSERT INTO @TABLE VALUES
    (1,'John',null),
    (1,'John','RE'),
    (2,'Smith',null),
    (2,'Smith','DOS'),
    (3,'Van',null),
    (4,'Sam','CR'),
    (5,'Bob',null)

    SELECT id,name,ref FROM
    (
     SELECT
        id,name,ref,RN = ROW_NUMBER() OVER (PARTITION BY id,name ORDER BY ref DESC)
     FROM
        @TABLE
    ) AS A
    WHERE RN < 2

You can use this too:

     SELECT
        u.id,
        u.name,
        MAX(u.ref) as Ref
     FROM
        @TABLE u
     GROUP BY
        u.id,
        u.name


问:
How can I run an external program from C and parse its output?
I've got a utility that outputs a list of files required by a game.  How can I run that utility within a C program and grab its output so I can act on it within the same program?

UPDATE: Good call on the lack of information.  The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux.  Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout).

答: In Linux and OS X, popen() really is your best bet, as dmckee pointed out, since both OSs support that call. In Windows, this should help: http://msdn.microsoft.com/en-us/library/ms682499.aspx

OwnerDisplayName: Trancecoder


问:
How can I take more control in ASP.NET?
I'm trying to build a very, very simple "micro-webapp" which I suspect will be of interest to a few Stack Overflow'rs if I ever get it done. I'm hosting it on my C# in Depth site, which is vanilla ASP.NET 3.5 (i.e. not MVC).

The flow is very simple:

If a user enters the app with a URL which doesn't specify all the parameters (or if any of them are invalid) I want to just display the user input controls. (There are only two.)

If a user enters the app with a URL which does have all the required parameters, I want to display the results and the input controls (so they can change the parameters)

Here are my self-imposed requirements (mixture of design and implementation):

I want the submission to use GET rather than POST, mostly so users can bookmark the page easily.

I don't want the URL to end up looking silly after submission, with extraneous bits and pieces on it. Just the main URL and the real parameters please.

Ideally I'd like to avoid requiring JavaScript at all. There's no good reason for it in this app.

I want to be able to access the controls during render time and set values etc. In particular, I want to be able to set the default values of the controls to the parameter values passed in, if ASP.NET can't do this automatically for me (within the other restrictions).

I'm happy to do all the parameter validation myself, and I don't need much in the way of server side events. It's really simple to set everything on page load instead of attaching events to buttons etc.

Most of this is okay, but I haven't found any way of completely removing the viewstate and keeping the rest of the useful functionality. Using the post from this blog post I've managed to avoid getting any actual value for the viewstate - but it still ends up as a parameter on the URL, which looks really ugly.

If I make it a plain HTML form instead of an ASP.NET form (i.e. take out runat="server") then I don't get any magic viewstate - but then I can't access the controls programmatically.

I could do all of this by ignoring most of ASP.NET and building up an XML document with LINQ to XML, and implementing IHttpHandler. That feels a bit low level though.

I realise that my problems could be solved by either relaxing my constraints (e.g. using POST and not caring about the surplus parameter) or by using ASP.NET MVC, but are my requirements really unreasonable?

Maybe ASP.NET just doesn't scale down to this sort of app? There's a very likely alternative though: I'm just being stupid, and there's a perfectly simple way of doing it that I just haven't found.

Any thoughts, anyone? (Cue comments of how the mighty are fallen, etc. That's fine - I hope I've never claimed to be an ASP.NET expert, as the truth is quite the opposite...)

答:
This solution will give you programmatic access to the controls in their entirety including all attributes on the controls. Also, only the text box values will appear in the URL upon submission so your GET request URL will be more "meaningful"

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JonSkeetForm.aspx.cs" Inherits="JonSkeetForm" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Jon Skeet's Form Page</title>
</head>
<body>
    <form action="JonSkeetForm.aspx" method="get">
    <div>
        <input type="text" ID="text1" runat="server" />
        <input type="text" ID="text2" runat="server" />
        <button type="submit">Submit</button>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <div>Some text</div>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>
</code>```

Then in your code-behind you can do everything you need on PageLoad

```<code>public partial class JonSkeetForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        text1.Value = Request.QueryString[text1.ClientID];
        text2.Value = Request.QueryString[text2.ClientID];
    }
}
</code>```

If you don't want a form that has runat="server", then you should use HTML controls. It's easier to work with for your purposes. Just use regular HTML tags and put runat="server" and give them an ID. Then you can access them programmatically and code without a ViewState.

The only downside is that you won't have access to many of the "helpful" ASP.NET server controls like GridViews. I included a Repeater in my example because I'm assuming that you want to have the fields on the same page as the results and (to my knowledge) a Repeater is the only DataBound control that will run without a runat="server" attribute in the Form tag.

OwnerDisplayName: Jon Skeet

Title: How can I take more control in ASP.NET?

LastEditorDisplayName: Jon Skeet

Body:
This solution will give you programmatic access to the controls in their entirety including all attributes on the controls. Also, only the text box values will appear in the URL upon submission so your GET request URL will be more "meaningful"

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JonSkeetForm.aspx.cs" Inherits="JonSkeetForm" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Jon Skeet's Form Page</title>
</head>
<body>
    <form action="JonSkeetForm.aspx" method="get">
    <div>
        <input type="text" ID="text1" runat="server" />
        <input type="text" ID="text2" runat="server" />
        <button type="submit">Submit</button>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <div>Some text</div>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

Then in your code-behind you can do everything you need on PageLoad

public partial class JonSkeetForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        text1.Value = Request.QueryString[text1.ClientID];
        text2.Value = Request.QueryString[text2.ClientID];
    }
}

If you don't want a form that has runat="server", then you should use HTML controls. It's easier to work with for your purposes. Just use regular HTML tags and put runat="server" and give them an ID. Then you can access them programmatically and code without a ViewState.

The only downside is that you won't have access to many of the "helpful" ASP.NET server controls like GridViews. I included a Repeater in my example because I'm assuming that you want to have the fields on the same page as the results and (to my knowledge) a Repeater is the only DataBound control that will run without a runat="server" attribute in the Form tag.

OwnerDisplayName: Dan

LastEditorDisplayName: DanHerbert


问:
WordPress, removing comments block programmatically
I want to remove Word Press comment block from specified 'n' posts. These posts are generated dynamically and don't want comment block</p>

答:
Are you using wp_insert_post to generate the posts? If so, set the option "comment_status" to "closed" when inserting.

To change the status on an existing post, use wp_update_post; you'll only need to send in the ID and the comment_status options to close (or open) comments.


问:
DoS attack from google ip range
I believe I've been attacked with multiples request (5/sec all day long) from google ip range (66.249.65.* - maybe a ip spoofing??). This requests have googlebot signature (Googlebot/2.1; +http://www.google.com/bot.html) on http header, but it try to get an old url (I desactivate it, cause it have been consume a lot of cpu/$). If I put this ip range on black list, I block the legit googlebot too :(  .

And the irony: My app (http://expoonews.com) is hosted by google app engine service!

How can I stop this behavior without block google bot?

Below a sample of my log to better understand.

```<code> A 2014-11-25 19:41:19.145 404 234 B 10ms /AddPageAction?url=http%3A%2F%2Flincoln.pioneer.kohalibrary.com%2Fcgi-bin%2Fkoha%2Fopac-search.pl%3Fidx%3Disbn%26q%3D1842172131%26do%3DSearch
66.249.65.82 - - [25/Nov/2014:13:41:19 -0800] "GET /AddPageAction?url=http%3A%2F%2Flincoln.pioneer.kohalibrary.com%2Fcgi-bin%2Fkoha%2Fopac-search.pl%3Fidx%3Disbn%26q%3D1842172131%26do%3DSearch HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=10 cpu_ms=0 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:19.550 404 234 B 11ms /AddPageAction?url=http%3A%2F%2Fwww.dnevniavaz.ba%2Fkultura%2Ffilm%2Fprica-o-hapsenju-ratnog-zlocinca
66.249.65.86 - - [25/Nov/2014:13:41:19 -0800] "GET /AddPageAction?url=http%3A%2F%2Fwww.dnevniavaz.ba%2Fkultura%2Ffilm%2Fprica-o-hapsenju-ratnog-zlocinca HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=11 cpu_ms=23 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:19.956 404 234 B 12ms /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FNewcastle_Local_Municipality
66.249.65.78 - - [25/Nov/2014:13:41:19 -0800] "GET /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FNewcastle_Local_Municipality HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=12 cpu_ms=0 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:20.426 404 234 B 10ms /AddPageAction?url=http%3A%2F%2Ftools.wmflabs.org%2Fgeohack%2Fgeohack.php%3Fpagename%3DRio_Grande_County%252C_Colorado%26params%3D37.61_N_-106.39_E_type%3Aadm2nd_region%3AUS-CO_source%3AUScensus1990
66.249.65.86 - - [25/Nov/2014:13:41:20 -0800] "GET /AddPageAction?url=http%3A%2F%2Ftools.wmflabs.org%2Fgeohack%2Fgeohack.php%3Fpagename%3DRio_Grande_County%252C_Colorado%26params%3D37.61_N_-106.39_E_type%3Aadm2nd_region%3AUS-CO_source%3AUScensus1990 HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=10 cpu_ms=23 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:20.763 404 234 B 11ms /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2F%23cite_ref-Istanbul_43-1
66.249.65.86 - - [25/Nov/2014:13:41:20 -0800] "GET /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2F%23cite_ref-Istanbul_43-1 HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=11 cpu_ms=0 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:21.166 404 234 B 10ms /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Findex.php%3Ftitle%3DHMAS%2520Pirie%26action%3Dhistory
66.249.65.86 - - [25/Nov/2014:13:41:21 -0800] "GET /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Findex.php%3Ftitle%3DHMAS%2520Pirie%26action%3Dhistory HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=10 cpu_ms=0 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:21.571 404 234 B 11ms /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Findex.php%3Ftitle%3DUniversity_of_Engineering_and_Technology_Taxila_Chakwal_Campus_University_of_Engineering_and_Technology_Taxila_Chakwal_Campus%26action%3Dedit%26redlink%3D1
66.249.65.78 - - [25/Nov/2014:13:41:21 -0800] "GET /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Findex.php%3Ftitle%3DUniversity_of_Engineering_and_Technology_Taxila_Chakwal_Campus_University_of_Engineering_and_Technology_Taxila_Chakwal_Campus%26action%3Dedit%26redlink%3D1 HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=11 cpu_ms=23 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16
</code>```

答: This suspicious function related googleBot web crawling on your URL, If you’ve recently added or made changes to a page on your site, you can ask Google to (re)index it using the Fetch as Google tool.</p>

Title: DoS attack from google ip range

Body:
I believe I've been attacked with multiples request (5/sec all day long) from google ip range (66.249.65.* - maybe a ip spoofing??). This requests have googlebot signature (Googlebot/2.1; +http://www.google.com/bot.html) on http header, but it try to get an old url (I desactivate it, cause it have been consume a lot of cpu/$). If I put this ip range on black list, I block the legit googlebot too :(  .

And the irony: My app (http://expoonews.com) is hosted by google app engine service!

How can I stop this behavior without block google bot?

Below a sample of my log to better understand.

 A 2014-11-25 19:41:19.145 404 234 B 10ms /AddPageAction?url=http%3A%2F%2Flincoln.pioneer.kohalibrary.com%2Fcgi-bin%2Fkoha%2Fopac-search.pl%3Fidx%3Disbn%26q%3D1842172131%26do%3DSearch
66.249.65.82 - - [25/Nov/2014:13:41:19 -0800] "GET /AddPageAction?url=http%3A%2F%2Flincoln.pioneer.kohalibrary.com%2Fcgi-bin%2Fkoha%2Fopac-search.pl%3Fidx%3Disbn%26q%3D1842172131%26do%3DSearch HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=10 cpu_ms=0 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:19.550 404 234 B 11ms /AddPageAction?url=http%3A%2F%2Fwww.dnevniavaz.ba%2Fkultura%2Ffilm%2Fprica-o-hapsenju-ratnog-zlocinca
66.249.65.86 - - [25/Nov/2014:13:41:19 -0800] "GET /AddPageAction?url=http%3A%2F%2Fwww.dnevniavaz.ba%2Fkultura%2Ffilm%2Fprica-o-hapsenju-ratnog-zlocinca HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=11 cpu_ms=23 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:19.956 404 234 B 12ms /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FNewcastle_Local_Municipality
66.249.65.78 - - [25/Nov/2014:13:41:19 -0800] "GET /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FNewcastle_Local_Municipality HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=12 cpu_ms=0 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:20.426 404 234 B 10ms /AddPageAction?url=http%3A%2F%2Ftools.wmflabs.org%2Fgeohack%2Fgeohack.php%3Fpagename%3DRio_Grande_County%252C_Colorado%26params%3D37.61_N_-106.39_E_type%3Aadm2nd_region%3AUS-CO_source%3AUScensus1990
66.249.65.86 - - [25/Nov/2014:13:41:20 -0800] "GET /AddPageAction?url=http%3A%2F%2Ftools.wmflabs.org%2Fgeohack%2Fgeohack.php%3Fpagename%3DRio_Grande_County%252C_Colorado%26params%3D37.61_N_-106.39_E_type%3Aadm2nd_region%3AUS-CO_source%3AUScensus1990 HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=10 cpu_ms=23 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:20.763 404 234 B 11ms /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2F%23cite_ref-Istanbul_43-1
66.249.65.86 - - [25/Nov/2014:13:41:20 -0800] "GET /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2F%23cite_ref-Istanbul_43-1 HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=11 cpu_ms=0 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:21.166 404 234 B 10ms /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Findex.php%3Ftitle%3DHMAS%2520Pirie%26action%3Dhistory
66.249.65.86 - - [25/Nov/2014:13:41:21 -0800] "GET /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Findex.php%3Ftitle%3DHMAS%2520Pirie%26action%3Dhistory HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=10 cpu_ms=0 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16

 A 2014-11-25 19:41:21.571 404 234 B 11ms /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Findex.php%3Ftitle%3DUniversity_of_Engineering_and_Technology_Taxila_Chakwal_Campus_University_of_Engineering_and_Technology_Taxila_Chakwal_Campus%26action%3Dedit%26redlink%3D1
66.249.65.78 - - [25/Nov/2014:13:41:21 -0800] "GET /AddPageAction?url=http%3A%2F%2Fen.wikipedia.org%2Fw%2Findex.php%3Ftitle%3DUniversity_of_Engineering_and_Technology_Taxila_Chakwal_Campus_University_of_Engineering_and_Technology_Taxila_Chakwal_Campus%26action%3Dedit%26redlink%3D1 HTTP/1.1" 404 234 - "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "expoonews.com" ms=11 cpu_ms=23 cpm_usd=0.000026 instance=00c61b117c8ad4ca005d37349157867d41adaf app_engine_release=1.9.16


问:
Error to access property from a library
I have a class that imports another one, and I'm trying to access a property of this class, but I'm getting an error telling me that the value has no member. What can I do?

The errors occur in self.cachedImageView

Class of the lib:

```<code> #import "JSQPhotoMediaItem.h"

 @interface JSQPhotoMediaItem ()

 @property (strong, nonatomic) UIImageView *cachedImageView;

 @end

 @implementation JSQPhotoMediaItem
</code>```

and the methods to implementation go on.

My Class trying to access cachedImageView

```<code> override func mediaView() -> UIView? {

    if !self.hasFile {
        return nil
    }

    if self.cachedImageView == nil {
        let size = self.mediaViewDisplaySize()

        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let lightGrayColor = UIColor.jsq_messageBubbleLightGray()
        imageView.backgroundColor = UIColor.jsq_messageBubbleLightGray()
        imageView.image = UIImage(named: "file_placeholder")?.jsq_imageMasked(with: lightGrayColor.jsq_colorByDarkeningColor(withValue: 0.4))
        imageView.contentMode = UIViewContentMode.center

        let RightMargin = CGFloat(10)
        let BottomMargin = CGFloat(20)

        self.label.frame = CGRect(x: 0, y: 0, width: imageView.frame.width / 2, height: 20)

        let point = CGPoint(x: 1.5 * imageView.center.x - RightMargin, y: imageView.frame.height - BottomMargin)
        self.label.center = imageView.convert(point, from: imageView.superview)
        self.label.textColor = UIColor.lightGray
        self.label.textAlignment = NSTextAlignment.right
        self.label.font = UIFont(name: "Helvetica", size: 14.0)
        imageView.addSubview(label)

        JSQMessagesMediaViewBubbleImageMasker.applyBubbleImageMask(toMediaView: imageView, isOutgoing: self.appliesMediaViewMaskAsOutgoing)

        self.cachedImageView = imageView
    }

    return self.cachedImageView
}
</code>```

答: The reason is because you are making you property in .m file rather then .h file. The .m file in objective c is private. If you want to make something public and accessible outside the class, declare it in .h file. It will work for sure. If this works, don't forget to accept the answer please.</p>

Title: Error to access property from a library

Body:
I have a class that imports another one, and I'm trying to access a property of this class, but I'm getting an error telling me that the value has no member. What can I do?

The errors occur in self.cachedImageView

Class of the lib:

 #import "JSQPhotoMediaItem.h"

 @interface JSQPhotoMediaItem ()

 @property (strong, nonatomic) UIImageView *cachedImageView;

 @end

 @implementation JSQPhotoMediaItem

and the methods to implementation go on.

My Class trying to access cachedImageView

 override func mediaView() -> UIView? {

    if !self.hasFile {
        return nil
    }

    if self.cachedImageView == nil {
        let size = self.mediaViewDisplaySize()

        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let lightGrayColor = UIColor.jsq_messageBubbleLightGray()
        imageView.backgroundColor = UIColor.jsq_messageBubbleLightGray()
        imageView.image = UIImage(named: "file_placeholder")?.jsq_imageMasked(with: lightGrayColor.jsq_colorByDarkeningColor(withValue: 0.4))
        imageView.contentMode = UIViewContentMode.center

        let RightMargin = CGFloat(10)
        let BottomMargin = CGFloat(20)

        self.label.frame = CGRect(x: 0, y: 0, width: imageView.frame.width / 2, height: 20)

        let point = CGPoint(x: 1.5 * imageView.center.x - RightMargin, y: imageView.frame.height - BottomMargin)
        self.label.center = imageView.convert(point, from: imageView.superview)
        self.label.textColor = UIColor.lightGray
        self.label.textAlignment = NSTextAlignment.right
        self.label.font = UIFont(name: "Helvetica", size: 14.0)
        imageView.addSubview(label)

        JSQMessagesMediaViewBubbleImageMasker.applyBubbleImageMask(toMediaView: imageView, isOutgoing: self.appliesMediaViewMaskAsOutgoing)

        self.cachedImageView = imageView
    }

    return self.cachedImageView
}


问:
I want to place images over a div that has a specific background
I want to create a div (100% wide and height auto). It will have this background image

And i want to place cars over this div.

The positions of the cars will be determined by the API.

The end result will be something like this.

Is is possible to achieve? Please guide me if it is possible. Thankyou.

答:
You can position the cars with position: absolute;:

```<code><div class="container">
 <img src="img/car.png" class="car car-1">
 <img src="img/car.png" class="car car-2">
</div>
</code>```

CSS:

```<code>.container {
  position: relative;
  background: url(img/parking.png) no-repeat top left / 100% auto;
  width: ...; height: ...;
}
.car {
  position: absolute;
}
.car-1 {
  top: ...; left: ...;
}
.car-2 {
  top: ...; left: ...;
}
</code>```

Body:
You can position the cars with position: absolute;:

<div class="container">
 <img src="img/car.png" class="car car-1">
 <img src="img/car.png" class="car car-2">
</div>

CSS:

.container {
  position: relative;
  background: url(img/parking.png) no-repeat top left / 100% auto;
  width: ...; height: ...;
}
.car {
  position: absolute;
}
.car-1 {
  top: ...; left: ...;
}
.car-2 {
  top: ...; left: ...;
}


问:
PHP - Updating or Creating Multi-Dimensional Arrays
In my code I am checking if two variables are false. If both are false, then I want to update an array called responseArray with the value. I am unable to figure out how to update the array twice without overwriting the value if both variables are false. This is being used to capture if username and email address already registered.

Here is the code:

```<code>if($usernameAvailable == false)
    {
      /*Update validation error array that username taken*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Username", "Username Already Taken");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Username"=>"Username Already Taken")), "requestSuccessful"=>false);
      }
    }

    if($emailAvailable == false)
    {
      /*Update validation error array that Email already registered*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Email", "Email Already Registered");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Email"=>"Email Already Registered")), "requestSuccessful"=>false);
      }
    }
</code>```

What I am getting when I enter both username and email that deliver a false on both is the following output:

{"ErrorArray":{"Validation":{"Username":"Username Already
  Taken"}},"requestSuccessful":false}

while it should also include the email item in the Validation array above because that also is false. This is exactly what I want to have as an output in this scenario:

{"ErrorArray":{"Validation":{"Username":"Username Already Taken",
  "Email":"Email already registered"}},"requestSuccessful":false}

Here is the code I use for the function array_push_assoc() just in case:

```<code>function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
  }
</code>```

答:
Your array push method returns a copy of the array passed to it, it has no effect on the original array $responseArray.

To fix that change your method to take a reference to the array and make the changes in place:

```<code>function array_push_assoc_inplace(&$array, $key, $value)
{
    $array[$key] = $value;
}
</code>```

However, most of the code seems unnecessary, you could simply use the following for the same result:

```<code>if($usernameAvailable == false){
    $responseArray['ErrorArray']['Validation']['Username']='Username Already Taken';
}
if($emailAvailable == false){
    $responseArray['ErrorArray']['Validation']['Email']='Email Already Registered';
}
</code>```

Body:
In my code I am checking if two variables are false. If both are false, then I want to update an array called responseArray with the value. I am unable to figure out how to update the array twice without overwriting the value if both variables are false. This is being used to capture if username and email address already registered.

Here is the code:

if($usernameAvailable == false)
    {
      /*Update validation error array that username taken*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Username", "Username Already Taken");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Username"=>"Username Already Taken")), "requestSuccessful"=>false);
      }
    }

    if($emailAvailable == false)
    {
      /*Update validation error array that Email already registered*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Email", "Email Already Registered");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Email"=>"Email Already Registered")), "requestSuccessful"=>false);
      }
    }

What I am getting when I enter both username and email that deliver a false on both is the following output:

{"ErrorArray":{"Validation":{"Username":"Username Already
  Taken"}},"requestSuccessful":false}

while it should also include the email item in the Validation array above because that also is false. This is exactly what I want to have as an output in this scenario:

{"ErrorArray":{"Validation":{"Username":"Username Already Taken",
  "Email":"Email already registered"}},"requestSuccessful":false}

Here is the code I use for the function array_push_assoc() just in case:

function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
  }

Body:
Your array push method returns a copy of the array passed to it, it has no effect on the original array $responseArray.

To fix that change your method to take a reference to the array and make the changes in place:

function array_push_assoc_inplace(&$array, $key, $value)
{
    $array[$key] = $value;
}

However, most of the code seems unnecessary, you could simply use the following for the same result:

if($usernameAvailable == false){
    $responseArray['ErrorArray']['Validation']['Username']='Username Already Taken';
}
if($emailAvailable == false){
    $responseArray['ErrorArray']['Validation']['Email']='Email Already Registered';
}


问:
Making DataFrame in pandas having diffence size of Lists in List
i have data like this

```<code>genre_list
Out[7]:
0                    [Action, Adventure, Fantasy, Sci-Fi]
1                            [Action, Adventure, Fantasy]
2                           [Action, Adventure, Thriller]
3                                      [Action, Thriller]
4                                           [Documentary]
5                             [Action, Adventure, Sci-Fi]
6                            [Action, Adventure, Romance]
7       [Adventure, Animation, Comedy, Family, Fantasy...
8                             [Action, Adventure, Sci-Fi]
9                   [Adventure, Family, Fantasy, Mystery]
10                            [Action, Adventure, Sci-Fi]
11                            [Action, Adventure, Sci-Fi]
</code>```

i coded to make Dataframe with difference size of list

```<code>genre_df = pd.DataFrame()
for i in range(len(genre_list)):
    genre_df = genre_df.append(pd.DataFrame(genre_list[i]).T)
</code>```

get this

```<code>genre_df.head()
Out[9]:
             0          1         2       3    4    5    6    7
0       Action  Adventure   Fantasy  Sci-Fi  NaN  NaN  NaN  NaN
0       Action  Adventure   Fantasy     NaN  NaN  NaN  NaN  NaN
0       Action  Adventure  Thriller     NaN  NaN  NaN  NaN  NaN
0       Action   Thriller       NaN     NaN  NaN  NaN  NaN  NaN
0  Documentary        NaN       NaN     NaN  NaN  NaN  NaN  NaN
</code>```

is there a simple way to get Dataframe ....?

答:
A numpy approach

```<code>lol = s.values.tolist()

lens = [len(l) for l in lol]

i = np.arange(len(lens)).repeat(lens)
j = np.concatenate([np.arange(l) for l in lens])
v = np.concatenate(lol)

pd.Series(v, [i, j]).unstack()

              0          1         2        3        4
0        Action  Adventure   Fantasy   Sci-Fi     None
1        Action  Adventure   Fantasy     None     None
2        Action  Adventure  Thriller     None     None
3        Action   Thriller      None     None     None
4   Documentary       None      None     None     None
5        Action  Adventure    Sci-Fi     None     None
6        Action  Adventure   Romance     None     None
7     Adventure  Animation    Comedy   Family  Fantasy
8        Action  Adventure    Sci-Fi     None     None
9     Adventure     Family   Fantasy  Mystery     None
10       Action  Adventure    Sci-Fi     None     None
11       Action  Adventure    Sci-Fi     None     None
</code>```

Body:
i have data like this

genre_list
Out[7]:
0                    [Action, Adventure, Fantasy, Sci-Fi]
1                            [Action, Adventure, Fantasy]
2                           [Action, Adventure, Thriller]
3                                      [Action, Thriller]
4                                           [Documentary]
5                             [Action, Adventure, Sci-Fi]
6                            [Action, Adventure, Romance]
7       [Adventure, Animation, Comedy, Family, Fantasy...
8                             [Action, Adventure, Sci-Fi]
9                   [Adventure, Family, Fantasy, Mystery]
10                            [Action, Adventure, Sci-Fi]
11                            [Action, Adventure, Sci-Fi]

i coded to make Dataframe with difference size of list

genre_df = pd.DataFrame()
for i in range(len(genre_list)):
    genre_df = genre_df.append(pd.DataFrame(genre_list[i]).T)

get this

genre_df.head()
Out[9]:
             0          1         2       3    4    5    6    7
0       Action  Adventure   Fantasy  Sci-Fi  NaN  NaN  NaN  NaN
0       Action  Adventure   Fantasy     NaN  NaN  NaN  NaN  NaN
0       Action  Adventure  Thriller     NaN  NaN  NaN  NaN  NaN
0       Action   Thriller       NaN     NaN  NaN  NaN  NaN  NaN
0  Documentary        NaN       NaN     NaN  NaN  NaN  NaN  NaN

is there a simple way to get Dataframe ....?

Body:
A numpy approach

lol = s.values.tolist()

lens = [len(l) for l in lol]

i = np.arange(len(lens)).repeat(lens)
j = np.concatenate([np.arange(l) for l in lens])
v = np.concatenate(lol)

pd.Series(v, [i, j]).unstack()

              0          1         2        3        4
0        Action  Adventure   Fantasy   Sci-Fi     None
1        Action  Adventure   Fantasy     None     None
2        Action  Adventure  Thriller     None     None
3        Action   Thriller      None     None     None
4   Documentary       None      None     None     None
5        Action  Adventure    Sci-Fi     None     None
6        Action  Adventure   Romance     None     None
7     Adventure  Animation    Comedy   Family  Fantasy
8        Action  Adventure    Sci-Fi     None     None
9     Adventure     Family   Fantasy  Mystery     None
10       Action  Adventure    Sci-Fi     None     None
11       Action  Adventure    Sci-Fi     None     None


问:
How to add images on second row after button click if first row is filled
I want to add images on button click in a row wise manner and if first row is filled then it should starts with next row .

I have defined scroll view horizontally with linear layout and it is adding horizontally but I want that the image should be added in next row if first row is already full, then it should starts with second row if second row has full then it should starts with third row and so on .

How can i do this ?

```<code>package neeraj.com.images;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
    LinearLayout linearLayout1;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);

    }

    public void onClick(View v){

        ImageView image = new ImageView(MainActivity.this);
            image.setBackgroundResource(R.mipmap.ic_launcher);
        linearLayout1.addView(image);

    }

}
</code>```

xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Button" />

    <HorizontalScrollView
        android:id="@+id/hsv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:fillViewport="true"
        android:measureAllChildren="false"
        android:scrollbars="none" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </HorizontalScrollView>

</LinearLayout>
</code>```

答:
I hope this might help, use Predicate Layout as your wrapper and add images to it dynamically.

Predicate Layout will automatically move image into second row when first row is filled.

Download the PredicateLayout.java file and paste it in your project.

Usage

```<code> <PredicateLayout
            android:id="@+id/image_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp">
        </PredicateLayout>
</code>```

Java

```<code>predicateLayout = (PredicateLayout) findViewById(R.id.image_container);
predicateLayout.addView(imageView); // add images on click
</code>```

Body:
I want to add images on button click in a row wise manner and if first row is filled then it should starts with next row .

I have defined scroll view horizontally with linear layout and it is adding horizontally but I want that the image should be added in next row if first row is already full, then it should starts with second row if second row has full then it should starts with third row and so on .

How can i do this ?

package neeraj.com.images;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
    LinearLayout linearLayout1;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);

    }

    public void onClick(View v){

        ImageView image = new ImageView(MainActivity.this);
            image.setBackgroundResource(R.mipmap.ic_launcher);
        linearLayout1.addView(image);

    }

}

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Button" />

    <HorizontalScrollView
        android:id="@+id/hsv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:fillViewport="true"
        android:measureAllChildren="false"
        android:scrollbars="none" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </HorizontalScrollView>

</LinearLayout>

Body:
I hope this might help, use Predicate Layout as your wrapper and add images to it dynamically.

Predicate Layout will automatically move image into second row when first row is filled.

Download the PredicateLayout.java file and paste it in your project.

Usage

 <PredicateLayout
            android:id="@+id/image_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp">
        </PredicateLayout>

Java

predicateLayout = (PredicateLayout) findViewById(R.id.image_container);
predicateLayout.addView(imageView); // add images on click


问:
Synchronized unordered_map in C++
I am using unordered_map from Boost. Are there any synchronized version of unordered_map? This is because I have quite a large number of unordered_map and manually synchronizing it using lock would be very messy.

Thanks.

答: Intel's Thread Building Blocks library has a class tbb::concurrent_hash_map that is an unordered map, allowing concurrent access. Internally it is implemented using a fine-grained locking scheme, but the basic outcome is that you can access it without race conditions.

Title: Synchronized unordered_map in C++


问:
Appcelerator not detecting android sdk api
When I attempt building a android distribution of my app through the appcelerator CLI, I get the following error: [ERROR] Target Android SDK API 23 is not installed.

I have installed android sdk api 23 but when I run appc ti info -t android it appears that Titanium is not recognizing the installed targets.

```
Appcelerator Command-Line Interface, version 6.0.0
Copyright (c) 2014-2017, Appcelerator, Inc.  All Rights Reserved.
Android SDK
  Android Executable          = /Users/Shared/Jenkins/Library/Android/sdk/tools/android
  ADB Executable              = /Users/Shared/Jenkins/Library/Android/sdk/platform-tools/adb
  SDK Path                    = /Users/Shared/Jenkins/Library/Android/sdk
Android NDK
  NDK Path                    = /Users/Shared/Jenkins/Library/Android/sdk/ndk-bundle
  NDK Version                 = 14.1.3816874
Android Platforms
  None
Android Add-Ons
  None
Android Emulators
  None
Genymotion Emulators
  None
Connected Android Devices
  None
Issues
  No issues detected! Your development environment should be working perfectly!
```

Output of sdkmanager --list

```
devbuild1:bin jenkins$ ./sdkmanager --list
Warning: File /Users/Shared/Jenkins/.android/repositories.cfg could not be loaded.
Installed packages:
  Path                              | Version      | Description                    | Location
  -------                           | -------      | -------                        | -------
  add-ons;addon-g..._apis-google-15 | 3            | Google APIs                    | add-ons/addon-g...apis-google-15/
  add-ons;addon-g..._apis-google-16 | 4            | Google APIs                    | add-ons/addon-g...apis-google-16/
  add-ons;addon-g..._apis-google-17 | 4            | Google APIs                    | add-ons/addon-g...apis-google-17/
  add-ons;addon-g..._apis-google-18 | 4            | Google APIs                    | add-ons/addon-g...apis-google-18/
  add-ons;addon-g..._apis-google-19 | 20           | Google APIs                    | add-ons/addon-g...apis-google-19/
  add-ons;addon-g..._apis-google-21 | 1            | Google APIs                    | add-ons/addon-g...apis-google-21/
  add-ons;addon-g..._apis-google-22 | 1            | Google APIs                    | add-ons/addon-g...apis-google-22/
  add-ons;addon-g..._apis-google-23 | 1            | Google APIs                    | add-ons/addon-g...apis-google-23/
  add-ons;addon-g..._apis-google-24 | 1            | Google APIs                    | add-ons/addon-g...apis-google-24/
  build-tools;25.0.2                | 25.0.2       | Android SDK Build-Tools 25.0.2 | build-tools/25.0.2/
  emulator                          | 26.0.0       | Android Emulator               | emulator/
  extras;android;m2repository       | 47.0.0       | Android Support Repository     | extras/android/m2repository/
  extras;google;m2repository        | 46           | Google Repository              | extras/google/m2repository/
  ndk-bundle                        | 14.1.3816874 | NDK                            | ndk-bundle/
  patcher;v4                        | 1            | SDK Patch Applier v4           | patcher/v4/
  platform-tools                    | 25.0.4       | Android SDK Platform-Tools     | platform-tools/
  platforms;android-14              | 4            | Android SDK Platform 14        | platforms/android-14/
  platforms;android-15              | 5            | Android SDK Platform 15        | platforms/android-15/
  platforms;android-16              | 5            | Android SDK Platform 16        | platforms/android-16/
  platforms;android-17              | 3            | Android SDK Platform 17        | platforms/android-17/
  platforms;android-18              | 3            | Android SDK Platform 18        | platforms/android-18/
  platforms;android-19              | 4            | Android SDK Platform 19        | platforms/android-19/
  platforms;android-20              | 2            | Android SDK Platform 20        | platforms/android-20/
  platforms;android-21              | 2            | Android SDK Platform 21        | platforms/android-21/
  platforms;android-22              | 2            | Android SDK Platform 22        | platforms/android-22/
  platforms;android-23              | 3            | Android SDK Platform 23        | platforms/android-23/
  platforms;android-24              | 2            | Android SDK Platform 24        | platforms/android-24/
  platforms;android-25              | 3            | Android SDK Platform 25        | platforms/android-25/
  sources;android-15                | 2            | Sources for Android 15         | sources/android-15/
  sources;android-16                | 2            | Sources for Android 16         | sources/android-16/
  sources;android-17                | 1            | Sources for Android 17         | sources/android-17/
  sources;android-18                | 1            | Sources for Android 18         | sources/android-18/
  sources;android-19                | 2            | Sources for Android 19         | sources/android-19/
  sources;android-20                | 1            | Sources for Android 20         | sources/android-20/
  sources;android-21                | 1            | Sources for Android 21         | sources/android-21/
  sources;android-22                | 1            | Sources for Android 22         | sources/android-22/
  sources;android-23                | 1            | Sources for Android 23         | sources/android-23/
  sources;android-24                | 1            | Sources for Android 24         | sources/android-24/
  sources;android-25                | 1            | Sources for Android 25         | sources/android-25/
  tools                             | 26.0.0       | Android SDK Tools              | tools/
```

答: In you I wouldn't use and Android SDK installed for another environment, but I would set Appcelerator to use an ad-hoc Android SDK containing only the API 23 downloaded from Appcelerator Studio. In my experience giving to Titanium an SDK downloaded for another purpose (Android native, Ionic, Xamarin, ...) is never a good idea.

Body:
When I attempt building a android distribution of my app through the appcelerator CLI, I get the following error: [ERROR] Target Android SDK API 23 is not installed.

I have installed android sdk api 23 but when I run appc ti info -t android it appears that Titanium is not recognizing the installed targets.

Appcelerator Command-Line Interface, version 6.0.0
Copyright (c) 2014-2017, Appcelerator, Inc.  All Rights Reserved.
Android SDK
  Android Executable          = /Users/Shared/Jenkins/Library/Android/sdk/tools/android
  ADB Executable              = /Users/Shared/Jenkins/Library/Android/sdk/platform-tools/adb
  SDK Path                    = /Users/Shared/Jenkins/Library/Android/sdk
Android NDK
  NDK Path                    = /Users/Shared/Jenkins/Library/Android/sdk/ndk-bundle
  NDK Version                 = 14.1.3816874
Android Platforms
  None
Android Add-Ons
  None
Android Emulators
  None
Genymotion Emulators
  None
Connected Android Devices
  None
Issues
  No issues detected! Your development environment should be working perfectly!

Output of sdkmanager --list

devbuild1:bin jenkins$ ./sdkmanager --list
Warning: File /Users/Shared/Jenkins/.android/repositories.cfg could not be loaded.
Installed packages:
  Path                              | Version      | Description                    | Location
  -------                           | -------      | -------                        | -------
  add-ons;addon-g..._apis-google-15 | 3            | Google APIs                    | add-ons/addon-g...apis-google-15/
  add-ons;addon-g..._apis-google-16 | 4            | Google APIs                    | add-ons/addon-g...apis-google-16/
  add-ons;addon-g..._apis-google-17 | 4            | Google APIs                    | add-ons/addon-g...apis-google-17/
  add-ons;addon-g..._apis-google-18 | 4            | Google APIs                    | add-ons/addon-g...apis-google-18/
  add-ons;addon-g..._apis-google-19 | 20           | Google APIs                    | add-ons/addon-g...apis-google-19/
  add-ons;addon-g..._apis-google-21 | 1            | Google APIs                    | add-ons/addon-g...apis-google-21/
  add-ons;addon-g..._apis-google-22 | 1            | Google APIs                    | add-ons/addon-g...apis-google-22/
  add-ons;addon-g..._apis-google-23 | 1            | Google APIs                    | add-ons/addon-g...apis-google-23/
  add-ons;addon-g..._apis-google-24 | 1            | Google APIs                    | add-ons/addon-g...apis-google-24/
  build-tools;25.0.2                | 25.0.2       | Android SDK Build-Tools 25.0.2 | build-tools/25.0.2/
  emulator                          | 26.0.0       | Android Emulator               | emulator/
  extras;android;m2repository       | 47.0.0       | Android Support Repository     | extras/android/m2repository/
  extras;google;m2repository        | 46           | Google Repository              | extras/google/m2repository/
  ndk-bundle                        | 14.1.3816874 | NDK                            | ndk-bundle/
  patcher;v4                        | 1            | SDK Patch Applier v4           | patcher/v4/
  platform-tools                    | 25.0.4       | Android SDK Platform-Tools     | platform-tools/
  platforms;android-14              | 4            | Android SDK Platform 14        | platforms/android-14/
  platforms;android-15              | 5            | Android SDK Platform 15        | platforms/android-15/
  platforms;android-16              | 5            | Android SDK Platform 16        | platforms/android-16/
  platforms;android-17              | 3            | Android SDK Platform 17        | platforms/android-17/
  platforms;android-18              | 3            | Android SDK Platform 18        | platforms/android-18/
  platforms;android-19              | 4            | Android SDK Platform 19        | platforms/android-19/
  platforms;android-20              | 2            | Android SDK Platform 20        | platforms/android-20/
  platforms;android-21              | 2            | Android SDK Platform 21        | platforms/android-21/
  platforms;android-22              | 2            | Android SDK Platform 22        | platforms/android-22/
  platforms;android-23              | 3            | Android SDK Platform 23        | platforms/android-23/
  platforms;android-24              | 2            | Android SDK Platform 24        | platforms/android-24/
  platforms;android-25              | 3            | Android SDK Platform 25        | platforms/android-25/
  sources;android-15                | 2            | Sources for Android 15         | sources/android-15/
  sources;android-16                | 2            | Sources for Android 16         | sources/android-16/
  sources;android-17                | 1            | Sources for Android 17         | sources/android-17/
  sources;android-18                | 1            | Sources for Android 18         | sources/android-18/
  sources;android-19                | 2            | Sources for Android 19         | sources/android-19/
  sources;android-20                | 1            | Sources for Android 20         | sources/android-20/
  sources;android-21                | 1            | Sources for Android 21         | sources/android-21/
  sources;android-22                | 1            | Sources for Android 22         | sources/android-22/
  sources;android-23                | 1            | Sources for Android 23         | sources/android-23/
  sources;android-24                | 1            | Sources for Android 24         | sources/android-24/
  sources;android-25                | 1            | Sources for Android 25         | sources/android-25/
  tools                             | 26.0.0       | Android SDK Tools              | tools/


问:
How to compare values of two List Arrays in Java
I have two lists as shown:

```<code>//list one = {1,2,3,4}
listone.add(1);
listone.add(2);
listone.add(3);
listone.add(4);

// list two = {3.0,4}
listtwo.add(3.0);
listtwo.add(4);
</code>```

I tried comparing 3 in listone to 3.0 in listtwo, but no matter what I do they don't seem to be equal. I was wondering, how can I detect that they are equal?

Also if I try to see they are a subset of each other:

```<code>Collections.indexOfSubList(listone,listtwo);
</code>```

Apparently this doesn't detect 3.0 as equal to 3.

So my question is, how do I test that 3 is equal to 3.0?

答:
Do not use the == to compare the List contents. Use compareTo(obj) instead.

Example:

A) Create two lists

```<code>ArrayList<Double> myList = new ArrayList<Double>();
//... fill list
ArrayList<Integer> myList2 = new ArrayList<Integer>();
//....fill list
</code>```

B) Sort them in the same order

C) Loop around and check each element using .compareTo()

```<code>for(int i=0; i<myList.size(); i++){

            if(myList.get(i).compareTo(Double.valueOf(myList2.get(i)))==0){
                //numbers are equal
            }
        }
</code>```

Of course this solution requires the two list to be same size.
The myList.get(i) == (Double)myList2.get(i) will not work

Body:
I have two lists as shown:

//list one = {1,2,3,4}
listone.add(1);
listone.add(2);
listone.add(3);
listone.add(4);

// list two = {3.0,4}
listtwo.add(3.0);
listtwo.add(4);

I tried comparing 3 in listone to 3.0 in listtwo, but no matter what I do they don't seem to be equal. I was wondering, how can I detect that they are equal?

Also if I try to see they are a subset of each other:

Collections.indexOfSubList(listone,listtwo);

Apparently this doesn't detect 3.0 as equal to 3.

So my question is, how do I test that 3 is equal to 3.0?

Body:
Do not use the == to compare the List contents. Use compareTo(obj) instead.

Example:

A) Create two lists

ArrayList<Double> myList = new ArrayList<Double>();
//... fill list
ArrayList<Integer> myList2 = new ArrayList<Integer>();
//....fill list

B) Sort them in the same order

C) Loop around and check each element using .compareTo()

for(int i=0; i<myList.size(); i++){

            if(myList.get(i).compareTo(Double.valueOf(myList2.get(i)))==0){
                //numbers are equal
            }
        }

Of course this solution requires the two list to be same size.
The myList.get(i) == (Double)myList2.get(i) will not work


问:
Automatically Delete/Expire Azure Blobs after a time period
With Azure Blob storage is it possible to either have an individual blob or all blobs within a container delete themselves after a certain period of time similar to Amazon AWS S3's Object Expiration Feature?  Or does Azure storage not provide such functionality?</p>

答: Looks like the feature is planned now at least: https://feedback.azure.com/forums/217298-storage/suggestions/2474308-provide-time-to-live-feature-for-blobs</p>


问:
Proper MIME type for OTF fonts
Searching the web, I find heaps of different suggestions for what the proper MIME type for a font is, but I have yet to try any MIME type that rids me of a Chrome warning such as the following:

Resource interpreted as font but transferred with MIME type font/otf

The font is an OTF.

I've tried the following MIME types so far

font/otf

application/font-otf

application/font

application/otf

application/octet-stream

application/x-font-otf

application/x-font-TrueType (I know it's not truetype, but one source quoted this for OTF)

答: As of February 2017, RFC 8081 adds font/* media types, which are also listed in the IANA Media Types list. font/otf is in this list.

Title: Proper MIME type for OTF fonts