text:
Q: ReWrite in web.config to go between mobile and desktop sites I am finishing up a new mobile website to compliment the desktop version.  Currently I have a rewrite rule in the web.config file on my desktop site that looks like so:
<system.webServer>
<rewrite>
  <rules>
    <rule name="MobileRedirect" patternSyntax="ECMAScript" stopProcessing="true">
      <match url=".*" ignoreCase="true" />
      <conditions logicalGrouping="MatchAll">
        <add input="{HTTP_COOKIE}" pattern="nomobile" ignoreCase="true" negate="true" />
        <add input="{HTTP_USER_AGENT}" pattern="android|blackberry|googlebot-mobile|iemobile|iphone|ipod|opera mobile|palmos|webos" />
      </conditions>
      <action type="Redirect" url="http://m.mysite.com" appendQueryString="false" redirectType="Found" />
    </rule>
  </rules>
</rewrite>

This works perfect if I never want the user to be able to use the desktop site while on a mobile device, but that is not always the case.  Some links on the mobile site DO link back into the desktop version.  I have a link on the footer of the mobile site to "view full site" as well.
So my question IS: how to properly handle cookie setting on that link and then detecting in the web.config and NOT redirecting to the mobile version IF it exists.... I have a conditional check in the web.config for http_cookie "nomobile", but I don't think it is properly working. Do I just send in a querystring value from the mobile and check that in the global.asax file or does that not work because the web.config runs first?
The desktop is a C# MVC4 site on IIS 7.5 if any of that helps, and the mobile site is a simply jquery mobile site.
Thank you!
EDIT:
I have tried checking the querystring in the global.asax file (code below) but it seems that "Request is not available in this context".
// create and set cookie if ?nomobile detected
        string forcedesktop = HttpContext.Current.Request["nomobile"];
            if(forcedesktop != null){
                HttpCookie nomobile = new HttpCookie("nomobile");
                Request.Cookies.Add(nomobile);
            }
        }


text:
Q: Minimize the use of "Many repeated if statement" I got a script using TONS of if statement to do a task... But....
Most of them repeated like:
if (parent.getObject()=='apple') {
  if (datatype('fruit')){
    //do a
    parent.setObjectType('fruit');
  }
  else if (datatype('beverage')){
    //do a
    parent.setObjectType('beverage');
  }
}

else if (parent.getObject()=='banana') {
  if (datatype('fruit')){
    //do a
    parent.setObjectType('fruit');
  }
  else if (datatype('beverage')){
    //do a
    parent.setObjectType('beverage');
  }
}

else if (parent.getObject()=='coconut') {
  if (datatype('fruit')){
    //do a
    parent.setObjectType('fruit');
  }
  else if (datatype('beverage')){
    //do a
    parent.setObjectType('beverage');
  }
}

else if (parent.getObject()=='Dewberry') {
  if (datatype('fruit')){
    //do a
    parent.setObjectType('fruit');
  }
  else if (datatype('beverage')){
    //do a
    parent.setObjectType('beverage');
  }
}

Is it possible for me to minimize the use of those repeated codes?
I don't want to use up all the spaces only with lines of if else statement...

