问:
Using kotlin constants in java switch expression
I've been looking into Kotlin lang recently and its interop with java. I have following java code:

```<code>public void select(int code) {
    switch code {
        case Service.CONSTANT_ONE:
            break;
        case Service.CONSTANT_TWO:
             break;
        default:
             break;
    }
}
</code>```

Where Service.kt written as follows:

```<code>class Service {
    companion object {
        val CONSTANT_ONE = 1
        val CONSTANT_TWO = 2
    }
}
</code>```

Java compiler says that CONSTANT_ONE and CONSTANT_TWO must be constants, but I don't know, how I can make them more constant than they are now. So my question is: how to use constants from kotlin in java swicth statement?

I'm using jdk8 and kotlin M14.

答:
A even more simple solution would be:
to declare the constants in the 'Kotlin file' instead of 'Kotlin class', which is basically declaring the constants outside the class scope and they can be referenced anywhere with proper imports.

```<code>const val CONSTANT_ONE = 1
const val CONSTANT_TWO = 2

class Service {
}
</code>```

Or if you want something that's similar to private static final int CONSTANT_ONE = 1;

You can declare the constants to be private in Kotlin file, and only classes within the same file have accesses to it.

```<code>private const val CONSTANT_ONE = 1
class A{
   // can access CONSTANT_ONE
}

class B{
  // can access CONSTANT_ONE
}
</code>```

Body:
I've been looking into Kotlin lang recently and its interop with java. I have following java code:

public void select(int code) {
    switch code {
        case Service.CONSTANT_ONE:
            break;
        case Service.CONSTANT_TWO:
             break;
        default:
             break;
    }
}

Where Service.kt written as follows:

class Service {
    companion object {
        val CONSTANT_ONE = 1
        val CONSTANT_TWO = 2
    }
}

Java compiler says that CONSTANT_ONE and CONSTANT_TWO must be constants, but I don't know, how I can make them more constant than they are now. So my question is: how to use constants from kotlin in java swicth statement?

I'm using jdk8 and kotlin M14.

Body:
A even more simple solution would be:
to declare the constants in the 'Kotlin file' instead of 'Kotlin class', which is basically declaring the constants outside the class scope and they can be referenced anywhere with proper imports.

const val CONSTANT_ONE = 1
const val CONSTANT_TWO = 2

class Service {
}

Or if you want something that's similar to private static final int CONSTANT_ONE = 1;

You can declare the constants to be private in Kotlin file, and only classes within the same file have accesses to it.

private const val CONSTANT_ONE = 1
class A{
   // can access CONSTANT_ONE
}

class B{
  // can access CONSTANT_ONE
}


来源: stackexchange

问:
IllegalStateException when trying to run spark streaming with twitter
I am new to spark and scala.  I am trying to run an example given in google.  I am encounting following exception when running this program.

Exception is:

```<code>17/05/25 11:13:42 ERROR ReceiverTracker: Deregistered receiver for stream 0: Restarting receiver with delay 2000ms: Error starting Twitter stream - java.lang.IllegalStateException: Authentication credentials are missing.
</code>```

Code that I am executing is as follows:

PrintTweets.scala

```<code>package example

    import org.apache.spark._
    import org.apache.spark.SparkContext._
    import org.apache.spark.streaming._
    import org.apache.spark.streaming.twitter._
    import org.apache.spark.streaming.StreamingContext._
    import org.apache.log4j.Level
    import Utilities._

object PrintTweets {

    def main(args: Array[String]) {

        // Configure Twitter credentials using twitter.txt
        setupTwitter()
        val appName = "TwitterData"
        val conf = new SparkConf()
        conf.setAppName(appName).setMaster("local[3]")

        val ssc = new StreamingContext(conf, Seconds(5))
        //val ssc = new StreamingContext("local[*]", "PrintTweets", Seconds(10))
        setupLogging()
        // Create a DStream from Twitter using our streaming context
        val tweets = TwitterUtils.createStream(ssc, None)
        // Now extract the text of each status update into RDD's using map()
        val statuses = tweets.map(status => status.getText())
        statuses.print()

    ssc.start()
    ssc.awaitTermination()
  }
}

Utilities.scala

package example

import org.apache.log4j.Level
import java.util.regex.Pattern
import java.util.regex.Matcher

object Utilities {
    /** Makes sure only ERROR messages get logged to avoid log spam. */
  def setupLogging() = {
      import org.apache.log4j.{Level, Logger}
      val rootLogger = Logger.getRootLogger()
      rootLogger.setLevel(Level.ERROR)
  }

  /** Configures Twitter service credentials using twiter.txt in the main workspace directory */
    def setupTwitter() = {
        import scala.io.Source

        for (line <- Source.fromFile("../twitter.txt").getLines) {
            val fields = line.split(" ")
            if (fields.length == 2) {
                System.setProperty("twitter4j.oauth." + fields(0), fields(1))
      }
    }
  }

  /** Retrieves a regex Pattern for parsing Apache access logs. */
  def apacheLogPattern():Pattern = {
    val ddd = "\\d{1,3}"
    val ip = s"($ddd\\.$ddd\\.$ddd\\.$ddd)?"
    val client = "(\\S+)"
    val user = "(\\S+)"
    val dateTime = "(\\[.+?\\])"
    val request = "\"(.*?)\""
    val status = "(\\d{3})"
    val bytes = "(\\S+)"
    val referer = "\"(.*?)\""
    val agent = "\"(.*?)\""
    val regex = s"$ip $client $user $dateTime $request $status $bytes $referer $agent"
    Pattern.compile(regex)
  }
}
</code>```

When I check using print statments I find the exception is happening at line
val tweets = TwitterUtils.createStream(ssc, None)

I am giving credentials in twitter.txt file which is read properly by program.  When I don't place twitter.txt in appropriate directory it shows explicit error, It shows explicit error unauthorized access when I give blank keys for customer key and secret etc in twitter.txt

If you need more details about error related information or versions of software let me know.

Thanks,
Madhu.

答:
After changing twitter.txt file syntax to following , single space between key and value it worked

consumerKey your_consumerKey
consumerSecret your_consumerSecret
accessToken your_accessToken
accessTokenSecret your_accessTokenSecret

ContentLicense: CC BY-SA 3.0

Body:
I am new to spark and scala.  I am trying to run an example given in google.  I am encounting following exception when running this program.

Exception is:

17/05/25 11:13:42 ERROR ReceiverTracker: Deregistered receiver for stream 0: Restarting receiver with delay 2000ms: Error starting Twitter stream - java.lang.IllegalStateException: Authentication credentials are missing.

Code that I am executing is as follows:

PrintTweets.scala

package example

    import org.apache.spark._
    import org.apache.spark.SparkContext._
    import org.apache.spark.streaming._
    import org.apache.spark.streaming.twitter._
    import org.apache.spark.streaming.StreamingContext._
    import org.apache.log4j.Level
    import Utilities._

object PrintTweets {

    def main(args: Array[String]) {

        // Configure Twitter credentials using twitter.txt
        setupTwitter()
        val appName = "TwitterData"
        val conf = new SparkConf()
        conf.setAppName(appName).setMaster("local[3]")

        val ssc = new StreamingContext(conf, Seconds(5))
        //val ssc = new StreamingContext("local[*]", "PrintTweets", Seconds(10))
        setupLogging()
        // Create a DStream from Twitter using our streaming context
        val tweets = TwitterUtils.createStream(ssc, None)
        // Now extract the text of each status update into RDD's using map()
        val statuses = tweets.map(status => status.getText())
        statuses.print()

    ssc.start()
    ssc.awaitTermination()
  }
}

Utilities.scala

package example

import org.apache.log4j.Level
import java.util.regex.Pattern
import java.util.regex.Matcher

object Utilities {
    /** Makes sure only ERROR messages get logged to avoid log spam. */
  def setupLogging() = {
      import org.apache.log4j.{Level, Logger}
      val rootLogger = Logger.getRootLogger()
      rootLogger.setLevel(Level.ERROR)
  }

  /** Configures Twitter service credentials using twiter.txt in the main workspace directory */
    def setupTwitter() = {
        import scala.io.Source

        for (line <- Source.fromFile("../twitter.txt").getLines) {
            val fields = line.split(" ")
            if (fields.length == 2) {
                System.setProperty("twitter4j.oauth." + fields(0), fields(1))
      }
    }
  }

  /** Retrieves a regex Pattern for parsing Apache access logs. */
  def apacheLogPattern():Pattern = {
    val ddd = "\\d{1,3}"
    val ip = s"($ddd\\.$ddd\\.$ddd\\.$ddd)?"
    val client = "(\\S+)"
    val user = "(\\S+)"
    val dateTime = "(\\[.+?\\])"
    val request = "\"(.*?)\""
    val status = "(\\d{3})"
    val bytes = "(\\S+)"
    val referer = "\"(.*?)\""
    val agent = "\"(.*?)\""
    val regex = s"$ip $client $user $dateTime $request $status $bytes $referer $agent"
    Pattern.compile(regex)
  }
}

When I check using print statments I find the exception is happening at line
val tweets = TwitterUtils.createStream(ssc, None)

I am giving credentials in twitter.txt file which is read properly by program.  When I don't place twitter.txt in appropriate directory it shows explicit error, It shows explicit error unauthorized access when I give blank keys for customer key and secret etc in twitter.txt

If you need more details about error related information or versions of software let me know.

Thanks,
Madhu.


问:
AS3 : How do I give my DisplayObjects custom properties?
I am very new to AS3, and I'm confused about how things that would have been simple in AS2 are so complex and tricky now. For example, I want to create a bunch TextField objects that, for some reason, rise up every frame (as in : object.y-=1; ).
However, I also need each TextField to reference the TextField that was created just before it.
I tried creating a variable that would hold such a reference : ThisTextField.Ref=LastTextField; but - this returns an "Access of possibly undefined property..." error. It seems I can only have custom properties on mere Objects ! This is annoying because an Object doesn't seem to accept event listeners (remember, I need them to do something every frame).

Is there a way to simply set custom properties on my TextFields, without having to use custom packages ? Or is there a way to use event listeners on Objects ?
I've read something about strict mode which could allow setting properties on other objects - what are the risks of turning it off ?

