问:
Android Camera2 Renderscript overheat issue
I have this overheat issue, that it turns off my phone after running for a couple of hours. I want to run this 24/7, please help me to improve this:

I use Camera2 interface, RAW format followed by a renderscript to convert YUV420888 to rgba. My renderscript is as below:

```<code>#pragma version(1)
#pragma rs java_package_name(com.sensennetworks.sengaze)
#pragma rs_fp_relaxed

rs_allocation gCurrentFrame;
rs_allocation gByteFrame;
int32_t gFrameWidth;

uchar4 __attribute__((kernel)) yuv2RGBAByteArray(uchar4 prevPixel,uint32_t x,uint32_t y)
{

    // Read in pixel values from latest frame - YUV color space
    // The functions rsGetElementAtYuv_uchar_? require API 18
    uchar4 curPixel;
    curPixel.r = rsGetElementAtYuv_uchar_Y(gCurrentFrame, x, y);
    curPixel.g = rsGetElementAtYuv_uchar_U(gCurrentFrame, x, y);
    curPixel.b = rsGetElementAtYuv_uchar_V(gCurrentFrame, x, y);

    // uchar4 rsYuvToRGBA_uchar4(uchar y, uchar u, uchar v);
    // This function uses the NTSC formulae to convert YUV to RBG
    uchar4 out = rsYuvToRGBA_uchar4(curPixel.r, curPixel.g, curPixel.b);

    rsSetElementAt_uchar(gByteFrame, out.r, 4 * (y*gFrameWidth + x) + 0 );
    rsSetElementAt_uchar(gByteFrame, out.g, 4 * (y*gFrameWidth + x) + 1 );
    rsSetElementAt_uchar(gByteFrame, out.b, 4 * (y*gFrameWidth + x) + 2 );
    rsSetElementAt_uchar(gByteFrame, 255, 4 * (y*gFrameWidth + x) + 3 );

    return out;
}
</code>```

This is where I call the renderscript to convert to rgba:

```<code>@Override
        public void onBufferAvailable(Allocation a) {
            inputAllocation.ioReceive();

            // Run processing pass if we should send a frame
            final long current = System.currentTimeMillis();
            if ((current - lastProcessed) >= frameEveryMs) {
                yuv2rgbaScript.forEach_yuv2RGBAByteArray(scriptAllocation, outputAllocation);
                if (rgbaByteArrayCallback != null) {
                    outputAllocationByte.copyTo(outBufferByte);
                    rgbaByteArrayCallback.onRGBAArrayByte(outBufferByte);
                }
                lastProcessed = current;
            }
        }
</code>```

And this is the callback to run image processing using OpenCV:

```<code>@Override
    public void onRGBAArrayByte(byte[] rgbaByteArray) {

        try {
            /* Fill images. */
            rgbaMat.put(0, 0, rgbaByteArray);

            analytic.processFrame(rgbaMat);

            /* Send fps to UI for debug purpose. */
            calcFPS(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
</code>```

The whole thing runs at ~22fps. I've checked carefully and there is no memory leaks. But after running this for some time even with the screen off, the phone gets very hot, and turn off itself. Note if I remove the image processing part, the issue still persists. What could be wrong with this? I could turn on the phone camera app and leave it running for hours without a problem.

Does renderscript cause the heat?

Does 22fps cause the heat? Maybe I should reduce it?

Does Android background service cause heat?

Thanks.

ps: I tested this on LG G4 with full Camera2 interface support.

答:
In theory, your device should throttle itself if it starts to overheat, and never shut down. This would just reduce your frame rate as the device warms up.   But some devices aren't as good at this as they should be, unfortunately.

Basically, anything that reduces your CPU / GPU usage will reduce power consumption and heat generation.  Basic tips:

Do not copy buffers. Each copy is very expensive when you're doing it at ~30fps.  Here, you're copying from Allocation to byte[], and then from that byte[] to the rgbaMat.  That's 2x as expensive as just copying from the Allocation to the rgbaMat. Unfortunately, I'm not sure there's a direct way to copy from the Allocation to the rgbaMat, or to create an Allocation that's backed by the same memory as the rgbaMat.

Are you sure you can't do your OpenCV processing on YUV data instead? That'll save you a lot of overhead here; the RGB->YUV conversion is not cheap when not done in hardware.

There's also an RS intrinsic, ScriptIntrinsicYuvToRgb, which may give you better performance than your hand-written loop.

Body:
I have this overheat issue, that it turns off my phone after running for a couple of hours. I want to run this 24/7, please help me to improve this:

I use Camera2 interface, RAW format followed by a renderscript to convert YUV420888 to rgba. My renderscript is as below:

#pragma version(1)
#pragma rs java_package_name(com.sensennetworks.sengaze)
#pragma rs_fp_relaxed

rs_allocation gCurrentFrame;
rs_allocation gByteFrame;
int32_t gFrameWidth;

uchar4 __attribute__((kernel)) yuv2RGBAByteArray(uchar4 prevPixel,uint32_t x,uint32_t y)
{

    // Read in pixel values from latest frame - YUV color space
    // The functions rsGetElementAtYuv_uchar_? require API 18
    uchar4 curPixel;
    curPixel.r = rsGetElementAtYuv_uchar_Y(gCurrentFrame, x, y);
    curPixel.g = rsGetElementAtYuv_uchar_U(gCurrentFrame, x, y);
    curPixel.b = rsGetElementAtYuv_uchar_V(gCurrentFrame, x, y);

    // uchar4 rsYuvToRGBA_uchar4(uchar y, uchar u, uchar v);
    // This function uses the NTSC formulae to convert YUV to RBG
    uchar4 out = rsYuvToRGBA_uchar4(curPixel.r, curPixel.g, curPixel.b);

    rsSetElementAt_uchar(gByteFrame, out.r, 4 * (y*gFrameWidth + x) + 0 );
    rsSetElementAt_uchar(gByteFrame, out.g, 4 * (y*gFrameWidth + x) + 1 );
    rsSetElementAt_uchar(gByteFrame, out.b, 4 * (y*gFrameWidth + x) + 2 );
    rsSetElementAt_uchar(gByteFrame, 255, 4 * (y*gFrameWidth + x) + 3 );

    return out;
}

This is where I call the renderscript to convert to rgba:

@Override
        public void onBufferAvailable(Allocation a) {
            inputAllocation.ioReceive();

            // Run processing pass if we should send a frame
            final long current = System.currentTimeMillis();
            if ((current - lastProcessed) >= frameEveryMs) {
                yuv2rgbaScript.forEach_yuv2RGBAByteArray(scriptAllocation, outputAllocation);
                if (rgbaByteArrayCallback != null) {
                    outputAllocationByte.copyTo(outBufferByte);
                    rgbaByteArrayCallback.onRGBAArrayByte(outBufferByte);
                }
                lastProcessed = current;
            }
        }

And this is the callback to run image processing using OpenCV:

