问:
How to serve image from Node Server without Express?
I am working on Node v6.10.2. I am trying to serve static elements with a simple NodeJS program. When I run the below mentioned code and go to http://localhost:3000/, I get this.

The image does not get retrieved here. But when I go to http://localhost:3000/img/logo.jpg, I get the image. How do I resolve this issue?

This is the server code

```<code>var http = require('http');
var fs = require('fs');

function serveStaticFile(res, path, contentType, responseCode) {
    if(!responseCode) responseCode = 200;

    // __dirname will resolve to the directory the executing script resides in.
    // So if your script resides in /home/sites/app.js, __dirname will resolve
    // to /home/sites.

    console.log(__dirname + path);

    fs.readFile(__dirname + path, function(err, data) {
        if(err) {
            res.writeHead(500, { 'Content-Type' : 'text/plain' });
            res.end('500 - Internal Error');
        }
        else {
            res.writeHead( responseCode, { 'Content-Type' : contentType });
            res.end(data);
        }
    });
}

http.createServer( function (req, res) {
    var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
    switch(path) {
        case '':
            serveStaticFile(res, '/public/home.html', 'text/html');
            break;
        case '/about':
            serveStaticFile(res, '/public/about.html', 'text/html');
            break;
        case '/img/logo.jpg':
            serveStaticFile(res, '/public/img/logo.jpg', 'image/jpeg');
            break;
        default:
            serveStaticFile(res, '/public/404.html', 'text/html', 404);
            break;
    }
}).listen(3000);

console.log('Server started on localhost:3000; press Ctrl-C to terminate...');
</code>```

This is the html file - home.html

```<code><!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    Welcome Home!!!
    <img href="localhost:3000/img/logo.jpg" alt="logo">
</body>
</html>
</code>```

答:
You are missing the http:// from the img src. I will also note that as @Shashank pointed out you should be using src rather than href.

Putting this all together:

```<code><img src="http://localhost:3000/img/logo.jpg" alt="logo">
</code>```

Body:
I am working on Node v6.10.2. I am trying to serve static elements with a simple NodeJS program. When I run the below mentioned code and go to http://localhost:3000/, I get this.

The image does not get retrieved here. But when I go to http://localhost:3000/img/logo.jpg, I get the image. How do I resolve this issue?

This is the server code

var http = require('http');
var fs = require('fs');

function serveStaticFile(res, path, contentType, responseCode) {
    if(!responseCode) responseCode = 200;

    // __dirname will resolve to the directory the executing script resides in.
    // So if your script resides in /home/sites/app.js, __dirname will resolve
    // to /home/sites.

    console.log(__dirname + path);

    fs.readFile(__dirname + path, function(err, data) {
        if(err) {
            res.writeHead(500, { 'Content-Type' : 'text/plain' });
            res.end('500 - Internal Error');
        }
        else {
            res.writeHead( responseCode, { 'Content-Type' : contentType });
            res.end(data);
        }
    });
}

http.createServer( function (req, res) {
    var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
    switch(path) {
        case '':
            serveStaticFile(res, '/public/home.html', 'text/html');
            break;
        case '/about':
            serveStaticFile(res, '/public/about.html', 'text/html');
            break;
        case '/img/logo.jpg':
            serveStaticFile(res, '/public/img/logo.jpg', 'image/jpeg');
            break;
        default:
            serveStaticFile(res, '/public/404.html', 'text/html', 404);
            break;
    }
}).listen(3000);

console.log('Server started on localhost:3000; press Ctrl-C to terminate...');

This is the html file - home.html

<!DOCTYPE html>

    <title>Home</title>

    Welcome Home!!!

Body:
You are missing the http:// from the img src. I will also note that as @Shashank pointed out you should be using src rather than href.

Putting this all together:

<img src="http://localhost:3000/img/logo.jpg" alt="logo">


来源: stackexchange

问:
Is it a memory leak of Image?
I'm making a photo browser. I load 15 photos as Images and add these Images to HGroup every time. When user presses 'next page', I first unload the existing Images by 'Image.unloadAndStop()' and 'Image.source=null', and then load new photos. However, it seems that the GC never works. The task monitor shows that the memory use of my AIR reaches as much as 1.2G! Some people said it's a bug of Image when you load a picture larger than 1.5M. Is it true? Can I solve this problem?

Thanks!

答:
In the past I have found orphaned listeners to be the culprit.  Any listener still tied to the asset will render the asset non-GC-able.  Make sure your cleanup method removes all listeners bound to the images.  Just a guess.

Have you tried bitMap.dispose() as you remove the images?  I believe this offers the bitmap for GC.

ContentLicense: CC BY-SA 2.5

Title: Is it a memory leak of Image?


问:
error after using imshow() in mac
My code:

```<code>import cv2
import numpy
import matplotlib

img=cv2.imread('square1.png')
cv2.imshow('FRAME',img)
cv2.waitKey()
</code>```

Error message:

```<code>Traceback (most recent call last):
  File "/Users/tusharsharma/Desktop/image project/test1.py", line 5, in <module> cv2.imshow('FRAME',img)
cv2.error: /Users/travis/build/skvark/opencv-python/opencv/modules/highgui/src/window.cpp:583:
error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support.
If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config,
then re-run cmake or configure script in function cvShowImage
</code>```

OS is macOS Sierra. I had installed OpenCV using homebrew for Python 3.

答:
You may check these tutorials for solving the problem on installing OpenCV 3 for Python 3 for macOS.

macOS: Install OpenCV 3 and Python 3.5

Install OpenCV 3 on macOS with Homebrew (the easy way)

Resolving macOS, OpenCV, and Homebrew install errors

Hope this help.

ContentLicense: CC BY-SA 3.0

Title: error after using imshow() in mac

Body:
My code:

import cv2
import numpy
import matplotlib

img=cv2.imread('square1.png')
cv2.imshow('FRAME',img)
cv2.waitKey()

Error message:

Traceback (most recent call last):
  File "/Users/tusharsharma/Desktop/image project/test1.py", line 5, in <module> cv2.imshow('FRAME',img)
cv2.error: /Users/travis/build/skvark/opencv-python/opencv/modules/highgui/src/window.cpp:583:
error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support.
If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config,
then re-run cmake or configure script in function cvShowImage

OS is macOS Sierra. I had installed OpenCV using homebrew for Python 3.


问:
checking the input type in C
I want to check if my input is an integer (and not a char or string for example).
I stumbled across this code (that works):

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

int main (void)
{
    float a;
    int q;

    printf("\nInsert number\t");
    scanf("%f",&a);

    q=(int)a;
    ++q;

    if((q - a) != 1)
        printf("\nThe number is not an integer\n\n");
    else
        printf("\nThe number is an integer\n\n");

    return 0;
}
</code>```

Can someone please explain why it works?

答:
The code itself is pretty simple, we are changing casting float to int and then incremented the int value:

```<code>q=(int)a;
++q;
</code>```

Then, everytime there was an int provided as the input, the result of (q-a) will be exactly 1. However, it the input provided (and saved to float a) was of type float, result will be greater less than 1 (for positive numbers).

This is because in (q-a), q will be converted to float and the result of it will also be float.

Refer for example for the C book:

Otherwise, if either operand is a float, then the other one is
  converted to float, and that is the type of the result.

Title: checking the input type in C

Body:
I want to check if my input is an integer (and not a char or string for example).
I stumbled across this code (that works):

#include <stdio.h>

int main (void)
{
    float a;
    int q;

    printf("\nInsert number\t");
    scanf("%f",&a);

    q=(int)a;
    ++q;

    if((q - a) != 1)
        printf("\nThe number is not an integer\n\n");
    else
        printf("\nThe number is an integer\n\n");

    return 0;
}

Can someone please explain why it works?

Body:
The code itself is pretty simple, we are changing casting float to int and then incremented the int value:

q=(int)a;
++q;

Then, everytime there was an int provided as the input, the result of (q-a) will be exactly 1. However, it the input provided (and saved to float a) was of type float, result will be greater less than 1 (for positive numbers).

This is because in (q-a), q will be converted to float and the result of it will also be float.

Refer for example for the C book:

Otherwise, if either operand is a float, then the other one is
  converted to float, and that is the type of the result.


问:
tkinter canvas stays minimized
how do I get a canvas to actually have a size?

```<code>root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

root.after(1, draw)
mainloop()
</code>```

just creates a window with a 1px canvas in the top left corner

edit: I omitted draw, because it didn’t throw anything, thus didn’t seem relevant. But since it runs perfectly if I n through it via pdb, here’s the full code:

```<code>from tkinter import *
from pdb import set_trace

class Field: #abstact
    def __init__(self, size):
        super().__init__()
        self.tiles = [[(None, 0) for i in range(size[1])] for j in     range(size[0])] #list of columns

    def get_tile(self, x,y):
        return tiles[x][y]

    def inc_tile(self, x,y,player):
        t = self.tiles[x][y]
        tiles[x][y] = (player, t[1])

class RectField(Field):
    def __init__(self, size):
        super().__init__(size)

    def select_tile(self, x, y):
        lx = len(self.tiles)
        rx = floor(x*lx)
        ly = len(self.tiles[rx])
        ry = floor(x*ly)
        return (rx, ry)

    def draw(self, canvas):
        canvas.delete(ALL)
        w = canvas.winfo_width()
        h = canvas.winfo_height()
        canvas.create_rectangle(0, 0, w, h, fill='#f0f')
        sx = w/len(self.tiles)
        for i in range(len(self.tiles)):
            sy = h/len(self.tiles[i])
            for j in range(len(self.tiles[i])):
                pl = self.tiles[i][j][0]
                cl = '#888' if not pl else ('#f20' if pl == 1 else '#02f')
                canvas.create_rectangle(i*sx, j*sy, (i+1)*sx, (j+1)*sy,     fill=cl, outline='#000')

    ##############################################################################    #####################
# MAIN
##############################################################################    #####################

root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

#set_trace()
field = RectField((4,4))

def init():
    canv.create_rectangle(0, 0, 600, 600, fill='#f0f')
    set_trace()
    field.draw(canv)
    root.update()