(this is my first time here, so I'm sorry if I sound confusing, or confused !)

答:
you can also use casting to save time, by converting your extended objects to their base class, assigning the property, and then switching them back.
For instance, everything extends Object so:

var myWhat:Object = myThing as Object;  //where myThing is whatever your orginal object was;
myWhat.customProp = "yellow";

var myNewThing:WhatEverMyObjectWasOrignially = myWhat as WhatEverMyObjectWasOrignially;
trace(myNewthing.customProp);

this has been very handy for me...

ContentLicense: CC BY-SA 2.5


问:
How to redirect to another view with parameter in this example?
I have an intro.html rendering view here:

```<code>def home(request):
    user = request.user
    small = user.username.title()
    cases = Case.objects.filter(users=user).order_by('-english')
    groups = user.groups.all()
    allgroups = Group.objects.all()
    suggestgroups = set(allgroups).difference(set(groups))
    allusers = User.objects.all().exclude(username=user.username)

    if not user.is_superuser:
        user_ex = UserEx.objects.get(user=request.user)
        friendlist = FriendList.objects.get(user=user_ex)
        friends = friendlist.friends.all().exclude(username=user.username)
        friendrequest = FriendReqRecList.objects.get(user=user_ex)
        friendrequestsent = FriendReqSentList.objects.get(user=user_ex)
        friendrequests = friendrequest.friend_rec_requests.all().exclude(username=user.username)
        friendrequestsents = friendrequestsent.friend_sent_requests.all().exclude(username=user.username)
        nonfriends = set(allusers).difference(set(friends))
        return render(request, 'intro.html',
                      {'allusers': allusers,
                       'cases': cases,
                       'friendrequests': friendrequests,
                       'friendrequestsents': friendrequestsents,
                       'friends': friends,
                       'groups': groups,
                       'nonfriends': nonfriends,
                       'small' : small,
                       'suggestgroups': suggestgroups})
    return render(request, 'intro.html', {'suggestgroups': suggestgroups,
                                          'cases': cases,
                                          'groups': groups,
                                          'small' : small})
</code>```

I have another share view which adds friends and groups to the intro.html (the change is only extra two parameters, sendfriends and sendgroups).

```<code>@login_required
def share(request):
    user = request.user
    small = user.username.title()
    cases = Case.objects.filter(users=user).order_by('-english')
    groups = user.groups.all()
    allgroups = Group.objects.all()
    suggestgroups = set(allgroups).difference(set(groups))
    allusers = User.objects.all().exclude(username=user.username)

    sendgroups = groups

    if not user.is_superuser:
        user_ex = UserEx.objects.get(user=request.user)
        friendlist = FriendList.objects.get(user=user_ex)
        friends = friendlist.friends.all().exclude(username=user.username)
        friendrequest = FriendReqRecList.objects.get(user=user_ex)
        friendrequestsent = FriendReqSentList.objects.get(user=user_ex)
        friendrequests = friendrequest.friend_rec_requests.all().exclude(username=user.username)
        friendrequestsents = friendrequestsent.friend_sent_requests.all().exclude(username=user.username)
        nonfriends = set(allusers).difference(set(friends))

        sendfriends = friendlist.friends.all().exclude(username=user.username)
        return render(request, 'intro.html',
                      {'sendfriends': sendfriends,
                       'sendgroups': sendgroups,
                       'allusers': allusers,
                       'cases': cases,
                       'friendrequests': friendrequests,
                       'friendrequestsents': friendrequestsents,
                       'friends': friends,
                       'groups': groups,
                       'nonfriends': nonfriends,
                       'small' : small,
                       'suggestgroups': suggestgroups})

    return render(request, 'intro.html', {'suggestgroups': suggestgroups,
                                          'cases': cases,
                                          'groups': groups,
                                          'small' : small})
</code>```

The second view also renders intro.html with extra two parameters (sendfriends and sendgroups). But I want to obey the don't repeat yourself (DRY) rule and use redirect() here. How can I pass these two parameters and redirect to home view over share view?

答:
What about this:</p>

```<code>def home(request):
    return render_intro(request)

@login_required
def share(request):
    return render_intro(request, is_share=True)

def render_intro(request, is_share=False):
    context = intro_context(request.user, is_share)
    return render(request, 'intro.html', context)

def intro_context(user, is_share=False):
    small = user.username.title()
    cases = Case.objects.filter(users=user).order_by('-english')
    groups = user.groups.all()
    allgroups = Group.objects.all()
    suggestgroups = set(allgroups).difference(set(groups))
    allusers = User.objects.all().exclude(username=user.username)

    if user.is_superuser:
        return {'suggestgroups': suggestgroups,
                'cases': cases,
                'groups': groups,
                'small' : small}

    user_ex = UserEx.objects.get(user=user)
    friendlist = FriendList.objects.get(user=user_ex)
    friends = friendlist.friends.all().exclude(username=user.username)
    friendrequest = FriendReqRecList.objects.get(user=user_ex)
    friendrequestsent = FriendReqSentList.objects.get(user=user_ex)
    friendrequests = friendrequest.friend_rec_requests.all().exclude(username=user.username)
    friendrequestsents = friendrequestsent.friend_sent_requests.all().exclude(username=user.username)
    nonfriends = set(allusers).difference(set(friends))

    context = {'allusers': allusers,
               'cases': cases,
               'friendrequests': friendrequests,
               'friendrequestsents': friendrequestsents,
               'friends': friends,
               'groups': groups,
               'nonfriends': nonfriends,
               'small' : small,
               'suggestgroups': suggestgroups}

    if is_share:
        sendgroups = groups
        sendfriends = friendlist.friends.all().exclude(username=user.username)
        context.update({'sendfriends': sendfriends,
                        'sendgroups': sendgroups})

    return context
</code>```

Body:
I have an intro.html rendering view here:

def home(request):
    user = request.user
    small = user.username.title()
    cases = Case.objects.filter(users=user).order_by('-english')
    groups = user.groups.all()
    allgroups = Group.objects.all()
    suggestgroups = set(allgroups).difference(set(groups))
    allusers = User.objects.all().exclude(username=user.username)

    if not user.is_superuser:
        user_ex = UserEx.objects.get(user=request.user)
        friendlist = FriendList.objects.get(user=user_ex)
        friends = friendlist.friends.all().exclude(username=user.username)
        friendrequest = FriendReqRecList.objects.get(user=user_ex)
        friendrequestsent = FriendReqSentList.objects.get(user=user_ex)
        friendrequests = friendrequest.friend_rec_requests.all().exclude(username=user.username)
        friendrequestsents = friendrequestsent.friend_sent_requests.all().exclude(username=user.username)
        nonfriends = set(allusers).difference(set(friends))
        return render(request, 'intro.html',
                      {'allusers': allusers,
                       'cases': cases,
                       'friendrequests': friendrequests,
                       'friendrequestsents': friendrequestsents,
                       'friends': friends,
                       'groups': groups,
                       'nonfriends': nonfriends,
                       'small' : small,
                       'suggestgroups': suggestgroups})
    return render(request, 'intro.html', {'suggestgroups': suggestgroups,
                                          'cases': cases,
                                          'groups': groups,
                                          'small' : small})

I have another share view which adds friends and groups to the intro.html (the change is only extra two parameters, sendfriends and sendgroups).

@login_required
def share(request):
    user = request.user
    small = user.username.title()
    cases = Case.objects.filter(users=user).order_by('-english')
    groups = user.groups.all()
    allgroups = Group.objects.all()
    suggestgroups = set(allgroups).difference(set(groups))
    allusers = User.objects.all().exclude(username=user.username)

    sendgroups = groups

    if not user.is_superuser:
        user_ex = UserEx.objects.get(user=request.user)
        friendlist = FriendList.objects.get(user=user_ex)
        friends = friendlist.friends.all().exclude(username=user.username)
        friendrequest = FriendReqRecList.objects.get(user=user_ex)
        friendrequestsent = FriendReqSentList.objects.get(user=user_ex)
        friendrequests = friendrequest.friend_rec_requests.all().exclude(username=user.username)
        friendrequestsents = friendrequestsent.friend_sent_requests.all().exclude(username=user.username)
        nonfriends = set(allusers).difference(set(friends))

        sendfriends = friendlist.friends.all().exclude(username=user.username)
        return render(request, 'intro.html',
                      {'sendfriends': sendfriends,
                       'sendgroups': sendgroups,
                       'allusers': allusers,
                       'cases': cases,
                       'friendrequests': friendrequests,
                       'friendrequestsents': friendrequestsents,
                       'friends': friends,
                       'groups': groups,
                       'nonfriends': nonfriends,
                       'small' : small,
                       'suggestgroups': suggestgroups})

    return render(request, 'intro.html', {'suggestgroups': suggestgroups,
                                          'cases': cases,
                                          'groups': groups,
                                          'small' : small})

The second view also renders intro.html with extra two parameters (sendfriends and sendgroups). But I want to obey the don't repeat yourself (DRY) rule and use redirect() here. How can I pass these two parameters and redirect to home view over share view?

Body:
What about this:

def home(request):
    return render_intro(request)

@login_required
def share(request):
    return render_intro(request, is_share=True)

def render_intro(request, is_share=False):
    context = intro_context(request.user, is_share)
    return render(request, 'intro.html', context)

def intro_context(user, is_share=False):
    small = user.username.title()
    cases = Case.objects.filter(users=user).order_by('-english')
    groups = user.groups.all()
    allgroups = Group.objects.all()
    suggestgroups = set(allgroups).difference(set(groups))
    allusers = User.objects.all().exclude(username=user.username)

    if user.is_superuser:
        return {'suggestgroups': suggestgroups,
                'cases': cases,
                'groups': groups,
                'small' : small}

    user_ex = UserEx.objects.get(user=user)
    friendlist = FriendList.objects.get(user=user_ex)
    friends = friendlist.friends.all().exclude(username=user.username)
    friendrequest = FriendReqRecList.objects.get(user=user_ex)
    friendrequestsent = FriendReqSentList.objects.get(user=user_ex)
    friendrequests = friendrequest.friend_rec_requests.all().exclude(username=user.username)
    friendrequestsents = friendrequestsent.friend_sent_requests.all().exclude(username=user.username)
    nonfriends = set(allusers).difference(set(friends))

    context = {'allusers': allusers,
               'cases': cases,
               'friendrequests': friendrequests,
               'friendrequestsents': friendrequestsents,
               'friends': friends,
               'groups': groups,
               'nonfriends': nonfriends,
               'small' : small,
               'suggestgroups': suggestgroups}

    if is_share:
        sendgroups = groups
        sendfriends = friendlist.friends.all().exclude(username=user.username)
        context.update({'sendfriends': sendfriends,
                        'sendgroups': sendgroups})

    return context


问:
number representation change using concatenation
There are many questions asking about how to concatenate a string and an integer for example 4 and "Blue" to 4Blue. This can be done by casting the integer as a string str(4) and adding it with "Blue" (str(4) + "Blue").

I am trying to convert a number to its three-digit equivalent (Or bearing form). For example, 40 would become 040.

I have quickly put together this code:

```<code>number=90
newn = number

one="0"
two="00"
num=str(number)
length=len(num)

if length == 1:
    newn = two + num
elif length == 2:
    newn = one + num
elif length == 3:
    pass

print(newn)
</code>```

Which outputs this, as expected:

```<code>090
>>>
</code>```

I was wondering what the simplest way of doing this would be, along with if this is a good method of achieving this.

答:
The following will do:

```<code>print('{:03}'.format(90))
</code>```

You can change the number 3 depending on how many leading zeros you want to have.

Hope it helps.

Body:
There are many questions asking about how to concatenate a string and an integer for example 4 and "Blue" to 4Blue. This can be done by casting the integer as a string str(4) and adding it with "Blue" (str(4) + "Blue").

I am trying to convert a number to its three-digit equivalent (Or bearing form). For example, 40 would become 040.

I have quickly put together this code:

number=90
newn = number

one="0"
two="00"
num=str(number)
length=len(num)

if length == 1:
    newn = two + num
elif length == 2:
    newn = one + num
elif length == 3:
    pass

print(newn)

Which outputs this, as expected:

090
>>>

I was wondering what the simplest way of doing this would be, along with if this is a good method of achieving this.

Body:
The following will do:

print('{:03}'.format(90))

You can change the number 3 depending on how many leading zeros you want to have.

Hope it helps.


问:
chartjs - json data for scatter graph, issue with date
I've got scatter graph, which doesn't show the axe X with dates:

```<code>var chart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [{
            label: 'label',
            data: [data],
            borderColor: "#000066"
        }],
    },
    options: {
        scales: {
            xAxes: [{
                type: "time",
                display: true,
                scaleLabel: {
                    display: true,
                    labelString: 'Date'
                },
            }]
        }
    }
});
</code>```

Variable data is in JSON format:

```<code>{"x":"2017-06-03T13:23:47.129Z","y":1.306},
{"x":"2017-06-03T14:17:24.960Z","y":1.299},
{"x":"2017-06-03T14:17:46.565Z","y":1.306},
...
</code>```

If I try to add data manually and make dates as Date objects in JS, then it works:

```<code>data: [{ "x": new Date("2017-06-03T14:17:46.565Z"), "y": 1.306 }]
</code>```

But I need to add data in JSON.

Update - defining the data variable:

```<code>            for (var j = 0; j < source.length; j++) {
                x = new Date(source[j].Date);
                y = source[j].value;
                var json = { x: x, y: y };
                data.push(json);
            }
</code>```

答:
I was able to make it work without using the brackets around the data variable: JSFiddle

EDIT1: How are you defining the variable? Any reason to make it an array at chart creation time?

EDIT2: I see what's happening. The json variable being created is the string representation of the JSON you want. Chart.js doesn't understand that when defining your dataset. You need an actual JSON object, like so:

```<code>var source = [{Date:"2017-06-03T13:23:47.129Z",value:1.306},
{Date:"2017-06-03T14:17:24.960Z",value:1.299},
{Date:"2017-06-03T14:17:46.565Z",value:1.306}];

var json = [];
for (var j = 0; j < source.length; j++) {
  var jsonObj = {x: source[j].Date, y: source[j].value};
  json.push(jsonObj);
}
</code>```

Body:
I've got scatter graph, which doesn't show the axe X with dates:

var chart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [{
            label: 'label',
            data: [data],
            borderColor: "#000066"
        }],
    },
    options: {
        scales: {
            xAxes: [{
                type: "time",
                display: true,
                scaleLabel: {
                    display: true,
                    labelString: 'Date'
                },
            }]
        }
    }
});

