问:
Something is deleting a console app. Why is it being deleted?
I need to learn how to use SMO within a C# program, so the first thing I did was start a new, console app and then began putting in the basics. I decided to make the app accept parameters so I can pass in things like usernames, logins, etc. As I work on it and build it I have a PowerShell window open where I can call the app, give it parameters or not, etc. But something weird is happening which I don't understand. Sometimes when I run the app in the PowerShell window, it's then deleted for some reason. Why is it doing that? I discovered it when it first gave me the following error message:

Program 'SmoListLogins.exe' failed to run: The system cannot find the file specifiedAt line:1 char:1 + .\SmoListLogins.exe "MYCOMPANY\Rod"

My SmoListLogins.exe program isn't there. Naturally I can easily re-create it, but I don't understand why its being deleted.

So you can see what I'm working with, here's the source code. I took it from a MSDN article and have added a little bit:

```<code>using System;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
namespace SmoListLogins
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                var userName = args[0];
                ListLogins(userName);
            }
            else
            {
                ListLogins();
            }
        }
        static private void ListLogins(string userName = "")
        {
            var userNamePassed = (userName != "");
            Server srv = new Server("YOURSQLINSTANCE");
            //Iterate through each database and display.
            foreach (Database db in srv.Databases)
            {
                Console.WriteLine("========");
                Console.WriteLine("Login Mappings for the database: " + db.Name);
                Console.WriteLine(" ");
                //Run the EnumLoginMappings method and return details of database user-login mappings to a DataTable object variable.
                DataTable d;
                try
                {
                    d = db.EnumLoginMappings();
                    //Display the mapping information.
                    foreach (DataRow r in d.Rows)
                    {
                        var userNameMatches = false;
                        var starting = true;
                        foreach (DataColumn c in r.Table.Columns)
                        {
                            if (!userNamePassed)
                            {
                                Console.WriteLine(c.ColumnName + " = " + r[c]);
                            }
                            else
                            {
                                if (starting)
                                {
                                    starting = false;
                                    if (userName == r[c].ToString())
                                    {
                                        userNameMatches = true;
                                    }
                                }
                                if (userNameMatches)
                                {
                                    Console.WriteLine(c.ColumnName + " = " + r[c]);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error processing database: {db.Name}");
                    Console.WriteLine($"Error: {ex.Message}");
                    Console.WriteLine();
                }
            }
        }
    }
}
</code>```

答:
I believe I now know what was deleting my executable. It wasn't something I thought of, so I'm sharing with everyone the answer. Today I got an email from our chief security officer, informing me that the program I wrote was being blocked by Symantec Endpoint Protection. In my testing I'd run my app over and over again. After a few iterations of that it would disappear. It didn't occur to me that it was our corporate AV that might be doing it. Now it looks as though that is exactly what was going on.

Thank you everyone for your input in trying to help me resolve this. I hope that if anyone else encounters this problem they might consider the possibility of their AV as the reason why the app they wrote disappears.

Body:
I need to learn how to use SMO within a C# program, so the first thing I did was start a new, console app and then began putting in the basics. I decided to make the app accept parameters so I can pass in things like usernames, logins, etc. As I work on it and build it I have a PowerShell window open where I can call the app, give it parameters or not, etc. But something weird is happening which I don't understand. Sometimes when I run the app in the PowerShell window, it's then deleted for some reason. Why is it doing that? I discovered it when it first gave me the following error message:

Program 'SmoListLogins.exe' failed to run: The system cannot find the file specifiedAt line:1 char:1 + .\SmoListLogins.exe "MYCOMPANY\Rod"

My SmoListLogins.exe program isn't there. Naturally I can easily re-create it, but I don't understand why its being deleted.

So you can see what I'm working with, here's the source code. I took it from a MSDN article and have added a little bit:

using System;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
namespace SmoListLogins
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                var userName = args[0];
                ListLogins(userName);
            }
            else
            {
                ListLogins();
            }
        }
        static private void ListLogins(string userName = "")
        {
            var userNamePassed = (userName != "");
            Server srv = new Server("YOURSQLINSTANCE");
            //Iterate through each database and display.
            foreach (Database db in srv.Databases)
            {
                Console.WriteLine("========");
                Console.WriteLine("Login Mappings for the database: " + db.Name);
                Console.WriteLine(" ");
                //Run the EnumLoginMappings method and return details of database user-login mappings to a DataTable object variable.
                DataTable d;
                try
                {
                    d = db.EnumLoginMappings();
                    //Display the mapping information.
                    foreach (DataRow r in d.Rows)
                    {
                        var userNameMatches = false;
                        var starting = true;
                        foreach (DataColumn c in r.Table.Columns)
                        {
                            if (!userNamePassed)
                            {
                                Console.WriteLine(c.ColumnName + " = " + r[c]);
                            }
                            else
                            {
                                if (starting)
                                {
                                    starting = false;
                                    if (userName == r[c].ToString())
                                    {
                                        userNameMatches = true;
                                    }
                                }
                                if (userNameMatches)
                                {
                                    Console.WriteLine(c.ColumnName + " = " + r[c]);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error processing database: {db.Name}");
                    Console.WriteLine($"Error: {ex.Message}");
                    Console.WriteLine();
                }
            }
        }
    }
}


来源: stackexchange

问:
NoReverseMatch in Django; views and urls are properly defined
I am currently working on a website and I am receiving an error that is driving me up a wall. I have the following url defined in urls.py.

```<code>urlpatterns = [
    url(r'^', views.homeFeed, name='home'),
    url(r'^posts/(?P<uid>[\w+])$', views.discussPostView, name='post')
    ]
</code>```

I then have the following code defining views.discussPostView.

```<code>def discussPostView(request, **kwargs):
    if request.method == 'GET':
        print(kwargs['uid'])
        post = get_object_or_404(DiscussPost, uid=kwargs['uid'])
        return render(request, 'discuss/post.html', {"post": post})
    if request.method == 'POST':
        reply = DiscussReply.objects.create(
            by=request.user,
            content=request.POST['reply'])
        reply.save()
        reply_to = DiscussPost.objects.get(pk=request.POST['post_id'])
        reply_to.replies.add(reply)
        reply_to.save()
        return HttpResponseRedirect(request.get_full_path())
</code>```

However, when I try to create a post on the site or access a post with a certain uid, I receive this error;

```<code>Reverse for 'post' with arguments '()'
and keyword arguments '{u'uid': u'CHacFvE_'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w+])$']
</code>```

I literally have no idea what's wrong with my code. I am a bit rusty on python so I might be missing some obvious pointers, but any pointers in the right direction would be helpful. Thank you!

Full error stack:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/ubuntu/workspace/discuss/views.py", line 15, in homeFeed
    "feeds": [DiscussPost.getFeed(request), DiscussPost.getNewPosts()]})
  File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py", line 67, in render
    template_name, context, request=request, using=using)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 97, in render_to_string
    return template.render(context, request)
  File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py", line 95, in render
    return self.template.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 206, in render
    return self._render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 197, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 173, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 197, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 69, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 326, in render
    return nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 220, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 220, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 513, in render
    six.reraise(*exc_info)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 499, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 600, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 508, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns))
NoReverseMatch: Reverse for 'post' with arguments '()' and keyword arguments '{u'uid': u'-lTmOw__'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w]+)$']
</code>```

答:
Your pattern is wrong, try this:</p>

```<code>'^posts/(?P<uid>\w+)$'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently working on a website and I am receiving an error that is driving me up a wall. I have the following url defined in urls.py.

urlpatterns = [
    url(r'^', views.homeFeed, name='home'),
    url(r'^posts/(?P<uid>[\w+])$', views.discussPostView, name='post')
    ]

I then have the following code defining views.discussPostView.

def discussPostView(request, **kwargs):
    if request.method == 'GET':
        print(kwargs['uid'])
        post = get_object_or_404(DiscussPost, uid=kwargs['uid'])
        return render(request, 'discuss/post.html', {"post": post})
    if request.method == 'POST':
        reply = DiscussReply.objects.create(
            by=request.user,
            content=request.POST['reply'])
        reply.save()
        reply_to = DiscussPost.objects.get(pk=request.POST['post_id'])
        reply_to.replies.add(reply)
        reply_to.save()
        return HttpResponseRedirect(request.get_full_path())

However, when I try to create a post on the site or access a post with a certain uid, I receive this error;

Reverse for 'post' with arguments '()'
and keyword arguments '{u'uid': u'CHacFvE_'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w+])$']

I literally have no idea what's wrong with my code. I am a bit rusty on python so I might be missing some obvious pointers, but any pointers in the right direction would be helpful. Thank you!