@Override
    public void onRGBAArrayByte(byte[] rgbaByteArray) {

        try {
            /* Fill images. */
            rgbaMat.put(0, 0, rgbaByteArray);

            analytic.processFrame(rgbaMat);

            /* Send fps to UI for debug purpose. */
            calcFPS(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

The whole thing runs at ~22fps. I've checked carefully and there is no memory leaks. But after running this for some time even with the screen off, the phone gets very hot, and turn off itself. Note if I remove the image processing part, the issue still persists. What could be wrong with this? I could turn on the phone camera app and leave it running for hours without a problem.

Does renderscript cause the heat?

Does 22fps cause the heat? Maybe I should reduce it?

Does Android background service cause heat?

Thanks.

ps: I tested this on LG G4 with full Camera2 interface support.


来源: stackexchange

问:
Set NodeJS's V8 engine's heapstack
My program crashes when i try to pull "too much" (for the heap) data up from my postgressql db and place it in an array...

JAVASCRIPT HEAP OUT OF MEMORY

The heap_size_limit in my PC is currently 1535115264 bytes or 1.42969 GB (https://nodejs.org/dist/latest-v6.x/docs/api/v8.html) which is exactly the amount my app consumes - before it crashes each time.

But i really can't figure out how to change this limit?

I have tried with:

--max_old_space_size=100000 (100 GB)

--max_new_space_size=100000000 (100 GB)

max_old_space_size in generel works - but not regarding the heap size.
max_new_space_size doesn't seem to change any thing at all :-(

I also tried to play with other options - but without luck.

--clever_optimizations

--optimize_for_size

--heap_profiler_trace_objects

--typed_array_max_size_in_heap

--stack_size

--max_executable_size

https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md

答:
--max_old_space_size is the way to go. Don't go overboard with it; huge values probably won't work well. There have also been some fixes in recent V8 versions to better support huge heaps; I think Node 6.x is too old to contain those, so you might have more success with a newer version.

You don't need (and probably shouldn't set) any other flags. (You definitely don't want a 100GB new space!)

What do you mean by "works - but not regarding the heap size"?

ContentLicense: CC BY-SA 3.0

Title: Set NodeJS's V8 engine's heapstack


问:
C# lock issues when writing to log
I have a class that programmatically creates a log using the Nlog framework. I have several processes running and creating their logs at the same time. I added a lock to the constructor of the class, as before the two threads were attempting to create a file at the same time which resulted in some annoying bugs (like only creating one log).

This seems to have solved that problem. However now i have the same issue with writing to the log, and using a lock has not helped. Here is the class.

```<code>public class CwiLogger
    {
        private Logger _log;
        private static Object createLogLock = new Object();
        private static Object writeLogLock = new Object();
        public CwiLogger(string logPath, string logName, string className)
        {
            lock (createLogLock)
            {
                var config = new LoggingConfiguration();
                var fileTarget = new FileTarget();
                config.AddTarget("file", fileTarget);
                fileTarget.FileName = Path.Combine(logPath, logName);
                fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}";
                var rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(rule);

                LogManager.Configuration = config;

                this._log = LogManager.GetLogger(className);
            }
        }

        public void AddToLog(string logText, LogLevel level = null)
        {
            lock (writeLogLock)
            {
                level = level ?? LogLevel.Info;
                this._log.Log(level, logText + "\n");
            }
        }
    }
</code>```

In my client code i run two threads each running a process that looks like this:

```<code>var log = new CwiLogger(@"C:\Users\jma\Documents\ProgrammingJunk\logTest", "Log2.txt", "Log2");
for (int i = 0; i < 100; i++)
{
    log.AddToLog("Log2 " + i);
}
</code>```

only i use log1 for one and log2 for the other.

in my output. One of the 2 logs always sucessfully counts to 99, while the other gets 4-5 in and then has no other output.

答:
Maybe something like this:

```<code>public class CwiLogger
{
    private static LoggingConfiguration _logConfig = new LoggingConfiguration();
    private static Object createLogLock = new Object();
    private Logger _log;

    public CwiLogger(string logPath, string logName, string className)
    {
            lock (createLogLock)
            {
                var fileTarget = _logConfig.FindTargetByName(logName);
                if (fileTarget == null)
                {
                    var fileTarget = new FileTarget(logName);
                    fileTarget.FileName = Path.Combine(logPath, logName);
                    fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}";
                    _logConfig.AddTarget(fileTarget);
                    var rule = new LoggingRule(className, LogLevel.Debug, fileTarget) { Final = true };
                    _logConfig.LoggingRules.Add(rule);
                    LogManager.Configuration = _logConfig;
                }
            }
        this._log = LogManager.GetLogger(className);
    }

    public void AddToLog(string logText, LogLevel level = null)
    {
        level = level ?? LogLevel.Info;
        this._log.Log(level, logText + "\n");
    }
}
</code>```

Or maybe steal some ideas from here: https://github.com/NLog/NLog/issues/1998

Title: C# lock issues when writing to log

Body:
I have a class that programmatically creates a log using the Nlog framework. I have several processes running and creating their logs at the same time. I added a lock to the constructor of the class, as before the two threads were attempting to create a file at the same time which resulted in some annoying bugs (like only creating one log).

This seems to have solved that problem. However now i have the same issue with writing to the log, and using a lock has not helped. Here is the class.

public class CwiLogger
    {
        private Logger _log;
        private static Object createLogLock = new Object();
        private static Object writeLogLock = new Object();
        public CwiLogger(string logPath, string logName, string className)
        {
            lock (createLogLock)
            {
                var config = new LoggingConfiguration();
                var fileTarget = new FileTarget();
                config.AddTarget("file", fileTarget);
                fileTarget.FileName = Path.Combine(logPath, logName);
                fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}";
                var rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(rule);

                LogManager.Configuration = config;

                this._log = LogManager.GetLogger(className);
            }
        }

        public void AddToLog(string logText, LogLevel level = null)
        {
            lock (writeLogLock)
            {
                level = level ?? LogLevel.Info;
                this._log.Log(level, logText + "\n");
            }
        }
    }

In my client code i run two threads each running a process that looks like this:

var log = new CwiLogger(@"C:\Users\jma\Documents\ProgrammingJunk\logTest", "Log2.txt", "Log2");
for (int i = 0; i < 100; i++)
{
    log.AddToLog("Log2 " + i);
}

only i use log1 for one and log2 for the other.

in my output. One of the 2 logs always sucessfully counts to 99, while the other gets 4-5 in and then has no other output.

Body:
Maybe something like this:

public class CwiLogger
{
    private static LoggingConfiguration _logConfig = new LoggingConfiguration();
    private static Object createLogLock = new Object();
    private Logger _log;

    public CwiLogger(string logPath, string logName, string className)
    {
            lock (createLogLock)
            {
                var fileTarget = _logConfig.FindTargetByName(logName);
                if (fileTarget == null)
                {
                    var fileTarget = new FileTarget(logName);
                    fileTarget.FileName = Path.Combine(logPath, logName);
                    fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}";
                    _logConfig.AddTarget(fileTarget);
                    var rule = new LoggingRule(className, LogLevel.Debug, fileTarget) { Final = true };
                    _logConfig.LoggingRules.Add(rule);
                    LogManager.Configuration = _logConfig;
                }
            }
        this._log = LogManager.GetLogger(className);
    }

    public void AddToLog(string logText, LogLevel level = null)
    {
        level = level ?? LogLevel.Info;
        this._log.Log(level, logText + "\n");
    }
}

Or maybe steal some ideas from here: https://github.com/NLog/NLog/issues/1998


问:
Unexpected results when trying to match string pattern
Given a string, return true if the first instance of "x" in the string is immediately followed by another "x". It will not work for the case of doubleX("axxbb"). It should return true but gives false.</p>

```<code>boolean doubleX(String str) {
  for (int i = 0; i < str.length(); i++) {
    if (str.substring(i) == "x") {
      if ( str.substring(i) == str.substring(i + 1)){
      return true;
      }

    }

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

答:
str.substring(i) doesn't do what you think it does - it returns a substring, not character number i.

Use str.charAt(i) instead.

Body:
Given a string, return true if the first instance of "x" in the string is immediately followed by another "x". It will not work for the case of doubleX("axxbb"). It should return true but gives false.

boolean doubleX(String str) {
  for (int i = 0; i < str.length(); i++) {
    if (str.substring(i) == "x") {
      if ( str.substring(i) == str.substring(i + 1)){
      return true;
      }

    }

  }
  return false;
}


问:
mb_strtolower not working
I have the following string:

```<code>$var = "RUA TANGARA"
</code>```

And I'm doing:

```<code>echo mb_strtolower(preg_replace('/[^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $var)), 'UTF-8');
</code>```

But this still returning "RUA TANGARA".

I use the preg_replace() because $var can be "RÜÁ TÃNAGARA".

Can someone help me?

答:
The issue is that you want to replace certain characters after the transliteration but you specified ^ (which has special meaning and means NOT) at the beginning of the character class [].

So you are replacing characters that are NOT ~'" (which happens to be all of them in your example), so it results in an empty string.  To fix, just escape the ^, move it away from the beginning or remove it if not needed and it should be fine:

```<code>/[\^~\'"]/
</code>```

Or:

```<code>/[~^\'"]/
</code>```

Working Example

Title: mb_strtolower not working

Body:
I have the following string:

$var = "RUA TANGARA"

And I'm doing:

echo mb_strtolower(preg_replace('/[^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $var)), 'UTF-8');

But this still returning "RUA TANGARA".

I use the preg_replace() because $var can be "RÜÁ TÃNAGARA".

Can someone help me?

Body:
The issue is that you want to replace certain characters after the transliteration but you specified ^ (which has special meaning and means NOT) at the beginning of the character class [].

So you are replacing characters that are NOT ~'" (which happens to be all of them in your example), so it results in an empty string.  To fix, just escape the ^, move it away from the beginning or remove it if not needed and it should be fine:

/[\^~\'"]/

Or:

/[~^\'"]/

Working Example


问:
python 3.6 coroutine was never awaited
So when ever I run my program and connect to it with the echo client it gives me this error.

```<code>Starting server
Serving on ('127.0.0.1', 8881)
Exception in callback UVTransport._call_connection_made
handle: <Handle UVTransport._call_connection_made>
Traceback (most recent call last):
File "uvloop/cbhandles.pyx", line 52, in uvloop.loop.Handle._run (uvloop/loop.c:48414)
File "uvloop/handles/tcp.pyx", line 141, in uvloop.loop.TCPTransport._call_connection_made (uvloop/loop.c:80488)
File "uvloop/handles/basetransport.pyx", line 140, in uvloop.loop.UVBaseTransport._call_connection_made (uvloop/loop.c:65774)
File "uvloop/handles/basetransport.pyx", line 137, in uvloop.loop.UVBaseTransport._call_connection_made (uvloop/loop.c:65671)
AttributeError: 'coroutine' object has no attribute 'connection_made'
/home/kenton/Programming/bridal/bridal-middle/middle/lib/server.py:16:RuntimeWarning: coroutine 'handle_request' was never awaited
loop.run_forever()
</code>```

As far as I know I have everything that should be awaited awaited.
Here is the code:

```<code>class Server:

    def __init__(self, port):
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    loop = asyncio.get_event_loop()
    server = loop.run_until_complete(self.init(loop))

    print("Serving on {}".format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        print("\rclosing the server")
        pass

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()

    async def init(self, loop):
        server = await loop.create_server(self.handle_request, '127.0.0.1', 8881)
        return server

    async def handle_request(self):
        print(datetime.datetime.now())
        reader = asyncio.StreamReader()
        writer = asyncio.StreamWriter()
        data = await reader.read(100)
        message = data.decode()
        addr = writer.get_extra_info('peername')
        code = message.partition('-')
        if code[0].startswith("1") or code[0].startswith("5"):
            accounts = lib.settings.database.accounts
            if code[0] == "101":
                result = await self.login_101(code, accounts, writer)
            if code[0] == "501":
                result = await accounts.find_one({"username":code[2]})
                print("looking up", code[0])
            #code logic to keep asking for a valid username if one exists
                if result is None:
                    username = code[2]
                    print(username, " does not exist. Creating")
                    writer.write(b"0")
                    await writer.drain()
                    data = await reader.read(100)
                    message = data.decode()
                    code = message.partition('-')
                    post = {"username":username,"password":code[0],"email":code[2]}
                    post_id = await accounts.insert_one(post).inserted_id
                    writer.write(b(post_id))
                    await writer.drain()
        print("Closed the client socket")
        writer.close()
        print(datetime.datetime.now())
</code>```

答:
Regarding your error message, the actual error is:

```<code>AttributeError: 'coroutine' object has no attribute 'connection_made'
</code>```

And the line below is just a warning (RuntimeWarning: coroutine 'handle_request' was never awaited).

You might be mixing asyncio.start_server with loop.create_server().

loop.create_server()'s first parameter is protocol_factory which is a callable that returns an instance of a Protocol (and not a coroutine as in your code above):

```<code>import asyncio

class MyProtocol(asyncio.Protocol):
    def connection_made(self, transport):
        print("Connection made", transport)

    def data_received(self, data):
        print("Data received", data)

loop = asyncio.get_event_loop()
# Each client connection will create a new protocol instance
coro = loop.create_server(MyProtocol, '127.0.0.1', 8888)
server = loop.run_until_complete(coro)
loop.run_forever()
</code>```

See full echo server example here.

ContentLicense: CC BY-SA 4.0

Title: python 3.6 coroutine was never awaited

Body:
So when ever I run my program and connect to it with the echo client it gives me this error.

Starting server
Serving on ('127.0.0.1', 8881)
Exception in callback UVTransport._call_connection_made
handle: <Handle UVTransport._call_connection_made>
Traceback (most recent call last):
File "uvloop/cbhandles.pyx", line 52, in uvloop.loop.Handle._run (uvloop/loop.c:48414)
File "uvloop/handles/tcp.pyx", line 141, in uvloop.loop.TCPTransport._call_connection_made (uvloop/loop.c:80488)
File "uvloop/handles/basetransport.pyx", line 140, in uvloop.loop.UVBaseTransport._call_connection_made (uvloop/loop.c:65774)
File "uvloop/handles/basetransport.pyx", line 137, in uvloop.loop.UVBaseTransport._call_connection_made (uvloop/loop.c:65671)
AttributeError: 'coroutine' object has no attribute 'connection_made'
/home/kenton/Programming/bridal/bridal-middle/middle/lib/server.py:16:RuntimeWarning: coroutine 'handle_request' was never awaited
loop.run_forever()

As far as I know I have everything that should be awaited awaited.
Here is the code:

class Server:

    def __init__(self, port):
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    loop = asyncio.get_event_loop()
    server = loop.run_until_complete(self.init(loop))

    print("Serving on {}".format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        print("\rclosing the server")
        pass

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()

    async def init(self, loop):
        server = await loop.create_server(self.handle_request, '127.0.0.1', 8881)
        return server

    async def handle_request(self):
        print(datetime.datetime.now())
        reader = asyncio.StreamReader()
        writer = asyncio.StreamWriter()
        data = await reader.read(100)
        message = data.decode()
        addr = writer.get_extra_info('peername')
        code = message.partition('-')
        if code[0].startswith("1") or code[0].startswith("5"):
            accounts = lib.settings.database.accounts
            if code[0] == "101":
                result = await self.login_101(code, accounts, writer)
            if code[0] == "501":
                result = await accounts.find_one({"username":code[2]})
                print("looking up", code[0])
            #code logic to keep asking for a valid username if one exists
                if result is None:
                    username = code[2]
                    print(username, " does not exist. Creating")
                    writer.write(b"0")
                    await writer.drain()
                    data = await reader.read(100)
                    message = data.decode()
                    code = message.partition('-')
                    post = {"username":username,"password":code[0],"email":code[2]}
                    post_id = await accounts.insert_one(post).inserted_id
                    writer.write(b(post_id))
                    await writer.drain()
        print("Closed the client socket")
        writer.close()
        print(datetime.datetime.now())

Body:
Regarding your error message, the actual error is:

AttributeError: 'coroutine' object has no attribute 'connection_made'

And the line below is just a warning (RuntimeWarning: coroutine 'handle_request' was never awaited).

You might be mixing asyncio.start_server with loop.create_server().

loop.create_server()'s first parameter is protocol_factory which is a callable that returns an instance of a Protocol (and not a coroutine as in your code above):

import asyncio

class MyProtocol(asyncio.Protocol):
    def connection_made(self, transport):
        print("Connection made", transport)

    def data_received(self, data):
        print("Data received", data)

loop = asyncio.get_event_loop()
# Each client connection will create a new protocol instance
coro = loop.create_server(MyProtocol, '127.0.0.1', 8888)
server = loop.run_until_complete(coro)
loop.run_forever()

See full echo server example here.


问:
Get json from request flask
Client code:

```<code>import requests
import json

url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)
</code>```

Server code:

```<code>from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/login', methods=['GET','POST'])
def login():
 if request.method == 'POST':

    username = request.form.get("user")
    password = request.form.get("pass")
    //more code
    return make_response("",200)

if __name__ == "__main__":
     app.run(host = "127.0.0.1", port = 5050)
</code>```

The problem is that my username and password are always None.

I also tried using:

```<code>content = request.get_json(force = True)
password = content['pass']
</code>```

and

```<code>request.form['user']
</code>```

When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

EDIT:

I did add json.dumps and used request.get_json() and it worked

答: I tried executing the same code that you have posted and I was able to fetch values for username and password instead of None.

Title: Get json from request flask

Body:
Client code:

import requests
import json

url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)

Server code:

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/login', methods=['GET','POST'])
def login():
 if request.method == 'POST':

    username = request.form.get("user")
    password = request.form.get("pass")
    //more code
    return make_response("",200)

if __name__ == "__main__":
     app.run(host = "127.0.0.1", port = 5050)

The problem is that my username and password are always None.

I also tried using:

content = request.get_json(force = True)
password = content['pass']

and

request.form['user']

When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

EDIT:

I did add json.dumps and used request.get_json() and it worked


问:
How can I have the main repository stored on a local network?
I'm wondering how can I have the main Mercurial repository stored on the local network and every developer connected to it can do the usual things (just like with BitBucket online.)

Thanks.

答:
Set up a machine running the apache HTTP server (or another webserver that can host hgwebdir)

Install the hgwebdir CGI script.

ContentLicense: CC BY-SA 2.5


问:
Tagging and Training NER dataset
I have a data set and I want to tag it for Named Entity Recognition. My dataset is in Persian.
I want to know how should I tag expressions like :

*** آقای مهدی کاظمی  = Mr Mehdi Kazemi / Mr will Smith. >>> (names with titles) should I tag all as a person or just the first name and last name should be tagged? (I mean should i also tag "Mr")

Mr  >>  b_per     ||     Mr >> O

Mehdi  >>   i_per || Mehdi >> b_per

Kazemi  >> i_per || Kazemi >> i_per

*** بیمارستان نور = Noor hospital >>> Should I tag the name only or the name and hospital both as Named Entity?

*** Eiffel tower / The Ministry of Defense (I mean the us DOD for example) >>> in Persian it is called :
وزارت دفاع    (vezarate defa)
should I only tag Defense ? or all together?

There are many more examples for schools, movies, cities, countries and.... since we use the entity class before the named entity.

I would appreciate if you can help me with tagging this dataset.

答: In general, you tag as the way you want the output to look. It's up to you if you want titles included, for example. However, Core NLP won't tag overlapping entities, so you have to make a decision in for cases like the hospital named after someone.</p>

Title: Tagging and Training NER dataset


问:
Laravel - Unable to override the create method for a model
When overriding the base Laravel model create method, the application fails. No errors are sent back to the browser, and the server logs are empty. The strange thing, it works just fine without the override. Not sure what I'm doing wrong.

Simplified controller function:

```<code>public function save(Request $request, $id = 0) {
    $myModel = MyModel::find($id);
    $data = $request->all();

    if (!$myModel) // Create a new row
    {
        $myModel = MyModel::create($data);
    }

    // ...
}
</code>```

This works fine until I add this function to the model:

```<code>class MyModel extends Model
{
    // ...

    public static function create($attributes = [])
    {
        return parent::create($attributes);
    }

    // ...
}
</code>```

Just to clarify, I'm not looking for a different way to implement this. I just need to know why the parent call is failing for me.

Here's some server info...

Server OS: Windows 7 (personal PC with XAMPP)

Laravel version 5.4.15

PHP version 5.6.30

答:
The explanation is that the public static function create() is not defined in the Illuminate\Database\Eloquent\Model class.

Is handled as dynamic method call, that is is handled by calling the function:

```<code>public static function __callStatic($method, $parameters)
</code>```

In the Illuminate\Database\Eloquent\Model class.

At the end the create() function is defined in the Illuminate\Database\Query\Builder class.
That is the reason you cant override it in your Model and call parent::create()

IMHO I have not tested entirely, you could try with:

```<code>public static function create($attributes)
{
    return (new static)->newQuery()->create($attributes);
}
</code>```

Body:
When overriding the base Laravel model create method, the application fails. No errors are sent back to the browser, and the server logs are empty. The strange thing, it works just fine without the override. Not sure what I'm doing wrong.

Simplified controller function:

public function save(Request $request, $id = 0) {
    $myModel = MyModel::find($id);
    $data = $request->all();

    if (!$myModel) // Create a new row
    {
        $myModel = MyModel::create($data);
    }

    // ...
}

This works fine until I add this function to the model:

class MyModel extends Model
{
    // ...

    public static function create($attributes = [])
    {
        return parent::create($attributes);
    }

    // ...
}

Just to clarify, I'm not looking for a different way to implement this. I just need to know why the parent call is failing for me.

Here's some server info...

Server OS: Windows 7 (personal PC with XAMPP)

Laravel version 5.4.15

PHP version 5.6.30

Body:
The explanation is that the public static function create() is not defined in the Illuminate\Database\Eloquent\Model class.

Is handled as dynamic method call, that is is handled by calling the function:

public static function __callStatic($method, $parameters)

In the Illuminate\Database\Eloquent\Model class.

At the end the create() function is defined in the Illuminate\Database\Query\Builder class.
That is the reason you cant override it in your Model and call parent::create()

IMHO I have not tested entirely, you could try with:

public static function create($attributes)
{
    return (new static)->newQuery()->create($attributes);
}


问:
react redux-thunk component doesn't render this.props
I'm new to react and I'm trying to understand on to make async ajax request. I was able to get the request completed and the data returned added to my state, but I can't render the data to my component. Here's my setup.

UserPage component

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getUsers } from '../../actions';

class User extends Component {
    displayName: 'User';

    componentWillMount() {
        this.props.getUsers();
    }

    renderUsers() {
        return this.props.users.map(user => {
            return (

{user.Name}

            );
        });
    }

    render() {
        var component;
        if (this.props.users) {
            component = this.renderUsers()
        } else {
            component =
asdf
;
        }

        return (

                {component}

        );
    };
};

function mapStateToProps(state) {
    return {
        users: state.all
    };
}

export default connect(mapStateToProps, { getUsers })(User);
```

<h3>Action</h3>

<pre class="lang-js prettyprint-override"><code>import request from '../helpers/request';
import { GET_USERS } from './types';

export function getUsers() {

    return request.get(GET_USERS, 'Person/GetPeople');
}
</code>```

With the get function from request.js module

get: function (action, url) {
        return (dispatch) => {
            axios.get(`${ROOT_URL}${url}`)
                .then(({ data }) => {
                    dispatch({
                        type: action,
                        payload: data
                    });
                });
        };
    }
```

<h3>User_reducer</h3>

<pre class="lang-js prettyprint-override"><code>import { GET_USERS } from '../actions/types';

export default function (state = {}, action) {
    switch (action.type) {
        case GET_USERS:
            console.log(action);
            return { ...state, all: action.payload }
        default:
            return state;
    };
}
</code>```

When I load the UserPage component, I can see the request being done and the state being updated in the redux dev tool, but I can't display this.props.users.

If I take out the if(this.props.users) in the render() method of the User component, I get an undefined on this.props.users.

What am I doing wrong?

Any help greatly appreciated! Thank you

SOLVED

The solution was to set the users property to state.users.all in the mapStateToProps function.

function mapStateToProps(state) {
    return {
        users: state.users.all
    };
}
```

Thank you

答:
Could you check, do you have this.renderUsers() defined in that render function? It might be you forgot to bind it, and that function is undefined?

Try to add this.renderUsers = this.renderUsers.bind(this); in your constructor and see, if it helps.

Body:
I'm new to react and I'm trying to understand on to make async ajax request. I was able to get the request completed and the data returned added to my state, but I can't render the data to my component. Here's my setup.

UserPage component

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getUsers } from '../../actions';

class User extends Component {
    displayName: 'User';

    componentWillMount() {
        this.props.getUsers();
    }

    renderUsers() {
        return this.props.users.map(user => {
            return (

{user.Name}

            );
        });
    }

    render() {
        var component;
        if (this.props.users) {
            component = this.renderUsers()
        } else {
            component =
asdf
;
        }

        return (

                {component}

        );
    };
};

function mapStateToProps(state) {
    return {
        users: state.all
    };
}

export default connect(mapStateToProps, { getUsers })(User);

Action

import request from '../helpers/request';
import { GET_USERS } from './types';

export function getUsers() {

    return request.get(GET_USERS, 'Person/GetPeople');
}

With the get function from request.js module

get: function (action, url) {
        return (dispatch) => {
            axios.get(`${ROOT_URL}${url}`)
                .then(({ data }) => {
                    dispatch({
                        type: action,
                        payload: data
                    });
                });
        };
    }

User_reducer

import { GET_USERS } from '../actions/types';

export default function (state = {}, action) {
    switch (action.type) {
        case GET_USERS:
            console.log(action);
            return { ...state, all: action.payload }
        default:
            return state;
    };
}

When I load the UserPage component, I can see the request being done and the state being updated in the redux dev tool, but I can't display this.props.users.

If I take out the if(this.props.users) in the render() method of the User component, I get an undefined on this.props.users.

What am I doing wrong?

Any help greatly appreciated! Thank you

SOLVED

The solution was to set the users property to state.users.all in the mapStateToProps function.

function mapStateToProps(state) {
    return {
        users: state.users.all
    };
}

Thank you


答:
```<code>boolean doubleX(String str){
  if (str == null){
    return false; //defensively check that the input is not null
  }
  int firstX = str.indexOf("x");
  if(firstX >=0 && firstX < str.length()-1){  //this ensures that we actually found an x and that there is at least 1 more character after it
     return str.charAt(firstX+1) == 'x'; //return true if the next char is an x
  }
  return false;  //otherwise return false

}
</code>```

Title: Unexpected results when trying to match string pattern


问:
C# / WPF create new button array with multiple function
I have wrote a code with this description:
First button calls FuncPopup(); function, after that every popup dialog creates new button. New button Create FuncPopup();. Old buttons should have various behavior.

```<code>        private void FuncPopup()
    {
        FuncMenu popup = new FuncMenu();
        popup.ShowDialog();
        if (popup.DialogResult.HasValue && popup.DialogResult.Value)
        {
            i++;
            newBtn[i] = new Button();
            FuncGird.Children.Add(newBtn[i]);
            Grid.SetColumn(newBtn[i], i);
            Grid.SetRow(newBtn[i], j);
            newBtn[i].Click += (sender, e) => clicked(i);
        }
    }
    void clicked(int g) {
        if (g >= i)
        {
            FuncPopup();
        }
        else (g < i){
            OtherFunction();
        }
    }
</code>```

i is a global variable. I expect Old buttons run OtherFunction(); but they always run FuncPopup();.

答:
That's because as you said i is global variable, and you attach the following handler:

```<code> newBtn[i].Click += (sender, e) => clicked(i);
</code>```

And you increment i all the time. You might think that value of i is fixed at the moment you attach this handler but it's not so. i in clicked(i) is the same global variable, which increments with every call. So g always equals i in that handler, and so for all buttons FuncPopup is called.

Instead save i to local variable and use that:

```<code>int tmp = i;
newBtn[i].Click += (sender, e) => clicked(tmp);
</code>```

Body:
I have wrote a code with this description:
First button calls FuncPopup(); function, after that every popup dialog creates new button. New button Create FuncPopup();. Old buttons should have various behavior.

        private void FuncPopup()
    {
        FuncMenu popup = new FuncMenu();
        popup.ShowDialog();
        if (popup.DialogResult.HasValue && popup.DialogResult.Value)
        {
            i++;
            newBtn[i] = new Button();
            FuncGird.Children.Add(newBtn[i]);
            Grid.SetColumn(newBtn[i], i);
            Grid.SetRow(newBtn[i], j);
            newBtn[i].Click += (sender, e) => clicked(i);
        }
    }
    void clicked(int g) {
        if (g >= i)
        {
            FuncPopup();
        }
        else (g < i){
            OtherFunction();
        }
    }

i is a global variable. I expect Old buttons run OtherFunction(); but they always run FuncPopup();.

Body:
That's because as you said i is global variable, and you attach the following handler:

 newBtn[i].Click += (sender, e) => clicked(i);

And you increment i all the time. You might think that value of i is fixed at the moment you attach this handler but it's not so. i in clicked(i) is the same global variable, which increments with every call. So g always equals i in that handler, and so for all buttons FuncPopup is called.

Instead save i to local variable and use that:

int tmp = i;
newBtn[i].Click += (sender, e) => clicked(tmp);


问:
react-native-network-info can't catch ip on ios device
I had used it for several month, but nowadays i can't catch IP address on iPhone and just got 'error'.  I don't know why.  Do you know?

```<code>NetworkInfo.getIPAddress(ip => {
  console.log(ip);
}
</code>```

console.log => error

my react-native version: 0.37.

答:
Try upgrading to react-native 0.40.  If this isn't possible, create an issue in Github.

I'm the maintainer of react-native-network-info-- it'll be easier to debug in Github since I don't have an exact answer yet.

Body:
I had used it for several month, but nowadays i can't catch IP address on iPhone and just got 'error'.  I don't know why.  Do you know?

NetworkInfo.getIPAddress(ip => {
  console.log(ip);
}

console.log => error

my react-native version: 0.37.


问:
Which of the following is the correct way to create links for the react components?
```<code>1. <a href={‘https://www.facebook.com/’}>Link1</a>
2. <a link-to={testContainer}>Link1</a>
3. <a href={[to-component]}>Link1</a>
4. <a href-to={‘https://www.facebook.com/’}>Link1</a>
</code>```

Sorry, but I am confused which is the correct answer. Which and why?

答:
One of the options not mentioned in your question is using react-router for routing needs. This would involve creating routes which would be later used to navigate the different components. The example below shows a sample Router.

```<code>      <Router >
        <Route path="/" component={Root}>
          <Route path="home" component={Home}/>
        </Route>
      </Router>
</code>```

You can use the Link object to create dynamic links which would navigate to the appropriate component.Using the above example, this would look like

<Link to="/home">Home</Link>

Body:
1. Link1
2. Link1
3. Link1
4. Link1

Sorry, but I am confused which is the correct answer. Which and why?

Body:
One of the options not mentioned in your question is using react-router for routing needs. This would involve creating routes which would be later used to navigate the different components. The example below shows a sample Router.

      <Router >
        <Route path="/" component={Root}>
          <Route path="home" component={Home}/>
        </Route>
      </Router>

You can use the Link object to create dynamic links which would navigate to the appropriate component.Using the above example, this would look like

<Link to="/home">Home</Link>


问:
Use dplyr to take first and last row in a sequence by group
I'm trying to use dplyr to take the first and last rows of repeated values by group. I'm doing this for efficiency reasons, particularly so that graphing is faster.

This is not a duplicate of Select first and last row from grouped data because I'm not asking for the strict first and last row in a group; I'm asking for the first and last row in a group by level (in my case 1's and 0's) that may appear in multiple chunks.

Here's an example. Say I want to remove all the redundant 1's and 0's from column C while keeping A and B intact.

```<code>df = data.frame(
    A = rep(c("a", "b"), each = 10),
    B = rep(c(1:10), 2),
    C = c(1,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1))

A  B C
a  1 1
a  2 0
a  3 0
a  4 0
a  5 0
a  6 0
a  7 1
a  8 1
a  9 1
a 10 1
b  1 0
b  2 0
b  3 0
b  4 1
b  5 0
b  6 0
b  7 0
b  8 0
b  9 0
b 10 1
</code>```

The end result should look like this:

```<code>A  B C
a  1 1
a  2 0
a  6 0
a  7 1
a 10 1
b  1 0
b  3 0
b  4 1
b  5 0
b  9 0
b 10 1
</code>```

Using unique will either not remove anything or just take one of the 1's or 0's without retaining the start-and-end quality that I'm trying to achieve. Is there a way to do this without a loop, perhaps using dplyr or forcats?

答:
I think that slice should get you close:

```<code>df %>%
  group_by(A,C) %>%
  slice(c(1, n()))
</code>```

gives

```<code>      A     B     C
  <chr> <int> <dbl>
1     a     2     0
2     a     6     0
3     a     1     1
4     a    10     1
5     b     1     0
6     b     9     0
7     b     4     1
8     b    10     1
</code>```

though this doesn't quite match your expected outcome. n() gives the last row in the group.

After your edit it is clear that you are not looking for the values within any group that is established (which is what my previous version did). You want to group by those runs of 1's or 0's. For that, you will need to create a column that checks whether or not the run of 1's/0's has changed and then one to identify the groups. Then, slice will work as described before. However, because some of your runs are only 1 row long, we need to only include n() if it is more than 1 (otherwise the 1 row shows up twice).

```<code>df %>%
  mutate(groupChanged = (C != lag(C, default = C[1]))
         , toCutBy = cumsum(groupChanged)
         ) %>%
  group_by(toCutBy) %>%
  slice(c(1, ifelse(n() == 1, NA, n())))
</code>```

Gives

```<code>       A     B     C groupChanged toCutBy
   <chr> <int> <dbl>        <lgl>   <int>
1      a     1     1        FALSE       0
2      a     2     0         TRUE       1
3      a     6     0        FALSE       1
4      a     7     1         TRUE       2
5      a    10     1        FALSE       2
6      b     1     0         TRUE       3
7      b     3     0        FALSE       3
8      b     4     1         TRUE       4
9      b     5     0         TRUE       5
10     b     9     0        FALSE       5
11     b    10     1         TRUE       6
</code>```

If the runs of 1 or 0 must stay within the level in column A, you also need to add a check for a change in column A to the call. In this example, it does not have an effect (so returns exactly the same values), but it may be desirable in other instances.

```<code>df %>%
  mutate(groupChanged = (C != lag(C, default = C[1]) |
                           A != lag(A, default = A[1]))
         , toCutBy = cumsum(groupChanged)
  ) %>%
  group_by(toCutBy) %>%
  slice(c(1, ifelse(n() == 1, NA, n())))
</code>```

Body:
I'm trying to use dplyr to take the first and last rows of repeated values by group. I'm doing this for efficiency reasons, particularly so that graphing is faster.

This is not a duplicate of Select first and last row from grouped data because I'm not asking for the strict first and last row in a group; I'm asking for the first and last row in a group by level (in my case 1's and 0's) that may appear in multiple chunks.

Here's an example. Say I want to remove all the redundant 1's and 0's from column C while keeping A and B intact.

df = data.frame(
    A = rep(c("a", "b"), each = 10),
    B = rep(c(1:10), 2),
    C = c(1,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1))

A  B C
a  1 1
a  2 0
a  3 0
a  4 0
a  5 0
a  6 0
a  7 1
a  8 1
a  9 1
a 10 1
b  1 0
b  2 0
b  3 0
b  4 1
b  5 0
b  6 0
b  7 0
b  8 0
b  9 0
b 10 1

The end result should look like this:

A  B C
a  1 1
a  2 0
a  6 0
a  7 1
a 10 1
b  1 0
b  3 0
b  4 1
b  5 0
b  9 0
b 10 1

Using unique will either not remove anything or just take one of the 1's or 0's without retaining the start-and-end quality that I'm trying to achieve. Is there a way to do this without a loop, perhaps using dplyr or forcats?

Body:
I think that slice should get you close:

df %>%
  group_by(A,C) %>%
  slice(c(1, n()))

gives

      A     B     C
  <chr> <int> <dbl>
1     a     2     0
2     a     6     0
3     a     1     1
4     a    10     1
5     b     1     0
6     b     9     0
7     b     4     1
8     b    10     1

though this doesn't quite match your expected outcome. n() gives the last row in the group.

After your edit it is clear that you are not looking for the values within any group that is established (which is what my previous version did). You want to group by those runs of 1's or 0's. For that, you will need to create a column that checks whether or not the run of 1's/0's has changed and then one to identify the groups. Then, slice will work as described before. However, because some of your runs are only 1 row long, we need to only include n() if it is more than 1 (otherwise the 1 row shows up twice).

df %>%
  mutate(groupChanged = (C != lag(C, default = C[1]))
         , toCutBy = cumsum(groupChanged)
         ) %>%
  group_by(toCutBy) %>%
  slice(c(1, ifelse(n() == 1, NA, n())))

Gives

       A     B     C groupChanged toCutBy
   <chr> <int> <dbl>        <lgl>   <int>
1      a     1     1        FALSE       0
2      a     2     0         TRUE       1
3      a     6     0        FALSE       1
4      a     7     1         TRUE       2
5      a    10     1        FALSE       2
6      b     1     0         TRUE       3
7      b     3     0        FALSE       3
8      b     4     1         TRUE       4
9      b     5     0         TRUE       5
10     b     9     0        FALSE       5
11     b    10     1         TRUE       6

If the runs of 1 or 0 must stay within the level in column A, you also need to add a check for a change in column A to the call. In this example, it does not have an effect (so returns exactly the same values), but it may be desirable in other instances.

df %>%
  mutate(groupChanged = (C != lag(C, default = C[1]) |
                           A != lag(A, default = A[1]))
         , toCutBy = cumsum(groupChanged)
  ) %>%
  group_by(toCutBy) %>%
  slice(c(1, ifelse(n() == 1, NA, n())))


问:
Salt stack grains data from sqlite3 external pillar
I am trying to pull results from a sqlite3 database (set up as an external salt pillar) and use jinja templating to set grains data.

Here is the relevant section of my salt master file:

```<code>sqlite3:
    database: '/var/lib/salt/stations.db'
    timeout: 5.0

ext_pillar:
    - sqlite3:
        fromdb:
            query: 'SELECT * FROM table;'
</code>```

And here is the relevant part of the init.sls file I am using to create the grains file:

```<code>{% set station_id = salt['grains.filter_by']({
    {% for row in query_result %}
    {% hostname = station_id %}
}, default="UNKNOWN", grain="host") %}
</code>```

I confirmed that the external pillar produces results by running

```<code>salt '*' sqlite3.fetch /var/lib/salt/stations.db 'SELECT * FROM test;'
</code>```

But I can't figure out how to get results into the jinja file.

I want something like

```<code>'SELECT * FROM table WHERE hostname=station_id LIMIT 1;'
</code>```

and use the result to set the grain environmental variable called 'hostname'.

But am not sure how to get there from here.

Any help is greatly appreciated.

答:
Thanks to the good folks in Saltstack IRC this problem is solved.

Master:

```<code>- sqlite3:
    station_map:
        query: 'SELECT hostname, id
                  FROM stations
                WHERE hostname like ?'
</code>```

init.sls:

```<code>{% set station_id = salt['grains.filter_by']({
    {% for row in station_map %}
    {{ hostname }} : {{ station_id }}
}, default="UNKNOWN", grain="host") %}
</code>```

Body:
I am trying to pull results from a sqlite3 database (set up as an external salt pillar) and use jinja templating to set grains data.

Here is the relevant section of my salt master file:

sqlite3:
    database: '/var/lib/salt/stations.db'
    timeout: 5.0

ext_pillar:
    - sqlite3:
        fromdb:
            query: 'SELECT * FROM table;'

And here is the relevant part of the init.sls file I am using to create the grains file:

{% set station_id = salt['grains.filter_by']({
    {% for row in query_result %}
    {% hostname = station_id %}
}, default="UNKNOWN", grain="host") %}

I confirmed that the external pillar produces results by running

salt '*' sqlite3.fetch /var/lib/salt/stations.db 'SELECT * FROM test;'

But I can't figure out how to get results into the jinja file.

I want something like

'SELECT * FROM table WHERE hostname=station_id LIMIT 1;'

and use the result to set the grain environmental variable called 'hostname'.

But am not sure how to get there from here.

Any help is greatly appreciated.

Body:
Thanks to the good folks in Saltstack IRC this problem is solved.

Master:

- sqlite3:
    station_map:
        query: 'SELECT hostname, id
                  FROM stations
                WHERE hostname like ?'

init.sls:

{% set station_id = salt['grains.filter_by']({
    {% for row in station_map %}
    {{ hostname }} : {{ station_id }}
}, default="UNKNOWN", grain="host") %}


问:
Expressing conditional HAML possibly with ternary operator
Trying to come up with a more compact way of expressing this conditional in HAML and Ruby, perhaps with a ternary operator:

```<code>- if @page.nil?
  %br (nothing yet)
- else
  %br #{@page.name}
</code>```

(looking for similar approach as per Neat way to conditionally test whether to add a class in HAML template)

Your help would be appreciated :)

答:
You can also embed in a string
assuming - order_count = 12:

%h5= Ordered #{ order_count == 1 ? "1 item" : "#{order_count} items" } for this session

Body:
Trying to come up with a more compact way of expressing this conditional in HAML and Ruby, perhaps with a ternary operator:

- if @page.nil?
  %br (nothing yet)
- else
  %br #{@page.name}

(looking for similar approach as per Neat way to conditionally test whether to add a class in HAML template)

Your help would be appreciated :)


问:
Cannot read property 'firstname' of undefined in sqlite database
i new at ionic and i'm trying using plugin cordova sqlite. And i can't read a column.
this is my code, like in all examples, but it is'nt working.

```<code>document.addEventListener('deviceready', function () {
            db = window.sqlitePlugin.openDatabase({ name: 'demo.db', location: 'default' });
            var query = "create table if not exists people (id integer primary key,firstname text,lastname text)";
            $cordovaSQLite.execute(db, query);
            query = "insert into people values ('a','b')";
            $cordovaSQLite.execute(db, query);
            query ="select * from people;";
            $cordovaSQLite.execute(db, query).then(function(result){
                console.log("OVOLIKO :"+result.rows.item.length);
                console.log("Selected: ->" + result.rows.item(0).firstname);
            },function(error){
            });
        });
</code>```

Error: Cannot read property 'firstname' of undefined. Can anybody help please.

答:
Your issue seems to be how you are attempting to access firstname. It is attempting to execute an item function with 0 as a parameter(i.e. item(0)), as opposed to accessing the first element of the item array(i.e. item[0]).

You need to replace result.rows.item(0).firstname with result.rows.item[0].firstname and I think that will work.

Body:
i new at ionic and i'm trying using plugin cordova sqlite. And i can't read a column.
this is my code, like in all examples, but it is'nt working.

document.addEventListener('deviceready', function () {
            db = window.sqlitePlugin.openDatabase({ name: 'demo.db', location: 'default' });
            var query = "create table if not exists people (id integer primary key,firstname text,lastname text)";
            $cordovaSQLite.execute(db, query);
            query = "insert into people values ('a','b')";
            $cordovaSQLite.execute(db, query);
            query ="select * from people;";
            $cordovaSQLite.execute(db, query).then(function(result){
                console.log("OVOLIKO :"+result.rows.item.length);
                console.log("Selected: ->" + result.rows.item(0).firstname);
            },function(error){
            });
        });

Error: Cannot read property 'firstname' of undefined. Can anybody help please.


问:
microsoft azure clearing cookies after application terminated
I have implemented microsoft azure sdk for authentication in our app. All done well.

But when user logged out I used this code

```<code>    NSError *error;
    [[ADKeychainTokenCache defaultKeychainCache] removeAllForClientId:[[NSUserDefaults standardUserDefaults] valueForKey:@"azureClientId"] error:&error];
</code>```

So if user stays on active and again if he would logs in then microsoft azure is able to get user info without entering credentials again.

but when app terminates and open again, asking for password.

I dont want to ask credentials again.

Is there any problem with my logout code?

答: You can't generally log out of a social provider - the functionality does not exist.  Explicitly, the auth information is stored in the UIWebView, generally as a cookie.  This is then passed onto the auth provider next time and the auth provider uses this information to silently authenticate you.</p>

Body:
I have implemented microsoft azure sdk for authentication in our app. All done well.

But when user logged out I used this code

    NSError *error;
    [[ADKeychainTokenCache defaultKeychainCache] removeAllForClientId:[[NSUserDefaults standardUserDefaults] valueForKey:@"azureClientId"] error:&error];

So if user stays on active and again if he would logs in then microsoft azure is able to get user info without entering credentials again.

but when app terminates and open again, asking for password.

I dont want to ask credentials again.

Is there any problem with my logout code?


问:
Grails - Spring Security Plugin - User has 'ROLE_NO_ROLES' after adding 'ROLE_ADMIN'
I am developing a web app using Grails, and I am trying to use the Admin Interface Plugin. For testing purposes, I created an admin user from BootStrap.groovy using the following lines of code:

```<code>def init = { servletContext ->
    def adminUser = User.findByUsername("episo_admin_root")
        if(!adminUser){
            print "Creating admin user... "
            adminUser = new User(username: username, emailAddress: emailAddress, password: password, birthDate: new Date(1, 1, 1),
                    sex: Sex.AGENDER, enabled: true, accountConfirmed: true, accountCreationDate: new Date())
            adminUser.save(flush: true, failOnError: true)
            def auth = adminUser.addAuthority(Roles.ROLE_ADMIN)
            auth.save(flush: true, failOnError: true)
        }
}
</code>```

I also added the following statement to check whether or not the user was getting the role:

if(adminUser.authorities.any { it.authority == Roles.ROLE_ADMIN }) println "Admin role added."

This check passes, and "Admin role added." is printed to the console.
Here is my configuration for Spring Security:

```<code>grails.plugin.springsecurity.rejectIfNoRule = true
grails.plugin.springsecurity.fii.rejectPublicInvocations = false
grails.plugin.springsecurity.interceptUrlMap = [
                '/':                      ['permitAll'],
                '/home':                  ['permitAll'],
                '/home.gsp':              ['permitAll'],
                '/assets/**':             ['permitAll'],
                ...
                ...
                '/**/js/**':              ['permitAll'],
                '/**/css/**':             ['permitAll'],
                '/**/images/**':          ['permitAll'],
                '/**/favicon.ico':        ['permitAll'],
                '/admin/**':              ['ROLE_ADMIN']
        ]
</code>```

And here is my configuration for the Admin Interface Plugin:

```<code>grails.plugin.admin.accessRoot = "/admin"
grails.plugin.admin.domains."Users" = [ "mypackage.User" ]
grails.plugin.admin.domains."My Groups" = [ "mypackage.Group" ]
grails.plugin.admin.domains."Security Groups" = [ 'mypackage.Authority', 'mypackage.UserAuthority' ]
grails.plugin.springsecurity.active = true
grails.plugin.springsecurity.useBasicAuth = true
grails.plugin.admin.security.role = "ROLE_ADMIN"
</code>```

However, when I login as the new admin user and navigate to "/admin", I get the Apache Tomcat "HTTP Status 403 - Access is Denied" page, and the following debug info is logged to the console:

```<code>Secure object: FilterInvocation: URL: /admin; Attributes: [ROLE_ADMIN]
Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@5ff53bc5: Principal: grails.plugin.springsecurity.userdetails.GrailsUser@d7469d37: Username: [PROTECTED]; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_NO_ROLES; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: [PROTECTED]; SessionId: null; Granted Authorities: ROLE_NO_ROLES
</code>```

If you scroll sideways on that debug info, you will see that Spring Security sees "Granted Authorities" to be ROLE_NO_ROLES.

Am I doing something wrong when adding the role to the user? Why won't Spring Security see that I have granted this user ROLE_ADMIN?

I've spent hours trying to debug this and I can't understand what is wrong with my code.

答:
I figured it out; I removed the following line from the config file which fixed my problem:</p>

```<code>grails.plugin.springsecurity.useRoleGroups = true
</code>```

Body:
I am developing a web app using Grails, and I am trying to use the Admin Interface Plugin. For testing purposes, I created an admin user from BootStrap.groovy using the following lines of code:

def init = { servletContext ->
    def adminUser = User.findByUsername("episo_admin_root")
        if(!adminUser){
            print "Creating admin user... "
            adminUser = new User(username: username, emailAddress: emailAddress, password: password, birthDate: new Date(1, 1, 1),
                    sex: Sex.AGENDER, enabled: true, accountConfirmed: true, accountCreationDate: new Date())
            adminUser.save(flush: true, failOnError: true)
            def auth = adminUser.addAuthority(Roles.ROLE_ADMIN)
            auth.save(flush: true, failOnError: true)
        }
}

I also added the following statement to check whether or not the user was getting the role:

if(adminUser.authorities.any { it.authority == Roles.ROLE_ADMIN }) println "Admin role added."

This check passes, and "Admin role added." is printed to the console.
Here is my configuration for Spring Security:

grails.plugin.springsecurity.rejectIfNoRule = true
grails.plugin.springsecurity.fii.rejectPublicInvocations = false
grails.plugin.springsecurity.interceptUrlMap = [
                '/':                      ['permitAll'],
                '/home':                  ['permitAll'],
                '/home.gsp':              ['permitAll'],
                '/assets/**':             ['permitAll'],
                ...
                ...
                '/**/js/**':              ['permitAll'],
                '/**/css/**':             ['permitAll'],
                '/**/images/**':          ['permitAll'],
                '/**/favicon.ico':        ['permitAll'],
                '/admin/**':              ['ROLE_ADMIN']
        ]

And here is my configuration for the Admin Interface Plugin:

grails.plugin.admin.accessRoot = "/admin"
grails.plugin.admin.domains."Users" = [ "mypackage.User" ]
grails.plugin.admin.domains."My Groups" = [ "mypackage.Group" ]
grails.plugin.admin.domains."Security Groups" = [ 'mypackage.Authority', 'mypackage.UserAuthority' ]
grails.plugin.springsecurity.active = true
grails.plugin.springsecurity.useBasicAuth = true
grails.plugin.admin.security.role = "ROLE_ADMIN"

However, when I login as the new admin user and navigate to "/admin", I get the Apache Tomcat "HTTP Status 403 - Access is Denied" page, and the following debug info is logged to the console:

Secure object: FilterInvocation: URL: /admin; Attributes: [ROLE_ADMIN]
Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@5ff53bc5: Principal: grails.plugin.springsecurity.userdetails.GrailsUser@d7469d37: Username: [PROTECTED]; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_NO_ROLES; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: [PROTECTED]; SessionId: null; Granted Authorities: ROLE_NO_ROLES

If you scroll sideways on that debug info, you will see that Spring Security sees "Granted Authorities" to be ROLE_NO_ROLES.

Am I doing something wrong when adding the role to the user? Why won't Spring Security see that I have granted this user ROLE_ADMIN?

I've spent hours trying to debug this and I can't understand what is wrong with my code.

Body:
I figured it out; I removed the following line from the config file which fixed my problem:

grails.plugin.springsecurity.useRoleGroups = true


问:
Integrating Facebook and Twitter in Xcode Scenes Swift iOS
I have developed a game in Xcode using sprite kit, and scenes. Now I am trying to integrate the functionality to post high scores to twitter and Facebook. I've looked around, and most people say to use SLComposeServiceViewController which is fine, until I try and present it. Because my app really only uses scenes, they never have the member function "presentViewController(....)". Thus, I am unable to ever present it. Anyone know any way around this?</p>

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch:UITouch = touches.first!
    let touchLocation = touch.location(in: self)
    let touchedNode = self.atPoint(touchLocation)

    if (touchedNode.name == "tryAgain") {
        let nextScene = Scene_LiveGame(size: self.scene!.size)
        nextScene.scaleMode = self.scaleMode
        self.view?.presentScene(nextScene, transition: SKTransition.fade(withDuration: 0.5))
    }
    else if (touchedNode.name == "share") {

        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {

        let fShare = SLComposeViewController(forServiceType: SLServiceTypeFacebook)

        self.presentViewController(fShare!, animated: true, completion: nil)
         //^This is where my problem is. Xcode is telling me that self has no member function presentViewController which I totally understand, because its a scene and thus doesn't share those functions. But every resource online has shown me this is the only way to do it

        }

    }
</code>```

答:
As I said, this can be done using notifications, like in this answer, or you can go with delegation:

First you should declare the MyDelegate protocol which defines one method called myMethod().

```<code> protocol MyDelegate:class {

        func myMethod()
    }
</code>```

That method is a requirement that every class must implement if it conforms to this protocl.

In our example, you can look at the scene as a worker, and a view controller as a boss. When the scene finishes its task, it notifies its boss (delegates responsibilities to him) about job completion, so that boss can decide what is next. I mean, I could say : "The scene is a boss, and it delegates responsibilities to his employee, the view controller..." But it doesn't really matter who you consider as a boss... The delegation pattern matters.

So, the view controller, should conform to this protocol, and it will implement the myMethod() (that will be called by the scene later):

```<code>class GameViewController: UIViewController, MyDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    //MARK: Conforming to MyDelegate protocol

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        if let scene = GameScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            scene.myDelegate = self

            // Present the scene
            view.presentScene(scene)
        }
    }
   }

func myMethod(){
    print("Do your stuff here")
}

 }