Variable data is in JSON format:

{"x":"2017-06-03T13:23:47.129Z","y":1.306},
{"x":"2017-06-03T14:17:24.960Z","y":1.299},
{"x":"2017-06-03T14:17:46.565Z","y":1.306},
...

If I try to add data manually and make dates as Date objects in JS, then it works:

data: [{ "x": new Date("2017-06-03T14:17:46.565Z"), "y": 1.306 }]

But I need to add data in JSON.

Update - defining the data variable:

            for (var j = 0; j < source.length; j++) {
                x = new Date(source[j].Date);
                y = source[j].value;
                var json = { x: x, y: y };
                data.push(json);
            }

Body:
I was able to make it work without using the brackets around the data variable: JSFiddle

EDIT1: How are you defining the variable? Any reason to make it an array at chart creation time?

EDIT2: I see what's happening. The json variable being created is the string representation of the JSON you want. Chart.js doesn't understand that when defining your dataset. You need an actual JSON object, like so:

var source = [{Date:"2017-06-03T13:23:47.129Z",value:1.306},
{Date:"2017-06-03T14:17:24.960Z",value:1.299},
{Date:"2017-06-03T14:17:46.565Z",value:1.306}];

var json = [];
for (var j = 0; j < source.length; j++) {
  var jsonObj = {x: source[j].Date, y: source[j].value};
  json.push(jsonObj);
}


问:
Filter dependencies copied by Maven's copy-dependency?
I need to essentially accomplish the following:

Build my library into a JAR. (Easy, already done.)

Copy my library's dependencies to a local folder, including the main project JAR, excluding dependencies marked as provided.

I can't seem to get the second part finished. Is there a better way to do this than how I'm doing it below? I'm essentially deploying these JARs to a lib directory on a server. Unfortunately, the code below includes all JARs, even provided ones, but doesn't include the project output JAR. Should I be using a different plugin for this?

```<code><?xml version="1.0"?>
<project>
    ...

    <dependencies>
        <dependency>
            <groupId>com.provided</groupId>
            <artifactId>provided-lib</artifactId>
            <version>1.2.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>

        ...

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>/hello</outputDirectory>
                            <excludeTransitive>true</excludeTransitive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
Adding my two cents.

Putting the <excludeScope>provided</excludeScope> in the execution didn't work.

To exclude the provided jars put the element outside of the execution:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <configuration>
        <excludeScope>provided</excludeScope>
    </configuration>
</plugin>
</code>```

Command: mvn dependency:copy-dependencies.

Jars are copied to target/dependency.

Body:
I need to essentially accomplish the following:

Build my library into a JAR. (Easy, already done.)

Copy my library's dependencies to a local folder, including the main project JAR, excluding dependencies marked as provided.

I can't seem to get the second part finished. Is there a better way to do this than how I'm doing it below? I'm essentially deploying these JARs to a lib directory on a server. Unfortunately, the code below includes all JARs, even provided ones, but doesn't include the project output JAR. Should I be using a different plugin for this?

<?xml version="1.0"?>
<project>
    ...

    <dependencies>
        <dependency>
            <groupId>com.provided</groupId>
            <artifactId>provided-lib</artifactId>
            <version>1.2.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>

        ...

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>/hello</outputDirectory>
                            <excludeTransitive>true</excludeTransitive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Body:
Adding my two cents.

Putting the <excludeScope>provided</excludeScope> in the execution didn't work.

To exclude the provided jars put the element outside of the execution:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <configuration>
        <excludeScope>provided</excludeScope>
    </configuration>
</plugin>

Command: mvn dependency:copy-dependencies.

Jars are copied to target/dependency.


问:
Write a function accepting wrapped constants, but only one level deep
I want to write a function (apologies for probably not using the correct term here) wubble which is true for specific constants and true for those constants if wrapped into another constant, but only one layer deep! Examples:

```<code>% are supposed to be TRUE:
?- wubble(foo).
?- wubble(bar).
?- wubble(wrapper(foo)).
?- wubble(wrapper(bar)).

% are suppoed to be FALSE:
?- wubble(not_in_knowledge_base).
?- wubble(wrapper(wrapper(foo))).
</code>```

The naive (at least in my brain) implementation looks like this:

```<code>wubble(foo).
wubble(bar).

wubble(wrapper(wrapper(_))) :- !, fail.
wubble(wrapper(X)) :- wubble(X).
</code>```

And this works with the queries above. However, I can't enumerate all valid X for wubble with this implementation:

```<code>?- wubble(X).
X = foo
X = bar
</code>```

So this is missing X = wrapper(foo) and X = wrapper(bar). Is it possible to fix my implementation somehow?

答:
You could separate the facts from the rules:</p>

```<code>wubble_(foo).
wubble_(bar).

wubble(X) :- wubble_(X).
wubble(wrapper(X)) :- wubble_(X).
</code>```

Body:
I want to write a function (apologies for probably not using the correct term here) wubble which is true for specific constants and true for those constants if wrapped into another constant, but only one layer deep! Examples:

% are supposed to be TRUE:
?- wubble(foo).
?- wubble(bar).
?- wubble(wrapper(foo)).
?- wubble(wrapper(bar)).

% are suppoed to be FALSE:
?- wubble(not_in_knowledge_base).
?- wubble(wrapper(wrapper(foo))).

The naive (at least in my brain) implementation looks like this:

wubble(foo).
wubble(bar).

wubble(wrapper(wrapper(_))) :- !, fail.
wubble(wrapper(X)) :- wubble(X).

And this works with the queries above. However, I can't enumerate all valid X for wubble with this implementation:

?- wubble(X).
X = foo
X = bar

So this is missing X = wrapper(foo) and X = wrapper(bar). Is it possible to fix my implementation somehow?