root.after(1, init)
mainloop()
</code>```

OS is ubuntu 16.04,
python version is the preinstalled python3, run via terminal

答:
Your canvas is not staying minimized. If you were to give the canvas a distinct background color you would see that it immediately fills the whole window, and stays that way.

You are getting 1 for the window width and height because you aren't giving tkinter enough time to draw  it before asking for the size. winfo_width and winfo_height return the actual height, and the actual height can't be computed until the window is actually visible on the screen.

The simplest solution is to force an update before calling your init function. You can do this by calling update and then calling init rather than using after.

Instead of this:

```<code>root.after(1, init)
</code>```

Do this:

```<code>root.update()
init()
</code>```

Title: tkinter canvas stays minimized

Body:
how do I get a canvas to actually have a size?

root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

root.after(1, draw)
mainloop()

just creates a window with a 1px canvas in the top left corner

edit: I omitted draw, because it didn’t throw anything, thus didn’t seem relevant. But since it runs perfectly if I n through it via pdb, here’s the full code:

from tkinter import *
from pdb import set_trace

class Field: #abstact
    def __init__(self, size):
        super().__init__()
        self.tiles = [[(None, 0) for i in range(size[1])] for j in     range(size[0])] #list of columns

    def get_tile(self, x,y):
        return tiles[x][y]

    def inc_tile(self, x,y,player):
        t = self.tiles[x][y]
        tiles[x][y] = (player, t[1])

class RectField(Field):
    def __init__(self, size):
        super().__init__(size)

    def select_tile(self, x, y):
        lx = len(self.tiles)
        rx = floor(x*lx)
        ly = len(self.tiles[rx])
        ry = floor(x*ly)
        return (rx, ry)

    def draw(self, canvas):
        canvas.delete(ALL)
        w = canvas.winfo_width()
        h = canvas.winfo_height()
        canvas.create_rectangle(0, 0, w, h, fill='#f0f')
        sx = w/len(self.tiles)
        for i in range(len(self.tiles)):
            sy = h/len(self.tiles[i])
            for j in range(len(self.tiles[i])):
                pl = self.tiles[i][j][0]
                cl = '#888' if not pl else ('#f20' if pl == 1 else '#02f')
                canvas.create_rectangle(i*sx, j*sy, (i+1)*sx, (j+1)*sy,     fill=cl, outline='#000')

    ##############################################################################    #####################
# MAIN
##############################################################################    #####################

root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

#set_trace()
field = RectField((4,4))

def init():
    canv.create_rectangle(0, 0, 600, 600, fill='#f0f')
    set_trace()
    field.draw(canv)
    root.update()

root.after(1, init)
mainloop()

OS is ubuntu 16.04,
python version is the preinstalled python3, run via terminal

Body:
Your canvas is not staying minimized. If you were to give the canvas a distinct background color you would see that it immediately fills the whole window, and stays that way.

You are getting 1 for the window width and height because you aren't giving tkinter enough time to draw  it before asking for the size. winfo_width and winfo_height return the actual height, and the actual height can't be computed until the window is actually visible on the screen.

The simplest solution is to force an update before calling your init function. You can do this by calling update and then calling init rather than using after.

Instead of this:

root.after(1, init)

Do this:

root.update()
init()


问:
Python List random choice
Looking for a help / solution here.

```<code>a = [1,2,3]
b = [1,2,3]
c = [1,2,3]
d = [a,b,c]

random.choice(random.choice(d))
</code>```

this gives me 1,2 or 3. But how to find which list variable this random function used out of a, b, c ? how can I use or what is the syntax of the index function for this ? for my program I have to pop the element the random choice returns.

答:
If you want to remove something from the randomly chosen list, you don't need to have the variable name. The list object itself will do.

In other words, just remove the selected number from the result that random.choice() gives you:

```<code>picked_list = random.choice(d)
picked = random.choice(picked_list)
picked_list.remove(picked)
</code>```

If you must have some kind of name, don't use separate variables for the input lists. Use a dictionary:

```<code>lists = {
    'a': [1, 2, 3],
    'b': [1, 2, 3],
    'c': [1, 2, 3],
}
list_picked = random.choice(lists)  # returns 'a', 'b', or 'c'
picked = random.choice(lists[list_picked])
lists[list_picked].remove(picked)
</code>```

Note that it'll be more efficient to just shuffle your lists up-front (putting them in random order), then pop elements as you need them:

```<code>d = [a, b, c]
for sublist in d:
    random.shuffle(sublist)

# later on
picked = random.choice(d).pop()  # remove the last element
</code>```

You'll have to figure out what it means to have an empty list there though.

Title: Python List random choice

Body:
Looking for a help / solution here.

a = [1,2,3]
b = [1,2,3]
c = [1,2,3]
d = [a,b,c]

random.choice(random.choice(d))

this gives me 1,2 or 3. But how to find which list variable this random function used out of a, b, c ? how can I use or what is the syntax of the index function for this ? for my program I have to pop the element the random choice returns.

Body:
If you want to remove something from the randomly chosen list, you don't need to have the variable name. The list object itself will do.

In other words, just remove the selected number from the result that random.choice() gives you:

picked_list = random.choice(d)
picked = random.choice(picked_list)
picked_list.remove(picked)

If you must have some kind of name, don't use separate variables for the input lists. Use a dictionary:

lists = {
    'a': [1, 2, 3],
    'b': [1, 2, 3],
    'c': [1, 2, 3],
}
list_picked = random.choice(lists)  # returns 'a', 'b', or 'c'
picked = random.choice(lists[list_picked])
lists[list_picked].remove(picked)

Note that it'll be more efficient to just shuffle your lists up-front (putting them in random order), then pop elements as you need them:

d = [a, b, c]
for sublist in d:
    random.shuffle(sublist)

# later on
picked = random.choice(d).pop()  # remove the last element

You'll have to figure out what it means to have an empty list there though.


问:
how to fix LookupError: base64 in python3 while running String decode() Method
I am running below program in python3, but getting an error

```<code>Str = "this is string example....wow!!!";
Str = Str.encode('base64','strict');
print ("Encoded String: " + Str)
print ("Decoded String: " + Str.decode('base64','strict'))
</code>```

and getting Error is:-

```<code>File "learn.py", line 646, in <module>
    Str = Str.encode('base64','strict');
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs
</code>```

答: Base64 is not a string encoding method, its a method for encoding bytes use the base64 module instead</p>

Body:
I am running below program in python3, but getting an error

Str = "this is string example....wow!!!";
Str = Str.encode('base64','strict');
print ("Encoded String: " + Str)
print ("Decoded String: " + Str.decode('base64','strict'))

and getting Error is:-

File "learn.py", line 646, in <module>
    Str = Str.encode('base64','strict');
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs


问:
How to setup Identity's Cookie Data Protection to use the Azure Storage Data Protector
When setting up the data protection and Identity, the Identity already needs a built IDataProtectionProvider, while the data protection api doesn't offer this.

ConfigureServices

```<code>IDataProtectionBuilder protectionBuilder = services
    .AddDataProtection()
    .PersistKeysToAzureBlobStorage(storageContainer, "keys.xml");
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    options.Cookies.ApplicationCookie.DataProtectionProvider = //NEEDS AN IDataProtectionProvider
}
</code>```

For custom cookies it can be set later, in the Configure:

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AutomaticChallenge = false,
    ExpireTimeSpan = TimeSpan.FromHours(1),
    DataProtectionProvider = app.ApplicationServices.GetService<IDataProtectionProvider>()
});
</code>```

Relevant docs:
https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/compatibility/cookie-sharing

答:
I've found that the above code already works.

Simply telling the data protection to store the keys in Azure seems to automatically resolve the Identity data protector to the same storage.

Only code needed compared to no shared keys:

services.AddDataProtection().PersistKeysToAzureBlobStorage(tableContainer, "keys.xml");

Body:
When setting up the data protection and Identity, the Identity already needs a built IDataProtectionProvider, while the data protection api doesn't offer this.

ConfigureServices

IDataProtectionBuilder protectionBuilder = services
    .AddDataProtection()
    .PersistKeysToAzureBlobStorage(storageContainer, "keys.xml");
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    options.Cookies.ApplicationCookie.DataProtectionProvider = //NEEDS AN IDataProtectionProvider
}

For custom cookies it can be set later, in the Configure:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AutomaticChallenge = false,
    ExpireTimeSpan = TimeSpan.FromHours(1),
    DataProtectionProvider = app.ApplicationServices.GetService<IDataProtectionProvider>()
});

Relevant docs:
https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/compatibility/cookie-sharing


问:
preg_replace EVERYTHING: text and line breaks
I have a text and simply want to remove everything after my first capture. I figured out that I repeat ".\s" at least as often as I have line breaks. But I hope there is a more flexible and dry solution for this.

```<code>$subject = "SomeText()                                  asaas
DFDFDFD

dsdsds

dsdsds";
$pattern = "#\).*\s*.*\s*.*\s*.*#" ;
$replacement = ")";
$newText = preg_replace($pattern, $replacement, $subject);
Utils_Echo::myEcho($subject);
Utils_Echo::myEcho($newText);

$pattern = "#\)[.\s]*#"; //I hoped something like this would work but it could not figure it out. Can you show me a way?
</code>```

答:
Ordered from the fastest to the slowest:

Without regex: the most obvious

```<code>$newText = ( false !== $pos = strpos($subject, ')') ) ? substr($subject, 0, $pos + 1)
                                                      : $subject;
</code>```

With preg_match: take what you want instead of replacing what you don't want

```<code>$newText = preg_match('~[^)]*\)~', $subject, $m) ? $m[0] : $subject;
</code>```

With preg_replace: the s modifier allows the dot to match the newline character

```<code>$newText = preg_replace('~\).*~s', ')', $subject);
</code>```

Body:
I have a text and simply want to remove everything after my first capture. I figured out that I repeat ".\s" at least as often as I have line breaks. But I hope there is a more flexible and dry solution for this.

$subject = "SomeText()                                  asaas
DFDFDFD

dsdsds