Full error stack:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/ubuntu/workspace/discuss/views.py", line 15, in homeFeed
    "feeds": [DiscussPost.getFeed(request), DiscussPost.getNewPosts()]})
  File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py", line 67, in render
    template_name, context, request=request, using=using)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 97, in render_to_string
    return template.render(context, request)
  File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py", line 95, in render
    return self.template.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 206, in render
    return self._render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 197, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 173, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 197, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 69, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 326, in render
    return nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 220, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 220, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 513, in render
    six.reraise(*exc_info)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 499, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 600, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 508, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns))
NoReverseMatch: Reverse for 'post' with arguments '()' and keyword arguments '{u'uid': u'-lTmOw__'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w]+)$']

Body:
Your pattern is wrong, try this:

'^posts/(?P<uid>\w+)$'


问:
How do I control which channel sound is played through using MATLAB?
I'm a novice MATLAB user, so apologies if the question is very basic. I need a .wav sound file to be played in a single, specific channel -- let's say the left channel. As it is, my code reads in the sound file, and I add in a column of zeros to nullify the channel I don't want, like so:

```<code>currentDir = pwd;
soundFile = [currentDir '\sound1.wav']; % load the file

[y, Fs] = audioread(soundFile); % read the file in

soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = 0; % nullifies the right channel

sound = audioplayer(soundData,Fs);
play(sound);
</code>```

As it stands, the code currently produces a sound that is full volume in the left speaker, and half volume (but still very much audible) in the right speaker. I have tried this with at least 20 .wav files, with the same result.

In case it's relevant, this happens even when I write in code that explicitly matches the length of the sound variable in 0s, like so:

```<code>[y, Fs] = audioread(soundFile);
silentChannel = zeros(size(y));

soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = silentChannel(:,2); % nullifies the right channel
</code>```

Does anybody know what I'm doing wrong, or have any thoughts?

答:
When I run your code the audio output is only audible in the left channel as you have specified.

@Austin Kootz' version with the sound()-function is just as good and also produces what you're looking for, but with audioplayer-object you have the ability to stop the playback in the middle of the playback (as you probably know)

Have you tried converting your .wav to another format to see if that makes a change?

Body:
I'm a novice MATLAB user, so apologies if the question is very basic. I need a .wav sound file to be played in a single, specific channel -- let's say the left channel. As it is, my code reads in the sound file, and I add in a column of zeros to nullify the channel I don't want, like so:

currentDir = pwd;
soundFile = [currentDir '\sound1.wav']; % load the file

[y, Fs] = audioread(soundFile); % read the file in

soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = 0; % nullifies the right channel

sound = audioplayer(soundData,Fs);
play(sound);

As it stands, the code currently produces a sound that is full volume in the left speaker, and half volume (but still very much audible) in the right speaker. I have tried this with at least 20 .wav files, with the same result.

In case it's relevant, this happens even when I write in code that explicitly matches the length of the sound variable in 0s, like so:

[y, Fs] = audioread(soundFile);
silentChannel = zeros(size(y));

soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = silentChannel(:,2); % nullifies the right channel

Does anybody know what I'm doing wrong, or have any thoughts?


问:
MAPE metric at h2O
What is correct way to implement MAPE under h2o framework?

I am interested to convert below function to h2o concept

```<code>def mape(a, b):
    mask = a <> 0
    return (np.fabs(a - b)/a)[mask].mean()
</code>```

答:
```<code>import h2o
h2o.init()
df = h2o.create_frame(rows=100, cols=2, missing_fraction=0, integer_fraction=1, integer_range=5)
print(df)

def mape(a, b):
    mask = a != 0
    return (abs(a-b)/a)[mask].mean()

mape(df[0],df[1])
</code>```

Title: MAPE metric at h2O

Body:
What is correct way to implement MAPE under h2o framework?

I am interested to convert below function to h2o concept

def mape(a, b):
    mask = a <> 0
    return (np.fabs(a - b)/a)[mask].mean()


问:
how can I write netflix zuul filter to change response location header attribute?
I have downstream service that redirect to x.jsp this location is not in gateway route for example

```<code>gateway route --- localhost:8080/app - 192.168.1.1:80 (DownStream app)
</code>```

in DownStream app when a user is not logged in, it redirects to 192.168.1.1:80/Login.jsp, which is in the Location header of the response.

This URL is not using the gateway.

I want to write a zuul filter to change this redirect url by mapping in zuul routes dynamic for example for each url that routes in zuul filter change Location header by the gateway. How can I do that?

答:
You downstream app should respect the x-forwarded-* headers, and not generate redirects like that. But the following filter will change the redirect location for you anyway:</p>

```<code>@Override
public String filterType() {
    return "post";
}

@Override
public int filterOrder() {
    return 0;
}

@Override
public boolean shouldFilter() {
    int status = RequestContext.getCurrentContext().getResponseStatusCode();
    return status >= 300 && status < 400;
}

@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    Map<String, String> requestHeaders = ctx.getZuulRequestHeaders();
    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
                .stream()
                .filter(stringStringPair -> LOCATION.equals(stringStringPair.first()))
                .findFirst();

        if (locationHeader.isPresent()) {
            String oldLocation = locationHeader.get().second();
            String newLocation = ...
            locationHeader.get().setSecond(newLocation);
        }
    return null;
}
</code>```

Body:
I have downstream service that redirect to x.jsp this location is not in gateway route for example

gateway route --- localhost:8080/app - 192.168.1.1:80 (DownStream app)

in DownStream app when a user is not logged in, it redirects to 192.168.1.1:80/Login.jsp, which is in the Location header of the response.

This URL is not using the gateway.

I want to write a zuul filter to change this redirect url by mapping in zuul routes dynamic for example for each url that routes in zuul filter change Location header by the gateway. How can I do that?

Body:
You downstream app should respect the x-forwarded-* headers, and not generate redirects like that. But the following filter will change the redirect location for you anyway:

@Override
public String filterType() {
    return "post";
}

@Override
public int filterOrder() {
    return 0;
}

@Override
public boolean shouldFilter() {
    int status = RequestContext.getCurrentContext().getResponseStatusCode();
    return status >= 300 && status < 400;
}

@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    Map<String, String> requestHeaders = ctx.getZuulRequestHeaders();
    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
                .stream()
                .filter(stringStringPair -> LOCATION.equals(stringStringPair.first()))
                .findFirst();

        if (locationHeader.isPresent()) {
            String oldLocation = locationHeader.get().second();
            String newLocation = ...
            locationHeader.get().setSecond(newLocation);
        }
    return null;
}


问:
How to make_shared count times, with different areas allocated without recur to a loop?
How to make_shared count times, with different areas allocated without recur to a loop?

I have the following code:

```<code>for( unsigned int count = 0; count < demandedSize; ++count  )
{
   m_connectionList.push_back( std::make_shared< Foo >( m_ip, m_port ));
}
</code>```

How to shorten this without a loop?

I know std::vector receaves a second argument as const T&, but in that case all shared_ptrs points to the same address (value is copied).

```<code>std::vector< std::shared_ptr<Foo> > vet( demandedSize, std::make_shared<Foo>( m_ip, m_port ) );
</code>```

How to execute make_shared count times, with different areas allocated as result without recur to a loop

答:
```<code>template<class X>
struct arrow_helper_t {
  X x;
  auto operator->()&& { return std::addressof(x); }
};
template<class X>
arrow_helper_t<X> arrow_helper(X&& x){ return {std::forward<X>(x)}; }

template<class F>
struct generator_iterator_t {
  std::size_t i = 0;
  F f;
  generator_iterator_t()=default;
  generator_iterator_t(generator_iterator_t const&)=default;
  generator_iterator_t(generator_iterator_t &&)=default;
  generator_iterator_t& operator=(generator_iterator_t const&)=default;
  generator_iterator_t& operator=(generator_iterator_t &&)=default;
  using iterator_category = std::input_iterator_tag;
  using reference=decltype(std::declval<F const&>()(std::declval<std::size_t const&>()));
  using value_type = std::decay_t<reference>;
  using pointer = arrow_helper_t<reference>;
  using difference_type = std::ptrdiff_t;
  using self_t = generator_iterator_t;
  friend bool operator!=(self_t const& lhs, self_t const& rhs) { return lhs.i != rhs.i; }
  friend bool operator==(self_t const& lhs, self_t const& rhs) { return lhs.i == rhs.i; }
  decltype(auto) operator*()const { return f(i); }
  auto operator->() const { return arrow_helper(**this); }
  self_t& operator++() { ++i; return *this; }
  self_t operator++(int) { auto r = *this; ++i; return r; }
};
template<class F>
generator_iterator_t<F>
generator_iterator( F f, std::size_t i ) {
  return {i, std::move(f)};
}
template<class F>
auto generator_range( F f, std::size_t i ) {
  return std::make_pair(
    generator_iterator(f, 0),
    generator_iterator(f, i)
  );
}

auto range = generator_range([&](auto){return std::make_shared< Foo >( m_ip, m_port );}, demandedSize);
m_connectionList.reserve( m_connectionList.size()+demandedSize );
m_connectionList.insert(m_connectionList.end(),
  range.first, range.second
);
</code>```