Body:
You could separate the facts from the rules:

wubble_(foo).
wubble_(bar).

wubble(X) :- wubble_(X).
wubble(wrapper(X)) :- wubble_(X).


问:
How "perfect" does a database have to be?
I'm designing a website to track weight lifting and calories. I've never designed my own database before and I figured I should get is as spot on as possible before I start coding. Every time I think I'm done, I get antsy that it's not perfect. I've mostly fleshed it out in MySQL Workbench but I still have a few questions.

How important is it to make the
database "perfect" before hand? How
hard is it to re-factor a database
later?

What does the engine option do? Right
now all tables are defaulting to
InnoDB engine? Any issues with this?

Are dataypes changeable after data
entry? Maybe not going from VARCHAR
to INT, but what about VARCHAR(45) to
VARCHAR(255)?

What are basic database rules that HAVE to
be followed for a successful design?

I've also attached my ERM diagram. If anyone could point out any obvious irregularities it would be greatly appreciated.

答:
Your design looks pretty good!

The main thing now is to walk throw your use cases and user dialogs and see if all the flows are easily supported.

A perfect user experience is more important than a perfect DB.


问:
Can’t remove items from a React state collection
I have these two methods defined in my React component:

```<code>handleAddMetric() {
    const metricKey = prompt('Name/key of metric');
    const newMetricItem = {
        name: metricKey,
        value: 100
    }
    let newMetrics = {};
    newMetrics[metricKey] = newMetricItem;
    const updatedMetrics = Object.assign({}, this.state.metrics, newMetrics);
    this.setState({ metrics: updatedMetrics });
}

handleRemoveMetric(keyName) {
    let updatedMetrics = this.state.metrics;
    delete updatedMetrics[keyName];
    console.log('handleRemoveMetric', this, keyName, updatedMetrics);
    this.setState({ metrics: updatedMetrics });
}
</code>```

Adding new values to this.state.metrics works fine, but deleting:

```<code><button onClick={this.handleRemoveMetric.bind(this, key)}>Delete</button>
</code>```

...calls my handleRemoveMetric function but doesn’t update the collection.

I first it was some issue with this but that doesn’t seem to be the case.

Any ideas?

Update: The console output is:

```<code>handleRemoveMetric Metrics {props: Object, context: Object, refs: Object, updater: Object, state: Object…}componentWillUnmount: function ()context: Objectprops: Objectref: Objectrefs: ObjectsetState: function (data, cb)state: Objectupdater: Object_reactInternalInstance: ReactCompositeComponentWrapperisMounted: (...)replaceState: (...)__proto__: ReactComponent
"myMetricKey"
Object {MRR: Object, moneyInBank: Object, wow: Object}
</code>```

...so at least the collection is updated locally.

答:
You need to copy it over to a new object.

```<code>const metrics = {
  ...this.state.metrics,
  [keyName]: null
};
this.setState({ metrics });
</code>```

should work.

Body:
I have these two methods defined in my React component:

handleAddMetric() {
    const metricKey = prompt('Name/key of metric');
    const newMetricItem = {
        name: metricKey,
        value: 100
    }
    let newMetrics = {};
    newMetrics[metricKey] = newMetricItem;
    const updatedMetrics = Object.assign({}, this.state.metrics, newMetrics);
    this.setState({ metrics: updatedMetrics });
}

handleRemoveMetric(keyName) {
    let updatedMetrics = this.state.metrics;
    delete updatedMetrics[keyName];
    console.log('handleRemoveMetric', this, keyName, updatedMetrics);
    this.setState({ metrics: updatedMetrics });
}

Adding new values to this.state.metrics works fine, but deleting:

<button onClick={this.handleRemoveMetric.bind(this, key)}>Delete</button>

...calls my handleRemoveMetric function but doesn’t update the collection.

I first it was some issue with this but that doesn’t seem to be the case.

Any ideas?

Update: The console output is:

handleRemoveMetric Metrics {props: Object, context: Object, refs: Object, updater: Object, state: Object…}componentWillUnmount: function ()context: Objectprops: Objectref: Objectrefs: ObjectsetState: function (data, cb)state: Objectupdater: Object_reactInternalInstance: ReactCompositeComponentWrapperisMounted: (...)replaceState: (...)__proto__: ReactComponent
"myMetricKey"
Object {MRR: Object, moneyInBank: Object, wow: Object}

...so at least the collection is updated locally.

Body:
You need to copy it over to a new object.

const metrics = {
  ...this.state.metrics,
  [keyName]: null
};
this.setState({ metrics });

should work.


答:
Use

```<code>s = str(num).zfill(3)
print(s)
</code>```

3 means leading zeros count.

Title: number representation change using concatenation

Body:
Use

s = str(num).zfill(3)
print(s)

3 means leading zeros count.


问:
Permission issue Google Play
I'm having trouble with androidpublisher.inapppurchases.get

My project is just according to https://code.google.com/p/google-api-java-client/wiki/OAuth2#Service_Accounts and it worked fine until I migrated to new Google Play Account. So now when I execute request Server-to-Server I am receiving this response.

```<code>{
  "code" : 401,
  "errors" : [ {
    "domain" : "androidpublisher",
    "message" : "The current user has insufficient permissions to perform the requested operation.",
    "reason" : "permissionDenied"
  } ],
  "message" : "The current user has insufficient permissions to perform the requested operation."
}
</code>```

Anybody is familiar with this response because in google documentation there is no clue about this.

答:
From Google Play Console go to (with admin access):

Setting (Left Panel)

Developer Account (Left Panel)

Users & permissions (Left Panel)

Click on the Invite New User button.

Enter the service account email (the same you have in the json file you are using and that google generated when you created the service account)

Select Administrator in the Role DropDown menu.

Click on SEND INVITATION

That's it. No one can stop you now! :)

Title: Permission issue Google Play

Body:
I'm having trouble with androidpublisher.inapppurchases.get

My project is just according to https://code.google.com/p/google-api-java-client/wiki/OAuth2#Service_Accounts and it worked fine until I migrated to new Google Play Account. So now when I execute request Server-to-Server I am receiving this response.

{
  "code" : 401,
  "errors" : [ {
    "domain" : "androidpublisher",
    "message" : "The current user has insufficient permissions to perform the requested operation.",
    "reason" : "permissionDenied"
  } ],
  "message" : "The current user has insufficient permissions to perform the requested operation."
}

Anybody is familiar with this response because in google documentation there is no clue about this.


问:
IF/ELSE $(document).ready Statement
I'm trying to write some jQuery to remove the default selected option of a select box once. Currently the $("#edit-field option:selected").remove(); removed = true;}; Works, but I'm having trouble putting it into a if/else statement.

```<code>$(document).ready (function remove() {
"use strict";
var removed = false;
if (removed = false) {
$("#edit-field option:selected").remove(); removed = true;}; else {
remove();}}
</code>```

Can anyone see anything wrong with my code?

答:
```<code>if (removed = false)
</code>```

This is wrong, you are reassigning the value of false to the variable.

```<code>if(removed === false)
</code>```

Is the comparative operator you should be using

https://www.w3schools.com/js/js_comparisons.asp

Title: IF/ELSE $(document).ready Statement

Body:
I'm trying to write some jQuery to remove the default selected option of a select box once. Currently the $("#edit-field option:selected").remove(); removed = true;}; Works, but I'm having trouble putting it into a if/else statement.

$(document).ready (function remove() {
"use strict";
var removed = false;
if (removed = false) {
$("#edit-field option:selected").remove(); removed = true;}; else {
remove();}}

Can anyone see anything wrong with my code?

Body:
if (removed = false)

This is wrong, you are reassigning the value of false to the variable.

if(removed === false)

Is the comparative operator you should be using

https://www.w3schools.com/js/js_comparisons.asp


问:
Makefile always thinks project is up to date - but files don't even exist
I have the following makefile:

```CCC = g++
CCFLAGS = -ansi

driver: driver.o graph.o
        $(CCC) -o driver driver.o graph.o

graph.o: graph.h
driver.o: graph.h

adjl:
        rm -f graph.h graph.cc
        ln -s adjl/graph.cc .
        ln -s adjl/graph.h .
        touch graph.cc graph.h
adjm:
        rm -f graph.h graph.cc
        ln -s adjm/graph.cc .
        ln -s adjm/graph.h .
        touch graph.cc graph.h

clean:
        rm -f *.o
real_clean: clean
        rm -f graph.cc graph.h
        rm -f driver```

The idea is that I am trying to link two different .cc/.h files depending on which implementation I want to use.  If I make real_clean, none of the .cc/.h files exist, I merely have a driver.cc file and the makefile in the folder.  If I call make, it says they are up to date.  This happens even if I edit the files in adjl/adjm to make them "newer" versions.

``` [95]% ls
adjl/  adjm/  driver.cc  makefile
 [96]% make adjl
make: `adjl' is up to date.
 [97]% make adjm
make: `adjm' is up to date.```

I took the template makefile from another project I had done, and they are written the same way but I can repeatedly make the same commands with no "up to date" issues.

I have googled but have not found a problem similar to mine (they generally seem to involve users who aren't cleaning before making).

Thanks to anyone for reading.

答:
The adjl and adjm targets are real targets. Since they have no dependencies, and the files are present (the 2 directories in your listing), make doesn't do anything (because they are around).

However, what you want is to specify adjl and adjm as phony targets (so that the commands are executed when you specify them). To do so,

```<code>.PHONY: adjl adjm
</code>```

Read http://www.gnu.org/software/automake/manual/make/Phony-Targets.html for more information.

EDIT

In fact, the real_clean and clean rules should probably also be made phony.

Body:
I have the following makefile:

CCC = g++
CCFLAGS = -ansi

driver: driver.o graph.o
        $(CCC) -o driver driver.o graph.o

graph.o: graph.h
driver.o: graph.h

adjl:
        rm -f graph.h graph.cc
        ln -s adjl/graph.cc .
        ln -s adjl/graph.h .
        touch graph.cc graph.h
adjm:
        rm -f graph.h graph.cc
        ln -s adjm/graph.cc .
        ln -s adjm/graph.h .
        touch graph.cc graph.h

clean:
        rm -f *.o
real_clean: clean
        rm -f graph.cc graph.h
        rm -f driver

The idea is that I am trying to link two different .cc/.h files depending on which implementation I want to use.  If I make real_clean, none of the .cc/.h files exist, I merely have a driver.cc file and the makefile in the folder.  If I call make, it says they are up to date.  This happens even if I edit the files in adjl/adjm to make them "newer" versions.

 [95]% ls
adjl/  adjm/  driver.cc  makefile
 [96]% make adjl
make: `adjl' is up to date.
 [97]% make adjm
make: `adjm' is up to date.

I took the template makefile from another project I had done, and they are written the same way but I can repeatedly make the same commands with no "up to date" issues.

I have googled but have not found a problem similar to mine (they generally seem to involve users who aren't cleaning before making).

Thanks to anyone for reading.

Body:
The adjl and adjm targets are real targets. Since they have no dependencies, and the files are present (the 2 directories in your listing), make doesn't do anything (because they are around).

However, what you want is to specify adjl and adjm as phony targets (so that the commands are executed when you specify them). To do so,

.PHONY: adjl adjm

Read http://www.gnu.org/software/automake/manual/make/Phony-Targets.html for more information.

EDIT

In fact, the real_clean and clean rules should probably also be made phony.


问:
Android BLE read value for characteristics is null
I am building an Android App for communication with  BLE hardware device.
Now I am able to fetch customServices and characteristics successfully and can read properties as well.
But the main issue is
        1) -it returns characteristics.getProperties() as 26 but expected answer should be WRITE/READ?NOTIFY.

       2) -while reading Value for a characteristics it reutns null
         (byte[] value=characteristics.getValue();).

Hardware device is sending "CALL" string as a value over BLE and I need to fetch it in byte[].
Please any help is appreciated.
Thank you in advance.

答:
1) This is correct, and you are actually receiving what you want. Check constants on this page: https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html