</code>```

And here is a code from the GameScene where you define the myDelegate property that we use to communicate with our view controller:

```<code>import SpriteKit

class GameScene: SKScene {

   weak var myDelegate:MyDelegate?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    self.myDelegate?.myMethod()

    }
}
</code>```

To find out when to choose delegation over notifications and vice-versa take a look at this article (or just search SO, there are some nice posts about that).

Body:
I have developed a game in Xcode using sprite kit, and scenes. Now I am trying to integrate the functionality to post high scores to twitter and Facebook. I've looked around, and most people say to use SLComposeServiceViewController which is fine, until I try and present it. Because my app really only uses scenes, they never have the member function "presentViewController(....)". Thus, I am unable to ever present it. Anyone know any way around this?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch:UITouch = touches.first!
    let touchLocation = touch.location(in: self)
    let touchedNode = self.atPoint(touchLocation)

    if (touchedNode.name == "tryAgain") {
        let nextScene = Scene_LiveGame(size: self.scene!.size)
        nextScene.scaleMode = self.scaleMode
        self.view?.presentScene(nextScene, transition: SKTransition.fade(withDuration: 0.5))
    }
    else if (touchedNode.name == "share") {

        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {

        let fShare = SLComposeViewController(forServiceType: SLServiceTypeFacebook)

        self.presentViewController(fShare!, animated: true, completion: nil)
         //^This is where my problem is. Xcode is telling me that self has no member function presentViewController which I totally understand, because its a scene and thus doesn't share those functions. But every resource online has shown me this is the only way to do it

        }

    }

Body:
As I said, this can be done using notifications, like in this answer, or you can go with delegation:

First you should declare the MyDelegate protocol which defines one method called myMethod().

 protocol MyDelegate:class {

        func myMethod()
    }

That method is a requirement that every class must implement if it conforms to this protocl.

In our example, you can look at the scene as a worker, and a view controller as a boss. When the scene finishes its task, it notifies its boss (delegates responsibilities to him) about job completion, so that boss can decide what is next. I mean, I could say : "The scene is a boss, and it delegates responsibilities to his employee, the view controller..." But it doesn't really matter who you consider as a boss... The delegation pattern matters.

So, the view controller, should conform to this protocol, and it will implement the myMethod() (that will be called by the scene later):

class GameViewController: UIViewController, MyDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    //MARK: Conforming to MyDelegate protocol

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        if let scene = GameScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            scene.myDelegate = self

            // Present the scene
            view.presentScene(scene)
        }
    }
   }

func myMethod(){
    print("Do your stuff here")
}

 }

And here is a code from the GameScene where you define the myDelegate property that we use to communicate with our view controller:

import SpriteKit

class GameScene: SKScene {

   weak var myDelegate:MyDelegate?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    self.myDelegate?.myMethod()

    }
}

To find out when to choose delegation over notifications and vice-versa take a look at this article (or just search SO, there are some nice posts about that).


问:
Mobile live geolocation
Im trying to get my Iphones live location to show on a map on my website.

Is there a way to acomplish this easily using HTML5 Geolocation or is it better to use  Google Maps Geolocation API, or some other library?

Thanks.

答:
I use Google Maps Geolocation API in WEB APP developed with .NET C #

And it was great

Title: Mobile live geolocation


问:
C# folders and sub folders
How to do this:

Check if folder upload exists (if nor then create it) ~/ uploads

Check if subfolder with username exists ~/uploads/folder with username

It as to check for each case individually because I could add a new user to the system and of course the folder uploads alredy exists, just need to create a sub folder with username

答:
You could try this :

```<code>using System;
using System.IO;

   public void CreateDirectories(string uploadDirPath, string userName)
   {
     string userDirPath= uploadDirPath + "\\" + userName ;

     if (!Directory.Exists(uploadDirPath))
     {
       Directory.CreateDirectory(uploadDirPath);

       if (!Directory.Exists(userDirPath))
           Directory.CreateDirectory (userDirPath);
     }
   }