or somesuch.  boost probably does it better.

live example.

Body:
How to make_shared count times, with different areas allocated without recur to a loop?

I have the following code:

for( unsigned int count = 0; count < demandedSize; ++count  )
{
   m_connectionList.push_back( std::make_shared< Foo >( m_ip, m_port ));
}

How to shorten this without a loop?

I know std::vector receaves a second argument as const T&, but in that case all shared_ptrs points to the same address (value is copied).

std::vector< std::shared_ptr<Foo> > vet( demandedSize, std::make_shared<Foo>( m_ip, m_port ) );

How to execute make_shared count times, with different areas allocated as result without recur to a loop

Body:
template<class X>
struct arrow_helper_t {
  X x;
  auto operator->()&& { return std::addressof(x); }
};
template<class X>
arrow_helper_t<X> arrow_helper(X&& x){ return {std::forward<X>(x)}; }

template<class F>
struct generator_iterator_t {
  std::size_t i = 0;
  F f;
  generator_iterator_t()=default;
  generator_iterator_t(generator_iterator_t const&)=default;
  generator_iterator_t(generator_iterator_t &&)=default;
  generator_iterator_t& operator=(generator_iterator_t const&)=default;
  generator_iterator_t& operator=(generator_iterator_t &&)=default;
  using iterator_category = std::input_iterator_tag;
  using reference=decltype(std::declval<F const&>()(std::declval<std::size_t const&>()));
  using value_type = std::decay_t<reference>;
  using pointer = arrow_helper_t<reference>;
  using difference_type = std::ptrdiff_t;
  using self_t = generator_iterator_t;
  friend bool operator!=(self_t const& lhs, self_t const& rhs) { return lhs.i != rhs.i; }
  friend bool operator==(self_t const& lhs, self_t const& rhs) { return lhs.i == rhs.i; }
  decltype(auto) operator*()const { return f(i); }
  auto operator->() const { return arrow_helper(**this); }
  self_t& operator++() { ++i; return *this; }
  self_t operator++(int) { auto r = *this; ++i; return r; }
};
template<class F>
generator_iterator_t<F>
generator_iterator( F f, std::size_t i ) {
  return {i, std::move(f)};
}
template<class F>
auto generator_range( F f, std::size_t i ) {
  return std::make_pair(
    generator_iterator(f, 0),
    generator_iterator(f, i)
  );
}

auto range = generator_range([&](auto){return std::make_shared< Foo >( m_ip, m_port );}, demandedSize);
m_connectionList.reserve( m_connectionList.size()+demandedSize );
m_connectionList.insert(m_connectionList.end(),
  range.first, range.second
);

or somesuch.  boost probably does it better.

live example.


问:
Double integral of objective function
I want to evaluate the double integral of my objective function (named myfunction, see below) using the build-in-function integral2.

I have tried to run this script;

```<code>f = @(r,theta) myfunction(r,theta);
integral2(f,0,2,0,2*pi);
</code>```

where myfunction is the following function:

```<code>function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
los(:,1)=x;
los(:,2)=y;
norm = (sum( sqrt( los(:,1).^2 + los(:,2).^2)));
fkt=norm*r;
end
</code>```

I am making the integral in polar coordinates, that why  fkt=norm*r.

Matlab gives me the following error message:

```<code>>> untitled2
Subscripted assignment dimension mismatch.

Error in myfunction (line 8)
los(:,1)=x;
</code>```

I can't figure out, what the problem is.

答: x is a matrix and you try to assign it to a column vector.</p>

Title: Double integral of objective function

Body:
I want to evaluate the double integral of my objective function (named myfunction, see below) using the build-in-function integral2.

I have tried to run this script;

f = @(r,theta) myfunction(r,theta);
integral2(f,0,2,0,2*pi);

where myfunction is the following function:

function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
los(:,1)=x;
los(:,2)=y;
norm = (sum( sqrt( los(:,1).^2 + los(:,2).^2)));
fkt=norm*r;
end

I am making the integral in polar coordinates, that why  fkt=norm*r.

Matlab gives me the following error message:

>> untitled2
Subscripted assignment dimension mismatch.

Error in myfunction (line 8)
los(:,1)=x;

I can't figure out, what the problem is.


问:
App Engine Admin API Error - The "appengine.applications.create" permission is required
We would like to automatically create a project ID and install our ULAPPH Cloud Desktop application using the App Engine Admin API (REST) and Golang.
https://cloud.google.com/appengine/docs/admin-api/?hl=en_US&_ga=1.265860687.1935695756.1490699302
https://ulapph-public-1.appspot.com/articles?TYPE=ARTICLE&DOC_ID=3&SID=TDSARTL-3

We were able to get a token but when we tried to create a project ID, we get the error below.

```<code>[Response OK] Successful connection to Appengine Admin API.
[Token] { "access_token" : "TOKEN_HERE", "expires_in" : 3599, "token_type" : "Bearer" }

[Response Code] 403
[Response Body] { "error": { "code": 403, "message": "Operation not allowed", "status": "PERMISSION_DENIED", "details": [ { "@type": "type.googleapis.com/google.rpc.ResourceInfo", "resourceType": "gae.api", "description": "The \"appengine.applications.create\" permission is required." } ] } }
</code>```

We are just using the REST API calls. Request for token was successful as you can see above and the scope is ok as well. Now, when we posted the request to create application, we are having the error that says "appengine.application.create" permission required.

How do we specify the permission?

What are the possible reasons why we are getting that error? Do we missed to send a field in JSON or in query?

As per below link, we just need to pass the json containing the id and location. We also just need to pass the token in the Authorization header. The same logic I have used successfully in accessing Youtube, Drive APIs etc so not sure what needs to be done since I have followed the docs available.

I have also posted the same issue in Google Groups and now waiting for their reply.

答:
It seems you've given no details about how you set up the account you're using to authorize the request. You'll need to make sure the appengine.applications.create permission is given to the account you're using, as mentioned in the error text. You can use the Google Identity and Access Management (IAM) API for this.

(by the way, I'd given this answer in the original thread, although you didn't reply or seem to take action on it. check it out! this is likely the solution you need!)

Body:
We would like to automatically create a project ID and install our ULAPPH Cloud Desktop application using the App Engine Admin API (REST) and Golang.
https://cloud.google.com/appengine/docs/admin-api/?hl=en_US&_ga=1.265860687.1935695756.1490699302
https://ulapph-public-1.appspot.com/articles?TYPE=ARTICLE&DOC_ID=3&SID=TDSARTL-3

We were able to get a token but when we tried to create a project ID, we get the error below.

[Response OK] Successful connection to Appengine Admin API.
[Token] { "access_token" : "TOKEN_HERE", "expires_in" : 3599, "token_type" : "Bearer" }

[Response Code] 403
[Response Body] { "error": { "code": 403, "message": "Operation not allowed", "status": "PERMISSION_DENIED", "details": [ { "@type": "type.googleapis.com/google.rpc.ResourceInfo", "resourceType": "gae.api", "description": "The \"appengine.applications.create\" permission is required." } ] } }

We are just using the REST API calls. Request for token was successful as you can see above and the scope is ok as well. Now, when we posted the request to create application, we are having the error that says "appengine.application.create" permission required.

How do we specify the permission?

What are the possible reasons why we are getting that error? Do we missed to send a field in JSON or in query?

As per below link, we just need to pass the json containing the id and location. We also just need to pass the token in the Authorization header. The same logic I have used successfully in accessing Youtube, Drive APIs etc so not sure what needs to be done since I have followed the docs available.

I have also posted the same issue in Google Groups and now waiting for their reply.


问:
Resource configuration class could not be loaded when trying to open index.html in eclipse
I am trying to open index.html from eclipse. But I got this error:

javax.servlet.ServletException: Resource configuration class
  com.sensorhound.things.rest.ThingsApplication could not be loaded.

I am using java EE framework.

Previously, I am writing my front-end code using a Node.js fake server. Then I create a maven project in eclipse to write my back-end code. And I didn't move my front-end code to this project until I finish writing up the back-end code.