dsdsds";
$pattern = "#\).*\s*.*\s*.*\s*.*#" ;
$replacement = ")";
$newText = preg_replace($pattern, $replacement, $subject);
Utils_Echo::myEcho($subject);
Utils_Echo::myEcho($newText);

$pattern = "#\)[.\s]*#"; //I hoped something like this would work but it could not figure it out. Can you show me a way?

Body:
Ordered from the fastest to the slowest:

Without regex: the most obvious

$newText = ( false !== $pos = strpos($subject, ')') ) ? substr($subject, 0, $pos + 1)
                                                      : $subject;

With preg_match: take what you want instead of replacing what you don't want

$newText = preg_match('~[^)]*\)~', $subject, $m) ? $m[0] : $subject;

With preg_replace: the s modifier allows the dot to match the newline character

$newText = preg_replace('~\).*~s', ')', $subject);


问:
No way to compile my own kotlin library
With Google I/O 2017, I decided to learn kotlin by developing my own library in kotlin for android. This library allows to get information from OpenWeatherMap API.
Link of the project : https://github.com/sokarcreative/EasyOWM

What's the problem ?
I just can't compile my library. I tried everything.
I have already compiled forked project and it worked but no way with my own library.

I created a new project with these gradlew scripts :

-- Project gradle

```<code>allprojects {
    repositories {
       ...
        maven { url 'https://jitpack.io' }
    }
}
</code>```

-- module gradle

```<code>dependencies {
    ...
    compile 'com.github.sokarcreative:easyowm:master-SNAPSHOT'
}
</code>```

Error : Failed to resolve: com.github.sokarcreative:easyowm:master-SNAPSHOT

I know this is a recurring question but no way to solve this problem.

Edit: just in case, the library works.
Here is the result on my galaxy tab S3:
EasyOWM screenshot

答: Problem solved with Android Studio 3.0 canary 3</p>

Title: No way to compile my own kotlin library

Body:
With Google I/O 2017, I decided to learn kotlin by developing my own library in kotlin for android. This library allows to get information from OpenWeatherMap API.
Link of the project : https://github.com/sokarcreative/EasyOWM

What's the problem ?
I just can't compile my library. I tried everything.
I have already compiled forked project and it worked but no way with my own library.

I created a new project with these gradlew scripts :

-- Project gradle

allprojects {
    repositories {
       ...
        maven { url 'https://jitpack.io' }
    }
}

-- module gradle

dependencies {
    ...
    compile 'com.github.sokarcreative:easyowm:master-SNAPSHOT'
}

Error : Failed to resolve: com.github.sokarcreative:easyowm:master-SNAPSHOT

I know this is a recurring question but no way to solve this problem.

Edit: just in case, the library works.
Here is the result on my galaxy tab S3:
EasyOWM screenshot


问:
How can I determine the class of an XML serialized object in C# before I deserialize it?
I have a server that accepts requests as XML serialized objects which could be any of 10 or so different Classes.  Of course in order for the server to process the request, it must first de-serialize the XML string back into an object.  To do that, it needs to know what class the object came from to choose the correct de-serializer and re-construct the object.  So it would be good to be able to just quickly inspect the XML string before attempting to de-serialize it to get the object type and then select the appropriate de-serializer.

I have been using the following code, but, like the song goes, "I know there's got to be a better way..."  Any suggestions or insight would be appreciated.

```<code> private void button1_Click(object sender, EventArgs e)
    {
        //any class - does not matter - create an object
        SomeClass tc = new SomeClass();
        //populate it
        tc.i = 5;
        tc.s = "Hello World";
        tc.d = 123.456;

        //Serialize it to XML
        StringWriter xml = new StringWriter();
        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(SomeClass));
        x.Serialize(xml, tc);

        //Extract the Class name and show the XML to the user without de-serializing it
        textBox1.Text = GetClassNameFromXMLSerializedString(xml.ToString());
    }

    private string GetClassNameFromXMLSerializedString(string xml)
    {
        //The class name is somewhere in the xml
        string classname = xml;
        //get the start of class name
        classname = xml.Substring(classname.IndexOf('>') + 4);
        //get the class name which is terminated by a space
        classname = classname.Substring(0, classname.IndexOf(' '));
        //return it
        return classname;
    }
</code>```

答:
If you really want to you can read the 3rd element like this:

```<code>using (XmlReader xr = XmlReader.Create(GenerateStreamFromString(xml.ToString())))
{
    xr.Read();
    xr.Read();
    xr.Read();

    textBox1.Text =  xr.Name;
}
</code>```

Using this helper function:

```<code>public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.Unicode.GetBytes(value ?? ""));
}
</code>```

All checks omitted..

If you want to you can test if the 1st element is xml and the 2nd one is empty.
I'm not really sure if this is a good idea.

Body:
I have a server that accepts requests as XML serialized objects which could be any of 10 or so different Classes.  Of course in order for the server to process the request, it must first de-serialize the XML string back into an object.  To do that, it needs to know what class the object came from to choose the correct de-serializer and re-construct the object.  So it would be good to be able to just quickly inspect the XML string before attempting to de-serialize it to get the object type and then select the appropriate de-serializer.

I have been using the following code, but, like the song goes, "I know there's got to be a better way..."  Any suggestions or insight would be appreciated.

 private void button1_Click(object sender, EventArgs e)
    {
        //any class - does not matter - create an object
        SomeClass tc = new SomeClass();
        //populate it
        tc.i = 5;
        tc.s = "Hello World";
        tc.d = 123.456;

        //Serialize it to XML
        StringWriter xml = new StringWriter();
        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(SomeClass));
        x.Serialize(xml, tc);

        //Extract the Class name and show the XML to the user without de-serializing it
        textBox1.Text = GetClassNameFromXMLSerializedString(xml.ToString());
    }

    private string GetClassNameFromXMLSerializedString(string xml)
    {
        //The class name is somewhere in the xml
        string classname = xml;
        //get the start of class name
        classname = xml.Substring(classname.IndexOf('>') + 4);
        //get the class name which is terminated by a space
        classname = classname.Substring(0, classname.IndexOf(' '));
        //return it
        return classname;
    }

Body:
If you really want to you can read the 3rd element like this:

using (XmlReader xr = XmlReader.Create(GenerateStreamFromString(xml.ToString())))
{
    xr.Read();
    xr.Read();
    xr.Read();

    textBox1.Text =  xr.Name;
}

Using this helper function:

public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.Unicode.GetBytes(value ?? ""));
}

All checks omitted..

If you want to you can test if the 1st element is xml and the 2nd one is empty.
I'm not really sure if this is a good idea.


问:
Not work createWriteStream and absolute path
I have 1 issue. Don't understand how it works.

I want create file within fs.createWriteStream and so works only with relative path. All folders was created

let p = path.resolve(`../uploads/${data.id}/${file.originalname}`).toString()

outStream = fs.createWriteStream(`./uploads/example.txt`,{flags:'w'}) //work
outStream = fs.createWriteStream(`${__dirname}/uploads/2/example.txt`,{flags:'w'}) //not work

outStream = fs.createWriteStream(p,{flags:'w'}) //not work```

ENOENT: no such file or directory, open '/Users/arsenkarapetan/Documents/sedalina/server/uploads/2/example.txt'

How it do correct? Maybe i don't have permission?

答:
The directory /Users/arsenkarapetan/Documents/sedalina/server/uploads/2/ needs to exist before you can create a file in it, and I think that it might not yet exist in your situation.

You can use a module like mkdirp to first create all the intermediate directories before creating the file stream.

Body:
I have 1 issue. Don't understand how it works.

I want create file within fs.createWriteStream and so works only with relative path. All folders was created

let p = path.resolve(`../uploads/${data.id}/${file.originalname}`).toString()

outStream = fs.createWriteStream(`./uploads/example.txt`,{flags:'w'}) //work
outStream = fs.createWriteStream(`${__dirname}/uploads/2/example.txt`,{flags:'w'}) //not work

outStream = fs.createWriteStream(p,{flags:'w'}) //not work

ENOENT: no such file or directory, open '/Users/arsenkarapetan/Documents/sedalina/server/uploads/2/example.txt'

How it do correct? Maybe i don't have permission?


问:
need instance of RDD but returned class 'pyspark.rdd.PipelinedRDD'
Hi I have this code in Notebooks and traying to code python spark:

```<code> mydataNoSQL.createOrReplaceTempView("mytable")
 spark.sql("SELECT * from mytable")
 return mydataNoSQL

def getsameData(df,spark):
result = spark.sql("select * from mytable where temeperature is not null")
return result.rdd.sample(False, 0.1).map(lambda row : (row.temperature))
</code>```

I need an instance RDD but I am geting an class 'pyspark.rdd.PipelinedRDD'

Any help will be wellcome.

答:
pyspark.rdd.PipelinedRDD is a subclass of RDD and it must have all the API's defined in the RDD. ie. PipelinedRDD is just a special type of RDD which is created when you run a map function on an RDD.

for example, take a look at the below snippet.

```<code>>>> rdd = spark.sparkContext.parallelize(range(1,10))
>>> type(rdd)
<class 'pyspark.rdd.RDD'> ## the type is RDD here
>>> rdd = rdd.map(lambda x: x * x)
>>> type(rdd)
<class 'pyspark.rdd.PipelinedRDD'> ## after the map operation the type is changed to pyspark.rdd.PipelinedRDD
</code>```

so you should just treat your pyspark.rdd.PipelinedRDD just as an RDD in your code.

There is no complete casting support in Python as it is a dynamically typed language. to forcefully convert your pyspark.rdd.PipelinedRDD to a normal RDD you can collect on rdd and parallelize it back

```<code>>>> rdd = spark.sparkContext.parallelize(rdd.collect())
>>> type(rdd)
<class 'pyspark.rdd.RDD'>
</code>```

Running collect on an RDD may cause MemoryError if the RDD's data is large.

Body:
Hi I have this code in Notebooks and traying to code python spark:

 mydataNoSQL.createOrReplaceTempView("mytable")
 spark.sql("SELECT * from mytable")
 return mydataNoSQL