</code>```

I leave it to you to wrap this up by calling the method in loops according to you specific logic and paramaterizing user names and folders

Title: C# folders and sub folders

Body:
You could try this :

using System;
using System.IO;

   public void CreateDirectories(string uploadDirPath, string userName)
   {
     string userDirPath= uploadDirPath + "\\" + userName ;

     if (!Directory.Exists(uploadDirPath))
     {
       Directory.CreateDirectory(uploadDirPath);

       if (!Directory.Exists(userDirPath))
           Directory.CreateDirectory (userDirPath);
     }
   }

I leave it to you to wrap this up by calling the method in loops according to you specific logic and paramaterizing user names and folders


问:
Set custom date in Bootstrap Date Range Picker
I want to set custom date in Bootstrap Date Range Picker as default like this format below:

Format: [today-7] - [today]

So the first one will show the date 7 days ago from the current date as default and second one will show current date as default.

Here is the source file link of my work: http://securesofts.com/masum.zip

Here is the screenshot where I want it: Date Range Picker
Thanks in Advance.

答:
try something like this:</p>

```<code>$('input').daterangepicker(
  {
    locale: {
      format: 'YYYY-MM-DD'
    },
    startDate: new Date(new Date().getTime() - (60*60*24*7*1000)),
    endDate: new Date
  }
)
</code>```

Body:
try something like this:

$('input').daterangepicker(
  {
    locale: {
      format: 'YYYY-MM-DD'
    },
    startDate: new Date(new Date().getTime() - (60*60*24*7*1000)),
    endDate: new Date
  }
)


问:
mod_wgi installation failed with python3
trying to install mod_wsgi for django1.9 (python version 3.5 ) . But getting below error</p>

```<code>gcc -pthread -shared build/temp.linux-x86_64-3.5/src/server/wsgi_validate.o build/temp.linux-x86_64-3.5/src/server/wsgi_thread.o build/temp.linux-x86_64-3.5/src/server/wsgi_stream.o build/temp.linux-x86_64-3.5/src/server/wsgi_server.o build/temp.linux-x86_64-3.5/src/server/wsgi_restrict.o build/temp.linux-x86_64-3.5/src/server/wsgi_metrics.o build/temp.linux-x86_64-3.5/src/server/wsgi_memory.o build/temp.linux-x86_64-3.5/src/server/wsgi_logger.o build/temp.linux-x86_64-3.5/src/server/wsgi_interp.o build/temp.linux-x86_64-3.5/src/server/wsgi_daemon.o build/temp.linux-x86_64-3.5/src/server/wsgi_convert.o build/temp.linux-x86_64-3.5/src/server/wsgi_buckets.o build/temp.linux-x86_64-3.5/src/server/wsgi_apache.o build/temp.linux-x86_64-3.5/src/server/mod_wsgi.o -o build/lib.linux-x86_64-3.5/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so -L/home/webdev01/python3/lib -L/home/webdev01/python3/lib/python3.5/config-3.5m -lpython3.5m
    /usr/bin/ld: /home/webdev01/python3/lib/libpython3.5m.a(abstract.o): relocation R_X86_64_32S against `_Py_NotImplementedStruct' can not be used when making a shared object; recompile with -fPIC
    /home/webdev01/python3/lib/libpython3.5m.a: could not read symbols: Bad value
    collect2: error: ld returned 1 exit status
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/web0/home/webdev01/pythonenv3/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-6atgj_5e-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-bcnhqmnp-record/install-record.txt --single-version-externally-managed --compile --install-headers /web0/home/webdev01/pythonenv3/include/site/python3.5/mod-wsgi" failed with error code 1 in /tmp/pip-6atgj_5e-build/
</code>```