What I did to test my front-end code before was start up my wildfly server and Cassandra database, then I will do a mvn wildfly:deploy under my back-end project directory. Then I will go to the front-end code folder and open the index.html in browser. It works fine.

Now I need to wrap up my project so I copy my front-end code to

src/main/webapps

directory, and update my project.

But when I try to open the index.html from eclipse. It give me this error.

For more reference, here is my web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>servlet 3.0 Web Application</display-name>
    <context-param>
        <param-name>resteasy.providers</param-name>
        <param-value>
                com.sensorhound.aigateway.ws.filters.CORSFilter
        </param-value>
    </context-param>
    <servlet>
        <servlet-name>ServletContainer</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.sensorhound.things.rest.ThingsApplication</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletContainer</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

Here is my pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sensorhound</groupId>
    <artifactId>aigateway</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>AI Gateway Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jetty.version>9.3.12.v20160915</jetty.version>
        <jersey.version>2.23.2</jersey.version>
        <ogm.version>5.0.4.Final</ogm.version>
        <hibernate.version>5.0.4.Final</hibernate.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.hibernate.ogm</groupId>
                <artifactId>hibernate-ogm-bom</artifactId>
                <version>5.0.4.Final</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-search-orm</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-search-infinispan</artifactId>
            <version>5.1.1.Final</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate.ogm</groupId>
            <artifactId>hibernate-ogm-cassandra</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
           <groupId>dom4j</groupId>
           <artifactId>dom4j</artifactId>
           <version>1.6.1</version>
           <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jandex</artifactId>
            <version>2.0.3.Final</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.7.3</version>
        </dependency>

        <!-- hibernate ogm -->
        <!-- Hibernate OGM Infinispan module; pulls in the OGM core module -->
        <dependency>
            <groupId>org.hibernate.ogm</groupId>
            <artifactId>hibernate-ogm-infinispan</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- standard APIs dependencies - provided in a Java EE container -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.transaction</groupId>
            <artifactId>jboss-transaction-api_1.2_spec</artifactId>
        </dependency>
        <!-- Add the Narayana Transactions Manager
         an implementation would be provided in a Java EE container,
         but this works nicely in Java SE as well -->
        <dependency>
            <groupId>org.jboss.narayana.jta</groupId>
            <artifactId>narayana-jta</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jboss-transaction-spi</artifactId>
            <version>7.5.0.Final</version>
        </dependency>
        <dependency>
            <groupId>jboss</groupId>
            <artifactId>jbossjta</artifactId>
            <version>4.2.2.GA</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <!-- dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlet</artifactId>
            <version>${jetty.version}</version> </dependency -->
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-http</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.fusesource.leveldbjni</groupId>
            <artifactId>leveldbjni-all</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.ejb</groupId>
            <artifactId>ejb-api</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>aigateway</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>1.1.0.Final</version>
                <configuration>
                <force>true</force>
<!--                <hostname>${wildfly-hostname}</hostname> -->
<!--                <username>${wildfly-user}</username> -->
<!--                <password>${wildfly-password}</password> -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

If you need more information, I am willing to share.

Thanks!

答: I solve this by remove servlet related tags in web.xml. Those are the code my co-workers added when using jetty server.</p>

Body:
I am trying to open index.html from eclipse. But I got this error:

javax.servlet.ServletException: Resource configuration class
  com.sensorhound.things.rest.ThingsApplication could not be loaded.

I am using java EE framework.

Previously, I am writing my front-end code using a Node.js fake server. Then I create a maven project in eclipse to write my back-end code. And I didn't move my front-end code to this project until I finish writing up the back-end code.

What I did to test my front-end code before was start up my wildfly server and Cassandra database, then I will do a mvn wildfly:deploy under my back-end project directory. Then I will go to the front-end code folder and open the index.html in browser. It works fine.

Now I need to wrap up my project so I copy my front-end code to

src/main/webapps

directory, and update my project.

But when I try to open the index.html from eclipse. It give me this error.

For more reference, here is my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>servlet 3.0 Web Application</display-name>
    <context-param>
        <param-name>resteasy.providers</param-name>
        <param-value>
                com.sensorhound.aigateway.ws.filters.CORSFilter
        </param-value>
    </context-param>
    <servlet>
        <servlet-name>ServletContainer</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.sensorhound.things.rest.ThingsApplication</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletContainer</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