def getsameData(df,spark):
result = spark.sql("select * from mytable where temeperature is not null")
return result.rdd.sample(False, 0.1).map(lambda row : (row.temperature))

I need an instance RDD but I am geting an class 'pyspark.rdd.PipelinedRDD'

Any help will be wellcome.

Body:
pyspark.rdd.PipelinedRDD is a subclass of RDD and it must have all the API's defined in the RDD. ie. PipelinedRDD is just a special type of RDD which is created when you run a map function on an RDD.

for example, take a look at the below snippet.

>>> rdd = spark.sparkContext.parallelize(range(1,10))
>>> type(rdd)
<class 'pyspark.rdd.RDD'> ## the type is RDD here
>>> rdd = rdd.map(lambda x: x * x)
>>> type(rdd)
<class 'pyspark.rdd.PipelinedRDD'> ## after the map operation the type is changed to pyspark.rdd.PipelinedRDD

so you should just treat your pyspark.rdd.PipelinedRDD just as an RDD in your code.

There is no complete casting support in Python as it is a dynamically typed language. to forcefully convert your pyspark.rdd.PipelinedRDD to a normal RDD you can collect on rdd and parallelize it back

>>> rdd = spark.sparkContext.parallelize(rdd.collect())
>>> type(rdd)
<class 'pyspark.rdd.RDD'>

Running collect on an RDD may cause MemoryError if the RDD's data is large.

ContentLicense: CC BY-SA 4.0


问:
GPIO Interface, object not callable
```<code>from tkinter import *
from tkinter import font

root = Tk()
root.title("Wills Gui")
root.geometry('1400x700')
#root.configure(background='black')

def P1C():
    if B1(fg) :
        B1.fg(fg = red)
        B1["text"] = "Pin 2 Active"
        B1["fg"] = "green"
    else:
        B1.fg(fg = green)
        B1["text"] = "Pin 2 Inactive"
        B1["fg"] = "red"

B1 = Button(root, height = 8, width = 15, font="Times 12 bold",
wraplength=80, command = P1C, text="| Q |   B1 Inactive", bg="black",
fg="yellow").grid(row =0,column =0)

root.mainloop()
</code>```

I have simplified the code i just need it to change the colour of the button text from green to red, etc every time it is pressed.

答:
The error is right there in the trace

```<code> in P1C if B1(fg) : NameError: name 'fg' is not defined
</code>```

The variable fg in the function is not defined prior to use.

Title: GPIO Interface, object not callable

Body:
from tkinter import *
from tkinter import font

root = Tk()
root.title("Wills Gui")
root.geometry('1400x700')
#root.configure(background='black')

def P1C():
    if B1(fg) :
        B1.fg(fg = red)
        B1["text"] = "Pin 2 Active"
        B1["fg"] = "green"
    else:
        B1.fg(fg = green)
        B1["text"] = "Pin 2 Inactive"
        B1["fg"] = "red"

B1 = Button(root, height = 8, width = 15, font="Times 12 bold",
wraplength=80, command = P1C, text="| Q |   B1 Inactive", bg="black",
fg="yellow").grid(row =0,column =0)

root.mainloop()

I have simplified the code i just need it to change the colour of the button text from green to red, etc every time it is pressed.

Body:
The error is right there in the trace

 in P1C if B1(fg) : NameError: name 'fg' is not defined

The variable fg in the function is not defined prior to use.


问:
no icons using fontawesome npm in meteor
I've installed fontawesome npm into my meteor app and I'm not able to to get the fontawesome icons to appear on the webpage. There's no error in my console so I'm not sure what I've done wrong.

Am I importing it in the wrong place?

Path: imports/ui/layouts/body/body.js

import fontawesome from 'fontawesome';

答:
Although the atmosphere library says to use npm.  I have spent quite a bit of time making the npm library work.  Both the less version and the normal css.  No luck sadly.

Use

```<code>Meteor add fortawesome:fontawesome
</code>```

I'd love to use the npm package, but at this point continuing to use the atmosphere package is easier, working and has no apparent disadvantage to what I can tell.

Body:
Although the atmosphere library says to use npm.  I have spent quite a bit of time making the npm library work.  Both the less version and the normal css.  No luck sadly.

Use

Meteor add fortawesome:fontawesome

I'd love to use the npm package, but at this point continuing to use the atmosphere package is easier, working and has no apparent disadvantage to what I can tell.


问:
Get values from complicated multidimensional arrays
I have an array like this

```<code>$officeLK = [
    [
        ['text' => "تا ۱ میلیون تومان", 'callback_data' => '111']
    ],
    [
        ['text' => "پانصد هزار تومان", 'callback_data' => '112']
    ],
    [
        ['text' => "۲ میلیون تومان", 'callback_data' => '113']
    ],
    [
        ['text' => "برگشت", 'callback_data' => '1']
    ]
];
</code>```

I need a function to give it the callback_data and it return the text value

答:
You could use a foreach loop to iterate through the array and check if the given callback matches.

For example :

```<code>$officeLK = [
    [
        ['text' => "تا ۱ میلیون تومان", 'callback_data' => '111']
    ],
    [
        ['text' => "پانصد هزار تومان", 'callback_data' => '112']
    ],
    [
        ['text' => "۲ میلیون تومان", 'callback_data' => '113']
    ],
    [
        ['text' => "برگشت", 'callback_data' => '1']
    ]
];

$given_callback = 113:

echo getTextByCallBack($given_callback, $officeLK);

function getTextByCallBack($callback, $officeLK)
{
    foreach ($officeLK as $item) {
        if ($item[0]['callback_data'] == $callback) {
            return $item[0]['text'];
        }
    }
}
</code>```

Will output :

۲ میلیون تومان

Body:
I have an array like this

$officeLK = [
    [
        ['text' => "تا ۱ میلیون تومان", 'callback_data' => '111']
    ],
    [
        ['text' => "پانصد هزار تومان", 'callback_data' => '112']
    ],
    [
        ['text' => "۲ میلیون تومان", 'callback_data' => '113']
    ],
    [
        ['text' => "برگشت", 'callback_data' => '1']
    ]
];

I need a function to give it the callback_data and it return the text value

Body:
You could use a foreach loop to iterate through the array and check if the given callback matches.

For example :

$officeLK = [
    [
        ['text' => "تا ۱ میلیون تومان", 'callback_data' => '111']
    ],
    [
        ['text' => "پانصد هزار تومان", 'callback_data' => '112']
    ],
    [
        ['text' => "۲ میلیون تومان", 'callback_data' => '113']
    ],
    [
        ['text' => "برگشت", 'callback_data' => '1']
    ]
];

$given_callback = 113:

echo getTextByCallBack($given_callback, $officeLK);

function getTextByCallBack($callback, $officeLK)
{
    foreach ($officeLK as $item) {
        if ($item[0]['callback_data'] == $callback) {
            return $item[0]['text'];
        }
    }
}

Will output :

۲ میلیون تومان


问:
Update query that should apply numbers to a text field fail
I have a simple update query that should apply numbers to a text field, but it keeps dropping the leading zero. Should be 054846, but ends up as 54846. Can't figure out what I'm missing.

```<code>Dim strsql As String
strsql = "UPDATE [Action]" _
       & "SET [Action] = (" & "054846" & ")"

DoCmd.RunSQL strsql
</code>```

Please help out

答: It sounds like the field in the table is defined as a string. But the SQL you have has the number as an integer because you didn't surround the value with single quotes. You will see the issue if you output the SQL string you're trying to run.</p>

Body:
I have a simple update query that should apply numbers to a text field, but it keeps dropping the leading zero. Should be 054846, but ends up as 54846. Can't figure out what I'm missing.

Dim strsql As String
strsql = "UPDATE [Action]" _
       & "SET [Action] = (" & "054846" & ")"

DoCmd.RunSQL strsql

Please help out


问:
What was original Jailbreak detection API Apple just removed in 4.2?
Apple seems to be removed the jailbreak detection API, as announced in http://www.engadget.com/2010/12/12/apple-mysteriously-kills-jailbreak-detection-api-while-hacker-bo
What was the original API removed? </p>

答: From what I understand, it was a server based API that basically made the phone tell the server if it was jailbroken, then apply the necessary actions to make sure somebody knew the phone was jailbroken.  It was only used in enterprise situations, so for the most part, no normal people had to be worried.  As a matter of fact, musclenerd tweeted that the iphone dev team didn't even attempt to fool it because they didn't think it was really necessary.</p>


问:
APN BadDeviceToken iff running dev version

The problem

I'm not receiving Push Notifications to my app when I'm working on it,

and the APN server returns "BadDeviceToken".

The situation

I've got to be missing something simple here, this is the situation :

When I send a Push Notification to my app downloaded from the App Store it works

When I send a Push Notification from the same server, to the same version (*) of my app but built off Xcode, the APN server returns a status: '400' fail with the failed[0].response.reason: 'BadDeviceToken'

(*) I say the same version, the code is the same and the plugins should be the same, but I have changed Cordova iOS version down to 3.x, from 4.x.

The tech

I'm using the newer method of Push Notifications where on the server I just have a .p8 APNs Auth Key on the server.

The server is node code using the node-apn plugin.

The client app is Cordova, using the Telerik Push Plugin.

What I've tried

I've tried creating a new APNs Auth Key and  uploading that to the server; that still works on the App Store version of the app, and APN still returns "BadDeviceToken" when sending to my locally built version of the app.

I've tried setting production: false on the server config for node-apn before sending the push to my locally built app; I still get the "BadDeviceToken" error.

Doing an extra hexadecimal encode to the token as per this question; result is that it still says "BadDeviceToken", though in that case it would actually be true.

Bumping the cordova-ios version back up to 4.3.1; still getting "BadDeviceToken".

Double checking that the "Push Notifications" Capability is on when building

Doing a Release build rather than a Debug build, as suggested here, and described here

The question(s)

Why is the APN server saying BadDeviceToken when that is obviously not true?

And, how can I fix it?

答:
In addition to @kris's answer:

You could've probably gone solved it as well by running the app through xCode, that will generate a development build, and will need to use the APNS development gateway with a development certificate, not the production certificate.