答:
Variation of:

http://modwsgi.readthedocs.io/en/develop/user-guides/installation-issues.html#mixing-32-bit-and-64-bit-packages

You need to install Python with a shared library.

Body:
trying to install mod_wsgi for django1.9 (python version 3.5 ) . But getting below error

gcc -pthread -shared build/temp.linux-x86_64-3.5/src/server/wsgi_validate.o build/temp.linux-x86_64-3.5/src/server/wsgi_thread.o build/temp.linux-x86_64-3.5/src/server/wsgi_stream.o build/temp.linux-x86_64-3.5/src/server/wsgi_server.o build/temp.linux-x86_64-3.5/src/server/wsgi_restrict.o build/temp.linux-x86_64-3.5/src/server/wsgi_metrics.o build/temp.linux-x86_64-3.5/src/server/wsgi_memory.o build/temp.linux-x86_64-3.5/src/server/wsgi_logger.o build/temp.linux-x86_64-3.5/src/server/wsgi_interp.o build/temp.linux-x86_64-3.5/src/server/wsgi_daemon.o build/temp.linux-x86_64-3.5/src/server/wsgi_convert.o build/temp.linux-x86_64-3.5/src/server/wsgi_buckets.o build/temp.linux-x86_64-3.5/src/server/wsgi_apache.o build/temp.linux-x86_64-3.5/src/server/mod_wsgi.o -o build/lib.linux-x86_64-3.5/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so -L/home/webdev01/python3/lib -L/home/webdev01/python3/lib/python3.5/config-3.5m -lpython3.5m
    /usr/bin/ld: /home/webdev01/python3/lib/libpython3.5m.a(abstract.o): relocation R_X86_64_32S against `_Py_NotImplementedStruct' can not be used when making a shared object; recompile with -fPIC
    /home/webdev01/python3/lib/libpython3.5m.a: could not read symbols: Bad value
    collect2: error: ld returned 1 exit status
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/web0/home/webdev01/pythonenv3/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-6atgj_5e-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-bcnhqmnp-record/install-record.txt --single-version-externally-managed --compile --install-headers /web0/home/webdev01/pythonenv3/include/site/python3.5/mod-wsgi" failed with error code 1 in /tmp/pip-6atgj_5e-build/


问:
Web Api OWIN Host with Unity
I'm trying to implement UNITY on my WebApi2 application.
The problem is that I'm using an existing SqlConnection, depending on an identifier found in the URL of the resource.
So I need the identifier provided in the request uri, to create my context with.
Is it possible to get the {dbIdentifier} from the request URI, and parse it into the constructor of MyRepo?

The Request usi will look like: /api/{dbIdentifier}/{controller}/{id}

The structure looks like...

```<code>Request POST /api/myDbIdentifier/my/ + PAYLOAD data