Here is my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sensorhound</groupId>
    <artifactId>aigateway</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>AI Gateway Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jetty.version>9.3.12.v20160915</jetty.version>
        <jersey.version>2.23.2</jersey.version>
        <ogm.version>5.0.4.Final</ogm.version>
        <hibernate.version>5.0.4.Final</hibernate.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.hibernate.ogm</groupId>
                <artifactId>hibernate-ogm-bom</artifactId>
                <version>5.0.4.Final</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-search-orm</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-search-infinispan</artifactId>
            <version>5.1.1.Final</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate.ogm</groupId>
            <artifactId>hibernate-ogm-cassandra</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
           <groupId>dom4j</groupId>
           <artifactId>dom4j</artifactId>
           <version>1.6.1</version>
           <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jandex</artifactId>
            <version>2.0.3.Final</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.7.3</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.ogm</groupId>
            <artifactId>hibernate-ogm-infinispan</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.transaction</groupId>
            <artifactId>jboss-transaction-api_1.2_spec</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jboss.narayana.jta</groupId>
            <artifactId>narayana-jta</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jboss-transaction-spi</artifactId>
            <version>7.5.0.Final</version>
        </dependency>
        <dependency>
            <groupId>jboss</groupId>
            <artifactId>jbossjta</artifactId>
            <version>4.2.2.GA</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>${jetty.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-http</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.fusesource.leveldbjni</groupId>
            <artifactId>leveldbjni-all</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.ejb</groupId>
            <artifactId>ejb-api</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>aigateway</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>1.1.0.Final</version>
                <configuration>
                <force>true</force>

                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

If you need more information, I am willing to share.

Thanks!


问:
OleDb - Incorrect syntax near the keyword 'DEFAULT'
Alright so, Im trying to do a simple update query to a table but I keep getting this error Incorrect syntax near the keyword 'DEFAULT'. The thing is. it only goes wrong when ome values are NULL, but I've checked and IT DOES allow null values. Here is my code for the query

```<code>public void UpdateQuery(String[] valores)
{
    conexion = this.Connections.OLEDBCONNECTION.ConnectionString;
    String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP), CODORG=ISNULL(?,CODORG), CODGRP=ISNULL(?,CODGRP), TXTDEN=ISNULL(?,TXTDEN),"
                 + " IDEACC=ISNULL(?,IDEACC), CODAPP=ISNULL(?,CODAPP), NUMPLZ=ISNULL(?,NUMPLZ), CODCUR=ISNULL(?,CODCUR), DATING=ISNULL(?,DATING),"
                 + " NUMACCCTE=ISNULL(?,NUMACCCTE), DATCAN=ISNULL(?,DATCAN), FLGESTADO=ISNULL(?,FLGESTADO), DATELI=ISNULL(?,DATELI),"
                 + " DATUPD=ISNULL(?,DATUPD), TXTADR=ISNULL(?,TXTADR), CODUSR=ISNULL(?,CODUSR)"
                 + " WHERE NUMACC = ?";

    using (OleDbConnection con = new OleDbConnection(conexion))
    {
        con.Open();
        using (OleDbCommand cmd = con.CreateCommand())
        {
            cmd.Parameters.Add("@CODTYP", OleDbType.VarChar, 3).Value = valores[1];
            cmd.Parameters.Add("@CODORG", OleDbType.VarChar, 18).Value = valores[2];
            cmd.Parameters.Add("@CODGRP", OleDbType.VarChar, 4).Value = valores[3];
            cmd.Parameters.Add("@TXTDEN", OleDbType.VarChar, 150).Value = valores[4];
            cmd.Parameters.Add("@IDEACC", OleDbType.Char, 1).Value = valores[5];
            cmd.Parameters.Add("@CODAPP", OleDbType.VarChar, 2).Value = valores[6];
            cmd.Parameters.Add("@NUMPLZ", OleDbType.VarChar, 3).Value = valores[7];
            cmd.Parameters.Add("@CODCUR", OleDbType.Char, 3).Value = valores[8];

            if (valores[9] == null)
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[9]);

            cmd.Parameters.Add("@NUMACCCTE", OleDbType.VarChar, 18).Value = valores[10];

            if (valores[11] == null)
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[11]);

            cmd.Parameters.Add("@FLGESTADO", OleDbType.Char, 1).Value = valores[12];

            if (valores[13] == null)
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[13]);

            cmd.Parameters.Add("@DATUPD", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[14]);
            cmd.Parameters.Add("@TXTADR", OleDbType.VarChar, 100).Value = valores[15];
            cmd.Parameters.Add("@CODUSR", OleDbType.VarChar, 7).Value = valores[16];
            cmd.Parameters.Add("@NUMACC", OleDbType.VarChar, 18).Value = valores[0];

            cmd.CommandText = query;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                byte[] emptybytes = new byte[0];

                this.Log("CustomMessage: Error en NUMACC: " + valores[0] + " | " + ex.Message, 0, emptybytes);
            }
            cmd.Parameters.Clear();
        }
        con.Close();
    }
}
</code>```

I have given the "yyyy-MM-dd HH:mm:ss" format for the datetime column. It works when I do it from SQl Server Management Studio, but thats it. Now, I know OLEDB doesnt really care about parameter name, it works on the same order is called in the query. Thats why I did it this way.

I've testing with just using

```<code>String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP) WHERE NUMACC = ?"
</code>```

and only using the first parameter and it works! but using the second value CODORG it throws the error.

In this case, valores[2] and valores[3] are null values, but since Im using ISNULL() in the query, I believe it shouldnt be a problem. Even if it is, the column allow null values, but its not updating

答:
From my comment, null and DBNull.Value are different things. Try </p>

```<code>cmd.Parameters.Add("@CODORG", OleDbType.VarChar, 18).Value = valores[2] ?? (object)DBNull.Value;
</code>```

Body:
Alright so, Im trying to do a simple update query to a table but I keep getting this error Incorrect syntax near the keyword 'DEFAULT'. The thing is. it only goes wrong when ome values are NULL, but I've checked and IT DOES allow null values. Here is my code for the query

public void UpdateQuery(String[] valores)
{
    conexion = this.Connections.OLEDBCONNECTION.ConnectionString;
    String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP), CODORG=ISNULL(?,CODORG), CODGRP=ISNULL(?,CODGRP), TXTDEN=ISNULL(?,TXTDEN),"
                 + " IDEACC=ISNULL(?,IDEACC), CODAPP=ISNULL(?,CODAPP), NUMPLZ=ISNULL(?,NUMPLZ), CODCUR=ISNULL(?,CODCUR), DATING=ISNULL(?,DATING),"
                 + " NUMACCCTE=ISNULL(?,NUMACCCTE), DATCAN=ISNULL(?,DATCAN), FLGESTADO=ISNULL(?,FLGESTADO), DATELI=ISNULL(?,DATELI),"
                 + " DATUPD=ISNULL(?,DATUPD), TXTADR=ISNULL(?,TXTADR), CODUSR=ISNULL(?,CODUSR)"
                 + " WHERE NUMACC = ?";

    using (OleDbConnection con = new OleDbConnection(conexion))
    {
        con.Open();
        using (OleDbCommand cmd = con.CreateCommand())
        {
            cmd.Parameters.Add("@CODTYP", OleDbType.VarChar, 3).Value = valores[1];
            cmd.Parameters.Add("@CODORG", OleDbType.VarChar, 18).Value = valores[2];
            cmd.Parameters.Add("@CODGRP", OleDbType.VarChar, 4).Value = valores[3];
            cmd.Parameters.Add("@TXTDEN", OleDbType.VarChar, 150).Value = valores[4];
            cmd.Parameters.Add("@IDEACC", OleDbType.Char, 1).Value = valores[5];
            cmd.Parameters.Add("@CODAPP", OleDbType.VarChar, 2).Value = valores[6];
            cmd.Parameters.Add("@NUMPLZ", OleDbType.VarChar, 3).Value = valores[7];
            cmd.Parameters.Add("@CODCUR", OleDbType.Char, 3).Value = valores[8];

            if (valores[9] == null)
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[9]);

            cmd.Parameters.Add("@NUMACCCTE", OleDbType.VarChar, 18).Value = valores[10];

            if (valores[11] == null)
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[11]);

            cmd.Parameters.Add("@FLGESTADO", OleDbType.Char, 1).Value = valores[12];

            if (valores[13] == null)
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[13]);

            cmd.Parameters.Add("@DATUPD", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[14]);
            cmd.Parameters.Add("@TXTADR", OleDbType.VarChar, 100).Value = valores[15];
            cmd.Parameters.Add("@CODUSR", OleDbType.VarChar, 7).Value = valores[16];
            cmd.Parameters.Add("@NUMACC", OleDbType.VarChar, 18).Value = valores[0];

            cmd.CommandText = query;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                byte[] emptybytes = new byte[0];

                this.Log("CustomMessage: Error en NUMACC: " + valores[0] + " | " + ex.Message, 0, emptybytes);
            }
            cmd.Parameters.Clear();
        }
        con.Close();
    }
}

I have given the "yyyy-MM-dd HH:mm:ss" format for the datetime column. It works when I do it from SQl Server Management Studio, but thats it. Now, I know OLEDB doesnt really care about parameter name, it works on the same order is called in the query. Thats why I did it this way.

I've testing with just using

String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP) WHERE NUMACC = ?"

and only using the first parameter and it works! but using the second value CODORG it throws the error.

In this case, valores[2] and valores[3] are null values, but since Im using ISNULL() in the query, I believe it shouldnt be a problem. Even if it is, the column allow null values, but its not updating

Body:
From my comment, null and DBNull.Value are different things. Try

cmd.Parameters.Add("@CODORG", OleDbType.VarChar, 18).Value = valores[2] ?? (object)DBNull.Value;


问:
Kotlin when() local variable introduction
Let's say I have an expensive function called doHardThings() which may return various different types, and I would like to take action based on the returned type. In Scala, this is a common use of the match construct:

```<code>def hardThings() = doHardThings() match {
     case a: OneResult => // Do stuff with a
     case b: OtherResult => // Do stuff with b
}
</code>```

I'm struggling to figure out how to do this cleanly in Kotlin without introducing a temporary variable for doHardThings():

```<code>fun hardThings() = when(doHardThings()) {
     is OneResult -> // Do stuff... with what?
     is OtherResult -> // Etc...
}
</code>```

What is an idiomatic Kotlin pattern for this common use case?

答:
Update: this is now possible, from Kotlin 1.3. Syntax is as follows:

```<code>fun hardThings() = when (val result = doHardThings()) {
     is OneResult -> // use result
     is OtherResult -> // use result some other way
}
</code>```

Old answer:

I think you'll just have to have a block body for the function and save the result of the operation to a local variable. Admittedly, this is not as neat as the Scala version.

The intended use of when with is checks is to pass in a variable and then use that same variable inside your branches, because then if it passes a check, it gets smart cast to the type it was checked for and you can access its methods and properties easily.

```<code>fun hardThings() {
    val result = doHardThings()
    when(result) {
        is OneResult ->   // result smart cast to OneResult
        is OtherResult -> // result smart cast to OtherResult
    }
}
</code>```

You could write some sort of wrapper around your operation somehow so that it only evaluates it once and otherwise returns the cached result, but it's probably not worth the complications that it introduces.

Another solution for creating the variable by @mfulton26 is to use let():

```<code>fun hardThings() = doHardThings().let {
    when(it) {
        is OneResult ->   // it smart cast to OneResult
        is OtherResult -> // it smart cast to OtherResult
    }
}
</code>```

Body:
Let's say I have an expensive function called doHardThings() which may return various different types, and I would like to take action based on the returned type. In Scala, this is a common use of the match construct:

def hardThings() = doHardThings() match {
     case a: OneResult => // Do stuff with a
     case b: OtherResult => // Do stuff with b
}

I'm struggling to figure out how to do this cleanly in Kotlin without introducing a temporary variable for doHardThings():

fun hardThings() = when(doHardThings()) {
     is OneResult -> // Do stuff... with what?
     is OtherResult -> // Etc...
}

What is an idiomatic Kotlin pattern for this common use case?

Body:
Update: this is now possible, from Kotlin 1.3. Syntax is as follows:

fun hardThings() = when (val result = doHardThings()) {
     is OneResult -> // use result
     is OtherResult -> // use result some other way
}

Old answer:

I think you'll just have to have a block body for the function and save the result of the operation to a local variable. Admittedly, this is not as neat as the Scala version.

The intended use of when with is checks is to pass in a variable and then use that same variable inside your branches, because then if it passes a check, it gets smart cast to the type it was checked for and you can access its methods and properties easily.

fun hardThings() {
    val result = doHardThings()
    when(result) {
        is OneResult ->   // result smart cast to OneResult
        is OtherResult -> // result smart cast to OtherResult
    }
}