2) Try characteristic.getStringValue();
OR this might be helpful
https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#readCharacteristic(android.bluetooth.BluetoothGattCharacteristic)


问:
HTML Inline Flex not adapting to main class
Here's the problem i'm facing.

I'm trying to create two container under the class of content4 with imagesetter as the class.
The motive is to move the margin 25% width from the left.

Now it looks for the picture is working fine.
But as for the text, i've tried all kind of display. The second text just doesn't want align to the right.

CSS:

```<code>#content4 {
    clear: both;
    overflow: auto;
}

.imghalf{
width:35%;
margin-left: 100px;

}

.imgsetter{
    padding-left:10%;
}

.t5 {
  font-family:actor;
  font-weight: bold;
  font-size:26px;
  margin-left:100px;
}

.t6 {
  display:inline-flex;
  font-family:actor;
  font-weight: bold;
  font-size:26px;
  margin-left:100px;
}
</code>```

HTML:

```<code><div id="content4" class="imgsetter">
<img class="imghalf" src="http://via.placeholder.com/450x300.png" />
<img class="imghalf" src="http://via.placeholder.com/450x300.png" />

<p class="t5">This is how we do it at stackoverflow man</p>
<p class="t6">This is how we do it at stackoverflow man</p>
</div>
</code>```

Codepen : https://codepen.io/jayvicious/pen/LLYvEm

Just suggestion from the pros,
Should i create 4 container with width of 25% each and park it under content4?
This is to tackle the responsiveness .

答:
Well, I fixed it by using changing the method to inline block:

HTML :

```<code><div id="content4" class="imgsetter">
<img class="imghalf" src="Projects/Sojo/Documentation/Slice/01_Home/itenarythumb01.png" />
<img class="imghalf" src="Projects/Sojo/Documentation/Slice/01_Home/itenarythumb02.png" />

<p class="t5 imghalf">5 Days 4 Nights Tokyo Free & Easy Travel!</p>
<p class="t5 imghalf">6 Days 5 Nights Nagano Nature Adventure </p>
</div>
</code>```

CSS changes:

```<code>.t5 {
  display: inline-block;
  font-family:actor;
  font-weight: bold;
  font-size:26px;
  margin-left:25%;
  padding-left: 100px;
}
</code>```

Explanation : I added two class based on the
 . So it will inherit the container that was divided by the margin-left 25%

Body:
Here's the problem i'm facing.

I'm trying to create two container under the class of content4 with imagesetter as the class.
The motive is to move the margin 25% width from the left.

Now it looks for the picture is working fine.
But as for the text, i've tried all kind of display. The second text just doesn't want align to the right.

CSS:

#content4 {
    clear: both;
    overflow: auto;
}

.imghalf{
width:35%;
margin-left: 100px;

}

.imgsetter{
    padding-left:10%;
}

.t5 {
  font-family:actor;
  font-weight: bold;
  font-size:26px;
  margin-left:100px;
}

.t6 {
  display:inline-flex;
  font-family:actor;
  font-weight: bold;
  font-size:26px;
  margin-left:100px;
}

HTML:

This is how we do it at stackoverflow man

This is how we do it at stackoverflow man

Codepen : https://codepen.io/jayvicious/pen/LLYvEm

Just suggestion from the pros,
Should i create 4 container with width of 25% each and park it under content4?
This is to tackle the responsiveness .

Body:
Well, I fixed it by using changing the method to inline block:

HTML :

<div id="content4" class="imgsetter">
<img class="imghalf" src="Projects/Sojo/Documentation/Slice/01_Home/itenarythumb01.png" />
<img class="imghalf" src="Projects/Sojo/Documentation/Slice/01_Home/itenarythumb02.png" />

<p class="t5 imghalf">5 Days 4 Nights Tokyo Free & Easy Travel!</p>
<p class="t5 imghalf">6 Days 5 Nights Nagano Nature Adventure </p>
</div>

CSS changes:

.t5 {
  display: inline-block;
  font-family:actor;
  font-weight: bold;
  font-size:26px;
  margin-left:25%;
  padding-left: 100px;
}

Explanation : I added two class based on the
 . So it will inherit the container that was divided by the margin-left 25%


问:
How to install pecl memcached extension on wamp?
I need to install memcached for my windows 64bit wamp running on localhost. My specific php version is 5.5.12.

I am using version 2.2.0 of the extension found here:

http://pecl.php.net/package/memcached

How do I install the extension as it is a .tgz file?

I tried finding a working dll for this extension without any success.

答:
Step 1:
Check in your PHP’s extension directory (like: C:\wamp64\bin\php\php5.6.25\ext) if not exists file php_memcache.dll, go to the page http://windows.php.net/downloads/pecl/releases/memcache/3.0.8/
to download this file (depends on your PHP version) and put php_memcache.dll in your directory C:\wamp64\bin\php\php5.6.25\ext

Step 2:
Edit your file php.ini, add this line:
extension=php_memcache.dll

Step 3: restart apache
and check now your phpinfo


问:
What datatype does Google Datastore use for legacy mode auto generated ids?
I have a client application that uses integers to store Datastore ids. This was working fine as the Datastore ids used to be sequencially generated but now needs to be  changed to auto generated to scale. The two options for autogenerating are default and legacy. The default option uses long datatype and hence will break the client. The legacy says it generates small integers but is there a guarantee that it won't cross to the long datatype.</p>

答: Cloud Datastore keys uses ids (long ints, 64-bit) or names (string). The auto-incrementing legacy id allocation starts off with small numbers, but given enough entities it will eventually exceed what can be stored in just a 32-bit int.</p>


问:
A program interpretation in C
I am new to c and sometimes I get confused by things I see.
I have the following code:

```<code>int
sstmm_()

{time_t ourtime;
 time(&ourtime);
 return (int)(ourtime&0x00000fff);
}
</code>```

I do not understand what the meaning of ourtime&0x00000fff is?
Is it a pointer yet? What is the rule of 0x00000fff?
Thank you so much.

答:
```<code>&
</code>```

stands for bitwise and operation here, it is not related to addresss and pointers

Title: A program interpretation in C

Body:
I am new to c and sometimes I get confused by things I see.
I have the following code:

int
sstmm_()

{time_t ourtime;
 time(&ourtime);
 return (int)(ourtime&0x00000fff);
}

I do not understand what the meaning of ourtime&0x00000fff is?
Is it a pointer yet? What is the rule of 0x00000fff?
Thank you so much.

Body:
&

stands for bitwise and operation here, it is not related to addresss and pointers


问:
Elixir - generate list of strings for navigational (breadcrumb purposes)
I'm pretty new to Elixir (loving it so far) and have been trying to figure out how to take a simple String such as

```<code>"folder1/folder2/folder3/last_folder"
</code>```

and turn it into a list of navigation links for each part of the path (except for the last_folder):

["https://wherever/folder1", "https://wherever/folder2",  "https://wherever/folder3"]

There must be a pretty simple way to do this - perhaps with recursion?

答:
There's no need for explicit recursion. Just split the path by / and do an Enum.scan/3, concatenating the accumulator and the current part with "/" as separator:

```<code>path = "folder1/folder2/folder3/last_folder"
parts = String.split(path, "/")

Enum.scan(parts, "", fn part, acc ->
  acc <> "/" <> part
end)
|> IO.inspect
</code>```

Output:

```<code>["/folder1", "/folder1/folder2", "/folder1/folder2/folder3",
 "/folder1/folder2/folder3/last_folder"]
</code>```

If you don't want the last one, you can drop the last part from parts by doing this instead:

```<code>parts = String.split(path, "/") |> Enum.drop(-1)
</code>```

```<code>["/folder1", "/folder1/folder2", "/folder1/folder2/folder3"]
</code>```

If you modify the initial value of the accumulator, you can add the base URL if you want:

```<code>path = "folder1/folder2/folder3/last_folder"
parts = String.split(path, "/") |> Enum.drop(-1)
Enum.scan(parts, "https://wherever", fn part, acc ->
  acc <> "/" <> part
end)
|> IO.inspect
</code>```

```<code>["https://wherever/folder1", "https://wherever/folder1/folder2",
 "https://wherever/folder1/folder2/folder3"]
</code>```

Body:
I'm pretty new to Elixir (loving it so far) and have been trying to figure out how to take a simple String such as

"folder1/folder2/folder3/last_folder"