Or if you are installing directly to your phone from Xcode, then you have to use Development security profile and make sure you are sending the notification from server side to iOS devlopment sand box. If you are using TestFlight/AppStore you need to use Production profile and make sure you are sending the notification to iOS production sandbox.

The SOLUTION however was found by the one that made the question itself, stating:

For some reason the Xcode project did´t use the right provision profile and the solution would be rather to re-install the app.

Further I'd like to explain what APNS_BAD_DEVICE_TOKEN is:

The specified device token was bad. Verify that you specified a valid token and that your Security Profile's type (development/production) matches your push certificate's type.


问:
Previously working Xamarin iOS project doesn't build and gives MSB6006 Error
When I try to build my Xamarin iOS project, I get this error:

/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/msbuild/15.0/bin/Roslyn/Microsoft.CSharp.Core.targets(5,5):
  Error MSB6006: "csc.exe" exited with code 1. (MSB6006)

Seems it's because of Mono 5.0, but I don't know how to fix it!

答: Try downloading and installing Mono 4.8.  You will need to be careful if you're using VS for Mac which requires Mono 5.0 or greater.  If that is the case you should be able to download 4.8 without making it the default and then change the .NET Runtime in preferences after launching VS to 4.8. </p>


问:
PHP - array_diff all similar values are compared and removed
I would appreciate a little help . I have tried array_diff(), intersect combos but not able to get my expected return.

Here is an example what i want to do.

First array.

```<code>Array
(
    [0] => 21
    [1] => 2
    [2] => 1
    [3] => 2
)
</code>```

Second array

```<code>Array
(
    [0] => 21
    [1] => 2
)
</code>```

using array_diff(firstarray, secondarray) i get following.

```<code>Array
(
    [2] => 1
)
</code>```

But what i want

```<code>Array
(
    [2] => 1
    [3] => 2
)
</code>```

keys from firstarray and secondarray wont necessarily be same.

答:
```<code>function array_true_diff($arrayOne, $arrayTwo = []) {
    if (count($arrayOne) < count($arrayTwo)) {
        $tmp = $arrayOne;
        $arrayOne = $arrayTwo;
        $arrayTwo = $tmp;
    }

    $diffs = [];
    foreach ($arrayOne as $key => $value) {
         if (!isset($arrayTwo[$key]) || $arrayTwo[$key] !== $value)  {
            $diffs[$key] = $value;
         }
     }
    return $diffs;
}
</code>```

print_r(array_true_diff(firstarray, secondarray))

Above function could fulfill your requirement.

Body:
I would appreciate a little help . I have tried array_diff(), intersect combos but not able to get my expected return.

Here is an example what i want to do.

First array.

Array
(
    [0] => 21
    [1] => 2
    [2] => 1
    [3] => 2
)

Second array

Array
(
    [0] => 21
    [1] => 2
)

using array_diff(firstarray, secondarray) i get following.

Array
(
    [2] => 1
)

But what i want

Array
(
    [2] => 1
    [3] => 2
)

keys from firstarray and secondarray wont necessarily be same.

Body:
function array_true_diff($arrayOne, $arrayTwo = []) {
    if (count($arrayOne) < count($arrayTwo)) {
        $tmp = $arrayOne;
        $arrayOne = $arrayTwo;
        $arrayTwo = $tmp;
    }

    $diffs = [];
    foreach ($arrayOne as $key => $value) {
         if (!isset($arrayTwo[$key]) || $arrayTwo[$key] !== $value)  {
            $diffs[$key] = $value;
         }
     }
    return $diffs;
}

print_r(array_true_diff(firstarray, secondarray))

Above function could fulfill your requirement.


问:
Vuejs - check if two data of different lists are same to display in the template
I would like to compare to list of data ( one is fetched from the server, and the other is from the default data).

Data from server:

```<code>[
  {
    "id": 7,
    "day": "14 April 2017",
    "time_list": [
      {
        "id": 25,
        "time": "11:00 AM",
      },
      {
        "id": 28,
        "time": "08:00 PM",
      }
    ]
  },
  {
    "id": 7,
    "day": "13 April 2017",
    "time_list": [
      {
        "id": 33,
        "time": "11:00 AM",
      },
      {
        "id": 22,
        "time": "02:00 PM",
      },
    ]
  },
]
</code>```

Default data of the front end javascript Vue component:

```<code>default_time_data: ["11:00 AM", "02:00 Pm", "05:00 PM", "08:00 PM"]
</code>```

What I would like to do is in the template:

```<code><template>
    <div v-for="day in show_routine_data">

        check if the time from the day.time_list is same as the showTime_count

        For each default_time of default_time_data, check if any of the time of day.time_list is equal to the default_time.

        If the default_time is equal to the time, then show its id.
        Else, show no data
    </div>
</template>
</code>```

I hope I was clear, if not please do ask. I have been scratching my head since this morning to solve this problem. Could you please help me out.

update:

I want the final data to display like this (from the above data):

```<code><ul>
    <li>
        <p>14th April 2017</p>
        <ul>
            <li><p> 25 </p></li>
            <li><p> No data </p></li>
            <li><p> No data </p></li>
            <li><p> 28 </p></li>
        <ul>
    <li>
    <li>
        <p>13th April 2017</p>
        <ul>
            <li><p> 33 </p></li>
            <li><p> 22 </p></li>
            <li><p> No data </p></li>
            <li><p> No data </p></li>
        <ul>
    <li>
</ul>
</code>```

答:
Basically you need to create a computed property where you gather your data which is ready to be rendered. Docs about computed properties: https://v2.vuejs.org/v2/guide/computed.html

Computed property is the way to go if you need to extract a piece of data, format it somehow, etc.

Also you need two v-for loops: one to loop through blocks and a nested one to loop through time ids.

Here's an example:

new Vue({
  el: '#app',
  data: {
    myArr: [
      {
        "id": 7,
        "day": "14 April 2017",
        "time_list": [
          {
            "id": 25,
            "time": "11:00 AM",
          },
          {
            "id": 28,
            "time": "08:00 PM",
          }
        ]
      },
      {
        "id": 7,
        "day": "13 April 2017",
        "time_list": [
          {
            "id": 33,
            "time": "11:00 AM",
          },
          {
            "id": 22,
            "time": "02:00 PM",
          },
        ]
      },
    ],
    default_time_data: ["11:00 AM", "02:00 PM", "05:00 PM", "08:00 PM"]
  },
  computed: {
    dataToRender: function() {
      return (this.myArr && this.myArr.length > 0) // if data is already fetched
        ? this.myArr.map(e => Object.assign({ day: e.day },
          {
            timeList: this.default_time_data
              // if time in default array - return id, otherwise 'No data'
              .map(dt => (e.time_list.map(({time}) => time).includes(dt)) ? e.time_list.find(tl => tl.time === dt).id : 'No data')
          }))
        : []; // if data hasn't arrived - return empty array
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.3.3/dist/vue.min.js"></script>

<div id="app">
   <ul v-if="dataToRender.length > 0"> <!-- check if data exists -->
     <li v-for="item of dataToRender">
       <p>{{ item.day }}</p>
       <ul>
         <li v-for="time of item.timeList">{{ time }}</li>
       </ul>
     </li>
   </ul>
</div></code>```

Body:
I would like to compare to list of data ( one is fetched from the server, and the other is from the default data).

Data from server:

[
  {
    "id": 7,
    "day": "14 April 2017",
    "time_list": [
      {
        "id": 25,
        "time": "11:00 AM",
      },
      {
        "id": 28,
        "time": "08:00 PM",
      }
    ]
  },
  {
    "id": 7,
    "day": "13 April 2017",
    "time_list": [
      {
        "id": 33,
        "time": "11:00 AM",
      },
      {
        "id": 22,
        "time": "02:00 PM",
      },
    ]
  },
]

Default data of the front end javascript Vue component:

default_time_data: ["11:00 AM", "02:00 Pm", "05:00 PM", "08:00 PM"]

What I would like to do is in the template:

<template>

        check if the time from the day.time_list is same as the showTime_count

        For each default_time of default_time_data, check if any of the time of day.time_list is equal to the default_time.

        If the default_time is equal to the time, then show its id.
        Else, show no data

</template>

I hope I was clear, if not please do ask. I have been scratching my head since this morning to solve this problem. Could you please help me out.

update:

I want the final data to display like this (from the above data):

14th April 2017

 25

 No data

 No data

 28

13th April 2017

 33

 22

 No data

 No data

Body:
Basically you need to create a computed property where you gather your data which is ready to be rendered. Docs about computed properties: https://v2.vuejs.org/v2/guide/computed.html

Computed property is the way to go if you need to extract a piece of data, format it somehow, etc.

Also you need two v-for loops: one to loop through blocks and a nested one to loop through time ids.

Here's an example:

new Vue({
  el: '#app',
  data: {
    myArr: [
      {
        "id": 7,
        "day": "14 April 2017",
        "time_list": [
          {
            "id": 25,
            "time": "11:00 AM",
          },
          {
            "id": 28,
            "time": "08:00 PM",
          }
        ]
      },
      {
        "id": 7,
        "day": "13 April 2017",
        "time_list": [
          {
            "id": 33,
            "time": "11:00 AM",
          },
          {
            "id": 22,
            "time": "02:00 PM",
          },
        ]
      },
    ],
    default_time_data: ["11:00 AM", "02:00 PM", "05:00 PM", "08:00 PM"]
  },
  computed: {
    dataToRender: function() {
      return (this.myArr && this.myArr.length > 0) // if data is already fetched
        ? this.myArr.map(e => Object.assign({ day: e.day },
          {
            timeList: this.default_time_data
              // if time in default array - return id, otherwise 'No data'
              .map(dt => (e.time_list.map(({time}) => time).includes(dt)) ? e.time_list.find(tl => tl.time === dt).id : 'No data')
          }))
        : []; // if data hasn't arrived - return empty array
    }
  }
});

<script src="https://unpkg.com/vue@2.3.3/dist/vue.min.js"></script>

<div id="app">
   <ul v-if="dataToRender.length > 0"> <!-- check if data exists -->
     <li v-for="item of dataToRender">
       <p>{{ item.day }}</p>
       <ul>
         <li v-for="time of item.timeList">{{ time }}</li>
       </ul>
     </li>
   </ul>
</div>


问:
game programmer portfolio
i want to work as a programmer in a game modification team. Most teams require a portfolio to show.

I haven't any previous experience with game programming and I would like to know what I should program and include in the portfolio

Thank you

答:
Include the best programming examples that you have.

C++ is used in the development of a lot of games so try to use that language.

You can use other languages as well through if they show off your programing experience a certain topic.

If you have any well polish projects that involve computer graphics, AI, physics,  or multithreading include those since are topics that are used very often in game development.

Another good idea is to go through these projects and provide comments if you haven't already.  Include a description of the project and the goals somewhere easy to find in the project.

Overall you should try to use examples that feature the above areas and that show that you know how to structure a large programming project.  Game development is alot smoother when you have a good project layout.

To quote an old professor: The first time you program a project you do it the wrong way. The second time you do it in a way that works but is not effective (difficult to modify, not efficent). The third time you program the project it's acceptable.

Title: game programmer portfolio


问:
How to link an existing Angular 2 app to Nodejs Server?
I have an Angular 2 app with this structure :

Structure of my Angular app

Then in server side :
Structure of server app

I see that there is 2 module dependencies folders, but I don't know which one I sould keep.

Here is my index.js file :

```<code>  const express = require('express');
  const path = require('path');
  const http = require('http');
  const bodyParser = require('body-parser');

  // Get our API routes
  //const api = require('./server/routes/api');

  const app = express();

  // Parsers for POST data
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));

  // Point static path to dist
  app.use(express.static(path.join(__dirname, 'client/portfolio')));

  // Set our api routes
  //app.use('/api', api);

  // Catch all other routes and return the index file
  app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'client/portfolio/src/index.html'));
  });

  /**
   * Get port from environment and store in Express.
   */
  const port = process.env.PORT || '3001';
  app.set('port', port);

  /**
   * Create HTTP server.
   */
  const server = http.createServer(app);

  /**
   * Listen on provided port, on all network interfaces.
   */
  server.listen(port, () => console.log(`API running on localhost:${port}`));