Controller:
public class MyController : ApiController
{
    private readonly IRepo _repo;

    public MyController(IRepo repo)
    {
        _repo = repo;
    }
}

Repo:
public class MyRepo : IRepo
{
    private readonly MyContext _context;

    public  MyRepo(string dbIdentifier)
    {
        _context = new MyContext(GetConnection(dbIdentifier));
    }

    public void Insert(string s)
    {
        //Inserting string in context and save changes
    }

    private DbConnection(string id)
    {
        //psudo find connecion from pool, and return instance of DbConnection...
    }
}

public interface IRepo
{
    void Insert(string s);
}

Context:
public class MyContext : DbContext
{
    public MyContext(DbConnection exitingConnection) : base(existingConnection, true)
    { }
}
</code>```

Btw, it's my first time playing around with WebApi and Unity, so please bear with my ignorance.

UPDATED Unity part of my code...

UnityResolver (taken from https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection):

```<code>public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer Container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException(nameof(container), "Please provider an IUnityContainer.");
        }
        Container = container;
    }

    public void Dispose()
    {
        Container.Dispose();
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return Container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return Container.ResolveAll(serviceType);
        }
        catch (Exception)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        return new UnityResolver(Container.CreateChildContainer());
    }
}
</code>```

Unity Register part in my startup:

```<code>public static void Register(HttpConfiguration config)
{
    // Configuring DI Container fo IoC (Invert of Control)
    var container = new UnityContainer();
    container.RegisterType<IRepo, MyRepo>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);
}
</code>```

答:
You can try the following:

1)Create a DelegatingHandler where you can access HtppRequestMessage.RequestUri

2)Extract dbIdentifier from Uri

3)Wrap dbIdentifier with a class (e.g. DbIdentifier) and register it in unity using HierarchicalLifetimeManager

4)Remember to register handler in owin:

```<code>httpConfiguration.MessageHandlers.Add(new DbIdentifierHandler());
</code>```

EDIT.
You can look into this post to find some inspiration :
How to pass Owin context to a Repo being injected into Api controller

Title: Web Api OWIN Host with Unity

Body:
I'm trying to implement UNITY on my WebApi2 application.
The problem is that I'm using an existing SqlConnection, depending on an identifier found in the URL of the resource.
So I need the identifier provided in the request uri, to create my context with.
Is it possible to get the {dbIdentifier} from the request URI, and parse it into the constructor of MyRepo?

The Request usi will look like: /api/{dbIdentifier}/{controller}/{id}

The structure looks like...

Request POST /api/myDbIdentifier/my/ + PAYLOAD data

Controller:
public class MyController : ApiController
{
    private readonly IRepo _repo;

    public MyController(IRepo repo)
    {
        _repo = repo;
    }
}

Repo:
public class MyRepo : IRepo
{
    private readonly MyContext _context;

    public  MyRepo(string dbIdentifier)
    {
        _context = new MyContext(GetConnection(dbIdentifier));
    }

    public void Insert(string s)
    {
        //Inserting string in context and save changes
    }

    private DbConnection(string id)
    {
        //psudo find connecion from pool, and return instance of DbConnection...
    }
}

public interface IRepo
{
    void Insert(string s);
}

Context:
public class MyContext : DbContext
{
    public MyContext(DbConnection exitingConnection) : base(existingConnection, true)
    { }
}

Btw, it's my first time playing around with WebApi and Unity, so please bear with my ignorance.

UPDATED Unity part of my code...

UnityResolver (taken from https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection):

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer Container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException(nameof(container), "Please provider an IUnityContainer.");
        }
        Container = container;
    }

    public void Dispose()
    {
        Container.Dispose();
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return Container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return Container.ResolveAll(serviceType);
        }
        catch (Exception)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        return new UnityResolver(Container.CreateChildContainer());
    }
}

Unity Register part in my startup:

public static void Register(HttpConfiguration config)
{
    // Configuring DI Container fo IoC (Invert of Control)
    var container = new UnityContainer();
    container.RegisterType<IRepo, MyRepo>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);
}

Body:
You can try the following:

1)Create a DelegatingHandler where you can access HtppRequestMessage.RequestUri

2)Extract dbIdentifier from Uri

3)Wrap dbIdentifier with a class (e.g. DbIdentifier) and register it in unity using HierarchicalLifetimeManager

4)Remember to register handler in owin:

httpConfiguration.MessageHandlers.Add(new DbIdentifierHandler());

EDIT.
You can look into this post to find some inspiration :
How to pass Owin context to a Repo being injected into Api controller


问:
How to configure on-behalf-of authentication in multi-tenant environment?
I have a native client that calls a service I wrote-- that in turn calls the Graph API (using the original caller's credentials).

This is exactly like the 'onbehalfof' sample found here (my code fails the same way as the sample):

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

When logging in as a user from the same tenant as the service (tenant A), everything works fine (just like the onbehalf of sample).  When logging in as a user from a different tenant (tenant B), I get an exception on this line in the service:

```<code>result = await authContext.AcquireTokenAsync(GraphResourceId, clientCred, userAssertion);
</code>```

(this is line 153 from TodoListController.cs in the onbehalfof sample).

The exception is this:

AADSTS65001: The user or administrator has not consented to use the
  application with ID 'de2fb28b-83f8-419d-9b00-3fbce0a60bf4'. Send an
  interactive authorization request for this user and resource.\r\nTrace
  ID: 6865c420-674a-4adf-a070-3d9b9c500200\r\nCorrelation ID:
  7e088563-d7fe-4131-a05c-cbe04dbb2bbd\r\nTimestamp: 2017-03-29
  22:56:58Z

The application id above refers to the service I wrote (which is the same line in the TodoListService in the onbehalfofsample).

I configured everything for multi-tenant authentication. But it's the additional call that my service is making to another service (Graph API) that's causing the problem.  What additional configuration do I need to do in the Azure portal to make this work?

答:
Here's the consent dialog that appears when a user from another tenant logs in:

Consent Dialog

Body:
I have a native client that calls a service I wrote-- that in turn calls the Graph API (using the original caller's credentials).

This is exactly like the 'onbehalfof' sample found here (my code fails the same way as the sample):

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

When logging in as a user from the same tenant as the service (tenant A), everything works fine (just like the onbehalf of sample).  When logging in as a user from a different tenant (tenant B), I get an exception on this line in the service:

result = await authContext.AcquireTokenAsync(GraphResourceId, clientCred, userAssertion);

(this is line 153 from TodoListController.cs in the onbehalfof sample).

The exception is this:

AADSTS65001: The user or administrator has not consented to use the
  application with ID 'de2fb28b-83f8-419d-9b00-3fbce0a60bf4'. Send an
  interactive authorization request for this user and resource.\r\nTrace
  ID: 6865c420-674a-4adf-a070-3d9b9c500200\r\nCorrelation ID:
  7e088563-d7fe-4131-a05c-cbe04dbb2bbd\r\nTimestamp: 2017-03-29
  22:56:58Z

The application id above refers to the service I wrote (which is the same line in the TodoListService in the onbehalfofsample).

I configured everything for multi-tenant authentication. But it's the additional call that my service is making to another service (Graph API) that's causing the problem.  What additional configuration do I need to do in the Azure portal to make this work?


问:
Creating a non-tracking in-app web browser
I am trying to create a webview (as an exercise) that does not track or store any browsing history locally.

I have made it so that when the webview is closed, it calls the following

```<code>[[NSURLSession sharedSession]resetWithCompletionHandler:^{}];
</code>```

but I am finding that things like google search history persists some how between sessions. I have also tried clearing cookies separately through

```<code>NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies]) {
       [storage deleteCookie:cookie];
    }