You could write some sort of wrapper around your operation somehow so that it only evaluates it once and otherwise returns the cached result, but it's probably not worth the complications that it introduces.

Another solution for creating the variable by @mfulton26 is to use let():

fun hardThings() = doHardThings().let {
    when(it) {
        is OneResult ->   // it smart cast to OneResult
        is OtherResult -> // it smart cast to OtherResult
    }
}

ContentLicense: CC BY-SA 4.0


问:
Saving big string in php using quercus
I'm using quercus for appengine. I tried saving a long php string (> 1000 characters) but appengine won't allow me as String can only hold 500 characters. So I tried using appengine's Text datatype. It lets me save, however, when I retrieve the data from PHP, it returns me a resource() type instead of string.

Let me explain with code:

```<code><?php
$a = new Text("this is a long string that contains more than 1000 characters");
$b = "this is a long string that contains more than 1000 characters";
$e = new Entity('Article');
$e->setProperty('content', $a); // this works fine
// $e->setProperty('content', $b); // will complain as strlen($b) is > 500
$db = DatastoreServiceFactory::getDatastoreService();
$id = KeyFactory::keyToString($db->put($e)); // works ok, returns the ID of Entity saved
?>
</code>```

Now all's fine and dandy, but when I retrieve the content of $e, it will return me a resource() type data.

```<code><?php
$q = new Query('Article');
$ps = $db->prepare($q);
foreach($ps->asIterable() as $i) {
    echo gettype($i->getProperty('content')); // this will echo Object, which when var_dump'd, gives me a resource() which is not convertible to php string, thus I can't get the human readable value
}
?>
</code>```

Is there any workaround to this? Any help is GREATLY appreciated as I've been pulling my hair for days...

答:
Ok solved it by converting java object to string</p>

```<code>$content = $i->getProperty('content');
if(is_object($content)) {
    if($content instanceof Text) {
        $content = $content->getValue();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Saving big string in php using quercus

Body:
I'm using quercus for appengine. I tried saving a long php string (> 1000 characters) but appengine won't allow me as String can only hold 500 characters. So I tried using appengine's Text datatype. It lets me save, however, when I retrieve the data from PHP, it returns me a resource() type instead of string.

Let me explain with code:

<?php
$a = new Text("this is a long string that contains more than 1000 characters");
$b = "this is a long string that contains more than 1000 characters";
$e = new Entity('Article');
$e->setProperty('content', $a); // this works fine
// $e->setProperty('content', $b); // will complain as strlen($b) is > 500
$db = DatastoreServiceFactory::getDatastoreService();
$id = KeyFactory::keyToString($db->put($e)); // works ok, returns the ID of Entity saved
?>

Now all's fine and dandy, but when I retrieve the content of $e, it will return me a resource() type data.

<?php
$q = new Query('Article');
$ps = $db->prepare($q);
foreach($ps->asIterable() as $i) {
    echo gettype($i->getProperty('content')); // this will echo Object, which when var_dump'd, gives me a resource() which is not convertible to php string, thus I can't get the human readable value
}
?>

Is there any workaround to this? Any help is GREATLY appreciated as I've been pulling my hair for days...

Body:
Ok solved it by converting java object to string

$content = $i->getProperty('content');
if(is_object($content)) {
    if($content instanceof Text) {
        $content = $content->getValue();
    }
}


问:
Date Range Based on Today
I am trying to write a stored procedure that will be called by an automated report on the 1st, 8th, 15th, and 22nd of each month.

Below I have the code I am currently trying to use however I keep getting the error Explicit conversion from data type int to date is not allowed. on the line for @StartDate if ran on the 1st. However I have tried commenting out that section and I just get the same error but then for the next @StartDate.

I need @StartDate and @EndDate to be able to change based on which day of the month the report is currently being ran.

On the 1st it would need to be ran from the 21st of the
previous month to the end of the previous month.

On the  8th it would need to be  1st of the current month to the  7th.

On the 15th it would need to be  8th of the current month to the 14th.

On the 22nd it would need to be 15th of the current month to the 21st.

```<code>Declare @RunDate    date
Declare @StartDate Date
Declare @EndDate    Date

Set  @RunDate = '3/1/2017'

If (Day(@RunDate) = 1)
Begin

Set @StartDate  = Convert(Date,(Month(DATEADD(d,-1,@Rundate)) + '/21/' + Case When Month(@Rundate) = '1' Then Year(@RunDate) Else Year(DATEADD(yy,-1,@Rundate)) End),101)
Set @EndDate    = Convert(date,DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@Rundate),0))),101)

End
Else
IF (Day(@RunDate) = 8)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/1/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/7/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 15)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/8/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/14/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 22)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/15/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/21/' + Year(@RunDate)),101)

End
</code>```

I am using SQL Server 2012 back end with SSMS 2016 front end. If that helps.

答:
Try changing the code to set the dates like this...

```<code>SET @StartDate = CONVERT(DATE,
    CONCAT(MONTH(DATEADD(d, -1, @Rundate)),
    '/21/',
     IIF(MONTH(@Rundate) = '1', YEAR(@RunDate), YEAR(DATEADD(yy,  -1, @Rundate)))) , 101)
</code>```

The full code will look like this...

```<code>Declare @RunDate    date
Declare @StartDate Date
Declare @EndDate    Date

Set  @RunDate = '3/1/2017'

If (Day(@RunDate) = 1)
Begin

Set @StartDate  = CONVERT(DATE, CONCAT(MONTH(DATEADD(d, -1, @Rundate)), '/21/',IIF(MONTH(@Rundate) = '1', YEAR(@RunDate), YEAR(DATEADD(yy,  -1, @Rundate)))) , 101)
Set @EndDate    = Convert(date,DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@Rundate),0))),101)

End
Else
IF (Day(@RunDate) = 8)
Begin

Set @StartDate  = Convert(Date, CONCAT(Month(@Rundate) , '/1/' , Year(@RunDate)) ,101)
Set @EndDate    = Convert(Date, CONCAT(Month(@Rundate) , '/7/' , Year(@RunDate)) ,101)

End
Else
If (Day(@Rundate) = 15)
Begin

Set @StartDate  = Convert(Date, CONCAT(Month(@Rundate) , '/8/' , Year(@RunDate)) ,101)
Set @EndDate    = Convert(Date, CONCAT(Month(@Rundate) , '/14/' , Year(@RunDate)) ,101)

End
Else
If (Day(@Rundate) = 22)
Begin

Set @StartDate  = Convert(Date, CONCAT(Month(@Rundate) , '/15/' , Year(@RunDate)) ,101)
Set @EndDate    = Convert(Date, CONCAT(Month(@Rundate) , '/21/' , Year(@RunDate)) ,101)

END

SELECT @StartDate, @EndDate
</code>```

You could even hide the repetitive code and create a simple function...

```<code>CREATE FUNCTION [dbo].[GetDateBasedOnStringNumber] (@num NVARCHAR(20), @RunDate DATE)
RETURNS DATE
WITH SCHEMABINDING AS
BEGIN
  DECLARE @retDate DATE
  SELECT  @retDate = Convert(Date, CONCAT(Month(@RunDate) , @num , Year(@RunDate)) ,101)

  RETURN @retDate ;