</code>```

When I start server I get this message :

Loading AppComponent content here ...

But it stops here and doesn't render the Angular application.

index.html file :

```<code><!DOCTYPE html>
<html>
   <head>
      <title>Angular QuickStart</title>
      <base href="/">
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="styles.css">
      <link href="node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!-- Polyfill(s) for older browsers -->
      <script src="node_modules/core-js/client/shim.min.js"></script>
      <script src="node_modules/hammerjs/hammer.js"></script>
      <script src="node_modules/zone.js/dist/zone.js"></script>
      <script src="node_modules/systemjs/dist/system.src.js"></script>
      <script src="systemjs.config.js"></script>
      <script>
         System.import('main.js').catch(function(err){ console.error(err); });
      </script>
   </head>
   <body>
      <my-app>Loading AppComponent content here ...</my-app>
   </body>
</html>
</code>```

答:
Here's a good example of integrating AngularJS with NodeJS [open tutorial]

The trick is in this block

```<code>/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
</code>```

Body:
I have an Angular 2 app with this structure :

Structure of my Angular app

Then in server side :
Structure of server app

I see that there is 2 module dependencies folders, but I don't know which one I sould keep.

Here is my index.js file :

  const express = require('express');
  const path = require('path');
  const http = require('http');
  const bodyParser = require('body-parser');

  // Get our API routes
  //const api = require('./server/routes/api');

  const app = express();

  // Parsers for POST data
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));

  // Point static path to dist
  app.use(express.static(path.join(__dirname, 'client/portfolio')));

  // Set our api routes
  //app.use('/api', api);

  // Catch all other routes and return the index file
  app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'client/portfolio/src/index.html'));
  });

  /**
   * Get port from environment and store in Express.
   */
  const port = process.env.PORT || '3001';
  app.set('port', port);

  /**
   * Create HTTP server.
   */
  const server = http.createServer(app);

  /**
   * Listen on provided port, on all network interfaces.
   */
  server.listen(port, () => console.log(`API running on localhost:${port}`));

When I start server I get this message :

Loading AppComponent content here ...

But it stops here and doesn't render the Angular application.

index.html file :

<!DOCTYPE html>

      <title>Angular QuickStart</title>
      <base href="/">
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="styles.css">
      <link href="node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <my-app>Loading AppComponent content here ...</my-app>

Body:
Here's a good example of integrating AngularJS with NodeJS [open tutorial]

The trick is in this block

/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});


问:
Data Binding with Android Studio 3.0 Canary 3
I am trying to use DataBinding in my existing project. As per the documentation I added below lines in app module's build.gradle and compiled the project.

```<code> dataBinding {
    enabled = true
}
</code>```

I got the below error:

```<code>Could not resolve all dependencies for configuration ':app:devDebugCompileClasspath'.
</code>```

Could not find com.android.databinding:baseLibrary:3.0.0-alpha3.
    Searched in the following locations:
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/google/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/google/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/android/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/android/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://jcenter.bintray.com/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://jcenter.bintray.com/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://jitpack.io/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://jitpack.io/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://maven.fabric.io/public/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://maven.fabric.io/public/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
    Required by:
        project :app
  Could not find com.android.databinding:baseLibrary:3.0.0-alpha3.
    Searched in the following locations:
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/google/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/google/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/android/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/android/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://jcenter.bintray.com/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://jcenter.bintray.com/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://jitpack.io/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://jitpack.io/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://maven.fabric.io/public/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://maven.fabric.io/public/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
    Required by:
        project :app > com.android.databinding:library:1.3.1
        project :app > com.android.databinding:adapters:1.3.1

Can anybody help me in solving this? I am using Android Studio 3.0 Canary 3.

My project level gradle

```<code>buildscript {
repositories {
    jcenter()
    maven {
        url 'https://maven.google.com'
    }
}
dependencies {
    classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2-4'
    classpath 'com.google.firebase:firebase-plugins:1.1.0'
    classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
    classpath 'com.google.gms:google-services:3.0.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    maven { url 'https://jitpack.io' }
}
}
</code>```

App level gradle

```<code>buildscript {
dependencies {
    //noinspection GradleDynamicVersion
    classpath 'io.fabric.tools:gradle:1.+'
}

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.firebase.firebase-perf'
apply plugin: 'io.fabric'
apply from: "../constants.gradle"

repositories {
    maven { url 'https://maven.fabric.io/public' }
}
android {
compileSdkVersion project.ext.compileSdk
buildToolsVersion "${project.ext.buildtools}"
signingConfigs {
    config {
        keyAlias keystoreProperties['keyAlias']
        keyPassword keystoreProperties['keyPassword']
        storeFile file(keystoreProperties['storeFile'])
        storePassword keystoreProperties['storePassword']
    }
}

// Data Binding Library
dataBinding {
    enabled = true
}
defaultConfig {
        applicationId "com.chanse.cee2048"
        minSdkVersion project.ext.minSdk
        targetSdkVersion project.ext.targetSdk
        versionCode versionCodeNo
        versionName versionNameMajor + "." + versionNameMinor + "." + versionNamePatch + "." + versionNameBuild
        vectorDrawables.useSupportLibrary = true
        versionNameSuffix ' (Beta)'
        signingConfig signingConfigs.config
    }
buildTypes {
    release {
//            debuggable true
//            shrinkResources true
        signingConfig signingConfigs.config
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        signingConfig signingConfigs.config
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
flavorDimensions "chanse"
productFlavors {
    dev {
        applicationIdSuffix '.debug'
        minSdkVersion project.ext.minSdkDebug

        // Build only for english and xxhdpi density
        resConfigs ("en", "xxhdpi")

        // Have a different application name for dev version
        resValue "string", "app_name", "Chanse Games Dev"
    }
    prod {
        // The actual minSdkVersion for the application.
        minSdkVersion project.ext.minSdk

        // Have a different application name for dev version
        resValue "string", "app_name", "Chanse Games"
    }
}
return void
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:appcompat-v7:${project.ext.support_library_version}"
compile "com.android.support:cardview-v7:${project.ext.support_library_version}"
compile "com.android.support:recyclerview-v7:${project.ext.support_library_version}"
compile "com.android.support:design:${project.ext.support_library_version}"
compile 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.databinding:library:1.3.1'
implementation 'com.android.databinding:adapters:1.3.1'
compile 'org.jetbrains.kotlin:kotlin-stdlib:1.1.2-4'
apply plugin: 'com.google.gms.google-services'
}
</code>```

答:
Add these lines to your module-level build.gradle as dependencies; Android Studio 3.0 changed the way it pulls in libraries that you previously downloaded via the SDK manager - https://developer.android.com/studio/build/dependencies.html#google-maven

```<code>implementation 'com.android.databinding:library:1.3.1'
implementation 'com.android.databinding:adapters:1.3.1'
</code>```

You may not need the second line, depending on how you use data binding.

Instead of implementation, you can also use the old compile. Using implementation will avoid build warnings going forward; it's a part of the new Gradle Java library plugin that the Android Gradle plugin uses by default now.

You will also need to add something like the following (typically in your module-level build.gradle) if you don't have it yet - this adds Google's new Maven repository for Android dependencies:

```<code>repositories {
    maven {
        url 'https://maven.google.com'
    }
}
</code>```

Body:
I am trying to use DataBinding in my existing project. As per the documentation I added below lines in app module's build.gradle and compiled the project.

 dataBinding {
    enabled = true
}

I got the below error:

Could not resolve all dependencies for configuration ':app:devDebugCompileClasspath'.

Could not find com.android.databinding:baseLibrary:3.0.0-alpha3.
    Searched in the following locations:
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/google/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/google/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/android/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/android/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://jcenter.bintray.com/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://jcenter.bintray.com/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://jitpack.io/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://jitpack.io/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://maven.fabric.io/public/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://maven.fabric.io/public/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
    Required by:
        project :app
  Could not find com.android.databinding:baseLibrary:3.0.0-alpha3.
    Searched in the following locations:
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/google/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/google/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/android/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        file:/C:/Users/incnayak/AppData/Local/Android/sdk/extras/android/m2repository/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://jcenter.bintray.com/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://jcenter.bintray.com/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://jitpack.io/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://jitpack.io/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
        https://maven.fabric.io/public/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.pom
        https://maven.fabric.io/public/com/android/databinding/baseLibrary/3.0.0-alpha3/baseLibrary-3.0.0-alpha3.jar
    Required by:
        project :app > com.android.databinding:library:1.3.1
        project :app > com.android.databinding:adapters:1.3.1

Can anybody help me in solving this? I am using Android Studio 3.0 Canary 3.

My project level gradle

buildscript {
repositories {
    jcenter()
    maven {
        url 'https://maven.google.com'
    }
}
dependencies {
    classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2-4'
    classpath 'com.google.firebase:firebase-plugins:1.1.0'
    classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
    classpath 'com.google.gms:google-services:3.0.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    maven { url 'https://jitpack.io' }
}
}

App level gradle

buildscript {
dependencies {
    //noinspection GradleDynamicVersion
    classpath 'io.fabric.tools:gradle:1.+'
}

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.firebase.firebase-perf'
apply plugin: 'io.fabric'
apply from: "../constants.gradle"

repositories {
    maven { url 'https://maven.fabric.io/public' }
}
android {
compileSdkVersion project.ext.compileSdk
buildToolsVersion "${project.ext.buildtools}"
signingConfigs {
    config {
        keyAlias keystoreProperties['keyAlias']
        keyPassword keystoreProperties['keyPassword']
        storeFile file(keystoreProperties['storeFile'])
        storePassword keystoreProperties['storePassword']
    }
}

// Data Binding Library
dataBinding {
    enabled = true
}
defaultConfig {
        applicationId "com.chanse.cee2048"
        minSdkVersion project.ext.minSdk
        targetSdkVersion project.ext.targetSdk
        versionCode versionCodeNo
        versionName versionNameMajor + "." + versionNameMinor + "." + versionNamePatch + "." + versionNameBuild
        vectorDrawables.useSupportLibrary = true
        versionNameSuffix ' (Beta)'
        signingConfig signingConfigs.config
    }
buildTypes {
    release {
//            debuggable true
//            shrinkResources true
        signingConfig signingConfigs.config
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        signingConfig signingConfigs.config
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
flavorDimensions "chanse"
productFlavors {
    dev {
        applicationIdSuffix '.debug'
        minSdkVersion project.ext.minSdkDebug

        // Build only for english and xxhdpi density
        resConfigs ("en", "xxhdpi")

        // Have a different application name for dev version
        resValue "string", "app_name", "Chanse Games Dev"
    }
    prod {
        // The actual minSdkVersion for the application.
        minSdkVersion project.ext.minSdk

        // Have a different application name for dev version
        resValue "string", "app_name", "Chanse Games"
    }
}
return void
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:appcompat-v7:${project.ext.support_library_version}"
compile "com.android.support:cardview-v7:${project.ext.support_library_version}"
compile "com.android.support:recyclerview-v7:${project.ext.support_library_version}"
compile "com.android.support:design:${project.ext.support_library_version}"
compile 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.databinding:library:1.3.1'
implementation 'com.android.databinding:adapters:1.3.1'
compile 'org.jetbrains.kotlin:kotlin-stdlib:1.1.2-4'
apply plugin: 'com.google.gms.google-services'
}

Body:
Add these lines to your module-level build.gradle as dependencies; Android Studio 3.0 changed the way it pulls in libraries that you previously downloaded via the SDK manager - https://developer.android.com/studio/build/dependencies.html#google-maven

implementation 'com.android.databinding:library:1.3.1'
implementation 'com.android.databinding:adapters:1.3.1'

You may not need the second line, depending on how you use data binding.

Instead of implementation, you can also use the old compile. Using implementation will avoid build warnings going forward; it's a part of the new Gradle Java library plugin that the Android Gradle plugin uses by default now.

You will also need to add something like the following (typically in your module-level build.gradle) if you don't have it yet - this adds Google's new Maven repository for Android dependencies:

repositories {
    maven {
        url 'https://maven.google.com'
    }
}


问:
C# : Replace text from < char until > char
So I am trying to replace all text from < chat until > char because of colors tags and etc...

I just tried this code:

```<code>while (text.Contains("<") || text.Contains(">"))
{
    text = text.Remove(text.IndexOf("<"), text.IndexOf(">"));
}
</code>```

And somewhy this code won't work.
Thanks for any help!

答:
The function Remove takes two arguments startIndex and count. Where count is the number of characters to remove.

```<code>public string Remove(
    int startIndex,
    int count
)
</code>```

You need to calculate the distance from < to >, and use that distance as the second argument for Remove. The code should look something like this:

```<code>while (text.Contains("<") || text.Contains(">"))
{
    var start = text.IndexOf("<");
    var end = text.IndexOf(">") + 1;
    var dist = end - start;
    text = text.Remove(start, dist);
}
</code>```

NOTE: You should add some additional checks making sure that < and > occurs in the expected order, and that they occur the same number of times.

Body:
So I am trying to replace all text from < chat until > char because of colors tags and etc...

I just tried this code:

while (text.Contains("<") || text.Contains(">"))
{
    text = text.Remove(text.IndexOf("<"), text.IndexOf(">"));
}

And somewhy this code won't work.
Thanks for any help!

Body:
The function Remove takes two arguments startIndex and count. Where count is the number of characters to remove.

public string Remove(
    int startIndex,
    int count
)

You need to calculate the distance from < to >, and use that distance as the second argument for Remove. The code should look something like this:

while (text.Contains("<") || text.Contains(">"))
{
    var start = text.IndexOf("<");
    var end = text.IndexOf(">") + 1;
    var dist = end - start;
    text = text.Remove(start, dist);
}

NOTE: You should add some additional checks making sure that < and > occurs in the expected order, and that they occur the same number of times.


问:
Junit Before/After and setup/teardown
Are the setUp and teardown (precondition and postcondition settings) identified by the name setUp() and teardown() or by @Before and @After?

In other words is it possible in JUnit to have a @Before teardown() and a @After setUp()?

答: It depends on the version of JUnit that you use. In case you have annotations, it's most probably JUnit 4. In such case it doesn't matter how you name your methods, what is more important is that which annotations you use. Usage of annotations helps in defining clear logic without "magic" with method names. If you use Junit 4, you can call methods whatever you want, you just need put corresponding annotations above them. </p>

Title: Junit Before/After and setup/teardown


问:
ag-grid Multi-Level Sorting for Groups
I'm using ag-grid with row grouping across 2 different levels: Title and Date.

How do I get the group column to display the hierarchy such that Title (rowGroupIndex: 0) is sorted ascending but Date (rowGroupIndex: 1) is sorted descending?

I've already tried setting the sort attributes on their column definitions and comparator: agGrid.defaultGroupComparator, but it will only follow one side. Either the group column displays Titles and Dates both in ascending or both in descending.

答: Your comparator can access each node object being sorted, determine which column it's from and return a response appropriate to whether you want that column sorted ascending or descending.</p>

Title: ag-grid Multi-Level Sorting for Groups


答:
JUnit 3: the methods are identified by name setUp and tearDown

JUnit 4: the methods are identified by annotation @Before and @After

JUnit 5: the methods are identified by annotation @BeforeEach and @AfterEach

edit: To answer your question, yes it is possible to write

```<code>@Before
public void tearDown() {...}
</code>```

but this would not increase the readability of your code.

Title: Junit Before/After and setup/teardown

Body:
Are the setUp and teardown (precondition and postcondition settings) identified by the name setUp() and teardown() or by @Before and @After?

In other words is it possible in JUnit to have a @Before teardown() and a @After setUp()?

Body:
JUnit 3: the methods are identified by name setUp and tearDown

JUnit 4: the methods are identified by annotation @Before and @After

JUnit 5: the methods are identified by annotation @BeforeEach and @AfterEach

edit: To answer your question, yes it is possible to write

@Before
public void tearDown() {...}

but this would not increase the readability of your code.


问:
Does Object destructing work by reference or it clones the object
I need to copy an object from this.state to change some of its property values.

For example in the following method state is being mutated directly (this.state.errors = {})

```<code>   authorFormIsValid = () => {
    var formIsValid = true;
    this.state.errors = {}; //clear any previous errors.

    if (this.state.author.firstName.length < 3) {
      this.state.errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (this.state.author.lastName.length < 3) {
      this.state.errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors: this.state.errors});
    return formIsValid;
  };
</code>```

To avoid this, I know that we can use :

a) The object spread operator

```<code>let errors={...this.state.errors};
</code>```

b) Or Object.assign

```<code>let errors=Object.assign({},this.state.errors);
</code>```

But sometimes I've seem some examples in which object destructuring it is used like this:

```<code>authorFormIsValid = () => {
    let formIsValid = true;

   //Destructuring error and authors from this.state
    let {errors, author} = this.state;

    errors = {}; //clear any previous errors.

    if (author.firstName.length < 3) {
      errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (author.lastName.length < 3) {
      errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors});
    return formIsValid;
  };
</code>```

So my question is , is it object destructuring equivalent to the other two methods mentioned above? I mean, will I avoid mutating the state directly by using simple object destructuring ?

答:
Object destructuring works by reference and hence you should not be mutating the object after destructuring it. So the practice of

```<code>let {errors, author} = this.state;

errors = {}; //clear any previous errors.
</code>```

is actually wrong.

See a snippet of reference call below

let obj = {
  foo: {
    bar: 1
  }
}

let { foo } = obj;

console.log(foo.bar);      // 1
console.log(obj.foo.bar); // 1

foo.bar++;

console.log(foo.bar);      // 2
console.log(obj.foo.bar); // 2```

Body:
I need to copy an object from this.state to change some of its property values.

For example in the following method state is being mutated directly (this.state.errors = {})

   authorFormIsValid = () => {
    var formIsValid = true;
    this.state.errors = {}; //clear any previous errors.

    if (this.state.author.firstName.length < 3) {
      this.state.errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (this.state.author.lastName.length < 3) {
      this.state.errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors: this.state.errors});
    return formIsValid;
  };

To avoid this, I know that we can use :

a) The object spread operator

let errors={...this.state.errors};

b) Or Object.assign

let errors=Object.assign({},this.state.errors);

But sometimes I've seem some examples in which object destructuring it is used like this:

authorFormIsValid = () => {
    let formIsValid = true;

   //Destructuring error and authors from this.state
    let {errors, author} = this.state;

    errors = {}; //clear any previous errors.

    if (author.firstName.length < 3) {
      errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (author.lastName.length < 3) {
      errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors});
    return formIsValid;
  };

So my question is , is it object destructuring equivalent to the other two methods mentioned above? I mean, will I avoid mutating the state directly by using simple object destructuring ?

Body:
Object destructuring works by reference and hence you should not be mutating the object after destructuring it. So the practice of

let {errors, author} = this.state;

errors = {}; //clear any previous errors.

is actually wrong.

See a snippet of reference call below

let obj = {
  foo: {
    bar: 1
  }
}

let { foo } = obj;

console.log(foo.bar);      // 1
console.log(obj.foo.bar); // 1

foo.bar++;

console.log(foo.bar);      // 2
console.log(obj.foo.bar); // 2


问:
iPhone UISearch AutoComplete Override With Custom Word Suggestions
I am trying to control/override the auto-complete feature when a user enters text in my iPhone app.

Specifically I'd like to auto-complete a collection of words I supply. For example let's say a word in my list is Macpapajona. When I type "mac" auto-complete will suggest Macpapajona.

How can I do this?

I understand that I have to use this type of method, but what code would provide the replacement bubble?  A custom UIView?

```<code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange(NSRange)range replacementString:(NSString *)string {

   if ([textField.text isEqualToString:@"ma"])
   if (![string isEqualToString:@"c"]) {
     // code to pop up a subview that has the word "Macpapajona" in it.
   }
}
</code>```

答: I ended up populating a tableview with suggested words.</p>

Body:
I am trying to control/override the auto-complete feature when a user enters text in my iPhone app.

Specifically I'd like to auto-complete a collection of words I supply. For example let's say a word in my list is Macpapajona. When I type "mac" auto-complete will suggest Macpapajona.

How can I do this?

I understand that I have to use this type of method, but what code would provide the replacement bubble?  A custom UIView?

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange(NSRange)range replacementString:(NSString *)string {

   if ([textField.text isEqualToString:@"ma"])
   if (![string isEqualToString:@"c"]) {
     // code to pop up a subview that has the word "Macpapajona" in it.
   }
}


问:
Redux reducers -- changing deeply-nested state
I'm trying to wrap my head around how to change deeply-nested state in redux. It makes sense to me to combine reducers and change first-level properties of the state for those pieces. Where I'm not so clear is on how to change the state of a deeply-nested property.
Let's pretend that I have a shopping cart app. Below is my state:

```<code>{
    cart: {
      items: []
    },
    account: {
      amountLeft: 100,
      discounts: {
        redeemed: [],
        coupons: {
          buyOneGetOne: false
        }
      }
    }
}
</code>```

When a user enters in a code, let's say they can redeem the "buyOneGetOne" coupon and that value should become true.
I have a reducer for cart and another for account. For a first-level property (like if I was clearing the cart's items), I would just do the following in my reducer:

```<code>case 'EMPTY_CART':
  return Object.assign({}, state, {items: []});
</code>```

For changing buyOneGetOne, however, it seems like I would first need to do an Object.assign on coupons (because buyOneGetOne was modified), then doing an Object.assign on discounts (because I had modified coupons), and then finally emitting the action so the reducer could do Object.assign on the account (because discounts has now changed). This seems really complicated and easy to do wrong, though, which leads me to believe there must be a better way.

Am I going about this all wrong? It seems like reducers are only used to modify the root level properties of the state (like cart and account) and that I shouldn't have a reducer that touches state inside the account (like a discounts reducer), because account already has a reducer. But when I only want to change one property far down the state tree, it gets complex to merge every object from that change all the way up the object chain to the child of the root...

Can you/should you have reducers inside of reducers, like in this case have a discounts reducer?

答:
Yes, separating those reducers is a right thing. Actually, if you are afraid that some of those actions will require change of other reducer, you can either react to other constant, or just dispatch another action.

I've created a library to address this issue -- to allow easy composition, and to avoid verbose syntax, along with merging result.
So, your example will look like that:

```<code>import { createTile, createSyncTile } from 'redux-tiles';

const cartItems = createSyncTile({
  type: ['account', 'cart'],
  fn: ({ params }) => ({ items: params.items })
});

const coupons = createSyncTile({
  type: ['account', 'coupons'],
  fn: ({ params }) => params,
});

const reedemedCoupons = createSyncTile({
  type: ['account', 'reedemedCoupons'],
  fn: ({ params }) => params.coupons
});

const account = createTile({
  type: ['account', 'info'],
  fn: ({ api }) => api.get('/client/info')
});
</code>```

Using this strategy each component is atomic, and you can easily create new and dispatch others, without affecting others, it makes it easier to refactor and remove some functionality in the future, when your "tiles" are following single responsibility principle.

Body:
I'm trying to wrap my head around how to change deeply-nested state in redux. It makes sense to me to combine reducers and change first-level properties of the state for those pieces. Where I'm not so clear is on how to change the state of a deeply-nested property.
Let's pretend that I have a shopping cart app. Below is my state:

{
    cart: {
      items: []
    },
    account: {
      amountLeft: 100,
      discounts: {
        redeemed: [],
        coupons: {
          buyOneGetOne: false
        }
      }
    }
}

When a user enters in a code, let's say they can redeem the "buyOneGetOne" coupon and that value should become true.
I have a reducer for cart and another for account. For a first-level property (like if I was clearing the cart's items), I would just do the following in my reducer:

case 'EMPTY_CART':
  return Object.assign({}, state, {items: []});

For changing buyOneGetOne, however, it seems like I would first need to do an Object.assign on coupons (because buyOneGetOne was modified), then doing an Object.assign on discounts (because I had modified coupons), and then finally emitting the action so the reducer could do Object.assign on the account (because discounts has now changed). This seems really complicated and easy to do wrong, though, which leads me to believe there must be a better way.

Am I going about this all wrong? It seems like reducers are only used to modify the root level properties of the state (like cart and account) and that I shouldn't have a reducer that touches state inside the account (like a discounts reducer), because account already has a reducer. But when I only want to change one property far down the state tree, it gets complex to merge every object from that change all the way up the object chain to the child of the root...

Can you/should you have reducers inside of reducers, like in this case have a discounts reducer?

Body:
Yes, separating those reducers is a right thing. Actually, if you are afraid that some of those actions will require change of other reducer, you can either react to other constant, or just dispatch another action.

I've created a library to address this issue -- to allow easy composition, and to avoid verbose syntax, along with merging result.
So, your example will look like that:

import { createTile, createSyncTile } from 'redux-tiles';

const cartItems = createSyncTile({
  type: ['account', 'cart'],
  fn: ({ params }) => ({ items: params.items })
});

const coupons = createSyncTile({
  type: ['account', 'coupons'],
  fn: ({ params }) => params,
});

const reedemedCoupons = createSyncTile({
  type: ['account', 'reedemedCoupons'],
  fn: ({ params }) => params.coupons
});

const account = createTile({
  type: ['account', 'info'],
  fn: ({ api }) => api.get('/client/info')
});

Using this strategy each component is atomic, and you can easily create new and dispatch others, without affecting others, it makes it easier to refactor and remove some functionality in the future, when your "tiles" are following single responsibility principle.


问:
Servers for video streaming 720p
Brother wants to stream 720p games from his colleagues in real time on his own site. I do not want to archive recordings. I wanted to ask if there are any services / servers for streaming video?</p>

答: Take a look at Wowza media systems. There are several options how to use it. Service on demand, using own servers, etc.</p>

Title: Servers for video streaming 720p


问:
How how to change spacemacs from helm to ivy?
During the initial setup spacemacs asked, "What type of completion framework do you want?" and I selected "helm".

Now I want to use ivy instead.
How to change spacemacs from helm to ivy?
There are 16 occurrences of "helm" in my ~/.spacemacs file.

I added "spacemacs-ivy" at top of ~/.spacemacs file and restarted, but that didn't work
 as described in https://www.reddit.com/r/emacs/comments/407q2c/ivy_is_now_available_in_spacemacs/ .
On restart emacs said "Spacemacs encountered an error while loading your '.spacemacs' file."

答:
If there is no .spacemacs file, Spacemacs asks some questions and creates a new .spacemacs file.

I reinstalled spacemacs by deleting .spacemacs file and then restarting emacs.
I answered the questions like this:

```<code>What is your preferred editing style? vim
What distribution of spacemacs would you like to start with? spacemacs
What type of completion framework do you want? ivy
</code>```

Now ivy is installed.

Body:
If there is no .spacemacs file, Spacemacs asks some questions and creates a new .spacemacs file.

I reinstalled spacemacs by deleting .spacemacs file and then restarting emacs.
I answered the questions like this:

What is your preferred editing style? vim
What distribution of spacemacs would you like to start with? spacemacs
What type of completion framework do you want? ivy

Now ivy is installed.


问:
Quick and dirty solution for communication between processes in different machines
I have two processes written in java in two machines within my network that should pass simple chunks of data to each other.

I'm looking for a quick and dirty way (without resorting to writing files and polling for changes on network share files)

答: java RMI (remote method interface)</p>

OwnerDisplayName: Dani

Body: java RMI (remote method interface)

OwnerDisplayName: Steve B.


问:
Does wifi scanning comply with Apple's guidelines to scan wifi hotspot on ios4
Does wifi scanning comply with Apple's guidelines to scan wifi hotspot on ios4</p>

答: Considering that's how the iPhone - any any other WiFi device - finds and connects to a hotspot, yes.</p>