and turn it into a list of navigation links for each part of the path (except for the last_folder):

["https://wherever/folder1", "https://wherever/folder2",  "https://wherever/folder3"]

There must be a pretty simple way to do this - perhaps with recursion?

Body:
There's no need for explicit recursion. Just split the path by / and do an Enum.scan/3, concatenating the accumulator and the current part with "/" as separator:

path = "folder1/folder2/folder3/last_folder"
parts = String.split(path, "/")

Enum.scan(parts, "", fn part, acc ->
  acc <> "/" <> part
end)
|> IO.inspect

Output:

["/folder1", "/folder1/folder2", "/folder1/folder2/folder3",
 "/folder1/folder2/folder3/last_folder"]

If you don't want the last one, you can drop the last part from parts by doing this instead:

parts = String.split(path, "/") |> Enum.drop(-1)

["/folder1", "/folder1/folder2", "/folder1/folder2/folder3"]

If you modify the initial value of the accumulator, you can add the base URL if you want:

path = "folder1/folder2/folder3/last_folder"
parts = String.split(path, "/") |> Enum.drop(-1)
Enum.scan(parts, "https://wherever", fn part, acc ->
  acc <> "/" <> part
end)
|> IO.inspect

["https://wherever/folder1", "https://wherever/folder1/folder2",
 "https://wherever/folder1/folder2/folder3"]


问:
solr sorting intended only for two document
Please see my sample solr document below.

```<code>{
   "title": "Apple"
},
{
  "title": "Banana",
  "popularity": 2
},
{
  "title": "Mango",
  "popularity": 3
},
{
  "title": "Lemon",
  "popularity": 1
}
</code>```

By default the query is "title":* so all those solr document will return as result, sorted by title ascending order. It will look like this

Apple
 Banana
 Lemon
 Mango

Now, what I want is to add another sorting which a bit tricky at least for me to implement :(. I want to sort it by title ascending and by popularity descending order which only involves the popularity that has a value of 3 and 2. The result should be like this

Mango
 Banana
 Apple
 Lemon

The question is what would be the query?

Thanks

答:
You can sort it as follows:</p>

```<code>sort=map(popularity,2,3, popularity,0) desc, title asc
</code>```

Body:
Please see my sample solr document below.

{
   "title": "Apple"
},
{
  "title": "Banana",
  "popularity": 2
},
{
  "title": "Mango",
  "popularity": 3
},
{
  "title": "Lemon",
  "popularity": 1
}

By default the query is "title":* so all those solr document will return as result, sorted by title ascending order. It will look like this

Apple
 Banana
 Lemon
 Mango

Now, what I want is to add another sorting which a bit tricky at least for me to implement :(. I want to sort it by title ascending and by popularity descending order which only involves the popularity that has a value of 3 and 2. The result should be like this

Mango
 Banana
 Apple
 Lemon

The question is what would be the query?

Thanks

Body:
You can sort it as follows:

sort=map(popularity,2,3, popularity,0) desc, title asc


问:
Saving image and then loading it in Swift (iOS)
I am saving an image using saveImage.

```<code>func saveImage (image: UIImage, path: String ) -> Bool{

    let pngImageData = UIImagePNGRepresentation(image)
    //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG

    print("!!!saving image at:  \(path)")

    let result = pngImageData!.writeToFile(path, atomically: true)

    return result
}
</code>```

New info:

Saving file does not work properly ("[-] ERROR SAVING FILE" is printed)--

```<code>            // save your image here into Document Directory
        let res = saveImage(tempImage, path: fileInDocumentsDirectory("abc.png"))
        if(res == true){
            print ("[+] FILE SAVED")
        }else{
            print ("[-] ERROR SAVING FILE")
        }
</code>```

Why doesn't the saveImage function save the image? Access rights?

Older info:

The debug info says:

```<code>!!!saving image at:  file:///var/mobile/Applications/BDB992FB-E378-4719-B7B7-E9A364EEE54B/Documents/tempImage
</code>```

Then I retrieve this location using

```<code>fileInDocumentsDirectory("tempImage")
</code>```

The result is correct.

Then I am loading the file using this path

```<code>    let image = UIImage(contentsOfFile: path)

    if image == nil {

        print("missing image at: \(path)")
    }else{
        print("!!!IMAGE FOUND at: \(path)")
    }
</code>```

The path is correct, but the message is "missing image at..". Is the file somehow inaccessible or not stored? What can be a reason for this behavior?

I am testing this code on iphone 4 with ios 7 and iphone 5 with ios 7 simulator.

Edit:
1. The fileInDocumentsDirectory function

```<code>func fileInDocumentsDirectory(filename: String) -> String {

    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let fileURL = documentsURL.URLByAppendingPathComponent(filename).absoluteString
    return fileURL
}
</code>```

答:
This function will save an image in the documents folder:

```<code>func saveImage(image: UIImage) -> Bool {
    guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
        return false
    }
    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent("fileName.png")!)
        return true
    } catch {
        print(error.localizedDescription)
        return false
    }
}
</code>```

To use:

```<code>let success = saveImage(image: UIImage(named: "image.png")!)
</code>```

This function will get that image:

```<code>func getSavedImage(named: String) -> UIImage? {
    if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
        return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
    }
    return nil
}
</code>```

To use:

```<code>if let image = getSavedImage(named: "fileName") {
    // do something with image
}
</code>```

Body:
I am saving an image using saveImage.

func saveImage (image: UIImage, path: String ) -> Bool{

    let pngImageData = UIImagePNGRepresentation(image)
    //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG

    print("!!!saving image at:  \(path)")

    let result = pngImageData!.writeToFile(path, atomically: true)

    return result
}

New info:

Saving file does not work properly ("[-] ERROR SAVING FILE" is printed)--

            // save your image here into Document Directory
        let res = saveImage(tempImage, path: fileInDocumentsDirectory("abc.png"))
        if(res == true){
            print ("[+] FILE SAVED")
        }else{
            print ("[-] ERROR SAVING FILE")
        }

Why doesn't the saveImage function save the image? Access rights?

Older info:

The debug info says:

!!!saving image at:  file:///var/mobile/Applications/BDB992FB-E378-4719-B7B7-E9A364EEE54B/Documents/tempImage

Then I retrieve this location using

fileInDocumentsDirectory("tempImage")

The result is correct.

Then I am loading the file using this path

    let image = UIImage(contentsOfFile: path)

    if image == nil {

        print("missing image at: \(path)")
    }else{
        print("!!!IMAGE FOUND at: \(path)")
    }

The path is correct, but the message is "missing image at..". Is the file somehow inaccessible or not stored? What can be a reason for this behavior?

I am testing this code on iphone 4 with ios 7 and iphone 5 with ios 7 simulator.

Edit:
1. The fileInDocumentsDirectory function

func fileInDocumentsDirectory(filename: String) -> String {

    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let fileURL = documentsURL.URLByAppendingPathComponent(filename).absoluteString
    return fileURL
}

Body:
This function will save an image in the documents folder:

func saveImage(image: UIImage) -> Bool {
    guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
        return false
    }
    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent("fileName.png")!)
        return true
    } catch {
        print(error.localizedDescription)
        return false
    }
}

To use:

let success = saveImage(image: UIImage(named: "image.png")!)

This function will get that image:

func getSavedImage(named: String) -> UIImage? {
    if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
        return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
    }
    return nil
}

To use:

if let image = getSavedImage(named: "fileName") {
    // do something with image
}

ContentLicense: CC BY-SA 4.0


问:
Name is not defined error for defined function?
I have a python script and I am receiving the following error:

File "C:\AIND\AIND-isolation\AIND-Isolation\game_agent.py", line 229, in minimax
  my_minimax(current_location, current_depth, max_depth)
  NameError: name 'my_minimax' is not defined
```

<p>Here is the code that causes the problem:</p>

```class MinimaxPlayer(IsolationPlayer):

    def my_minimax(self, current_location, current_depth, max_depth):
        print("my_minimax")

    def minimax(self, game, depth):

        if self.time_left() < self.TIMER_THRESHOLD:
            raise SearchTimeout()

        # TODO: finish this function!
        legal_moves = game.get_legal_moves()

        if not legal_moves:
            return (-1, -1)

        _, move = max([(self.score(game.forecast_move(node), self), node)
                        for node in legal_moves])

        current_depth = 0
        max_depth = depth
        current_location = game.get_player_location(self)

        my_minimax(current_location, current_depth, max_depth)

        return move