END;
</code>```

and then use this pattern instead...

```<code>SELECT @StartDate = dbo.GetDateBasedOnStringNumber('/1/', @RunDate)
SELECT @EndDate = dbo.GetDateBasedOnStringNumber('/7/', @RunDate)
</code>```

Title: Date Range Based on Today

Body:
I am trying to write a stored procedure that will be called by an automated report on the 1st, 8th, 15th, and 22nd of each month.

Below I have the code I am currently trying to use however I keep getting the error Explicit conversion from data type int to date is not allowed. on the line for @StartDate if ran on the 1st. However I have tried commenting out that section and I just get the same error but then for the next @StartDate.

I need @StartDate and @EndDate to be able to change based on which day of the month the report is currently being ran.

On the 1st it would need to be ran from the 21st of the
previous month to the end of the previous month.

On the  8th it would need to be  1st of the current month to the  7th.

On the 15th it would need to be  8th of the current month to the 14th.

On the 22nd it would need to be 15th of the current month to the 21st.

Declare @RunDate    date
Declare @StartDate Date
Declare @EndDate    Date

Set  @RunDate = '3/1/2017'

If (Day(@RunDate) = 1)
Begin

Set @StartDate  = Convert(Date,(Month(DATEADD(d,-1,@Rundate)) + '/21/' + Case When Month(@Rundate) = '1' Then Year(@RunDate) Else Year(DATEADD(yy,-1,@Rundate)) End),101)
Set @EndDate    = Convert(date,DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@Rundate),0))),101)

End
Else
IF (Day(@RunDate) = 8)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/1/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/7/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 15)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/8/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/14/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 22)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/15/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/21/' + Year(@RunDate)),101)

End

I am using SQL Server 2012 back end with SSMS 2016 front end. If that helps.

Body:
Try changing the code to set the dates like this...

SET @StartDate = CONVERT(DATE,
    CONCAT(MONTH(DATEADD(d, -1, @Rundate)),
    '/21/',
     IIF(MONTH(@Rundate) = '1', YEAR(@RunDate), YEAR(DATEADD(yy,  -1, @Rundate)))) , 101)

The full code will look like this...

Declare @RunDate    date
Declare @StartDate Date
Declare @EndDate    Date

Set  @RunDate = '3/1/2017'

If (Day(@RunDate) = 1)
Begin

Set @StartDate  = CONVERT(DATE, CONCAT(MONTH(DATEADD(d, -1, @Rundate)), '/21/',IIF(MONTH(@Rundate) = '1', YEAR(@RunDate), YEAR(DATEADD(yy,  -1, @Rundate)))) , 101)
Set @EndDate    = Convert(date,DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@Rundate),0))),101)

End
Else
IF (Day(@RunDate) = 8)
Begin

Set @StartDate  = Convert(Date, CONCAT(Month(@Rundate) , '/1/' , Year(@RunDate)) ,101)
Set @EndDate    = Convert(Date, CONCAT(Month(@Rundate) , '/7/' , Year(@RunDate)) ,101)

End
Else
If (Day(@Rundate) = 15)
Begin

Set @StartDate  = Convert(Date, CONCAT(Month(@Rundate) , '/8/' , Year(@RunDate)) ,101)
Set @EndDate    = Convert(Date, CONCAT(Month(@Rundate) , '/14/' , Year(@RunDate)) ,101)

End
Else
If (Day(@Rundate) = 22)
Begin

Set @StartDate  = Convert(Date, CONCAT(Month(@Rundate) , '/15/' , Year(@RunDate)) ,101)
Set @EndDate    = Convert(Date, CONCAT(Month(@Rundate) , '/21/' , Year(@RunDate)) ,101)

END

SELECT @StartDate, @EndDate

You could even hide the repetitive code and create a simple function...

CREATE FUNCTION [dbo].[GetDateBasedOnStringNumber] (@num NVARCHAR(20), @RunDate DATE)
RETURNS DATE
WITH SCHEMABINDING AS
BEGIN
  DECLARE @retDate DATE
  SELECT  @retDate = Convert(Date, CONCAT(Month(@RunDate) , @num , Year(@RunDate)) ,101)

  RETURN @retDate ;
END;

and then use this pattern instead...

SELECT @StartDate = dbo.GetDateBasedOnStringNumber('/1/', @RunDate)
SELECT @EndDate = dbo.GetDateBasedOnStringNumber('/7/', @RunDate)


问:
How can I use xsl:import with a variable in the path name?
Essentially I want do this in XSL:

```<code><xsl:include href="_domains/{$domain}/templates/header.xsl" />
</code>```

But I can't seem to use a variable ($domain) in the include.  Any suggestions on a work around?

答:
With the addition of static parameters, it is now possible to conditionally include in XSLT 3.0. Static parameters can be used in the use-when attribute of the xsl:include.

Now we can declare parameters with default values of false() and then override the ones we need at run time...

```<code><xsl:param name="someparam" as="xs:boolean" select="false()"
  static="yes" required="no"/>
<xsl:include href="include_me.xsl" use-when="$someparam"/>
</code>```

Here is a full working example tested with Saxon-HE v9.7 (also tested with Saxon-PE 9.5).

XML Input (test.xml)

```<code><doc>
    <foo/>
</doc>
</code>```

Main XSLT 3.0 (test_main.xsl)

```<code><xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="inc1" as="xs:boolean" select="false()"
    static="yes" required="no"/>
  <xsl:param name="inc2" as="xs:boolean" select="false()"
    static="yes" required="no"/>

  <xsl:include href="test_inc1.xsl" use-when="$inc1"/>
  <xsl:include href="test_inc2.xsl" use-when="$inc2"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

First possible included XSLT 3.0 (test_inc1.xsl)

```<code><xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="foo">
    <xsl:copy>INCLUDE FILE 1!!!</xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

Second possible included XSLT 3.0 (test_inc2.xsl)

```<code><xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="foo">
    <xsl:copy>INCLUDE FILE 2!!!</xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

Command line (setting inc2 to true)

```<code>java -cp "saxon9he.jar" net.sf.saxon.Transform -s:"test.xml" -xsl:"test_main.xsl" inc2="true"
</code>```

Output

```<code><doc>
   <foo>INCLUDE FILE 2!!!</foo>
</doc>
</code>```

Body:
Essentially I want do this in XSL:

<xsl:include href="_domains/{$domain}/templates/header.xsl" />

But I can't seem to use a variable ($domain) in the include.  Any suggestions on a work around?

Body:
With the addition of static parameters, it is now possible to conditionally include in XSLT 3.0. Static parameters can be used in the use-when attribute of the xsl:include.

Now we can declare parameters with default values of false() and then override the ones we need at run time...

<xsl:param name="someparam" as="xs:boolean" select="false()"
  static="yes" required="no"/>
<xsl:include href="include_me.xsl" use-when="$someparam"/>

Here is a full working example tested with Saxon-HE v9.7 (also tested with Saxon-PE 9.5).

XML Input (test.xml)

<doc>
    <foo/>
</doc>

Main XSLT 3.0 (test_main.xsl)

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="inc1" as="xs:boolean" select="false()"
    static="yes" required="no"/>
  <xsl:param name="inc2" as="xs:boolean" select="false()"
    static="yes" required="no"/>

  <xsl:include href="test_inc1.xsl" use-when="$inc1"/>
  <xsl:include href="test_inc2.xsl" use-when="$inc2"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

First possible included XSLT 3.0 (test_inc1.xsl)

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="foo">
    <xsl:copy>INCLUDE FILE 1!!!</xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Second possible included XSLT 3.0 (test_inc2.xsl)

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="foo">
    <xsl:copy>INCLUDE FILE 2!!!</xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Command line (setting inc2 to true)

java -cp "saxon9he.jar" net.sf.saxon.Transform -s:"test.xml" -xsl:"test_main.xsl" inc2="true"

Output

<doc>
   <foo>INCLUDE FILE 2!!!</foo>
</doc>


问:
Django get the Model name using ORM's related field name
I have a string like this order__product__category__description which is a related expression of my Django's model structure

Now I have a model called Shipment

field = 'order__product__category__description'

Here description is a column name of table/model Category. Here comes the question, just by having this model Shipment and this field string order__product__category__description how do I find these models Order, Product, Category.

My use-case is I need to store all the field_names of Category in a list. Any idea on how to connect the dots? having left with just two details Shipment & that field string.

First thing comes to mind is to split by __ and to come up with a list like this ['order','product','category'] and to iterate the model _meta based on the field name. Any other elegant ways would be appreciated.

答:
If you want to get the related model from the model class (rather than the related instance from a model instance), you can use _meta.get_field() combined with field.related_model to get the related model class:

```<code>from django.core.exceptions import FieldDoesNotExist

model = Shipment
lookup = 'order__product__category__description'

for name in lookup.split('__'):
    try:
        field = model._meta.get_field(name)
    except FieldDoesNotExist:
        # name is probably a lookup or transform such as __contains
        break
    if hasattr(field, 'related_model'):
        # field is a relation
        model = field.related_model
    else:
        # field is not a relation, any name that follows is
        # probably a lookup or transform
        break
</code>```

Then do with model what you want.

Body:
If you want to get the related model from the model class (rather than the related instance from a model instance), you can use _meta.get_field() combined with field.related_model to get the related model class:

from django.core.exceptions import FieldDoesNotExist

model = Shipment
lookup = 'order__product__category__description'

for name in lookup.split('__'):
    try:
        field = model._meta.get_field(name)
    except FieldDoesNotExist:
        # name is probably a lookup or transform such as __contains
        break
    if hasattr(field, 'related_model'):
        # field is a relation
        model = field.related_model
    else:
        # field is not a relation, any name that follows is
        # probably a lookup or transform
        break

Then do with model what you want.


问:
Swift Playgrounds aren't acting correctly after Xcode Update
I have been making a Swift playground that uses the touchesBegan method to accept user interaction. It has been working fine, along with the NewtonsCradle and other Swift playgrounds I have downloaded from the internet. But I just updated my Xcode to version 8.3 and NO Swift playgrounds are currently working.