A: I'm not sure whether your actual code is a bit more diverse, but what you have posted can exactly be replicated by
if (['apple', 'banana', 'coconut', 'Dewberry'].some(function(fruit) {
    return parent.getObject()==fruit;
}) {
    var type = ['fruit', 'beverage'].find(datatype);
    if (type) {
       //do a
       parent.setObjectType(type);
    }
}

(where the find function is something like the following
Array.prototype.find = function(predicate, context) {
    for (var i=0; i<this.length; i++)
        if (predicate.call(context, this[i], i))
            return this[i];
    return null;
};

A: Without seeing more code maybe you could use something like this:
function doTask(a, b) {
    var as_string = a + ";" + b;

    switch (as_string) {
        case "1;1":
            //code when a=1 and b=1
                break;
        case "1;2":
            //code when a=1 and b=2
                break;
    }
}

var a = 1;
var b = 1;

doTask(a, b);

A: You can simply use The switch Statement, it's more efficient in the case you have many possible values:
switch (parent.getObject()) {
        case "apple":
            switch (datatype) {
                case "fruit":
                  //Task //do task a
                  //do task b with value 1
                  break;
                case "beverage":
                  //do task a
                  //do task b with value 2
                  break;
            }

            break;
        case "banana":
            // Task a with ...
            break;
       // And put all your possible values
 }

You have just to manage the possible vlaues of parent.getObject() and datatype.

A: You may or may not be able to reduce if statements depending on your code.
For example if you're adding odd numbers from 0 to n, you an either loop from 0 to n and use if statements to check if the number is odd.  However if you happen to know Gauss's rule 1/2*n*(n+1), you can compute this value in one line without any looping or conditional statements (by removing the k(k+1); k even numbers).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prestashop 1.7.5.1 and Nginx I have installed the latest version of Prestashop in a FreeBSD 12 with NGINX and MySQL. Installation ran flawless, however I'm having some issues with Prestashop URLs.
The frontshop works flawless, but the admin area some links works and other give me error 404.
On menu items that have the url like this:
http://store.mysite.com/admin012m0ojju/index.php?controller=AdminContacts&token=c931df617c24255d7b5eafd4d48aXXXX
The admin area works perfectly, HOWEVER, with menu items with links like this:
http://store.mysite.com/admin012m0ojju/index.php/configure/shop/customer-preferences/?_token=7t4DT8jf-KWSBXxegnntVE6gO7hpRieXVem-XXXX
I get a 404 page.
It is obvious something is wrong with URL Rewrites in NGINX, but after several hours on google and researching I decided to ask for help...
This is my nginx.conf section
upstream fastcgi_backend {
       server   unix:/var/run/php-fpm.sock;
    }

server {
            listen 80;
            listen 443 ssl;
            ssl_certificate         /usr/local/etc/letsencrypt/live/store.mysite.com/fullchain.pem;
            ssl_certificate_key     /usr/local/etc/letsencrypt/live/store.mysite.com/privkey.pem;
            server_name store.mysite.com;
            index index.php index.html index.htm;
            root /var/www/prestashop;
            location / {
                    rewrite ^/api/?(.*)$ /webservice/dispatcher.php?url=$1 last;
                    rewrite ^/([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$1$2.jpg last;
                    rewrite ^/([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$1$2$3.jpg last;
                    rewrite ^/([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$1$2$3$4.jpg last;
                    rewrite ^/([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$1$2$3$4$5.jpg last;
                    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6.jpg last;
                    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7.jpg last;
                    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8.jpg last;
                    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9.jpg last;
                    rewrite ^/c/([0-9]+)(-[_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2.jpg last;
                    rewrite ^/c/([a-zA-Z-]+)(-[0-9]+)?/.+\.jpg$ /img/c/$1.jpg last;
                    rewrite ^/([0-9]+)(-[_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2.jpg last;
                    try_files $uri $uri/ /index.php?$args;
            }
            location ~ \.php$ {
                    root    /var/www/prestashop;
                    fastcgi_pass   fastcgi_backend;
                    fastcgi_index  index.php;
                    #fastcgi_param SCRIPT_FILENAME $request_filename;
                    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                    #fastcgi_param REQUEST_URI $uri?$args;
                    include        fastcgi_params;
            }
        }

Does anyone have any clue on how to fix the rewrites?

A: After banging my head seems like I have fixed the issue:
Added this to my nginx.conf:
location ~ /(sell|improve|configure|international|_profiler|product|feature|attribute|supplier|combination|specific-price)/(.*)$ {
      try_files $uri $uri/ /index.php?q=$uri&$args $admin_dir/index.php$is_args$args;
    }


text:
Q: How to replace only the item at the top of a fragment back stack with another fragment? When I perform getSupportFragmentManager().popBackStack(); it pops the back stack and performs the fragment transaction associated with the popped back stack entry.
I have 3 fragment:
 - FragmentA
 - FragmentB
 - FragmentC
My activity performs 3 transactions when promoted by the user:

*

*Fragment A is first added to my container.

*Then FragmentA is detached and FragmentB is added. And the transaction is added to the back stack.

*Then what I want is for FragmentC to replace only fragmentB and change the back stack entry such that when the user presses the back button, FragmentA should show up.

Here is my code that performs transaction 3:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.popBackStack();
ft.remove(fragmentB)
    .add(R.id.container, fragmentC, tag)
    .addToBackStack(null)
    .commit();

Transactions 1 and 2 seem to work fine. However, when I attempt to perform transaction 3, what happens is that FragmentB is replaced by FragmentC but Fragment A also shows up right before FragmentC is drawn over it and FragmentA continues to be seen behind FragmentC.
What am I doing wrong? How can I replace FragmentB with FragmentC without having FragmentA reveal in the background.

A: I found a workaround if not a solution.
It seems that in transaction 3, when I remove FragmentB the previously detached FragmentA automatically gets added. That was what was causing FragmentA to be shown behind FragmentC.
The workaround is to detach FragmentA again after removing FragmentA like so:
ft.remove(fragmentB)
    .detach(fragmentA) // Detach FragmentA that is automatically added by the removing of fragmentB
    .add(R.id.container, fragmentC, tag)
    .addToBackStack(null)
    .commit();


text:
Q: want xpath result by casperjs I just try to echo all HTML of google result to standout. but I got the ten time 'undefined' only.
undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined
below is my code, what is wrong?
casper.then(
function(){
    this.echo(
    this.evaluate(function(){
        var returnHTML="";
        var elementsResult=__utils__.getElementsByXPath("id('ires')/ol/li");

        for (ele in elementsResult){
            returnHTML=returnHTML + ele.outerHTML;
        }

        return returnHTML;
    }));
}
);

A: What exactly are you trying to do? You could get the HTML of the results simply with return document.getElementById('ires').innerHTML;.


text:
Q: v-on:click inside a Vue Component does not work I have a simple Vue instance for a sidebar in my application where it lists all the menu of the sidebar. I have a local component for the template like so.
template:'

'+
    ''+
        ''+
            ''+
        ''+
        'Purchase Order'+
    ''+
    '
'+
        '
Profile
'+
        '
Login
'+
        '
Lockscreen
'+
    '
'+
'

'

There is some weird error which says

property or method "toggleOpenChild" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

You can check out the DEMO here.

A: Your toggleOpenChild should be placed in your component's methods, like this:
components: {
  "side-bar-modules": {
    template:
      '

' +
      '' +
      "" +
      '' +
      "" +
      'Purchase Order' +
      "" +
      '
' +
      '
Profile
' +
      '
Login
' +
      '
Lockscreen
' +
      "
" +
      "

",
    data: function() {
      return {
        user: []
      };
    },
    methods: {
      //function to close/open the child elements
      //when the parent menu is clicked.
      toggleOpenChild: function(event) {
        var currentParent = $(event.currentTarget)
          .find(".custom-erp-menu-parent")
          .text();
        var childListID = currentParent.toLowerCase().replace(/ /g, "-");
        $(".custom-erp-menu-list > ul")
          .not($("#" + childListID + "-child"))
          .slideUp()
          .removeClass("custom-erp-menu-child-open");
        if ($("#" + childListID + "-child").is(":hidden")) {
          $("#" + childListID + "-child")
            .slideDown(300)
            .toggleClass("custom-erp-menu-child-open");
        } else {
          $("#" + childListID + "-child")
            .slideUp(300)
            .toggleClass("custom-erp-menu-child-open");
        }
      }
    }
  }
}

Here's the updated fiddle:
https://jsfiddle.net/cgxnLajf/1/

A: The toggleOpenChild is in the parent wrapper, but your calling in in the child component where it does not exist.
Depending on your structure - you can either move that method into the child component, or tweak and use vue events.
    {
      template:
        '

' +
        '' +
        "" +
        '' +
        "" +
        'Purchase Order' +
        "" +
        '
' +
        '
Profile
' +
        '
Login
' +
        '
Lockscreen
' +
        "
" +
        "

",
      data: function() {
        return {
          user: []
        };
      },
      methods : {

        // method has to be part of the component
        toggleOpenChild : function()
        {
          console.log('open child');
        }
      }
}

adpated from your demo : https://codepen.io/anon/pen/ePrOqm


text:
Q: can a crawler be written entirely in javascript? I was wondering - can a crawler be written entirely in javascript? That way, the crawler is only called when a user needs the information and everything is run from the individual user's computer.
if crawler is written server side - doesn't that also run the risk of the IP being blocked?

A: It's possible to write a crawler in javascript, using, for example, Node.JS. However, you probably won't be able to write one in a user's browser. This is because:

*

*The browser security model restricts the javascript to accessing only your own domain, so you can only index your own site.

*Each user will need to re-crawl your entire site each time, meaning lots of time (minutes, hours, or even days depending on the size of the site) spent crawling before the user's query can be answered, as well as lots of bandwidth usage because this is multiplied over your entire userbase. Not to mention the user's browser might not allow your JS enough storage for its index.

A: First off, before talking details, you must understand that crawling is extremely slow. Getting any kind of meaningful web indexing takes minutes if you're looking on one site, and days at the very least if you're looking into multiple sources (often weeks, months or years). Serving a search by crawling live is not viable at all.
As for details, there's nothing preventing one from writing a crawler in Javascript. However, not in Browser-embedded javascript, at least not without a server-side proxy due to the cross-origin policy.

A: There are ways to deal with the cross domain problem. Search for "Access-Control-Allow-Origin" and you'll see how.
The easiest way to implement such a crawler is to write addon(firefox) or extension(chrome), then inject your javascript code into the visited page. That way, you'll see exactly the same thing as the document author sees. You can simply call document,body.innerText, then post the content to your server for indexing.
I myself have such a crawler working, with several browsers on different ip address crawling.


text:
Q: app crashses after update but not after re-install I've uploaded a new beta version of my app to the Google Play store.
If I update to the new version from an existing version, the app crashes right after the splash screen.
BUT, if I uninstall and re-install the new version, the app works fine.
Any idea what can cause this scenario? any idea how can I understand what's going on?
Thanks.

A: You need to check logcat for crashing reasons, were to an application crash.
Possible reason is :
You access the data in the new version of the application, which is not available in the old version of the application.

A: I finally realized that I added properties to my data classes, but I didn't add migration to the room DB, so I received exceptions when building the room DB.
I don't fully understand why it caused me exceptions only when updating the app to the new version, and not when uninstalling the older version and then installing the new one. I can see some logic in it, but I would love to hear (or read...) an exact explanation if anyone knows.
Thanks.


text:
Q: OAuth flow, iPhone -> Rails -> Facebook I'm building an app with both a web client and a iPhone client.
On the web client I authenticate users through Facebook with Omniauth, the user can then post actions on the app to Facebook. That works good.
I'm having some problem implementing the Auth flow from the iPhone application.
I've set up Doorkeeper in the rails app as an OAuth provider. Although I'm not sure how the authentication flow should be implemented.
I've come up with this:
The user can log in to Facebook in the iPhone and get a token. The idea is then to send the token, along with the Facebook uid to the rails app, store it, and authenticate the user with Omniauth. Once the user is authenticated generate a token with Doorkeeper and send it back to the iPhone app.
If it's the first time the user authenticates against the rails app, a new user will be created.
The user can then do actions against a JSON-api and the rails app will take care of the Facebook integration since the Facebook token is stored on the user record.
The application will also span over several domains so I'll need to have multiple Doorkeeper applications registered to provide different callback uri's.
Does this seem like a viable solution?
Is it secure?
Is there alternative flows / approaches?
Thanks.

A: The solution I went with is summarized as followed:

*

*Client starts oath flow w/ Facebook (using login button etc)

*Client gets auth token and posts back to server

*Server looks up user via FB API call w/ token

*Server does lookup/create of user based on FB id

*User is logged in if a user with FB id association lookup is successful

I have a diagram and more detail here: http://www.eggie5.com/57-ios-rails-oauth-flow


text:
Q: iTerm2 outputs random characters when the remote tmux exits abnormally I use tmux on my remote terminal. I found that when the remote terminal was disconnected abnormally (e.g., I just closed my laptop without exiting remote terminal normally), my terminal on iTerm will start to output random characters if I scroll my mouse, or click.
Any advice how to fix it?

A: I had the same issue and found this answer which helped me: Disable mouse reporting in a terminal session after tmux exits unexpectedly
To disable Mouse Reporting from bash, use this code:
printf '\e[?1000l'


text:
Q: How to map PC (ARMv5) address to source code? I'm developing on an ARM9E processor running Linux. Sometimes my application crashes with the following message :

[  142.410000] Alignment trap: rtspserverd (996) PC=0x4034f61c
  Instr=0xe591300c Address=0x0000000d FSR 0x001

How can I translate the PC address to actual source code? In other words, how can I make sense out of this message?

A: With objdump. Dump your executable, then search for 4034f61c:.
The -x, --disassemble, and -l options are particularly useful.

A: You can turn on listings in the compiler and tell the linker to produce a map file. The map file will give you the meaning of the absolute addresses up to the function where the problem occurs, while the listing will help you pinpoint the exact location of the exception within the function.
For example in gcc you can do
gcc -Wa,-a,-ad -c foo.c > foo.lst

to produce a listing in the file foo.lst.
-Wa, sends the following options to the assembler (gas).
-a tells gas to produce a listing on standard output.
-ad tells gas to omit debug directives, which would otherwise add a lot of clutter.
The option for the GNU linker to produce a map file is -M or --print-map. If you link with gcc you need to pass the option to the linker with an option starting with -Wl,, for example -Wl,-M.
Alternatively you could also run your application in the debugger (e.g. gdb) and look at the stack dump after the crash with the bt command.


text:
Q: wkhtmltopdf offsetHeight difference I am using wkhtmltopdf 0.9.9. I need to know the offsetHeight of a dynamically generated HTML element; this is done via Javascript, before wkhtmltopdf converts to PDF file. However, I am noticing value difference when I tested it out in HTML and in PDF result.
Here is the standalone test case:

Test

Hello

Test
Test
Test
Test
Test

In HTMl (via browser), the #test element contains value of 110.
However, in the generated PDF, the #test element contains value of 343.
How is this happening, and what could be the solution for this inconsistency?

A: I set the width of the body element to the width of the PDF.
body {
  width: 210mm;
}

In conclusion, when I measure the height of the content using e.x. $('#content').height() the size seems to be correct.

A: I also encountered the same issue but with wkhtmltopdf 0.11.
I found out that these pre 0.12 versions does not support the --viewport-size parameter, the application will not have a proper "window" width.
Also notice that none of your HTML elements have an explicit width value set. This will result in a very thin "virtual window" where the application renders your HTML. And this will result in having the inner text split in multiple lines, with the node having very high height value.
What i could do to fix this issue is to explicitly set the desired width of one of the html elements. (the widest one so the wkhtmltopdf could use that as "window" width)


text:
Q: Removing divs gives error So I created a dice simulator with an option to reset the table. I create new divs with dice number by appendChild and want to remove it with remove().
Even though it appears to be working I keep getting errors.
The code and error is below:

function addMoreDice() {
  for (var i = 0; i < numInput.value; i++) {
    var div = document.createElement('div');
    div.className = "diceStyle";
    div.id = "dice" + String(i);
    div.innerHTML = Math.floor((Math.random() * 6) + 1);

    document.getElementById('diceTable').appendChild(div);
    howManyDice++;
  }
  currentValue = numInput.value;

}

function removeDice() {
  var removeDiv = document.getElementsByClassName("diceStyle");
  for (var i = 0; i < numInput.value; i++) {
    removeDiv[numInput.value - i - 1].remove();
  }
}

Uncaught TypeError: Cannot read property 'remove' of undefined
    at removeDice
Updating with html, although there isnt really anything there:

Pick how many dice you want to roll:

<input id="diceNumber" type="number" name="diceNumber" onchange="return addMoreDice()">

Edited removeDice function, sadly changes nothing, works, but gives errors
function removeDice(){
var removeDiv = document.getElementsByClassName("diceStyle");
var value = numInput.value;
if(value >0){
    for(var i=value; i > 0; i--){
        removeDiv[i-1].remove();
    }
}
}

A: The issue appears to be in the removeDice() function. Removing an item from the array decreases the number of items in the array (obviously), but the for-loop is assuming that the array still has the same number of items as when the for-loop started. So if the for-loop started with 5 items, and then removes one, there will be only 4 items in the array. Since the for-loop is assuming that there are 5 items, it will try to remove the 5th item in the array, but since the array only has 4 items, there is no 5th item to remove, causing an error. To fix the issue, loop backwards:
for(var i = numInput.value; i > 0; i--)


text:
Q: Refresh html page using c# script I have a HTML page in my project location and I am trying to populate values from my c# script to the place holder in HTML page. But every first time when i was running the script values got populated with correct details, but in the second run when i am changing my values like my name salary then HTML page doesn't reflect this new value and old data got appeared. Please suggest

A: Your question doesn't really explain much, in particular which technology your utilizing.  It appears as if you lack an understanding of:

*

*View State

Viable information can be found here.  In an Web-Form application, you'll not only need to account for persistence of the View State, but the Page Life Cycle as well.  It will play an important role in understanding the fundamentals.
You stated the following:

The first time the page loads the data exist, when I update the data
  the old data exist rather than the new data.

Your issue could stem from either a Postback or the control your utilizing.  When a Postback occurs, it means exactly what it states, a Client's interaction with your application transmits data back to the server.
You can remedy such a problem with:

*

*Update Panel

*Page.IsPostback

*Databind();

*Ajax

The problem has viable solutions, however until you truly understand the problem we can't specifically help you remedy the issue.  This should point you in the proper direction though.


text:
Q: How to Retrieve Selected Value of RadioButtonList How to read those selected items using datareader and make the radiobutton enabled in the list.
Radiobuttonlist1.Text=??

A: Radiobuttonlist1.SelectedValue = YourValue
So if you have a reader:
reader("MyColumn")
Then you can do:
RadioButtonList1.SelectedValue = CType(reader("MyColumn"), Integer) 'is my col an integer
If you want to display the item selected or the text:
For text:
RadiobuttonList1.SelectedItem.Text 'for text
For value:
RadiobuttonList1.SelectedItem.Value 'for value


text:
Q: Can Tyrus server use inner class endpoints? I am having a problem getting an extremely simple standalone Tyrus websocket server to work. I have gotten this to work under very specific circumstances that don't make sense to me.
The case that works correctly is where I define a top-level (in its own file) server endpoint class and annotate it with @ServerEndpoint. This class includes methods annotated with @OnOpen, @OnMessage, and @OnClose, all typical stuff. I pass this class to the Server constructor. My simple client can connect to this server, and send it messages successfully that are received by the server.
The problem occurs when I change the top-level server endpoint class to be an inner class of the class that is initializing the server (this is the ONLY change I made). In this case my client can connect and the client's @OnOpen method is called. But the server does not instantiate the server endpoint and, consequently, its @OnOpen method is never called. Obviously, server message receipt does not occur.
Is there a requirement in Tyrus that annotated server endpoint classes can't be inner classes? If not, are there specific permissions on server endpoint classes (everything has been made public attempting to get this to work with no luck)? I'm using Tyrus 1.9 with JDK 1.7 on a Mac, OSX 1.9.5.
The simple server (including and configured to use the inner server endpoint that fails):
package tyrus.example;

import java.util.concurrent.TimeUnit;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.glassfish.tyrus.server.Server;

public class SimpleServer
{
    private static final String HOST_ADDR = "localhost";
    private static final int HOST_PORT = 8025;

    public static void main(String[] args) {
        Server websocketServer = new Server(HOST_ADDR, HOST_PORT, "/ws", null, InnerSimpleServerEndpoint.class);

        try {
            websocketServer.start();
            Thread.sleep(TimeUnit.MINUTES.toMillis(5));
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        websocketServer.stop();

        System.out.println("Done.");
    }

    @ServerEndpoint("/myapp")
    public class InnerSimpleServerEndpoint {
        @OnOpen
        public void onOpen(Session session) {
            System.out.println("Connection received for "+session.getRequestURI());
        }

        @OnMessage
        public void onMessage(String message, Session session) {
            System.out.println("Message received: "+message);
        }

        @OnClose
        public void onClose(Session session, CloseReason closeReason) {
            System.out.println("Session closed, reason: "+closeReason);
        }
    }
}

The simple client:
package tyrus.example;

import java.io.IOException;
import java.net.URI;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;

import org.glassfish.tyrus.client.ClientManager;

public class SimpleClient
{
    private static final String DEF_WS_URL = "ws://localhost:8025/ws/myapp";

    public static void main(String[] args) {
        ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
        ClientManager client = ClientManager.createClient();

        try {
            client.connectToServer(new ClientEndpoint(), cec, new URI(DEF_WS_URL));
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Done.");
    }

    private static class ClientEndpoint extends Endpoint {
        @Override
        public void onOpen(Session session, EndpointConfig config) {
            System.out.println("ClientEndpoint: server session opened: "+session);

            session.addMessageHandler(new MessageHandler.Whole<String>() {
                @Override
                public void onMessage(String message) {
                    System.out.println("ClientEndpoint: received message: "+message);
                }
            });

            try {
                session.getBasicRemote().sendText("Hello server!");
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

And finally the non-inner class server endpoint that works when the server uses it:
package tyrus.example;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/myapp")
public class SimpleServerEndpoint {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connection received for "+session.getRequestURI());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Message received: "+message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("Session closed, reason: "+closeReason);
    }
}

A: On the server, the endpoint can be an inner class, but it also has to be static. Even though the code runs and serves, for some reason, I am only able to make it work if the server endpoint is static as well. Ie: Change to add static in the server code:

    @ServerEndpoint("/myapp")
    public static class InnerSimpleServerEndpoint {
    }

You may also want to add

    @OnError
    public void onError(Session session, Throwable throwable) {
      //...
    }

A: Endpoint can be inner class, BUT it has to be instantiable - class ClientEndpoint in your failing example is private, thus Tyrus cannot create instance of it.
Change it to public and it should work as expected.

A: The inner class should be static otherwise it can not be instantiated without an instance of the outer class. Look at this:
https://www.javatpoint.com/why-we-use-static-class-in-java
So if the the class that is annotated with @ServerEndpoint is not static it can not be instantiated.


text:
Q: How to add multiple state in one cubit in flutter bloc pattern? I was developing an application in flutter which does OTP based authentication to log in. Earlier I was managing the states in the class itself so that I can use the setState method to render the UI accordingly. Then I changed into flutter_bloc cubit pattern to manage the states. But I fail to understand that how can I keep track of multiple states in one cubit.
Consider the following code of State and Cubit,

**State**.

@immutable
abstract class LoginState {}

class LoginInitial extends LoginState {
  final Map loginState;
  LoginInitial({this.loginState});
}

**Cubit**
class LoginCubit extends Cubit<LoginState> {
  Map loginState = {
    "isPhoneSubmitted": false,
    "isOtpArrived": false,
  };
  LoginCubit()
      : super(
          LoginInitial(
            loginState: {
              "isPhoneSubmitted": false,
              "isOtpArrived": false,
            },
          ),
        );

  void sendOtp() {
    emit(
      LoginInitial(
        loginState: {
          "isPhoneSubmitted": true,
          "isOtpArrived": false,
        },
      ),
    );
    Future.delayed(Duration(seconds: 4), () {
      emit(
        LoginInitial(
          loginState: {
            "isPhoneSubmitted": true,
            "isOtpArrived": true,
          },
        ),
      );
    });
  }
}

Here, Initially, I'm setting both values inside the map as false. And when the user clicks on the button setting the isPhoneSubmitted to true. And a few seconds later isOtpArrived to true(In future after getting OTP). However, I don't think this is the right approach to implement the pattern. Consider If I have 10 properties in a class and I'm sending a map of 10 properties each time when emit method is called.
Can someone help me understand or implement the best practice to hold/update multiple states to the widget the Cubit is listening to?
Also, in the widget, this is how I'm listening to the changes,
 BlocBuilder<LoginCubit, LoginState>(builder: (context, state) {
                final data = (state as LoginInitial).loginState;
                if (!data["isPhoneSubmitted"]) {
                  return phoneNumberSubmitWidget();
                } else {
                  return codeVerificationWidget();
                }
              }),

A:
However, I don't think this is the right approach to implement the pattern.

You are correct. The first step for complex state switches is to not use Cubit but an actual Bloc. Cubits are meant for very simple data with basically no state flow logic at all. Like an int. Or maybe a DarkTheme/LightTheme switch. Or maybe the language, where it can only ever be one and exactly one.
But you have a complex flow. With "in-between" states. So use a Bloc and read the tutorial on this, in this case probable the login tutorial.


text:
Q: How to constrain the navigation bar and prevent it from moving I am creating NSDate objects, and I have a navigation bar that I am trying to maintain in a static position at the top of the screen.
I want my NSDate objects to be created underneath the navigation bar, but they are being created above the navigation bar and push the navigation bar down.

This is my insertNewObject function
- (void)insertNewObject
{
if (!_objects) {
    _objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

I suspect it has to do with this function which calls the insertNewObject method. Specifically I believe that the self call means that it is telling it to create it at the top of the ViewController.
- (IBAction)addData:(id)sender {
// call insertNewObject
[self insertNewObject];
}

How can I constrain my navigation bar and prevent the new NSDate objects from being created above the navigation bar?

A: If you want to use a navigation bar (not a navigation controller), then you need to use a UIViewController rather than a UITableViewController. A UITableViewController's view is the table view, so anything you add to the view becomes a subview of the table. With a UIViewController, you can add the navigation bar at the top, then add the table view underneath. You'll have to add an IBOutlet for the table view, and make the controller the data source and delegate for your table (those things are automatic when you use a UITableViewController).
The alternative, of course, is to just embed your UITableViewController in a navigation controller.


text:
Q: Domino Server is installed on Unix or Windows? Can someone please let me know How to programmatically find out whether the Domino server is installed on Unix or Windows.
Is there any Domino server API to find out in which OS(OS related information) the domino server is running.

A: You can use the formula @Platform function for this.

When it is used in column, selection, or scheduled agent formulas,
  @Platform returns the current platform where the database resides. If
  the database resides on a server, @Platform returns the server
  platform; if the database resides locally, @Platform returns the
  workstation platform.

A: If you open the main Domino Directory on the server ( names.nsf ) and look at the server/servers view you will see a list of all the Domino servers that are setup. Each record contains a reference to the OS that is running the server.

A: In LotusScript or with the COM classes, use NotesSession.Platform().  In Java, use Session.getPlatform().  Note that in either case, your code must be running on the actual server that you are testing.


text:
Q: How to correctly throw an error from child process I have an express controller, and my idea was to execute child process, and if there was an error , throw it and catch on a client. If I do it like below, when I throw error it crash whole running process, I can't handle an error and I have to restart my server.
const { fork } = require('child_process')

const foo = asyncHandler(async (req, res) => {
  const _process = fork(path.join(__dirname, '../myfile.js'))

  _process.send({ data: req.body })
  _process.on('message', (message) => {
    if (message.error) {
      res.status(500)
      throw new Error(message.error)
    } eles res.status(200).send()
  })
})

If I throw an error like this, it ok, I can handle it on client, nothing crashes but this time it throws an error before child process ends.
const { fork } = require('child_process')

const foo = asyncHandler(async (req, res) => {
  const _process = fork(path.join(__dirname, '../myfile.js'))
  let _message = null
   _message.error = 'THIS MESSAGE WILL BE THROWN'

  _process.send({ data: req.body })
  _process.on('message', (message) => {
    _message = message
  })

  if (_message.error) {
    res.status(500)
    throw new Error(message.error)
  } else res.status(200).send()
})

So, does anyone know how to throw an error correctly after child process ends?


text:
Q: Why does my Pygame window flicker when animating objects? So my pygame window just won't stop flickering. I know if only one item is in snake.snakearray, it won't flicker.
#class for the array
class snake:
  snakearray = [[ScreenConfigs.width / 2,ScreenConfigs.height / 2],[ScreenConfigs.width / 2,ScreenConfigs.height / 2]]
  direction = "up"
  increment = 0.1

#loop to draw the snake
while Running:
 for snakeBit in snake.snakearray:
  pygame.draw.rect(display,"black",(0,0,ScreenConfigs.width,ScreenConfigs.height))
  pygame.draw.rect(display,"white",(snakeBit[0],snakeBit[1],30,30))
  pygame.display.flip()

I tried putting the pygame.display.flip() outside of the loop and it only drew that last rectangle. (because when you call pygame.draw.rect, it disregards the last one drew)

A: Multiple calls to pygame.display.update() or pygame.display.flip() causes flickering. Updating the display once at the end of the application loop is sufficient. But you also need to clear the display only once before drawing the scene:
while Running:
    # [...]

    # clear display
    pygame.draw.rect(display,"black", (0,0,ScreenConfigs.width,ScreenConfigs.height))

    # draw scene
    for snakeBit in snake.snakearray:
        pygame.draw.rect(display,"white",(snakeBit[0],snakeBit[1],30,30))

    # update display
    pygame.display.flip()

Clearing the display can also be done with fill:
while Running:
    # [...]

    # clear display
    display.fill("black")

    # draw scene
    for snakeBit in snake.snakearray:
        pygame.draw.rect(display,"white",(snakeBit[0],snakeBit[1],30,30))

    # update display
    pygame.display.flip()

Each object in the scene is drawn to the pygame.Surface object associated with the display. To create animated objects, the entire scene must be redrawn in each frame. Therefore, the display must be cleared at the beginning of each frame in the application loop. If you draw on the Surface associated to the PyGame display, this is not immediately visible in the display. The changes become visible, when the display is updated with either pygame.display.update() or pygame.display.flip().


text:
Q: Why is my page not redirecting even though it does not error out? I have this function that utilizes jQuery's post feature to send an ajax request to my logout handler, which destroys the session (set by asp.net) and redirects to the login page:
<script type="text/javascript">
    //<![CDATA[
    function doLogout() {
        var conf = false;
        conf = confirm("Really log out?");
        if (conf === true) {
            $.post("logout.ashx");
        }
    }
    //]]>
</script>

So far, the logout link functions fine: user clicks it, the confirmation box pops up, and if they click yes it loads up the logout handler:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    With context
        If .Session IsNot Nothing Then
            context.Session.Clear()
            context.Session.Abandon()
        End If
        .Server.Transfer("default.aspx", False)
    End With
End Sub

I have tried using Response.Redirect as well, nothing different happens.
I have verified by tracing that everything is functioning fine. There are no javascript or asp.net errors. The only problem is the page in the browser does not change.
Any ideas?

A: When you post an ajax request you can redirect at the server all you want, but all you are doing is determining which page ultimately responds to that ajax request.  If you want to redirect the entire page, you need to post from the entire page, or build the javascript that handles the response to know when you'll want to redirect and do it there.

A: The problem is that the callback to the server is an asynchronous javascript call and not a page postback.
if you wish to change the page in the browser you will also have to do this in your javascript function after the call to your logout function.


text:
Q: How can I run a command after fabric updates my servers? Specifically, after I update several servers, I want to print out how many servers were updated. Any advice?

A: One option would be to run the fab task(s) via fabs execute method. The result of the execute method is a dict with the hosts as keys, which would give you a hint for the number of processed hosts.


text:
Q: Data link to accdb file I want to make a data link(Connection Managers) from SQL server 2012, 64 bit to an accdb Microsoft access 2013 file.
I am using Microsoft office 12.0 Access Database engine OLE DB Provider and I have changed the Run64BitRuntime properties to False. However, I am receiving the following error:
 Test Connection Failed because of an initializing provider. Unrecognized database format 'C:\Access\Myfile.accdb'.

Also I have already  run these queries
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' ,
N'AllowInProcess' , 1
GO EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' ,
N'DynamicParameters' , 1

Thanks for your replies.


text:
Q: How to display web2py errors directly (auto redirect to ticket) When developing a web2py application, its pretty normal to have various syntax errors, db issues and such.
However, when debugging these problems (in a non production system), a ticket link is presented by default, instead of the actual ticket.
Is there a way to auto redirect to the actual ticket , eliminating the need to click (and wait for the actual ticket to load)?

A: Try adding something like the following to your /web2py/routes.py file:
error_message_ticket='''
  <html><head>
    <script language="javascript">
      location.replace("/admin/default/ticket/%(ticket)s")
    </script>
    <!-- this is junk text else IE does not display the page: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx //-->
  </head></html>'''

For more details, see Routes on Error in the online book.


text:
Q: MySQL nested query Lookup error I am trying to use nested query to avoid having to issue two different queries. My nested query is as shown below;
INSERT INTO roles (
   _id,
   user_id,
   user_role)
VALUES (
((SELECT _id FROM roles ORDER BY _id DESC LIMIT 1)+1), '454', 'USER')

But when I execute I get;

Lookup Error - MySQL Database Error: You can't specify target table
  'roles' for update in FROM clause

Is there any work around to this query or I simply can't do insert and select on the same table?

A: If you're using MySQL >= 4.0.14, you can use INSERT ... SELECT:
INSERT INTO roles (
  _id,
 user_id,
 user_role
)
SELECT _id + 1, '454', 'USER' FROM roles ORDER BY _id DESC LIMIT 1

However, it looks as though you probably just want to make your _id column AUTO_INCREMENT and then don't provide any value for it.  MySQL will do the rest:
ALTER TABLE roles MODIFY _id INT AUTO_INCREMENT;
INSERT INTO roles (user_id, user_role) VALUES (454, 'USER');

A: INSERT INTO roles
SELECT _id+1,'454', 'USER' FROM roles ORDER BY _id DESC LIMIT 1


text:
Q: Time intelligence based on different year types I am developing an OLAP cube using SQL Server 2008 SSAS.
I have a dimDate table, and my fact data needs to be sliced by two different year types.

*

*First is calendar year, that is January 1 to December 31

*Second is manufacturing year of agricultural crops, which starts at July 1st and ends at June 30th
Here is how my date table looks like:

So YearG, MonthG and QuarterG represents the manufacturing values.
All is working as long as I slice the fact data straight on these fields
But trying to use more sophisticated calculations such as parallel period, ytd etc does not work on this well as it calculates based on the year derived from the date key, which is the calendar year.
Here is an MDX example for a YTD calculation I perform in this cube:
AGGREGATE((ANCESTOR([Dim Date 2].[Time].Currentmember, [Dim Date 2].[Time].[Year])), [Measures].[NIS])

How can I make it show the correct aggregation for the manufacturing year? That is sum all the values of the measure from July 1st to the currently sliced time?
Thank you


text:
Q: NyroModal, access data from parent page I am using a nyroModal with an Iframe via target=_blank. In the parent page I have a set of checkboxes and base on what is checked i want to add some extra data to the modal window.
Is there i way that I can access those checkboxes from the modal?
I have also tried to modify the link to the page and send them info from checkboxes as parameters using
    $(mapModalSelector).nyroModal();
    $(mapModalSelector).click('click', function (e) {
        e.preventDefault();
        var link = 'base/view/'+jsonData;
        $.nmManual(link);

        return false;
   });

but in this way it loops somehow and i get extra close buttons and the page is not rendered.

A: try it something like this , For example reading text box present on parent then
 parent.document.getElementById('myTxtBoxId').value


text:
Q: How to Update old values with new values in Spark? How to Update old values with new values in Spark
E.g., in fruits Column I want to replace Apple value with Banana using PySpark

A: df = df.replace({'Apple': 'Banana'}, 'fruits')


text:
Q: Non-linear regression, force the curve to go through a starting point I have two sets of points:
x=[300  292 310 330]
y=[0.01 60  120 160]

I need to find curve of best fit through those points. I know it has a form:
$$x=C_1+C_2\text{log}(y)+C_3y$$
Using nlinfit in Matlab does the job as shown:
But the problem I have is that the curve does not start at the initial point (0.01, 300) and I need it to start at this exact point. How to achieve this?


text:
Q: htaccess Redirect to a folder and then rewrite again Hopefully, this is not duplicated.
I´m trying to bring structure to my site and be clean, I´m separating content. It is an angular app, I´mean 2 apps in one domain separated thru the folder name
So I´m trying following:
domain.xy/folder
should internal redirect to
domain.xy/anotherfolder
after that, I´m using angular hashtag links and I don´t want them to be shown. When the file or folder doesn´t exist then add a #
domain.xy/link1
becomes to
domain.xy/#/link1
I´m trying around with this code, and it´s working fine if not separated. I thought When the first rule passed with flag [L] It will do another loop with the rewritten URL but Here I got the error that this is not working, and like he is not passing the first rule when I type something like
domain.xy/folder/link1
This is the latest code I was trying. Maybe someone sees the error in my thinking and give me a hint or advise? Thanks in advance.
RewriteEngine On
Options FollowSymLinks

RewriteBase /

# Rewrites folder
RewriteRule ^supplier/(.*)$ /_supplier/$1 [L,NC]
RewriteRule ^agency/(.*)$ /_agency/$1 [L,NC]

# Folder doesn`t exist then it is a angular link
# rewrite with # tag
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]

A: I found myself with a false use of angular $locationProvider.html5Mode(true); and rewriting URLs.
I changed now the structure for the use of hashbang in my project. Now it's working correctly.
Thank you all for viewing.


text:
Q: Using collection_select in Rails form? I need a multiple selection choice in a Rails form to create a new Topic, when creating a new Topic users can select a Language from the drop-down menu.
Topic.rb
class Topic < ActiveRecord::Base
  has_one :language
end

language.rb
class Language < ActiveRecord::Base
  belongs_to :topic
end

How would I use the collection_select method to have a user select a language?
The topic DB has a language field.
The language DB has a name field which I want to display to the user and a permalink field which I want to be the value of the dropdown that is stored in the topic db.

A: collection_select(:topic, :language_id, Language.all, :permalink, :name)

A: Collection Select
My understanding is that collection_select is not dependent on your associations
According to the Rails Documentation, and based off our own experience, the collection_select functionality can work with "pure" data, like this:
<%= subscriber.collection_select(:subscriber_id, Subscriber.where(:user_id => current_user.id), :id, :name_with_email, include_blank: 'Subscribers') %>

Selecting A Language
In your case, there are several issues which need to be addressed
Firstly, your foreign_key needs to be corrected in the topic database:

The topic DB has a language field

Your topic DB needs to reference langugage_id, like this:

id | language_id | created_at | updated_at

Once this has been done, it means you can populate the topics db with the language_id required to make to make the relation work. I'd use this collection_select for this:
<%= form_for @topic do |f| %>
    <%= f.collection_select(:langauge_id, Language.all, :id, :name, include_blank: 'Languages') %>
<% end %>


text:
Q: How to use solve this using a subquery? Please consider the following tables:
Table Name: Person
Person_Id   Name

Table Name: DVD
DVD_ID  Owner_ID  Title

I want a query that returns the list of DVDs that belong to owners who own "Superman". Here is my solution:
SELECT p.name,d.dvd_id
FROM  DVD d,Person p
WHERE p.person_id = d.dvd_id
AND Title = 'Superman' ;

My interviewer was expecting me to use a subquery. Is that possible? Is my query the right approach?

A: Hope so, This will help you.
select dvd_id
from DVD
where Owner_ID in
(select person_id
 from person
 where name = 'Superman')

using = where i used in will also help in same way.

A: Please check this:
select
    *
from
    DVD
where
    Owner_ID=(select Person_Id from Person where Name='Superman')

Given name superman is unique.


text:
Q: Spring - SOAP: "No endpoint mapping found for.." I have this problem:
 [L: org.springframework.ws.server.EndpointNotFound] - [M: No endpoint mapping found for
 [SaajSoapMessage {http://spring.io/guides/gs-producing-web-service}getCountryRequest]]

following this guide (no xml config).
My service config:
@Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {

    MessageDispatcherServlet servlet = new MessageDispatcherServlet();
    servlet.setApplicationContext(applicationContext);
    servlet.setTransformWsdlLocations(true);
    return new ServletRegistrationBean(servlet, "/ws/*");
}

@Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {

    DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
    wsdl11Definition.setPortTypeName("CountriesPort");
    wsdl11Definition.setLocationUri("/ws");
    wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
    wsdl11Definition.setSchema(countriesSchema);
    return wsdl11Definition;
}

@Bean
public XsdSchema countriesSchema() {

    return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}

My endpoint:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

@Endpoint
public class CountryEndpoint {
  private static final String NAMESPACE_URI = "http://spring.io/guides/gs-producing-web-service";

  private CountryRepository countryRepository;

  @Autowired
  public CountryEndpoint(CountryRepository countryRepository) {
    this.countryRepository = countryRepository;
  }

  @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
  @ResponsePayload
  public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) {

    GetCountryResponse response = new GetCountryResponse();
    response.setCountry(this.countryRepository.findCountry(request.getName()));

    return response;
  }
}

and the xsd file:

<xs:element name="getCountryRequest">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="name" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="getCountryResponse">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="country" type="tns:country"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:complexType name="country">
    <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="population" type="xs:int"/>
        <xs:element name="capital" type="xs:string"/>
        <xs:element name="currency" type="tns:currency"/>
    </xs:sequence>
</xs:complexType>

<xs:simpleType name="currency">
    <xs:restriction base="xs:string">
        <xs:enumeration value="GBP"/>
        <xs:enumeration value="EUR"/>
        <xs:enumeration value="PLN"/>
    </xs:restriction>
</xs:simpleType>

One note, I changed the import for service config because I'm on Spring 1.3.3, instead the guide it's on Spring 1.4 and more, so my import:
import org.springframework.boot.context.embedded.ServletRegistrationBean;

it's deprecated.
Thanks for any suggestion :)


text:
Q: Redis: Get all keys from queue which have a value equal to some criteria I have a bunch of jobs I store on redis, each identified by a special key, with a hash as their value that contains some information. These jobs get picked up, computed, and once they are done, they have a success field that is set to true if the computation was finished successfully.  I want to populate a list of all the keys that have the success key in their value hash set to true.
e.g. redis storage:
foo_key_1 => {bar_hash_key: bar_value, baz_hash_key: baz_value, success: true}
foo_key_2 => {bar_hash_key: bar_value, baz_hash_key: baz_value, success: false}

With the example above, I'd like a simple, efficient way of scanning through all keys in redis and their success field, and end up with [foo_key_1] as a result.
Currently my approach is as follows (in ruby pseudocode):
# redis is a connection to my redis server
all_keys = redis.keys                      # list of all keys in redis
for i in all_keys do                       # iterate through all keys in redis
  if (redis.hgetall i)["success"] == true  # if that key has success = true attrib
    completed_keys.append(i)               # append that key to a new list
  end
end

The problem, as you might guess, is I have a lot of keys on redis, and this, albeit O(N) in performance gets fairly sluggish in terms of performance, due to its iterative nature.  I have pored through the redis docs/commands but nothing leapt out at me as a potential candidate to solve this problem more efficiently, I am no redis guru, but it seems fairly straightforward, you put stuff in and take stuff out.  Are there any possible vectorized operations I might have overlooked?
Many thanks.

A: You cannot do it without iterating through all keys, because redis supports only key fetching. You can reduce that complexity if you happen to know a pattern for the keys where you have to look, even in this case redis will fetch all the keys in background(with some optimizations, because it will fetch them in batches http://www.rubydoc.info/github/redis/redis-rb/Redis:scan). Something like:
$redis.scan_each(match: "foo*").to_a

You can find how to write your own pattern here https://redis.io/commands/KEYS
However, if you can control what values the keys take you can make them take a value with a little hint to help you in this search, like:

*

*let's make each key with this form "foo#{your_number}:#{success_bool}"

*when search use this pattern "foo*:1"

A: To do this efficiently only using Redis, you would have to keep an updated, "Redis-queryable", SET or LIST of success/completed keys.
At a fundamental level, it sounds like what you really have here is a job queue (and a second job queue for the successful first jobs). Unless you specifically want to implement this on your own, have you looked into job queue implementations?


text:
Q: how to extract jenkins credentials to python script I am having a groovy script that uses some credentials from jenkins credentials like this:
stage('Download tokens') {
        withCredentials([string(credentialsId: 'jenkins-token', variable: 'token')])

I want something similar to this in python to retrive the token in order for passing it to a python module which needs the token to e authenticated. Is there a way I can do this?
Thanks,

A: I got it work by doing this:

stage('Download tokens') {
        withCredentials([string(credentialsId: 'jenkins-token', variable: 'token')]) {

            sh "export token=${token}"

             sh """
                   export token="${token}"

                   python3 script.py
             """

        }
    }

and in the script itself I called the token I need like this:
vault_token = os.environ['token']


text:
Q: Is there a demo on how to integrate Amazon Connect and Google DialogFlow for NLP? I would like to get an understanding as to how to use Amazon Connect's capability to connect with the Google Dialogflow for Natural Language Processing (NLP).

A: This is not possible. Amazon Connect provides NLP exclusively via Amazon Lex

A: You use Lex to record the utterance, then in the validation Lambda function, you send the Lex transcript to Dialogflow. Set the Lambda function's response as appropriate based on Dialogflow's response.
Edit: While technically possible, I have a hard time seeing logical reasons for doing this - additional cost using both Lex and Lambda, and you'd have to maintain both Lex and Dialogflow. Not saying Lex is perfect but it is a good product, if you're using Amazon Connect I don't see how a cost-benefit analysis could favor the use of Dialogflow over Lex.


text:
Q: BlueTooth Low Energy app is not working on My Devices Nexsus 4 and Nexsus Tab 7 I have Downloaded couple of BLE Apps from Google play. I have enabled Both Devices Blue Tooth. Whenever i am scanning Devices but no devices is showing in the list. How does BLE works, please suggest me. I am new to use BLE. Also I have downloaded sample code from Git hub "https://github.com/StevenRudenko/BleSensorTag". This callback method is not called.
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

    @Override
    public void onLeScan(final BluetoothDevice device, int rssi,
            byte[] scanRecord) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("TAG", "name : " + device.getName()
                        + "describeContents : " + device.describeContents()
                        + "getBondState : " + device.getBondState()
                        + "getAddress : " + device.getAddress()
                        + "getType : " + device.getType() + "toString: "
                        + device.toString());
                mLeDeviceListAdapter.addDevice(device);
                mLeDeviceListAdapter.notifyDataSetChanged();
            }
        });
    }
};

please suggest me, how BLE works, Any help will we appreciated.

A: Android devices does not support client mode. They only can work as a Master in connection (They must be GATT client too because the most common scenario is an Android device collecting information from sensors/beacons which they are considered as GATT servers).
The problem you are facing right now is that your devices are both listening for advertising packets but really there is nothing generating those packets. You need a sensor/beacon in order to test Bluetooth Low Energy Android capabilities.


text:
Q: what is the integration of $\int\cot(e^x)\cdot e^x dx$? what is
$$
\int\cot(e^x)\cdot e^x dx
$$
This is my answer is it right
$$
u=e^x\\
du=e^x dx\\
dx=\frac{1}{e^x}du
$$
Then $$\int\cot(u)\cdot u \frac{1}{u}du=\int \cot(u)\ du=\csc^2(u)$$
Is this answer right

A: $$\int e^x\cot{e^x}dx=\int\frac{e^x\cos{e^x}}{\sin{e^x}}dx=\int\frac{1}{\sin{e^x}}d(\sin{e^x})=\ln|\sin{e^x}|+C$$

A: You have the right idea. Using $u=e^x$, we have $du=e^x\,dx$ so $$\int\cot(e^x)\cdot e^x\,dx=\int\cot u \, du=\int\frac{\cos u}{\sin u}\, du$$ Now let $v=\sin u$. Then $dv=\cos u\, du$ so $$\int\cot u\, du=\int\frac1v\, dv=\ln|v|+C$$ where $C$ is a constant.
Therefore $$\boxed{\int\cot(e^x)\cdot e^x\,dx=\ln|\sin(e^x)|+C}$$

A: No, your answer is not correct, but you were on the right track for the most part. Your problem was that you were looking at the wrong table when you were taking the integral of $\cot{u}$. Instead of the antiderivate of the cotangent function which is $\int\cot{x}\:dx=\ln{|\sin{x}|}+C$, you used its derivative $\left(\frac{d}{dx}\cot{x}=-\csc^2 x\right)$ to finish off the problem (you also dropped the minus sign for some reason). You got it completely backwards. Anyway, this is a simple integration by substitution (sometimes called u-substitution) problem. Integration by substitution is nothing more than the chain rule done backwards.
$$
\int\cot e^x\cdot e^x dx=\\
u=e^{x}\implies\\
\frac{du}{dx}=\frac{d}{dx}e^{x}\implies\\
\frac{du}{dx}=e^{x}\implies\\
dx=\frac{du}{e^{x}}\\
=\int\cot u\cdot u \frac{du}{u}=
\int\cot{u} du=
\ln{|\sin{u}|}+C=
\ln{|\sin{e^{x}}|}+C
$$
Answer: $\ln{|\sin{e^{x}}|}+C$.


text:
Q: Reading Text From Row 1 Column 2 (ListView)
I'm trying to write Column 1 + Column 2 for every row but I keep getting:

I actually had it working at one point, but I re-opened the project and now it doesn't.
Any idea as to what's happening?

A: the discription of listitem.clear:Removes all items and columns from the control.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.clear(v=vs.110).aspx
Since the are no items in the listview you cannot retieve the first one(listview1.items[0])

A: You trying to access an array where the there is no data. You can surround it with a try catch also to avoid crash. or test there is data with an if clause
if(listview1.Items[0].subItems[1]!=null)
  sr.write(...);


text:
Q: Angular Material So i have installed angular, angular-material, angular-aria, angular-animate dependencies to my system.
I just want to test out this up and coming styling method.
It seems I'm stuck at the beginning. Can you tell me whats wrong with the code?
These are my 3 files.

*

*app.js

*styles.css

*index.html

My output is {{title1}} at the centre-top of the webpage.

angular.module('MyApp', ['ngMaterial'])
  .controller("MyController", function($scope) {
    $scope.title1 = 'Lol';
  });
.buttondemoBasicUsage section {
  background: #f7f7f7;
  border-radius: 3px;
  text-align: center;
  margin: 1em;
  position: relative !important;
  padding-bottom: 10px;
}
.buttondemoBasicUsage md-content {
  margin-right: 7px;
}
.buttondemoBasicUsage section .md-button {
  margin-top: 16px;
  margin-bottom: 16px;
}
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="styles.css">
  <link rel="stylesheet" type="text/css" href="angular-material.css">
  <title>AngularJS</title>

    <md-content>

        <md-button>{{title1}}</md-button>

    </md-content>

A: This is really just a matter of referencing the files to the correct places in your project.
Replacing all your local references to CDN's, your code is working flawlessly: http://codepen.io/qvazzler/pen/vOaqXW
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/0.10.0/angular-material.css">
    <title>AngularJS</title>

        <md-content>

                <md-button>{{title1}}</md-button>

        </md-content>

A helpful thing to do in these cases is to open the Chrome developer tools (CTRL + SHIFT + I), get to the Console section and look at the error messages.
Link to guide on using DevTools: https://developer.chrome.com/devtools
If I were to actually answer your question on why it's not working, we'd have to see your file structure, but as it is common that js files are located in a folder separate from your html files, you'd have to add "../" to the beginning of your href's to access a parent folder.
Example:
[My Project]
jsfolder
- angular.js
- angular-material.js
cssfolder
- angular-material.css
- styles.css
html
- index.html

To access angular.js from your index.html, you'd have to write href="../jsfolder/angular.js"

A: I fixed your imports.

angular.module('MyApp', ['ngMaterial'])
  .controller("MyController", function($scope) {
    $scope.title1 = 'Lol';
  });
.buttondemoBasicUsage section {
  background: #f7f7f7;
  border-radius: 3px;
  text-align: center;
  margin: 1em;
  position: relative !important;
  padding-bottom: 10px;
}
.buttondemoBasicUsage md-content {
  margin-right: 7px;
}
.buttondemoBasicUsage section .md-button {
  margin-top: 16px;
  margin-bottom: 16px;
}
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="styles.css">
  <link rel="stylesheet" type="text/css" href="angular-material.css">
  <title>AngularJS</title>

    <md-content>

        <md-button>{{title1}}</md-button>

    </md-content>

A: I suggest to use typescripts or a kind of that option, first steps are hard but later you ll be in better solution.
please dont make writing code pain and gain.
happy codings.


text:
Q: How to tag a certain folder in my source tree? I am using the mercurial command line and I can't find out how to tag a certain folder. My source repository consists from different libraries so I'd like to tag them separately.
I also mistakenly tagged my whole source tree, so I'd like to know how do I erase a tag before I create the new tag.

A: You can only tag a revision, not a specific file or folder.
To erase a tag, issue the following command:
hg tag --remove TAG

To move a tag to a different revision:
hg tag --force TAG --rev REV

Note that in both cases, you'll end up creating a new changeset on top of the one you're at, you can't eradicate the commit that was created when the original tag was made.

A: As Lasse states, you can only tag a revision of the entire repository in Mercurial. In order to tag different components in your repository you could consider using Mercurial Subrepositories. Subrepositories allow you to treat individual components (what you are calling libraries) as independent repositories, and pull them together into a single, functional unit.
In terms of BitBucket's limitation on private repos - you could consider making some of them public, or placing the main repository on a local machine or server if you're concerned about exposing source publicly. If you're interested in hosting something yourself, Redmine is a good free tool that would allow you to serve as many repos as you want.


text:
Q: SQL dependency on relational tables I have two related tables (tbVehicles and tbVehiclesDoc) I am running the below sql dependency but it is firring many time and my program freezes. please assist.
I want the program to update these tables when another user modifies them.
my Code:
Public Sub getdata()
    Try
        If tbdataset.Tables.Contains("tbVehicles") Then

            If tbdataset.Tables("tbVehiclesDoc") IsNot Nothing Then
                For f As Integer = tbdataset.Tables("tbVehiclesDoc").ChildRelations.Count - 1 To 0 Step -1
                    tbdataset.Tables("tbVehiclesDoc").ChildRelations(f).ChildTable.Constraints.Remove(tbdataset.Tables("tbVehiclesDoc").ChildRelations(f).RelationName)
                    tbdataset.Tables("tbVehiclesDoc").ChildRelations.RemoveAt(f)
                Next
                tbdataset.Tables("tbVehiclesDoc").ChildRelations.Clear()
                tbdataset.Tables("tbVehiclesDoc").ParentRelations.Clear()
                tbdataset.Tables("tbVehiclesDoc").Constraints.Clear()
                tbdataset.Tables.Remove("tbVehiclesDoc")
            End If
            tbdataset.Tables.Remove("tbVehicles")
            tbdataset.EnforceConstraints = True
        End If
        gridVehicles.DataSource = Nothing
    Catch ex As Exception
        MsgBox(ex.ToString)
        '   Exit Sub
    End Try
    command.Notification = Nothing
    Dim dependency As New SqlDependency(command)
    AddHandler dependency.OnChange, AddressOf dependency_OnChange

    Dim adapter As New SqlDataAdapter(command)
    adapter.Fill(tbdataset, "tbVehicles")
    '----
End Sub

Private Sub toupdate()
    If CanRequestNotifications() Then
        If connection Is Nothing Then
            connection = New SqlConnection(GetConnectionString())
            connection.Open()
        End If
        If connection.State = ConnectionState.Closed Then
            connection.Open()
        End If
        If command Is Nothing Then
            command = New SqlCommand(GETSQL(), connection)
        End If

    End If
    getdata()
End Sub

Private Function GETSQL() As String
    Return "Select Rtrim(VehcID) as VehcID,RTrim(VehcModel), Rtrim(VehcRegNo) as VehcRegNo, Rtrim(VehcFourWheel), Rtrim(VehcCondition), Rtrim(VehcLastKM),Rtrim(VehcBranch), Rtrim(VehcDepartment), Rtrim(VehcDriver), Rtrim(VehcRemarks), VehcPic from dbo.tbVehicles"
End Function

Private Sub dependency_OnChange(ByVal sender As Object, ByVal e As SqlNotificationEventArgs)

    ' This event will occur on a thread pool thread.
    ' It is illegal to update the UI from a worker thread
    ' The following code checks to see if it is safe
    ' update the UI.
    Dim i As ISynchronizeInvoke = CType(Me, ISynchronizeInvoke)

    ' If InvokeRequired returns True, the code
    ' is executing on a worker thread.
    If i.InvokeRequired Then
        ' Create a delegate to perform the thread switch
        Dim tempDelegate As New OnChangeEventHandler( _
            AddressOf dependency_OnChange)

        Dim args() As Object = {sender, e}

        ' Marshal the data from the worker thread
        ' to the UI thread.
        i.BeginInvoke(tempDelegate, args)

        Return
    End If

    ' Remove the handler since it's only good
    ' for a single notification
    Dim dependency As SqlDependency = _
        CType(sender, SqlDependency)

    RemoveHandler dependency.OnChange, _
       AddressOf dependency_OnChange

    ' Reload the dataset that's bound to the grid.
    getdata()
End Sub


text:
Q: Re-connect to a specific AccessPoint using OpenNETCF I am attempting to have an application for Windows Mobile CE re-connect to a specific WEP Enabled network if it becomes available.  I believe that this code scans through the currently available access points to get a reference to the network I need:
                // we have communicated with the server, so save the access point for future reference
                INetworkInterface[] wniNet = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface wni in wniNet)
                {
                    if (wni is WirelessNetworkInterface)
                    {
                        WirelessNetworkInterface wWireless = wni as WirelessNetworkInterface;
                        //if (mwniServerConnection == null)
                        if (string.IsNullOrEmpty(msAccessPointName))
                        {
                            MessageBox.Show("assigning: " + wWireless.AssociatedAccessPoint.ToString() + " to instance var.", "testing");

                            // first attempt to save the WEP enabled access point to the preferred networks
                            //WirelessZeroConfigNetworkInterface wWifiConnection = new WirelessZeroConfigNetworkInterface();
                            //wWifiConnection.AddPreferredNetwork(wWireless.AssociatedAccessPoint.ToString(),
                            //    wWireless.InfrastructureMode,
                            //    "9876543210",
                            //    1,
                            //    wWireless.AuthenticationMode,
                            //    WEPStatus.WEPEnabled,
                            //    null);
                            mwniServerConnection = wWireless;
                            msAccessPointName = wWireless.AssociatedAccessPoint.ToString();
                        }
                    }
                }

I am a little out of my depth having found the OpenNETCF library yesterday, I'd like to ask if there are any examples of code that can test if the network ac is available, and to connect if it is.

A: I found that using adapter.SetWirelessSettings re-connects the hand held device to the specific access point found in order communicate on the specific network my server runs on:
public static bool AttemptToReConnectAccessPoint()
{
    bool wbRtn = false;

    // attempt to connect to the proper network
    if (U.mapAccessPoint != null)
    {
        // if we are currently on the right access point, we don't want to blow off the connection
        if (CheckIfAccessPointIsCurrent()) return true;
        foreach (OpenNETCF.Net.Adapter wAdapter in OpenNETCF.Net.Networking.GetAdapters())
        {
            bool wbFound = false;
            foreach (OpenNETCF.Net.AccessPoint wAccessPoint in wAdapter.NearbyAccessPoints)
            {
                if (wAccessPoint.Name == U.mapAccessPoint.Name)
                {
                    wbRtn = wAdapter.SetWirelessSettings(wAccessPoint.Name);
                    // give the re-connect script a second to finish
                    Thread.Sleep(1000);
                    Application.DoEvents();
                    break;
                }
            }
            if (wbFound) break;
        }
    }

    return wbRtn;
}


text:
Q: Bulk API - Invalid field 'Revision' on FeedItem I query FeedItem on all fields using Bulk-API. This is the query:
SELECT Id, ParentId, Type, CreatedById, CreatedDate, IsDeleted, LastModifiedDate, SystemModstamp, Revision, LastEditById, LastEditDate, CommentCount, LikeCount, Title, Body, LinkUrl, RelatedRecordId, ContentFileName, ContentDescription, ContentType, ContentSize, InsertedById, BestCommentId, HasContent, HasLink FROM FeedItem

and I get the bulk job failed stating:

-------------- Failed ----------FeedItem [BatchInfo   state='Failed' stateMessage='InvalidBatch : Failed to process query: INVALID_FIELD:
  LastModifiedDate, SystemModstamp, Revision, LastEditById, LastEditDate
  ^ ERROR at Row:1:Column:99 No such column 'Revision' on entity
  'FeedItem'. If you are attempting to use a custom field, be sure to
  append the '__c' after the custom field name. Please reference your
  WSDL or the describe call for the appropriate names.'
  createdDate='java.util.GregorianCalendar[time=1441115985000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=8,WEEK_OF_YEAR=36,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=244,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=59,SECOND=45,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]' systemModstamp='java.util.GregorianCalendar[time=1441115985000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=8,WEEK_OF_YEAR=36,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=244,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=59,SECOND=45,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]' numberRecordsProcessed='0' numberRecordsFailed='0'
  totalProcessingTime='0' apiActiveProcessingTime='0'
  apexProcessingTime='0' ]

This may be similar to the question. I am not sure whether this is an issue only for FeedItem. Am I missing anything here?

A: The field Revision in FeedItem object is added in the Summer'15 which comes with a feature called Chatter Post Feed Editing.
The feature should be manually enabled by the Administrator or the one who have Customize Application system permission.
For the orgs which doesn't have this feature enabled, there won't be any new fields available.
Please check the Knowledge Article 000214510 for more information on enabling this feature.


text:
Q: javascript input field to number I need to convert an input field into a number. So if the input field is empty, or contains letters, the number would be 0.
This doesn't work:
var trade_gold = document.getElementById('trade_gold').value;
if (trade_gold < 1) {

I've tried parseInt on it too, can't seem to work it. Any advice?

A: var val = document.getElementById('trade_gold').value,
    trade_gold = parseFloat(val) || 0;

A: var value = document.getElementById('trade_gold').value;

value = parseInt(value, 10);

// parseInt will return NaN if the conversion failed
if (isNaN(value)) {
    value = 0;
}

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

A: var trade_gold = 0;
try{
    trade_gold = parseInt(document.getElementById('trade_gold').value, 10);
}catch(e){}

A: this will checks whether the it's a number or not, and change the value to 0 if it's not.
var trade_gold = document.getElementById('trade_gold').value;
if (trade_gold.search(/[^0-9]/)>=0)
{
       // not a number
       trade_gold = 0;
}


text:
Q: Como darle animaciones a estos progress bar con scripts en vue con tailwind css? Busco de mil maneras para darles animaciones a mis progress bar y no lo logro, desconozo muchisimo el tema de los componentes.
Aqui les dejo mis progress bar, si alguien me echa una mano!

A:

function move() {
  var elem = document.getElementById("myBar");
  var width = 1;
  var id = setInterval(frame, 10);
  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      elem.style.width = width + '%';
    }
  }
}
#myProgress {
  width: 100%;
  background-color: grey;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: green;
}
<button class="w3-button w3-green w3-left" onclick="move()">Run</button>


text:
Q: What causes a finally block to execute too soon? I have a try-catch-finally block that looks like so:
ResultSet rs;
PreparedStatement ps;
Connection conn;
try {
    for (int i = 0; i < list.size(); i++) {
        ** execute SQL query **
    }
} catch (Exception e) {
    throw e;
} finally {
    ** close result set **
    ** close prepared statement **
    ** close connection **
}

I've verified that my ArrayList list had 534 elements in it.  The problem is that the finally block to close everything is executing after the first occurrence of my for loop which causes the next occurrence to throw an exception because the connection is now closed.
I've never encountered a situation where the finally block executes before the try block has completed.  What could cause this scenario?

A: Basically, what is happening is that finally is working as expected.  The short explanation is that a finally block is executed no matter how the try block terminates.
In your example, and based on what you have said, the most likely scenario is as follows:

*

*the loop body throws some exception,

*the exception is caught and rethrown, and

*the finally block is then executed.

The finally block will NOT be executed before the try block "terminates", so your theory that the finally block is causing the loop body to fail is not correct.
Reference:  http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

A: Without more source I would guess that you are not committing your transaction.
If you switch your connection to not auto-commit and then forget to commit your transaction it may seem like your finally block is executing before your queries when in fact they are merely awaiting committal before executing.
See here for a discussion.


text:
Q: Android cache heavy object for fragment Where is the best place to cache a heavy object (long initiation time) to not build each time when I enter the fragment. I'm thinking to keep it in Activity and pass each time when fragment is initialized. Does it sound sensible? Is there any good pattern for that?

A: Does it sound sensible?
Yes it is sensible if same object shares its properties with different fragments and/or locations.
Is there any good pattern for that?
I can't recall any specific pattern for given scenario but there is a good practice to coomunicate between Activity and Fragment. Have a look at Communicating with Other Fragments

A:
no, the object takes a lots of things from DB and does some extra calculation. The computing time is around 5 seconds. Can't do it each time when enter the fragment

Too litle info to fully answer your question. Still, it may be sufficient to just cache the result of your computation and show it on subsequent use, while for the first time it may be acceptable to even block the UI, show "Please wait. Calculating" for that 5 secs. Or, perhaps better from user perspective spawn background thread which either reads cached value or does the computation and once that phase is done, notifies (i.e. using event bus, rxjava or even broadcast) fragment to update itself with privided calculation results


text:
Q: Certain invoices missing from the "All Invoices" API response We use the Intuit API V2 to import Invoices from QuickBooks Desktop.
At one point we imported a few invoices that no longer show up in the list of "all invoices".
But if we request the invoices "by id" (one at a time) we do get them. They still have an open balance > 0.
Is there a reason why these invoices don't show up in the "all invoices" list? We did request all the pages.
Something that we noticed is that the problematic invoices all have Lines with SalesTaxCodeId 2 and seem to be "Tax returns".

A: Florin,
I have answered this question many times on Stackoverflow. You need to review the Sync Activity and Sync Status for any error the object may have encountered while syncing from Intuit to the customer's desktop QuickBooks file.

Objects that encounter an error are flagged and no longer appear in a query unless you set a filter to retrieve errored objects.

Lastly, you should always post your xml requests one for the query all and one for the individual.
For your reference:
http://docs.developer.intuit.com/0025_Intuit_Anywhere/0050_Data_Services/v2/0500_QuickBooks_Windows/0600_Object_Reference/SyncActivity
http://docs.developer.intuit.com/0025_Intuit_Anywhere/0050_Data_Services/v2/0500_QuickBooks_Windows/0600_Object_Reference/SyncStatus
http://docs.developer.intuit.com/0025_Intuit_Anywhere/0050_Data_Services/v2/0500_QuickBooks_Windows/0100_Calling_Data_Services/0015_Retrieving_Objects#Objects_in_Error_State


text:
Q: How to add Vue project with Vue cli to existing asp.net 4.6 Webforms project I tried adding a vue project to a sub-folder in my asp.net 4.6 website project using vue cli.
I would edit the vue app using vs code.
The problems I ran into:

*

*I can't use the npm server (npm run serve) address since I need to make calls to webapi in asp.net website. First the cors problem, and even after intsalling AspNet cors I have the webforms authentication problem. This is why I run the vue app with vs 2017 from the sub-folder using iis express Like so 'http://localhost:1234/vue-subfolder', which brings me to the
next problem

*I would have to run npm run build every time I made any change to
vue app. Running npm run serve would not update the vue app
running on iis express.

*I'm also using TFS for source control. Each time I would run `npm
run build' I would get file does not exist errors since js files get deleted and created.
Is there a way create  and  edit the vue app in vs 2017 and have it auto built on saving changes?


text:
Q: Clearing an Ion selection option I have an Ion Select with Ion Select options generated dynamically. Sometimes there may be only one ion select option (as the user has only created one project, for example) available for the Ion Select.
When the user clicks on a select option it opens a project page, I want to give the user the option to re-select the same project again and thus clear the previous selection
I've tried binding a NgModel and set it to null as per:
ion-item-options not displaying
 <ion-select mode="md" interface="popover" style="position: absolute; opacity: 0;" #projectSelect
                               (ionChange)="selectProject(projectSelect.value, p)"
[(ngModel)]="selection">
        <ion-select-option *ngFor="let b of p.buildings; let i = index" [selected]="false" [value]="b.buildingName">
                           {{b.buildingName}}
        </ion-select-option>

then in selectProject() I set
selectProject(buildingName: string, project: Project) {
        // always! reset the selection
        this.selection = null;

but it does not clear the selection and the user is unable to re-select a previously selected option.
I have even tried having a button with (click)=clearSelection() setting selection=null to no avail.
I was expecting the selection to be cleared and to allow the user to re-select the ion select.

A: This works with ionic ^4.7.1 when I tried it:
import { IonSelect } from '@ionic/angular';

// ...

// refer to the select via the template reference
@ViewChild('projectSelect', { static: false }) projectSelect: IonSelect;

selectProject(buildingName: string, project: any) {
  // do stuff
  this.projectSelect.value = '';
}

So you can remove ngModel altogether:
<ion-select mode="md" interface="popover" #projectSelect
    (ionChange)="selectProject(projectSelect.value, p)">
  <ion-select-option *ngFor="let b of p.buildings;" [value]="b.buildingName">
    {{b.buildingName}}
  </ion-select-option>
</ion-select>


text:
Q: How to change model variable by onclick function used in template asynchronously (without refreshing explicitly) I am making a django app where the user can post status'. The list of his previous status' is also showed on the same page with a delete post option against each post. I have added an onclick function to that button which uses ajax calls to change the class variable in models.py. ie. the delete variable in class status_class in models.py changes its value from 0 to 1 after the delete post button is clicked. And then only the posts with delete=1 are showed. Help me modify the delete_post function in the script so that it works as I've mentioned above. Please do mention if any other changes are needed. Thanks.
Models.py
from django.db import models
from django.contrib.auth.models import User

class status_class(models.Model):
    username=models.ForeignKey(User)
    text=models.CharField(max_length=2000, null=False, blank=False)
    pub_date=models.DateTimeField("Published: ")
    delete=models.IntegerField(default=0)

     def __unicode__(self):
        return self.text

Script in template

URL
url(r'^delete_post/$', 'status.views.deletepost_view', name='deletepost_view'),

View
@csrf_exempt
def deletepost_view(request):
    value=request.POST.get("value")
    b=User.objects.filter(id=str(value))
    #delete change statement
    resp=json.dumps(b)
    return HttpResponse(resp, content_type="application/json")

Template
{% for i in d %}

{{ i.text }} &nbsp&nbsp&nbsp&nbsp {{ i.pub_date }}
<button type="button" class="btn btn-danger" onclick="deletepost(i.id);"> Delete Post </button>

{% endfor %}

NOTE: Also help me with this. I want to filter posts and show only that posts having the delete variable equal to 0. ie. that have not been deleted. Where should I write the filter statement?

A: The changes to the following would work.
View
def deletepost_view(request):

    value=request.POST.get("value")
    b=status_class.objects.get(id=str(value))
    b.delete = 1
    b.save()

    resp=json.dumps(b)

    return HttpResponse(resp, content_type="application/json")

Template
{% for i in d %}

{% if i.delete == 0  %}
      {{ i.text }}&nbsp&nbsp&nbsp&nbsp {{ i.pub_date }}
      <button type="button" class="btn btn-danger" onclick="deletepost({{ i.id }});"> Delete Post </button>

   {% endif %}

{% endfor %}


text:
Q: Is there a way configure NetBeans to block indent with the Tab key? I started using NetBeans for Python development, and so far it looks pretty good. One thing that bothers me is that when I highlight a few lines of text and hit the Tab key, it doesn't do what almost every other editor does, but rather just adds four spaces at the end of the block.
I know NetBeans has a block indent action (somewhat oddly called "Shift Right"), but it seems impossible to bind the Tab key to anything. For now I've settled on Ctrl+Shift+I for block indent as a tribute to my Delphi days, but really, I'd just like make it work like Eclipse/IntelliJ/Notepad2 and do a block indent on Tab.
Any tips?
EDIT: OK, so it seems that this behavior only occurs if I select a bunch of lines and the cursor is positioned on an empty line. This looks like a bug, so I'm going to file a report.
Thanks guys!
EDIT 2: In case anyone's interested, Issue 155735

A: Tab should indent the selected lines, and Shift-Tab dedent. The behavior you're describing sounds like a bug. Can you open the keybindings dialog and see what your Tab key is bound to?
Another thing you could try is clearing your userdir in case there is old cruft in there.
If these things don't work, please file an issue so we can reproduce and track this down --
http://scripting.netbeans.org/issues/enter_bug.cgi?component=python&issue_type=DEFECT
-- Tor

A: This should be fixed now - in build #415 and later from http://deadlock.netbeans.org/hudson/job/python/ .  Thanks for the bug report.

A: Had you changed the default keys at some point? Tab works for block indent for me.


text:
Q: Push firebase uid to multiple locations - Angularfire2 Ionic 3 I have the following which simply pushes a name into the database along with a uid.  I would like to store that uid in another location at the same time. How can I achieve this?  Im using ionic 3, angularfire2.
addName() {
      let prompt = this.alertCtrl.create({
        title: 'Name of user',
        message: "Enter a name for this new user",
        inputs: [
          {
            name: 'Name',
            placeholder: 'Username'
          },
        ],
        buttons: [
          {
            text: 'Cancel',
            handler: data => {
              console.log('Cancel clicked');
            }
          },
          {
            text: 'Save',
            handler: data => {
              this.users.push({
                title: data.Name,

              });

              this.posts.push({
                title: data.Name
              });
            }
          }
        ]
      });
      prompt.present();
    }

Thanks in advance

A: Your code doesn't authenticate a user, so there's no UID (short for user-id) involved.
But if you're looking to use the same push ID when writing to two locations:
handler: data => {
  var key = this.users.push().key;
  this.users.child(key).set({
    title: data.Name,

  });

  this.posts.child(key).set({
    title: data.Name
  });
}

You can even combine the two set operations into a single update, but I'm not sure how your users and posts references are related. If both are direct children from the root, it'd be:
handler: data => {
  var key = this.users.push().key;
  var updates = {};
  updates["users/"+key+"/title"] = data.Name;
  updates["posts/"+key+"/title"] = data.Name;
  this.ref.update(updates);
}


text:
Q: ¿Cual es el número máximo de usuarios que puede tener una Base de Datos Mysql? Me refiero a usuarios creados con la sentencia: CREATE USER ...
De ser ilimitado (o estar limitado por las capacidades de almacenamiento), ¿afectaría al rendimiento tener, por ejemplo, un millón de usuarios ?
Muchas gracias.


text:
Q: What is projection of WGS84 in GIS software? WGS84 is a reference ellipsoid that determines coordinates of every point on Earth using latitude, longitude and height about the its surface.
This ellipsoid is often used as a base to make maps. Though, to make a map on a flat paper or a flat digital screen you need a projection too. An example of a popular projection would be UTM.
Mainstream GIS software give plethora of projection alternatives to display your data layers. Among them, they also let you display your data using WGS84 only.
I think they are using a certain projection but what projection is that?

A: By "using WGS84 only" it sounds like you are referring to a Geographic Coordinate System based on the WGS 1984 datum.
A Geographic Coordinate System does NOT have a projection.
Only a Projected Coordinate System has a projection.

A: The term "WGS84" refers both to a reference ellipsoid and to a geographic coordinate system (aka EPSG:4326) - hence your confusion.

A: WGS84 doesn't define a projection, so it's up to the GIS software to decide which projection to use for displaying the data on the screen (unless you manually pick a projection, of course).
In the simplest case, a plate carée projection (i.e. equidistant cylindrical with standard parallel 0°) is used, which in essence just interprets the angular units of the geographic coordinates as linear units of a cartesian coordinate system. This is the projection used by proj4 based systems, e.g. QGIS or GRASS, for all coordinate reference systems that use +proj=latlong or +proj=longlat.
MapInfo also uses an equidistant cylindrical projection for displaying geographic coordinates, with the twist that the parallel at the center of the map is used as the standard parallel. This means that if the map is centered on the equator, a plate carée projection results, but at other latitudes φ, the map will be stretched by a factor of 1/cos(φ), which helps reduce distortion.

A: WGS84 is a "horizontal datum" - a mathematical representation of the Earth used to reference points.
Both geographic coordinate system's and projected coordinate systems can use WGS84 as the datum they reference. The difference is geographic coordinate systems are not projected, they are in latitude and longitude. In other words, not all measures of latitude and longitude are equivalent - they need to be referenced to a datum - most likely WGS84. Projected coordinate systems on the other hand are "flat"  - but still need a point of reference (datum) to define locations in space.
In other words, the datum is used to determine the origin of points on Earth by referencing a central point inside the Earth model.

A: WGS is required to see/define where your map is on a globe/world, and UTM defines where your place/map is on a flat-land/screen