```

I defined the function before I use it. Why can't the function be found?

答:
my_minimax is a method of MinimaxPlayer.

Call self.my_minimax(...)

Body:
I have a python script and I am receiving the following error:

File "C:\AIND\AIND-isolation\AIND-Isolation\game_agent.py", line 229, in minimax
  my_minimax(current_location, current_depth, max_depth)
  NameError: name 'my_minimax' is not defined

Here is the code that causes the problem:

class MinimaxPlayer(IsolationPlayer):

    def my_minimax(self, current_location, current_depth, max_depth):
        print("my_minimax")

    def minimax(self, game, depth):

        if self.time_left() < self.TIMER_THRESHOLD:
            raise SearchTimeout()

        # TODO: finish this function!
        legal_moves = game.get_legal_moves()

        if not legal_moves:
            return (-1, -1)

        _, move = max([(self.score(game.forecast_move(node), self), node)
                        for node in legal_moves])

        current_depth = 0
        max_depth = depth
        current_location = game.get_player_location(self)

        my_minimax(current_location, current_depth, max_depth)

        return move

I defined the function before I use it. Why can't the function be found?


问:
Xamarin Forms Pop-in with custom renderers
I have a Xamarin Forms app for android that makes use of custom renderers for images. I have optimized these images to the point where the Bitmaps are only around 600kb in memory with InSampleSize, but I am having issues with pop-in. Namely, when I open a page using these images from my MasterDetailPage, the images load fast, but you can still see them pop into view 100-200ms after the page is displayed.

Here's how I'm loading the pages in my MasterDetailPage

```<code>private void Button_Clicked(object sender, EventArgs e)
{
    var temp = new NavigationPage(new Pages.HomePage());
    Detail = temp;
    IsPresented = false;
}
</code>```

What I would like to do is, if possible, pre-render the page before it is navigated to in the UI to cover up the pop-in, or any other solution that would essentially remove it completely.

答:
Usually in Xamarin Forms people use FFImageLoading library

Xamarin.iOS, Xamarin.Android, Xamarin.Forms and Windows (WinRT, UWP)
support

Configurable disk and memory caching

Multiple image views using the same image source (url, path, resource) will use only one bitmap which is cached in memory (less memory usage)

Deduplication of similar download/load requests. (If 100 similar requests arrive at same time then one real loading will be performed while 99 others
will wait)

Error and loading placeholders support

Images can be automatically downsampled to specified size (less memory usage)

Fluent API which is inspired by Picasso naming SVG & WebP support

Image loading Fade-In animations support

Can retry image downloads (RetryCount, RetryDelay)

Android bitmap optimization. Saves 50% of memory by trying not to use transparency channel when possible.

Transformations support BlurredTransformation CircleTransformation,
RoundedTransformation, CornersTransformation, CropTransformation
ColorSpaceTransformation, GrayscaleTransformation,
SepiaTransformation, TintTransformation FlipTransformation,
RotateTransformation

Supports custom transformations (native platform
ITransformation implementations)

Here you can find some docs

Body:
I have a Xamarin Forms app for android that makes use of custom renderers for images. I have optimized these images to the point where the Bitmaps are only around 600kb in memory with InSampleSize, but I am having issues with pop-in. Namely, when I open a page using these images from my MasterDetailPage, the images load fast, but you can still see them pop into view 100-200ms after the page is displayed.

Here's how I'm loading the pages in my MasterDetailPage

private void Button_Clicked(object sender, EventArgs e)
{
    var temp = new NavigationPage(new Pages.HomePage());
    Detail = temp;
    IsPresented = false;
}

What I would like to do is, if possible, pre-render the page before it is navigated to in the UI to cover up the pop-in, or any other solution that would essentially remove it completely.


问:
How do you find a particular piece of functionality in a large codebase?
I was fascinated by the "press Tab to search site" feature in chromium, so naturally I wanted to see how exactly it was implemented in code.

A little background for anybody who aren't familiar with this. After navigating to some site, say wikipedia, and doing a search, chromium remembers the name of the query variable and will let you press tab and search the site directly from the address bar. Neat!

Problem is the codebase for chromium is huge and I've had no luck in finding the method/function that handles this.

How do you approach a large codebase when you are looking for the implementation of a particular piece of functionality? Any tricks for narrowing it down? Preferably it should not require building the software with debug symbols and following the flow through the program.

答: Ask the Chromium team. They don't give points or bronze pixels but they're definitely the authority and right people to ask this sort of questions.</p>


问:
New single after error
i develop my own download user data flow, and have problem. Buyt first some code, method explanation:

```<code>loginManager.getAccessToken() //Returns Single<String> where string is my access token
loginManager.getRefreshToken() //Returns Single<String> where string is my refresh token
loginManager.downloadUserAccountData(String accessToken) //Returns Single<String> where string is my json response
loginManager.refreshAccessToken(String refreshToken) //Returns Single<String> where string is new access token
userManager.parseUserJson(String json) //Returns Single<User> where User is my user model
userManager.storeUser(User user) //Returns Completable
</code>```

Currently I doning something like that:

```<code>Completable getAndStoreUserData = loginManager.getAccessToken()
        .flatMap(loginManager::downloadUserAccountData)
        .flatMap(userManager::parseUserJson)
        .flatMapCompletable(userManager::storeUser);
</code>```

But this does not support, refresh access token and retry download. Server throw 403 when my accessToken is not current, so i return error in that case in my function downloadUserAccountData

Now i have tried to use doOnError() and onErrorReturn() but both of this operartors don't met my requirements. This is because doOnError() allow only to e.g. display Log and dont return anything. onErrorReturn() lets me return only value not a Single<Value>.

This is pseudocode i trying to achieve:

```<code>Completable getAndStoreUserData = loginManager.getAccessToken()
        .flatMap(loginManager::downloadUserAccountData)
        .onErrorReturn(error -> loginManager.getRefreshToken()
                .flatMap(loginManager::refreshAccessToken)
                .flatMap(loginManager::downloadUserAccountData)
        .flatMap(userManager::parseUserJson)
        .flatMapCompletable(userManager::storeUser);
</code>```

Any examples appreciated :)

答:
I finally managed, how to do it. As @Cochi proposed i have used retryWhen() function. This is very simple example based on String for anyone else:

```<code>String body = null;

@Override
protected void onStart() {
    super.onStart();

    Single<String> stringSingle = Single.create(source -> {
                if(body != null) {
                    source.onSuccess(body);
                }
                else {
                    source.onError(new Exception("403"));
                }
            })
            .retryWhen(errors -> errors.flatMap(error -> {
                if(error.getMessage().contains("403")) {
                    Throwable throwable = refresh().blockingGet();
                    if(throwable == null) {
                        return Flowable.just(new Object());
                    }
                    return Flowable.error(throwable);
                }
                return Flowable.error(error);
            }))
            .flatMap(obj -> Single.just(obj.toString()));
}

public Completable refresh() {
    return Completable.create(source -> {
        try {
            body = "Success";
            source.onComplete();
        }
        catch (Exception e) {
            source.onError(e);
        }
    });
}
</code>```

And there is full example, using my code:

```<code>Completable getAndStoreUserData() {}
    Completable getAndStoreUserData = loginManager.getAccessToken()
            .flatMap(loginManager::downloadUserAccountData)
            .retryWhen(errors -> errors.flatmap(this::retryConditionChecker))
            .flatMapCompletable(userManager::storeUser);

    return getAndStoreUserData
}