My Swift playground is no longer accepting any user input.
For example I set up a test view and when I click on it "touched" does not print:

```<code>class TestView : UIView {
public init() {

    super.init(frame:CGRect(x: 0, y: 0, width: 50, height: 50))

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

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

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

}

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

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

}

}
var controller = TestView()
PlaygroundPage.current.liveView = controller
PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

I also tried running the NewtonsCradle code (one updated for Swift 3.0 so that is not the problem) and the balls do NOT respond to user interaction and they just swing on their own. See this picture of them stuck in the up-left position:

Any one have any idea what is going wrong, or what I can do? I am really pressed for time to get this to work. I also cannot roll back to the previous version of Xcode as I need the Playground to work on the latest version.

EDIT: I just updated to MacOS 10.12.4 and it is still broken. Any help?

EDIT 2: I have gotten others to confirm this as an issue for them. Perhaps others can also confirm this and if possible file an Apple Bug Report as well or come up with a fix.

答:
Here is quick fix from Apple Engineers

You just need to quit Xcode and execute following command in terminal:

```<code>defaults write com.apple.dt.xcode IDEPlaygroundDisableSimulatorAlternateFramebuffer -bool YES
</code>```

It helped in my case where all UIPanGestureRecognizers stopped working after updating to Xcode 8.3.

Also note that this will decrease quality of rendered playground.

Body:
I have been making a Swift playground that uses the touchesBegan method to accept user interaction. It has been working fine, along with the NewtonsCradle and other Swift playgrounds I have downloaded from the internet. But I just updated my Xcode to version 8.3 and NO Swift playgrounds are currently working.

My Swift playground is no longer accepting any user input.
For example I set up a test view and when I click on it "touched" does not print:

class TestView : UIView {
public init() {

    super.init(frame:CGRect(x: 0, y: 0, width: 50, height: 50))

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

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

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

}

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

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

}

}
var controller = TestView()
PlaygroundPage.current.liveView = controller
PlaygroundPage.current.needsIndefiniteExecution = true

I also tried running the NewtonsCradle code (one updated for Swift 3.0 so that is not the problem) and the balls do NOT respond to user interaction and they just swing on their own. See this picture of them stuck in the up-left position:

Any one have any idea what is going wrong, or what I can do? I am really pressed for time to get this to work. I also cannot roll back to the previous version of Xcode as I need the Playground to work on the latest version.

EDIT: I just updated to MacOS 10.12.4 and it is still broken. Any help?

EDIT 2: I have gotten others to confirm this as an issue for them. Perhaps others can also confirm this and if possible file an Apple Bug Report as well or come up with a fix.

Body:
Here is quick fix from Apple Engineers

You just need to quit Xcode and execute following command in terminal:

defaults write com.apple.dt.xcode IDEPlaygroundDisableSimulatorAlternateFramebuffer -bool YES

It helped in my case where all UIPanGestureRecognizers stopped working after updating to Xcode 8.3.

Also note that this will decrease quality of rendered playground.


问:
How to make a merge join
I have one main table and two other tables.

dict_country: id

user_country_ticket: country_id, ticket

country_ticket: country_id, ticket

This select:

```<code>select self.id, ct.ticket, uct.ticket
from country self
left join user_country_ticket uct on uct.country_id = self.id
left join country_ticket ct on ct.country_id = self.id
</code>```

returns

id, ticket, ticket

66, 3, 2

I want to join only one ticket.

From user_country_ticket if there is ticket in that table,

otherwise ticket should be joined from country_ticket,

otherwise ticket should be null

so select must return

id, ticket

66, 3

答:
you can use coalesce:</p>

```<code>select self.id, coalesce(ct.ticket,uct.ticket)
from country self
left join user_country_ticket uct on uct.country_id = self.id
left join country_ticket ct on ct.country_id = self.id
</code>```

Title: How to make a merge join

Body:
I have one main table and two other tables.

dict_country: id

user_country_ticket: country_id, ticket

country_ticket: country_id, ticket

This select:

select self.id, ct.ticket, uct.ticket
from country self
left join user_country_ticket uct on uct.country_id = self.id
left join country_ticket ct on ct.country_id = self.id

returns

id, ticket, ticket

66, 3, 2

I want to join only one ticket.

From user_country_ticket if there is ticket in that table,

otherwise ticket should be joined from country_ticket,

otherwise ticket should be null

so select must return

id, ticket

66, 3

Body:
you can use coalesce:

select self.id, coalesce(ct.ticket,uct.ticket)
from country self
left join user_country_ticket uct on uct.country_id = self.id
left join country_ticket ct on ct.country_id = self.id


问:
What exactly is JSON?
I'm new to the web application domain. I have been watching some hot and eye-catching discussions regarding JSON everywhere.

Can someone briefly explain what JSON is? Do you have links to websites or forums that can help enlighten me about JSON?

答:
It's a way of representing simple data structures as a string, usually for data interchange.

JSON web site

Title: What exactly is JSON?


问:
How to query records in multiple time zones using their own time zones with Rails or raw SQL
Here's my issue: I have records stored in my DB with UTC time zones but! I need to query those records and return everything within a day according the record's own time zone, regardless of its UTC date.

Example?

Let's say I have a record uploaded at 00:30 on a Tuesday in America/Denver and I have a bunch of records uploaded at 00:30 on a Monday in America/Los_Angeles.

Alright, now, when I query for records made on Monday, the whole day, I'm getting that Tuesday record because 00:30 in America/Denver is technically on Monday in America/Los_Angeles. I'm running raw SQL to try and solve this in my Rails project, but... no dice.

Any help on this?

```<code>SELECT
DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone) as uploaded_at,
count(DISTINCT photos.id)
FROM photos, areas
WHERE photos.category IN ('landscape', 'family', 'animal', 'saucy', 'feet', 'portrait')
AND photos.uploaded_at
BETWEEN '2017-03-27 00:00:00 UTC' AND '2017-04-02 23:59:59 UTC'
GROUP BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone)
ORDER BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone);
</code>```

答:
Something you can do in your WHERE clause. Hope it helps.</p>

```<code>BETWEEN IIF(TimeZone=-4,substract 4 hours to UTC time,
IIF(TimeZone=-5,substract 5 hours to UTC time,
IIF(TimeZone=-6,substract 6 hours to UTC time,
IIF(TimeZone=-7,substract 7 hours to UTC time,
IIF(TimeZone=-8,substract 8 hours to UTC time, UTC Time)))))
AND
IIF(TimeZone=-4,substract 4 hours to UTC time,
IIF(TimeZone=-5,substract 5 hours to UTC time,
IIF(TimeZone=-6,substract 6 hours to UTC time,
IIF(TimeZone=-7,substract 7 hours to UTC time,
IIF(TimeZone=-8,substract 8 hours to UTC time, UTC Time)))))
</code>```

Body:
Here's my issue: I have records stored in my DB with UTC time zones but! I need to query those records and return everything within a day according the record's own time zone, regardless of its UTC date.

Example?

Let's say I have a record uploaded at 00:30 on a Tuesday in America/Denver and I have a bunch of records uploaded at 00:30 on a Monday in America/Los_Angeles.

Alright, now, when I query for records made on Monday, the whole day, I'm getting that Tuesday record because 00:30 in America/Denver is technically on Monday in America/Los_Angeles. I'm running raw SQL to try and solve this in my Rails project, but... no dice.

Any help on this?

SELECT
DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone) as uploaded_at,
count(DISTINCT photos.id)
FROM photos, areas
WHERE photos.category IN ('landscape', 'family', 'animal', 'saucy', 'feet', 'portrait')
AND photos.uploaded_at
BETWEEN '2017-03-27 00:00:00 UTC' AND '2017-04-02 23:59:59 UTC'
GROUP BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone)
ORDER BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone);

Body:
Something you can do in your WHERE clause. Hope it helps.

BETWEEN IIF(TimeZone=-4,substract 4 hours to UTC time,
IIF(TimeZone=-5,substract 5 hours to UTC time,
IIF(TimeZone=-6,substract 6 hours to UTC time,
IIF(TimeZone=-7,substract 7 hours to UTC time,
IIF(TimeZone=-8,substract 8 hours to UTC time, UTC Time)))))
AND
IIF(TimeZone=-4,substract 4 hours to UTC time,
IIF(TimeZone=-5,substract 5 hours to UTC time,
IIF(TimeZone=-6,substract 6 hours to UTC time,
IIF(TimeZone=-7,substract 7 hours to UTC time,
IIF(TimeZone=-8,substract 8 hours to UTC time, UTC Time)))))