[[NSUserDefaults standardUserDefaults] synchronize];
</code>```

still to no avail. Google searches still show when a new web view is created.

Is anyone aware of a way to remove the identifier that google is using to match that search history back to me? I'm concerned it's something like the bundle identifier, which is probably a bit trickier to prevent being read.

Any ideas are appreciated.

Regards,

Luke

答:
Try setting nonPersistentDataStore for WKWebsiteDataStore of WKWebViewConfiguration

Here is a sample code snippet

```<code>let webVuConfiguration = WKWebViewConfiguration()
webVuConfiguration.websiteDataStore =WKWebsiteDataStore.nonPersistentDataStore()
let webView = WKWebView(frame: webviewRect, configuration: webVuConfiguration)
</code>```

Body:
I am trying to create a webview (as an exercise) that does not track or store any browsing history locally.

I have made it so that when the webview is closed, it calls the following

[[NSURLSession sharedSession]resetWithCompletionHandler:^{}];

but I am finding that things like google search history persists some how between sessions. I have also tried clearing cookies separately through

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies]) {
       [storage deleteCookie:cookie];
    }
[[NSUserDefaults standardUserDefaults] synchronize];

still to no avail. Google searches still show when a new web view is created.

Is anyone aware of a way to remove the identifier that google is using to match that search history back to me? I'm concerned it's something like the bundle identifier, which is probably a bit trickier to prevent being read.

Any ideas are appreciated.

Regards,

Luke

Body:
Try setting nonPersistentDataStore for WKWebsiteDataStore of WKWebViewConfiguration

Here is a sample code snippet

let webVuConfiguration = WKWebViewConfiguration()
webVuConfiguration.websiteDataStore =WKWebsiteDataStore.nonPersistentDataStore()
let webView = WKWebView(frame: webviewRect, configuration: webVuConfiguration)