Publisher<?> retryConditionChecker(Throwable error) {
    if(error.getMessage().contains("403")) {

        Throwable throwable = loginManager.getRefreshToken()
                .flatMap(loginManager::refreshAccessToken)
                .flatMapCompletable(loginManager::replaceAccessToken)
                .blockingGet();

        if(throwable == null) {
            return Flowable.just(new Object());
        }
        return Flowable.error(throwable);
    }
    return Flowable.error(error);
}
</code>```

But biggest problem there is blockingGet(). I believe this is very bad solution. Maybe anyone know any better one?

Title: New single after error

Body:
i develop my own download user data flow, and have problem. Buyt first some code, method explanation:

loginManager.getAccessToken() //Returns Single<String> where string is my access token
loginManager.getRefreshToken() //Returns Single<String> where string is my refresh token
loginManager.downloadUserAccountData(String accessToken) //Returns Single<String> where string is my json response
loginManager.refreshAccessToken(String refreshToken) //Returns Single<String> where string is new access token
userManager.parseUserJson(String json) //Returns Single<User> where User is my user model
userManager.storeUser(User user) //Returns Completable

Currently I doning something like that:

Completable getAndStoreUserData = loginManager.getAccessToken()
        .flatMap(loginManager::downloadUserAccountData)
        .flatMap(userManager::parseUserJson)
        .flatMapCompletable(userManager::storeUser);

But this does not support, refresh access token and retry download. Server throw 403 when my accessToken is not current, so i return error in that case in my function downloadUserAccountData

Now i have tried to use doOnError() and onErrorReturn() but both of this operartors don't met my requirements. This is because doOnError() allow only to e.g. display Log and dont return anything. onErrorReturn() lets me return only value not a Single<Value>.

This is pseudocode i trying to achieve:

Completable getAndStoreUserData = loginManager.getAccessToken()
        .flatMap(loginManager::downloadUserAccountData)
        .onErrorReturn(error -> loginManager.getRefreshToken()
                .flatMap(loginManager::refreshAccessToken)
                .flatMap(loginManager::downloadUserAccountData)
        .flatMap(userManager::parseUserJson)
        .flatMapCompletable(userManager::storeUser);

Any examples appreciated :)

Body:
I finally managed, how to do it. As @Cochi proposed i have used retryWhen() function. This is very simple example based on String for anyone else:

String body = null;

@Override
protected void onStart() {
    super.onStart();

    Single<String> stringSingle = Single.create(source -> {
                if(body != null) {
                    source.onSuccess(body);
                }
                else {
                    source.onError(new Exception("403"));
                }
            })
            .retryWhen(errors -> errors.flatMap(error -> {
                if(error.getMessage().contains("403")) {
                    Throwable throwable = refresh().blockingGet();
                    if(throwable == null) {
                        return Flowable.just(new Object());
                    }
                    return Flowable.error(throwable);
                }
                return Flowable.error(error);
            }))
            .flatMap(obj -> Single.just(obj.toString()));
}

public Completable refresh() {
    return Completable.create(source -> {
        try {
            body = "Success";
            source.onComplete();
        }
        catch (Exception e) {
            source.onError(e);
        }
    });
}

And there is full example, using my code:

Completable getAndStoreUserData() {}
    Completable getAndStoreUserData = loginManager.getAccessToken()
            .flatMap(loginManager::downloadUserAccountData)
            .retryWhen(errors -> errors.flatmap(this::retryConditionChecker))
            .flatMapCompletable(userManager::storeUser);

    return getAndStoreUserData
}

Publisher<?> retryConditionChecker(Throwable error) {
    if(error.getMessage().contains("403")) {

        Throwable throwable = loginManager.getRefreshToken()
                .flatMap(loginManager::refreshAccessToken)
                .flatMapCompletable(loginManager::replaceAccessToken)
                .blockingGet();

        if(throwable == null) {
            return Flowable.just(new Object());
        }
        return Flowable.error(throwable);
    }
    return Flowable.error(error);
}

But biggest problem there is blockingGet(). I believe this is very bad solution. Maybe anyone know any better one?


问:
How do i remove "random.math" enemies on my canvas at level three
I am creating a small game atm. There is infinite levels in the game. In the different levels enemies spawn from the y-akses with the "Random.math", so they just spawn randomly. There is player, who have to shoot the small enemies.

Regarding to my question. At level 3 i want the "Random.math" enemies to disappear and add a "Boss" istead. A link to the under progress

game

http://www.beproductive.dk/examgame/ss.html

This is my nextLevel function:

```<code>function nextLevel() {
"use strict"
settings.level++;
addEnemies();
// change text
levelText.text = "level " + settings.level;
// put it to the left of the screen
levelText.x = -100;
levelText.y = -100;
levelText.textAlign = "center";
levelText.textBaseline = "middle";

// animate in
createjs.Tween.get(levelText).to({
        x: 300,
        y: 400

    }, 1500, createjs.Ease.backOut).wait(500).to({
            x: 800,
            y: -100
        },
        1000)
    // animate out

// sound
createjs.Sound.play('vundet');

if (settings.level == 3) {
     console.log("bosslevel");

    var temp = new createjs.Sprite(enemiesSS, "sprite4");
    temp.width = 16;
    temp.height = 16;
    temp.x = 50;
    temp.y = 50;

    stage.addChild(temp);

}
</code>```

}

With this piece of code here, it should remove the ramdom spawn enemies, where only the "Boss" is left on the canvas. I just can't figure it out where to place it in my nextlevel function:

```<code>   for (var i = enemies.length - 1; i >= 0; i--) {
        stage.removeChild(enemies[i]);
    } enemies = []
</code>```

Yours sincerely

答:
You could create an if statement saying if it's a specific level to add a boss instead of adding enemies. </p>

```<code>If(level == 30 || level == 40)
    addBoss();

 Else
    addEnemies();
</code>```

Body:
I am creating a small game atm. There is infinite levels in the game. In the different levels enemies spawn from the y-akses with the "Random.math", so they just spawn randomly. There is player, who have to shoot the small enemies.

Regarding to my question. At level 3 i want the "Random.math" enemies to disappear and add a "Boss" istead. A link to the under progress

game

http://www.beproductive.dk/examgame/ss.html

This is my nextLevel function:

function nextLevel() {
"use strict"
settings.level++;
addEnemies();
// change text
levelText.text = "level " + settings.level;
// put it to the left of the screen
levelText.x = -100;
levelText.y = -100;
levelText.textAlign = "center";
levelText.textBaseline = "middle";

// animate in
createjs.Tween.get(levelText).to({
        x: 300,
        y: 400

    }, 1500, createjs.Ease.backOut).wait(500).to({
            x: 800,
            y: -100
        },
        1000)
    // animate out

// sound
createjs.Sound.play('vundet');

if (settings.level == 3) {
     console.log("bosslevel");

    var temp = new createjs.Sprite(enemiesSS, "sprite4");
    temp.width = 16;
    temp.height = 16;
    temp.x = 50;
    temp.y = 50;

    stage.addChild(temp);

}

}

With this piece of code here, it should remove the ramdom spawn enemies, where only the "Boss" is left on the canvas. I just can't figure it out where to place it in my nextlevel function:

   for (var i = enemies.length - 1; i >= 0; i--) {
        stage.removeChild(enemies[i]);
    } enemies = []

Yours sincerely

Body:
You could create an if statement saying if it's a specific level to add a boss instead of adding enemies.

If(level == 30 || level == 40)
    addBoss();

 Else
    addEnemies();


问:
Applying `const` CV-qualifier to decaying array-style `T arr[]` function parameter (intended to decay to `T * const arr`)
I'll start by pointing out that this question is purely out of curiosity, in so hoping to avoid discussions such as

"Consider staying away from new/dynamic arrays, and use fit-for-purpose stdlib containers instead, e.g. std::vector."

or

"Why would you want to use int arr[] parameter syntax on the first place? I always thought that it is considered to be one of the confusing abominations."

Decaying an array-style function parameter to T * const arr?

If I'm not wrong, the function signatures in the two following functions–intended to be called with a dynamically allocated C-style array–are equivalent due to decay, the first argument being (explicitly or by decay) a raw pointer to int.

```<code>// A) mutable raw ptr to mutable elements
void foo(int * arr, unsigned n)
{
  // ...
  arr = nullptr; // legal
}

// B) mutable raw ptr to mutable elements
void foo(int arr[], unsigned n)
      /* decays to int * arr */
{
  // ...
  arr = nullptr; // legal
}

// ... used e.g. as
int * arr = new int[3]{1, 2, 3}; // c++11
foo(arr, 3);
delete[] arr;
</code>```

Now, let's say for some reason we would like the raw pointer (which has been passed to the function as a copy by value) to be a const pointer (e.g. for correctness). For A), this is straight-forward:

```<code>// A') const raw ptr to mutable elements
void foo(int * const arr, unsigned n)
{
  arr = nullptr; // illegal, OK!
  // ...
}
</code>```

For B) however, I haven't been able to perform this modification.

Question:

Is it possible to specify an "array-type" function parameter (intended for a dynamic array argument) that decays into T * const arr?

(I'm naturally happy to receive a proper duplicate target that answers this; I wasn't able to find one myself. The closest one I found doesn't quite answer the above, as far as I can tell).

答:
No, it's not possible to do this, it would be useless syntax, and since neither the top-level const nor the array type is actually part of the function signature it would just be misleading.

If you want to declare the parameter as a non-modifiable pointer then do that. Don't write some other type which is decayed to something different.

You can still declare it using the array for if you think there's some reason to do that, and then add the const in the definition:

```<code>// declaration
void foo(int arr[], unsigned n);

// definition
void foo(int * const arr, unsigned n)
{
  ...
}
</code>```

Body:
I'll start by pointing out that this question is purely out of curiosity, in so hoping to avoid discussions such as

"Consider staying away from new/dynamic arrays, and use fit-for-purpose stdlib containers instead, e.g. std::vector."

or

"Why would you want to use int arr[] parameter syntax on the first place? I always thought that it is considered to be one of the confusing abominations."

Decaying an array-style function parameter to T * const arr?

If I'm not wrong, the function signatures in the two following functions–intended to be called with a dynamically allocated C-style array–are equivalent due to decay, the first argument being (explicitly or by decay) a raw pointer to int.

// A) mutable raw ptr to mutable elements
void foo(int * arr, unsigned n)
{
  // ...
  arr = nullptr; // legal
}

// B) mutable raw ptr to mutable elements
void foo(int arr[], unsigned n)
      /* decays to int * arr */
{
  // ...
  arr = nullptr; // legal
}

// ... used e.g. as
int * arr = new int[3]{1, 2, 3}; // c++11
foo(arr, 3);
delete[] arr;

Now, let's say for some reason we would like the raw pointer (which has been passed to the function as a copy by value) to be a const pointer (e.g. for correctness). For A), this is straight-forward:

// A') const raw ptr to mutable elements
void foo(int * const arr, unsigned n)
{
  arr = nullptr; // illegal, OK!
  // ...
}

For B) however, I haven't been able to perform this modification.

Question:

Is it possible to specify an "array-type" function parameter (intended for a dynamic array argument) that decays into T * const arr?

(I'm naturally happy to receive a proper duplicate target that answers this; I wasn't able to find one myself. The closest one I found doesn't quite answer the above, as far as I can tell).

Body:
No, it's not possible to do this, it would be useless syntax, and since neither the top-level const nor the array type is actually part of the function signature it would just be misleading.

If you want to declare the parameter as a non-modifiable pointer then do that. Don't write some other type which is decayed to something different.

You can still declare it using the array for if you think there's some reason to do that, and then add the const in the definition:

// declaration
void foo(int arr[], unsigned n);

// definition
void foo(int * const arr, unsigned n)
{
  ...
}


问:
Flex-box Dilema
I have been working on a site with a left pop open Navigation bar. I got it right to get my content to wrap with flex-box and wrap, but my #main section does not wrap when the nav bar is opened and falls off my page. Any one able to assist me with this as I am super new to CSS3.

Layout:What the layout looks like

My problem:My content bleeding off of my page

Code (HTML):

```<code><!DOCTYPE html>

<html>
<head>

<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="nav.js"></script>

</head>

<body>

<nav id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn"
    onclick="closeNav()">×</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Contact</a>
</nav>

<section id="main">
  <span style="font-size:30px;cursor:pointer"
    onclick="openNav()">☰</span>
  <br>
  <section class="box-container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </section>
</section>

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

Code (CSS):

```<code>* {
box-sizing: border-box;
}

body {
font-family: arial;
}

.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: flex;
    flex-wrap: wrap;
    transition: 0.3s;
}

.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 15px;
    font-size: 26px;
    margin-left: 30px;
}

/* PROBLEM ARIA */

#main {
    transition: margin-left .5s;
    padding: 16px;
    display: flex;
    flex-flow: wrap;
    width: auto;
    /*float: left;*/
}

.box {
    text-align: center;
    width: calc(33.33% - 20px);
    height: 280px;
    margin: 10px;
    background-color: black;
}

.box-container {
    padding: 25px;
    min-width: 97vw;
    display: flex;
    flex-wrap: wrap;
    background-color: white;
    margin: auto;
}
</code>```

答:
Without the HTML code we can only guess based on the images you posted, but it seems your .sidenav  is part of the flex container, that's why it moves the rest of the stuff when it becomes visible.

Just take your .sidenav out of the flex-container (#main)  and let it be independent from the flex stuff.

Title: Flex-box Dilema

Body:
I have been working on a site with a left pop open Navigation bar. I got it right to get my content to wrap with flex-box and wrap, but my #main section does not wrap when the nav bar is opened and falls off my page. Any one able to assist me with this as I am super new to CSS3.

Layout:What the layout looks like

My problem:My content bleeding off of my page

Code (HTML):

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="style.css">

  ×
  About
  Services
  Contact

  ☰

Code (CSS):

* {
box-sizing: border-box;
}

body {
font-family: arial;
}

.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: flex;
    flex-wrap: wrap;
    transition: 0.3s;
}

.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 15px;
    font-size: 26px;
    margin-left: 30px;
}

/* PROBLEM ARIA */

#main {
    transition: margin-left .5s;
    padding: 16px;
    display: flex;
    flex-flow: wrap;
    width: auto;
    /*float: left;*/
}

.box {
    text-align: center;
    width: calc(33.33% - 20px);
    height: 280px;
    margin: 10px;
    background-color: black;
}

.box-container {
    padding: 25px;
    min-width: 97vw;
    display: flex;
    flex-wrap: wrap;
    background-color: white;
    margin: auto;
}