text:
Q: Moment.js - how do I get the number of years since a date, not rounded up? I'm trying to calculate a person's age using Moment.js, but I'm finding that the otherwise useful fromNow method rounds up the years. For instance, if today is 12/27/2012 and the person's birth date is 02/26/1978, moment("02/26/1978", "MM/DD/YYYY").fromNow() returns '35 years ago'. How can I make Moment.js ignore the number of months, and simply return the number of years (i.e. 34) since the date?

A: Try this:
 moment("02/26/1978", "MM/DD/YYYY").fromNow().split(" ")[0];

Explanation:
We receive string something like this: '23 days ago'. Split it to array: ['23', 'days', 'ago'] and then take first item '23'.

A: http://jsfiddle.net/xR8t5/27/
if you do not want fraction values:
var years = moment().diff('1981-01-01', 'years',false);
alert( years);

if you want fraction values:
var years = moment().diff('1981-01-01', 'years',true);
alert( years);

Units can be [seconds, minutes, hours, days, weeks, months, years]

A: This method works for me. It's checking if the person has had their birthday this year and subtracts one year otherwise.
// date is the moment you're calculating the age of
var now = moment().unix();
var then = date.unix();
var diff = (now - then) / (60 * 60 * 24 * 365);
var years = Math.floor(diff);

Edit: First version didn't quite work perfectly. The updated one should

A: Using moment.js is as easy as:
var years = moment().diff('1981-01-01', 'years');
var days = moment().diff('1981-01-01', 'days');

For additional reference, you can read moment.js official documentation.

A: There appears to be a difference function that accepts time intervals to use as well as an option to not round the result. So, something like
Math.floor(moment(new Date()).diff(moment("02/26/1978","MM/DD/YYYY"),'years',true)))

I haven't tried this, and I'm not completely familiar with moment, but it seems like this should get what you want (without having to reset the month).

A: If you dont want to use any module for age calculation
var age = Math.floor((new Date() - new Date(date_of_birth)) / 1000 / 60 / 60 / 24 / 365.25)

A: This method is easy and powerful.
Value is a date  and  "DD-MM-YYYY" is the mask of the date.
moment().diff(moment(value, "DD-MM-YYYY"), 'years');

A: I found that it would work to reset the month to January for both dates (the provided date and the present):
> moment("02/26/1978", "MM/DD/YYYY").month(0).from(moment().month(0))
"34 years ago"

A: When you want to show years and the remaining days:
var m = moment(d.birthday.date, "DD.MM.YYYY");
var years = moment().diff(m, 'years', false);
var days = moment().diff(m.add(years, 'years'), 'days', false);
alert(years + ' years, ' + days + ' days');

A: You can try this:
moment
.duration({
  years: moment(Date.now()).diff(datetime, "years", false),
})
.humanize()

A: I prefer this small method.
function getAgeFromBirthday(birthday) {
    if(birthday){
      var totalMonths = moment().diff(birthday, 'months');
      var years = parseInt(totalMonths / 12);
      var months = totalMonths % 12;
        if(months !== 0){
           return parseFloat(years + '.' + months);
         }
    return years;
      }
    return null;
}

A: Get years and days using moment.js library
import moment from 'moment'

export function getAge(dateString: string) {
  const date = moment(dateString, 'YYYY-MM-DD')
  const years = moment().diff(date, 'years')
  const days = moment().diff(date.add(years, 'years'), 'days', false)
  return { years, days }
}

const birthDate = "1997-04-01T00:00:00.000Z";
const age = getAge(birthDate);

// Today is 2022-04-09
console.log({ age })
// Result: { age: { years: 25, days: 8 } }

A: Here is the simple one using moment.js
let dt = dob;

        let age = '';

        let bY = Number(moment(dt).format('YYYY'));
        let bM = Number(moment(dt).format('MM'));
        let bD = Number(moment(dt).format('DD'));

        let tY = Number(moment().format('YYYY'));
        let tM = Number(moment().format('MM'));
        let tD = Number(moment().format('DD'));

        age += (tY - bY) + ' Y ';

        if (tM < bM) {
            age += (tM - bM + 12) + ' M ';
            tY = tY - 1;
        } else {
            age += (tM - bM) + ' M '
        }

        if (tD < bD) {
            age += (tD - bD + 30) + ' D ';
            tM = tM - 1;
        } else {
            age += (tD - bD) + ' D '
        }

        //AGE MONTH DAYS
        console.log(age);


text:
Q: IE8 crashing on reload only when site on localhost, only when javascript is enabled, only in IE8 mode Here are the versions:

*

*IE 8.0.6001.18702

*Visual Studio Web Developer 2010 10.0.40219.1.SP1Rel

*.Net 4.0.30319 SP1Rel

*jQuery 1.6.2

When I run the site on localhost through Visual Studio, with IE set to IE8 mode and javascript enabled, the browser will crash when the page is reloaded. It doesn't crash when URL is changed or tab/window closed. The messages I get are:
VS JIT message:

An unhandled win32 exception occurred in iexplore.exe [some PID].

Error when debugging with VS:

Unhandled exception at 0x3fa078d8 in iexplore.exe: 0xC0000005: Access violation reading location 0x00000008.

Call stack location: mshtml.dll!3fa078d8()

3FA078D8  mov         eax,dword ptr [ebx+8]

When I cancel out of debugging the page usually loads just fine in the tab. Every now and then I'll get the "We were unable to return you to the page you were viewing." message.
To make it even more fun, this only happens on the home page of the site, and isn't reproduceable on the DEV server. Switching to IE7 mode makes the crashes never occur. Or commenting out some of the javascript files loaded at the bottom of the page.
I've tried running IE8 with Addons disabled, and the crashes still happen. I tried running with Fiddler enabled and it still crashes.

A: I think the crashes may have been related to the use of window.setTimeout() and window.setInterval() since they seem to be the only common functionality used across the different JS files that cause the project to stop crashing when commented out. In our global.js I've added this code to use instead:
(function (w) {

    w.windowBind = function (eventName, handler) {
        if (w.attachEvent) {
            w.attachEvent("on" + eventName, handler);
        } else if (w.addEventListener) {
            w.addEventListener(eventName, handler, false);
        }
    };

    var timeoutsToExpire = [],
        expireTimeouts = function () {
            for (var i = 0, l = timeoutsToExpire.length; i < l; i++) {
                w.clearTimeout(timeoutsToExpire[i]);
            }
            timeoutsToExpire = [];
        },
        intervalsToExpire = [],
        expireIntervals = function () {
            for (var i = 0, l = intervalsToExpire.length; i < l; i++) {
                w.clearInterval(intervalsToExpire[i]);
            }
            intervalsToExpire = [];
        };

    w.setExpiringTimeout = function (func, time) {
        var id = w.setTimeout(func, time);
        timeoutsToExpire.push(id);
        return id;
    };

    w.setExpiringInterval = function (func, time) {
        var id = w.setInterval(func, time);
        intervalsToExpire.push(id);
        return id;
    };

    w.windowBind("unload", function () {
        // expire timers
        expireTimeouts();
        expireIntervals();
    });
    w.windowBind("beforeunload", function () {
        // expire timers
        expireTimeouts();
        expireIntervals();
    });

})(window);

Then I updated the previous window.setTimeout() and window.setInterval() references to use these helpers instead. This seems to fix it for now.
Update: maybe I posted too soon, it just crashed for me again. They seem to be very intermittent now though.
Update 2: ok, it seems to happen reliably when I shift+refresh now, ugh.
Update 3: tried out latest jQuery RC, and the crashes went away, the release notes mention 2 IE8 crashing bugs: http://blog.jquery.com/2011/08/29/jquery-1-6-3-rc1-released/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Computing Log-likelihood Model Manually for Logit Model A log-likelihood function takes on the form of: logL$=\Sigma^{n}_{i=1}(y_ilog(\frac{e^{\beta' x_i}}{1+e^{\beta'x_i}} )+(1-y_i)(\frac{e^{\beta' x_i}}{1+e^{\beta'x_i}})$
My logit model is estimated as follows:
glm.logit=glm(model,binomial(),data)

Estimating $y_i$
yi=data$y

x's as a matrix of the dependent variable
 xi=cbind(data$x1+data$x2+...)

Taking the estimates of $\beta$ from my model
betai=coef(glm.logit)

Putting the these together:
xibetai<-xi%*%t(betai)

Estimating the logistic form:
logiti<-exp(xibetai)/(1+exp(xibetai))

Putting everything together in the form of a log-likelihood model:
LogLi<-yi%*%log(logiti)+(1-yi)%*%log(1-logiti)

Issue with the fact that you can't take take the log of a negative value, so I only get about half of my coefficients in the output.

A: Both your log-likelihood equation and your R code have some errors:
$$
\begin{split}
\eta_i & = \mathbf{X}_i \boldsymbol{\beta} \quad \textrm{(so far so good)} \\
p_i & = \exp(\eta_i)/(1+\exp(\eta_i)) = 1/(1+\exp(-\eta_i)) \\
L_i & = y_i \log p_i + (1-y) \log(1-p_i) \\
L & = \sum L_i
\end{split}
$$
In R you can use plogis() for the logistic ($1/(1+\exp(-\eta_i))$):
p <- plogis(X %*% beta)
sum(y*log(p) + (1-y)*log(1-p))

(or dbinom(y, prob=p, size=1, log=TRUE))
If your coefficients include an intercept, $\mathbf{X}$ should include a column of 1s at the corresponding position (usually the first column). You can check various intermediate results with predict(fitted_model, type="link") ($\eta$), predict(fitted_model, type="response") ($p$).


text:
Q: Loading two Iframes is failing I am trying to load two iframes one on top of the other and i only see the top one visible

A: You have to close the iframe.

It's not a self-closing element.


text:
Q: Binary Cosine Cofficient I was given the following forumulae for calculating this
sim=|Q∩D|  / √|Q|√|D|
I went ahed and implemented a class to compare strings consisting of a series of words
#pragma once

#include <vector>
#include <string>
#include <iostream>
#include <vector>

using namespace std;

class StringSet
{
public:
 StringSet(void);
 StringSet( const string the_strings[], const int no_of_strings);
 ~StringSet(void);
 StringSet( const vector<string> the_strings);
 void add_string( const string the_string);
 bool remove_string( const string the_string);
 void clear_set(void);
 int no_of_strings(void) const;
 friend ostream& operator <<(ostream& outs, StringSet& the_strings);
 friend StringSet operator *(const StringSet& first, const StringSet& second);
 friend StringSet operator +(const StringSet& first, const StringSet& second);
 double binary_coefficient( const StringSet& the_second_set);

private:
 vector<string> set;
};

#include "StdAfx.h"
#include "StringSet.h"
#include <iterator>
#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <cmath>

StringSet::StringSet(void)
{
}

StringSet::~StringSet(void)
{
}

StringSet::StringSet( const vector<string> the_strings)
{
 set = the_strings;
}

StringSet::StringSet( const string the_strings[], const int no_of_strings)
{
 copy( the_strings, &the_strings[no_of_strings], back_inserter(set));
}

void StringSet::add_string( const string the_string)
{
 try
 {
  if( find( set.begin(), set.end(), the_string) == set.end())
  {
   set.push_back(the_string);
  }
  else
  {
   //String is already in the set.
   throw domain_error("String is already in the set");
  }
 }
 catch( domain_error e)
 {
  cout << e.what();
  exit(1);
 }

}

bool StringSet::remove_string( const string the_string)
{
 //Found the occurrence of the string. return it an iterator pointing to it.
 vector<string>::iterator iter;
 if( ( iter = find( set.begin(), set.end(), the_string) ) != set.end())
 {
  set.erase(iter);
  return true;
 }
 return false;
}
void StringSet::clear_set(void)
{
 set.clear();
}

int StringSet::no_of_strings(void) const
{
 return set.size();
}

ostream& operator <<(ostream& outs, StringSet& the_strings)
{
 vector<string>::const_iterator const_iter = the_strings.set.begin();
 for( ; const_iter != the_strings.set.end(); const_iter++)
 {
  cout << *const_iter << " ";
 }
 cout << endl;
 return outs;
}

//This function returns the union of the two string sets.

StringSet operator *(const StringSet& first, const StringSet& second)
{
 vector<string> new_string_set;
 new_string_set = first.set;
 for( unsigned int i = 0; i < second.set.size(); i++)
 {
  vector<string>::const_iterator const_iter = find(new_string_set.begin(), new_string_set.end(), second.set[i]);
  //String is new - include it.
  if( const_iter == new_string_set.end() )
  {
   new_string_set.push_back(second.set[i]);
  }
 }
 StringSet the_set(new_string_set);
 return the_set;
}
//This method returns the intersection of the two string sets.

StringSet operator +(const StringSet& first, const StringSet& second)
{
 //For each string in the first string look though the second and see if
 //there is a matching pair, in which case include the string in the set.
 vector<string> new_string_set;
 vector<string>::const_iterator const_iter = first.set.begin();
 for ( ; const_iter != first.set.end(); ++const_iter)
 {
  //Then search through the entire second string to see if
  //there is a duplicate.
  vector<string>::const_iterator const_iter2 = second.set.begin();
  for( ; const_iter2 != second.set.end(); const_iter2++)
  {
   if( *const_iter == *const_iter2 )
   {
    new_string_set.push_back(*const_iter);
   }
  }
 }
 StringSet new_set(new_string_set);
 return new_set;

}

double StringSet::binary_coefficient( const StringSet& the_second_set)
{
 double coefficient;
 StringSet intersection = the_second_set + set;

 coefficient = intersection.no_of_strings() / sqrt((double) no_of_strings()) * sqrt((double)the_second_set.no_of_strings());
 return coefficient;
}

However when I try and calculate the coefficient using the following main function:
// Exercise13.cpp : main project file.

#include "stdafx.h"
#include <boost/regex.hpp>
#include "StringSet.h"

using namespace System;
using namespace System::Runtime::InteropServices;

using namespace boost;

//This function takes as input a string, which
//is then broken down into a series of words
//where the punctuaction is ignored.

StringSet break_string( const string the_string)
{
 regex re;
 cmatch matches;
 StringSet words;
 string search_pattern = "\\b(\\w)+\\b";

 try
 {
  // Assign the regular expression for parsing.
  re = search_pattern;
 }
 catch( regex_error& e)
 {
  cout << search_pattern << " is not a valid regular expression: \""
   << e.what() << "\"" << endl;
  exit(1);
 }

 sregex_token_iterator p(the_string.begin(), the_string.end(), re, 0);
 sregex_token_iterator end;
 for( ; p != end; ++p)
 {
   string new_string(p->first, p->second);
   String^ copy_han = gcnew String(new_string.c_str());
   String^ copy_han2 = copy_han->ToLower();
   char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(copy_han2);
   string new_string2(str2);
   words.add_string(new_string2);
 }

 return words;

}

int main(array<System::String ^> ^args)
{
 StringSet words = break_string("Here is a string, with some; words");
 StringSet words2 = break_string("There is another string,");

 cout << words.binary_coefficient(words2);
    return 0;
}

I get an index which is 1.5116 rather than a value from 0 to 1.
Does anybody have a clue why this is the case?
Any help would be appreciated.

A: You need more parentheses in the final calculation. a / b * c is parsed as (a / b) * c, but you want a / (b * c).

A: Maybe it's just a precedence matter
coefficient = intersection.no_of_strings() / sqrt((double) no_of_strings()) * sqrt((double)the_second_set.no_of_strings());

doesn't specify that you have to first multiply, then divide. Their precedence is the same but I'm not sure about choosen behaviour.. did you try specifying it:
coefficient = intersection.no_of_strings() / (sqrt((double) no_of_strings()) * sqrt((double)the_second_set.no_of_strings()));


text:
Q: how can i increase the output current in a transformerless power supply? I am designing a 12VDC, 200mA transformerless power supply using 1N4007(diode) for rectification, a ceramic capacitor 475k and 10R resistor for limiting, a zener diode (1N4742A) for a regulated output. After the connections am not still getting the output current, the current is needed to drive a relay of 12VDC 160mA.

A: Summary

*

*ALWAYS remember that any part of this circuit MUST be considered to be live and that a user may die if they touch any part of this circuit.

*If your circuit is half wave and operating at 110 VAC and 60 Hz then the capacitor needs to be about 10 uF.

*If your circuit is half wave and operating at 230 VAC and 50 Hz then Iout should be about 190 mA. If it isn't then you may have the zener in the wrong position.

*The zener diode should be on the AC side of the rectifier diode.

*Note that capacitor tolerances can be wide - your capacitor actual value  needs to be at least as large as calculations indicate.

*A comprehensive design guide can be found in
Microchip AN954 Transformerless Power Supplies ...
An offline transformerless supply can be made using a series capacitor to provide series impedance.
 capacitor impedance is 1/(2 x Pi x frequency x C).
 For say 1 uF at say 60 Hz Xc = 1/( 2 x 3.14 x 60 x 1E-6) =~ 2650 ohms reactive
For 110 VAC if this capacitor was placed across the mains the AC current flow would be
 I = V/R = 110/2650 = 40 mA.
 To get 160 mA the capacitor would need to be 4 uF.
BUT that's for AC power.
 If a full wave bridge is used the power delivered at DC is the same but if, as is usual, half wave is used then the capacitor needs to be about double or here = 8 uF. Say 10 uF actual.
IF the 475k capacotor = 4.7 uF (as it appears) and if you are running on 110 VAC then your capacitor appears to be about half the size it should be.
Note also the comment on zener placement below. .
To make this into a power supply, rather than just connecting across the mains a "load" is created which uses the AC current to create a lower voltage supply. The driving voltage is now Vac - Vdc. Not much change usually. A simple version of this looks like this:

The resistor limits surge current. It can play a role in voltage dropping if large enough but is usually small.
 The zener diode provides its breakdown voltage in one direction and acts like a diode in the other direction. Without this diode action the capacitor would have no AC return path and the circuit would not work.
 If the zener is moved to the DC side of D2 then a reverse biased diode must be used where the zener now is
__
The power output can be about doubled by using full wave rectification - like so:

An online calculator that allows the design of a full wave transformerless power supply can be found here .
 Using this calculator a value of 10 uF gave 218 mA at ~12 VDC for 110 VAC, 60 Hz input. 50 Hz gave 180 mA.
230 VAC, 50 HZ, 4.75 uF full wave , 12 VDC gives 192 mA
A half wave circuit will give about half that.

ADDED
C1 MUST be mains rated.
 BR1 can be 4 x 1N400x diodes or a mains rated bridge. (Theoretically does not need to be mains rated but ...).
Caps that are rated to connect across mains (phase-neutral) are X rated and must withstand Vrms x 1.414 PLUS expected peaks and surges and transients. They are made of sterner stuff than eg just a 230 VAC x 1.414 Volt cap for 230 VAC operation. Caps that are designed to operate from mains to ground (eg phase-ground) are Y rated - a lesser but still demanding requirement.

A: 200mA is a lot for a capacitve dropper supply. If you're driving a relay, consider using one with a 24 or 48V coil instead of 12V, so less current is needed.
Take a look at Power Integrations Linkswitch-TN devices, which can be a good alternative to capacitor droppers when the current requirement is more than can be got with a sensible-sized capacitor.


text:
Q: Building OnsenUI Cordova app, adding a controller doesn't work After following the OnsenUI Getting Started guide i've begun to develop a Cordova app that works how I like.
I used the Sliding Menu template for the app. So far, so good. I've modified this so that it has the base pages that I want, but now that I'm ready to add functionality, i've searched for adding controllers.
I found the AngularJS Controllers page. To ensure it would work as they suggest, I added it as explained in the document linked. Added the code to app.js, included this in the page (below the Angular and Onsen JS script tags) and added the ng-controller to an ons-page element, but then when I run the app (I'm debugging in Chrome browser with cordova run browser) the controller does not do as intended (the {{ greeting }} tag remains) and the sliding menu functionality is broken - i.e. the hamburger icon disappears, the font isn't loaded and the button is gone. Swipe still works, however.
Inside a div as in the linked example the whole page doesn't break, but the same error occurs and no controller is called.
The chrome error is:
Error: [ng:areq] Argument 'GreetingController' is not a function, got undefined
http://errors.angularjs.org/1.4.8/ng/areq?p0=GreetingController&p1=not%20a%20function%2C%20got%20undefined
    at angular.js:68
    at assertArg (angular.js:1815)
    at assertArgFn (angular.js:1825)
    at angular.js:9158
    at setupControllers (angular.js:8228)
    at nodeLinkFn (angular.js:8270)
    at compositeLinkFn (angular.js:7731)
    at publicLinkFn (angular.js:7611)
    at Class.extend._appendMainPage (onsenui.js:12656)
    at onsenui.js:12735

I've searched to see if there is a parent class I should use but there is hundreds of instances of angular.module() in the code included with the template and I don't know which is the right one to call.
I have downloaded the vanilla template and implemented exactly as outlined on the AngularJS page above and the result is the same so I'm confident it's not my code.
I have removed the ng-controller call in the HTML page and the page works correctly.
I have no idea where to go from here, Chrome profiling doesn't reveal anything to me (but I am certainly not the picture of a Javascript developer).
I'd be appreciative of any help!

A: Ended up resolving this. Updated Angular and Onsen using the version supplied in the template - and it worked.
There is a chance I'd accidentally modified one of the supplied file perhaps, or there was a genuine bug in the version I was using. I'll never know.
It's fixed now :)


text:
Q: Joint values from different queries into one I have 6 tables of data.
I have 2 different queries that produce a table like this
| PERCENTAGE | COMPANY | TYPE |

(the companies are always the same in all tables, the only thing that changes is the PERCENTAGE and the type). Each query gets the total_percentage of an given company for one of the 2 different types.
For example:
Query 1 result:

| PERCENTAGE | COMPANY | TYPE |
0.0213 | Apple | Phones
0.3452 | Microsoft | Phones

Query 2:
|PERCENTAGE | COMPANY | TYPE |
0.4243 | Apple | Computers
...

And the result is:
Result:
| SUMMED_TOTAL| COMPANY |
0.0213 + 0.4243 | Apple
...

The summed percentage rows wont sum > 1, dont worry.
What i'd like to do is get the TOTAL_PERCENTAGE, from all types (all 2 queries) summed by company.
Any idea of an query? Im a begginer so it's kinda hard. You can literally use the names to do the query.

A: Use union all and group by:
select company, type, sum(percentage)
from ((select company, type, percentage from query1) union all
      (select company, type, percentage from query2)
     ) ct
group by company, type;


text:
Q: Check if Windows user or group exists, supporting domain names I'm interested in check if a given username or group name exist. I need to support AD controllers and multidomain. So the following are valid entries for me:
MYDOMAIN\John
John@mydomain.com
OTHERDOMAIN\Administrators

So, I want to implement is exactly the same functionality as MS windows implements when you edit the permissions of a folder, then you type a name and click "Check names" button.
Is there a Windows API that work as described in a single call?
Thanks in advance


text:
Q: SWIFT Message Testing using Jmeter I need help, I have been told to do performance testing using Jmeter on IBM MQ for SWIFT message types, they are the format or schema used to send messages to financial institutions on the SWIFT network.
Has anyone had done any testing using jmeter, I need help or sample code how we can do testing using Jmeter for SWIFT Message, looks like we need to change the data during run time.
https://www.iso20022.org/15022/uhb/finmt541.htm

A: Sample code for sending messages to IBMMQ is quite simple:
import com.ibm.msg.client.jms.JmsFactoryFactory
import com.ibm.msg.client.wmq.WMQConstants

import javax.jms.Session

def hostName = "your IBMMQ Host"
def hostPort = 1414
def channelName = "DEV.APP.SVRCONN"
def queueManagerName = "QM1"
def queueName = "DEV.QUEUE.1"

def ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER)
def cf = ff.createConnectionFactory()

cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, hostName)
cf.setIntProperty(WMQConstants.WMQ_PORT, hostPort)
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, channelName)
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT)
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, queueManagerName)

def conn = cf.createConnection("app", "test")
def sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE)

def destination = sess.createQueue(queueName)

conn.start()

def producer = sess.createProducer(destination)

def payload = "your message here"
def msg = sess.createTextMessage(payload)

producer.send(msg)

producer.close()

Check out the following material:

*

*Write and run your first IBM MQ JMS application

*IBM MQ testing with JMeter - Learn How
With regards to building the SWIFT message - you have already provided the link showing how the body should look like.


text:
Q: PySpark pattern matching and assigning associated values df1:
campaign_name   campaign_team
einsurancep09   other
estoreemicardcdwpnov06  other
estoreemicardwmnov06    other
estoreemicardgenericspnov06 other

df2:
terms   product_category    product
insurance   insurance   null
def emi store
ab  bhi asd
de  lic cards
a   credit  cards

Below are my scenarios:

*

*'terms' column (df2) is sorted according to the string length in descending order.

*It should be compared with the campaign_name of df1 for contains/like.

*Whichever terms string matches first with the campaign_name, its product_category and product should be picked up and should be added as new columns in df1.

*For campaign_name value "einsurancep09", "insurance" value from terms is contained in campaign_name so its product_category and product is picked up and added as df1 in the output.

*Another eg: Consider rest 3 records where you contain def, ab and de in the campaign_name string but we are picking product_category and product of "def" as it appeared first and is the longest in the length when compared with "ab" and "de"

Below is my code:
df1 = df1.withColumn("product_category",when(df1.campaign_name.contains(df2.terms),df2.product_category).otherwise('other'))

But, it gives me below error:
   raise converted from None
pyspark.sql.utils.AnalysisException: Resolved attribute(s) terms#37,product_category#38 missing from campaign_name#16,campaign_team#17 in operator !Project [campaign_name#16, campaign_team#17, CASE WHEN Contains(campaign_name#16, terms#37) THEN product_category#38 ELSE other END AS product_category#44].;
!Project [campaign_name#16, campaign_team#17, CASE WHEN Contains(campaign_name#16, terms#37) THEN product_category#38 ELSE other END AS product_category#44]
+- Relation[campaign_name#16,campaign_team#17] csv

So where am I going wrong?
As per stack's answer, I am getting below output:
+---------------+-------------+---------+----------------+-------+
|campaign_name  |campaign_team|terms    |product_category|product|
+---------------+-------------+---------+----------------+-------+
|einsurancepnm06|other        |insurance|Insurance       |NaN    |
+---------------+-------------+---------+----------------+-------+

Expected output:

A: Assumption
Dataset df1 should have an order to meet the OP requirement. So I introduce the rec_no column
df = spark.sql("""
select 'abcdefcdwpnovo6' campaign_name, 'other' campaign_team union all
select 'abcdefdwpnovo6' , 'other' union all
select 'abcdefgenericpnovo6' , 'other'
""")
df.createOrReplaceTempView("df")
df.show()

+-------------------+-------------+
|      campaign_name|campaign_team|
+-------------------+-------------+
|    abcdefcdwpnovo6|        other|
|     abcdefdwpnovo6|        other|
|abcdefgenericpnovo6|        other|
+-------------------+-------------+

df1 = spark.sql("""
select 1 rec_no, 'def' terms, 'emi' product_category, 'store' product union all
select 2, 'abc' ,'bhi' ,'asd' union all
select 3, 'de' ,'lic' ,'cards' union all
select 4, 'a' ,'credit' ,'cards'
""")
df1.createOrReplaceTempView("df1")
df1.show()

+------+-----+----------------+-------+
|rec_no|terms|product_category|product|
+------+-----+----------------+-------+
|     1|  def|             emi|  store|
|     2|  abc|             bhi|    asd|
|     3|   de|             lic|  cards|
|     4|    a|          credit|  cards|
+------+-----+----------------+-------+

Output:
You can drop the ps, rk and rec_no columns
spark.sql("""
with t1 ( select * from df a cross join df1 b ),
     t2 ( select rec_no, campaign_name,campaign_team,terms,product_category,product x, position(terms,campaign_name) ps,
    rank() over(order by rec_no) rk from t1  where position(terms,campaign_name)>0 )
    select * from t2 where rk=1
""").show()

+------+-------------------+-------------+-----+----------------+-----+---+---+
|rec_no|      campaign_name|campaign_team|terms|product_category|    x| ps| rk|
+------+-------------------+-------------+-----+----------------+-----+---+---+
|     1|    abcdefcdwpnovo6|        other|  def|             emi|store|  4|  1|
|     1|     abcdefdwpnovo6|        other|  def|             emi|store|  4|  1|
|     1|abcdefgenericpnovo6|        other|  def|             emi|store|  4|  1|
+------+-------------------+-------------+-----+----------------+-----+---+---+

Update-1:
The OP's question is still not clear. Try below.
spark.sql("""
with t1 ( select * from df a cross join df1 b ),
     t2 ( select rec_no, campaign_name,campaign_team,terms,product_category,product, position(product_category,campaign_name) ps,
    rank() over(partition by product_category order by rec_no) rk from t1 where position(product_category,campaign_name)>0
    )
    select * from t2 where rk=1 order by rec_no
""").show(truncate=False)

+------+---------------------------+-------------+---------+----------------+-------+---+---+
|rec_no|campaign_name              |campaign_team|terms    |product_category|product|ps |rk |
+------+---------------------------+-------------+---------+----------------+-------+---+---+
|1     |einsurancep09              |other        |insurance|insurance       |null   |2  |1  |
|2     |estoreemicardcdwpnov06     |other        |def      |emi             |store  |7  |1  |
|2     |estoreemicardgenericspnov06|other        |def      |emi             |store  |7  |1  |
|2     |estoreemicardwmnov06       |other        |def      |emi             |store  |7  |1  |
+------+---------------------------+-------------+---------+----------------+-------+---+---+

A: If the volume of dataframe df2 is high, then the spark will not be optimized to perform such operations. If it is not (< 200 records) then there are two feasible approaches that we can use for solving this:

*

*CROSS Join

*UDF
Approach 1: CROSS Join
Steps:

*

*Add new column rw and assign row number as per require order in df2.

*Cross Join df1 and sorted df2 and create a new dataframe df3.

*Use contains columnar function and add new column match.

*Select the first Row after partition By all df1 columns and order by df2 row number and match column
Code
>>> df1.show(truncate=False)
+---------------------------+-------------+
|campaign_name              |campaign_team|
+---------------------------+-------------+
|einsurancep09              |other        |
|estoreemicardcdwpnov06     |other        |
|estoreemicardwmnov06       |other        |
|estoreemicardgenericspnov06|other        |
|abcdefcdwpnov06            |other        |
|abcdefwmnov06              |other        |
|abcdefgenericspnov06       |other        |
+---------------------------+-------------+

>>> df2.show(truncate=False)
+---------+----------------+-------+---+
|terms    |product_category|product|rw |
+---------+----------------+-------+---+
|insurance|insurance       |null   |1  |
|def      |emi             |store  |2  |
|ab       |bhi             |asd    |3  |
|de       |lic             |cards  |4  |
|a        |credit          |cards  |5  |
+---------+----------------+-------+---+

>>> df3 = df1.crossJoin(df2)
>>> df4 = df3.withColumn("match", col("campaign_name").contains(col("terms")))
>>> W = Window.partitionBy(col("campaign_name"), col("campaign_team")).orderBy(col("match").desc(), col("rw"))

>>> finalDF = df4.withColumn("rn", row_number().over(W)).filter(col("rn") == lit(1)).drop("rn", "terms","rw","match")
>>> finalDF.show(truncate=False)
+---------------------------+-------------+----------------+-------+
|campaign_name              |campaign_team|product_category|product|
+---------------------------+-------------+----------------+-------+
|estoreemicardgenericspnov06|other        |credit          |cards  |
|abcdefwmnov06              |other        |emi             |store  |
|estoreemicardcdwpnov06     |other        |credit          |cards  |
|estoreemicardwmnov06       |other        |credit          |cards  |
|einsurancep09              |other        |insurance       |null   |
|abcdefgenericspnov06       |other        |emi             |store  |
|abcdefcdwpnov06            |other        |emi             |store  |
+---------------------------+-------------+----------------+-------+

Approach 2 UDF
Steps:

*

*Add new column rw and assign row number as per require order in df2.

*based on row number collect all df2 rows into a single row and create a new Dataframe df3.

*Use any approach from below and create a new Dataframe df4.

*

*Convert the df3 row into String Variable and add String literal as a new column in df1.
Or

*cross Join df1 and df3.

*Declare UDF as below.

*Call UDF and add a new column with the return value.

*Create require columns from output returns.

Code
>>> df3 = df2.na.fill("").groupBy(lit(1)).agg(sort_array(collect_list(concat(col("rw"),lit(":"), col("terms"), lit(":"), col("product_category"), lit(":"), col("product")))).alias("Check")).withColumn("Check", concat_ws(",", col("Check"))).drop("1")
>>> df3.show(truncate=False)
+-----------------------------------------------------------------------------------+
|Check                                                                              |
+-----------------------------------------------------------------------------------+
|1:insurance:insurance:,2:def:emi:store,3:ab:bhi:asd,4:de:lic:cards,5:a:credit:cards|
+-----------------------------------------------------------------------------------+

>>> df4 = df1.crossJoin(df3)
>>> def categoryFunction(name, Check):
        checkList = Check.lower().split(",")
        out = ""
        match = False
        for Key in checkList:
            keyword = Key.split(":",2)
            terms = keyword[1]
            tempOut = keyword[2]
            if terms in name.lower():
                out = tempOut
                match = True
            if match:
                break
        return out

>>> categoryUDF = udf(categoryFunction, StringType())
>>> finalDF = df4.withColumn("out", categoryUDF(col("campaign_name"), col("Check"))).drop("Check").withColumn("out", split(col("out"), ":")).withColumn("product_category", col("out")[0]).withColumn("product", col("out")[1]).drop("out").show(truncate=False)
>>> finalDF.show(truncate=False)
+---------------------------+-------------+----------------+-------+
|campaign_name              |campaign_team|product_category|product|
+---------------------------+-------------+----------------+-------+
|einsurancep09              |other        |insurance       |       |
|estoreemicardcdwpnov06     |other        |credit          |cards  |
|estoreemicardwmnov06       |other        |credit          |cards  |
|estoreemicardgenericspnov06|other        |credit          |cards  |
|abcdefcdwpnov06            |other        |emi             |store  |
|abcdefwmnov06              |other        |emi             |store  |
|abcdefgenericspnov06       |other        |emi             |store  |
+---------------------------+-------------+----------------+-------+


text:
Q: How to overwrite one model property in ASP.Net core I have a model with say 10 properties. A, B, C and so on...
Property A is an array.
For each value in array I generate one  tag like this:

    @foreach (var item in Model.A)
    {

            @item.Text

    }

When user clicks on some link I should redirect it to the same page, but with Some model property changed. For example:
Current url: my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=
with model ?name=Alex&age=20&from=fr&CurrentA=
If user clicks on  with text foo it should be redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=foo
then is clicks on  with text bar and it should be now redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=bar
So entire query string (except one parameter) should be preserved to send current model state to server while I want to set one value and redirect it to the same page but with new value.
Eventually, it should acts like postback with one extra value setted to model
Is it possible or I should use JS and perform everything myself?

A: Manually i solved it like this:
First, create hidden fields for every property in model:
<form asp-controller="search" asp-action="index" method="get" role="form" id="searchForm" asp-antiforgery="false">
    <input asp-for="SessionId" type="hidden" name="sessionId" value="@Model.SessionId" />
    <input asp-for="Quantity" type="hidden" name="quantity" value="@Model.Quantity"/>
    <input asp-for="SortField" type="hidden" name="sortField" value="@Model.SortField"/>
    <input asp-for="IsAscending" type="hidden" name="IsAscending" value="@Model.IsAscending" />
    <input asp-for="Offset" type="hidden" name="offset" value="0" />

    ...
</form>

Then, use JS to replace value in hidden field and then submit form. Values from inputs will be autimatically converter in query string, so everything works fine:
function sortDocuments(sortField) {
    var sField = document.getElementById('SortField');
    var isDescending = document.getElementById('IsAscending');
    if (sField.value === sortField) {
        if (isDescending.value.toUpperCase() === 'FALSE') {
            isDescending.value = 'TRUE';
        } else {
            sField.value = 'rank';
            isDescending.value = 'FALSE';
        }
    } else {
        sField.value = sortField;
        isDescending.value = 'FALSE';
    }
    document.getElementById('searchForm').submit();
}

Not very elegant, but it does its job.


text:
Q: Delete duplicate records in SQL Server? Consider a column named EmployeeName table Employee. The goal is to delete repeated records, based on the EmployeeName field.
EmployeeName
------------
Anand
Anand
Anil
Dipak
Anil
Dipak
Dipak
Anil

Using one query, I want to delete the records which are repeated.
How can this be done with TSQL in SQL Server?

A: You could try something like the following:
delete T1
from MyTable T1, MyTable T2
where T1.dupField = T2.dupField
and T1.uniqueField > T2.uniqueField

(this assumes that you have an integer based unique field)
Personally though I'd say you were better off trying to correct the fact that duplicate entries are being added to the database before it occurs rather than as a post fix-it operation.

A: Assuming that your Employee table also has a unique column (ID in the example below), the following will work:
delete from Employee
where ID not in
(
    select min(ID)
    from Employee
    group by EmployeeName
);

This will leave the version with the lowest ID in the table.
Edit
Re McGyver's comment - as of SQL 2012

MIN can be used with numeric, char, varchar, uniqueidentifier, or datetime columns, but not with bit columns

For 2008 R2 and earlier,

MIN can be used with numeric, char, varchar, or datetime columns, but not with bit columns (and it also doesn't work with GUID's)

For 2008R2 you'll need to cast the GUID to a type supported by MIN, e.g.
delete from GuidEmployees
where CAST(ID AS binary(16)) not in
(
    select min(CAST(ID AS binary(16)))
    from GuidEmployees
    group by EmployeeName
);

SqlFiddle for various types in Sql 2008
SqlFiddle for various types in Sql 2012

A: WITH CTE AS
(
   SELECT EmployeeName,
          ROW_NUMBER() OVER(PARTITION BY EmployeeName ORDER BY EmployeeName) AS R
   FROM employee_table
)
DELETE CTE WHERE R > 1;

The magic of common table expressions.

A: DELETE
FROM MyTable
WHERE ID NOT IN (
     SELECT MAX(ID)
     FROM MyTable
     GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

WITH TempUsers (FirstName, LastName, duplicateRecordCount)
AS
(
    SELECT FirstName, LastName,
    ROW_NUMBER() OVER (PARTITIONBY FirstName, LastName ORDERBY FirstName) AS duplicateRecordCount
    FROM dbo.Users
)
DELETE
FROM TempUsers
WHERE duplicateRecordCount > 1

A: You can do this with window functions. It will order the dupes by empId, and delete all but the first one.
delete x from (
  select *, rn=row_number() over (partition by EmployeeName order by empId)
  from Employee
) x
where rn > 1;

Run it as a select to see what would be deleted:
select *
from (
  select *, rn=row_number() over (partition by EmployeeName order by empId)
  from Employee
) x
where rn > 1;

A: Try
DELETE
FROM employee
WHERE rowid NOT IN (SELECT MAX(rowid) FROM employee
GROUP BY EmployeeName);

A: If you're looking for a way to remove duplicates, yet you have a foreign key pointing to the table with duplicates, you could take the following approach using a slow yet effective cursor.
It will relocate the duplicate keys on the foreign key table.
create table #properOlvChangeCodes(
    id int not null,
    name nvarchar(max) not null
)

DECLARE @name VARCHAR(MAX);
DECLARE @id INT;
DECLARE @newid INT;
DECLARE @oldid INT;

DECLARE OLVTRCCursor CURSOR FOR SELECT id, name FROM Sales_OrderLineVersionChangeReasonCode;
OPEN OLVTRCCursor;
FETCH NEXT FROM OLVTRCCursor INTO @id, @name;
WHILE @@FETCH_STATUS = 0
BEGIN
        -- determine if it should be replaced (is already in temptable with name)
        if(exists(select * from #properOlvChangeCodes where Name=@name)) begin
            -- if it is, finds its id
            Select  top 1 @newid = id
            from    Sales_OrderLineVersionChangeReasonCode
            where   Name = @name

            -- replace terminationreasoncodeid in olv for the new terminationreasoncodeid
            update Sales_OrderLineVersion set ChangeReasonCodeId = @newid where ChangeReasonCodeId = @id

            -- delete the record from the terminationreasoncode
            delete from Sales_OrderLineVersionChangeReasonCode where Id = @id
        end else begin
            -- insert into temp table if new
            insert into #properOlvChangeCodes(Id, name)
            values(@id, @name)
        end

        FETCH NEXT FROM OLVTRCCursor INTO @id, @name;
END;
CLOSE OLVTRCCursor;
DEALLOCATE OLVTRCCursor;

drop table #properOlvChangeCodes

A: delete from person
where ID not in
(
        select t.id from
        (select min(ID) as id from person
         group by email
        ) as t
);

A: Please see the below way of deletion too.
Declare @Employee table (EmployeeName varchar(10))

Insert into @Employee values
('Anand'),('Anand'),('Anil'),('Dipak'),
('Anil'),('Dipak'),('Dipak'),('Anil')

Select * from @Employee

Created a sample table named @Employee and loaded it with given data.
Delete  aliasName from (
Select  *,
        ROW_NUMBER() over (Partition by EmployeeName order by EmployeeName) as rowNumber
From    @Employee) aliasName
Where   rowNumber > 1

Select * from @Employee

Result:

I know, this is asked six years ago, posting just incase it is helpful for anyone.

A: Here's a nice way of deduplicating records in a table that has an identity column based on a desired primary key that you can define at runtime.  Before I start I'll populate a sample data set to work with using the following code:
if exists (select 1 from sys.all_objects where type='u' and name='_original')
drop table _original

declare @startyear int = 2017
declare @endyear int = 2018
declare @iterator int = 1
declare @income money = cast((SELECT round(RAND()*(5000-4990)+4990 , 2)) as money)
declare @salesrepid int = cast(floor(rand()*(9100-9000)+9000) as varchar(4))
create table #original (rowid int identity, monthyear varchar(max), salesrepid int, sale money)
while @iterator<=50000 begin
insert #original
select (Select cast(floor(rand()*(@endyear-@startyear)+@startyear) as varchar(4))+'-'+ cast(floor(rand()*(13-1)+1) as varchar(2)) ),  @salesrepid , @income
set  @salesrepid  = cast(floor(rand()*(9100-9000)+9000) as varchar(4))
set @income = cast((SELECT round(RAND()*(5000-4990)+4990 , 2)) as money)
set @iterator=@iterator+1
end
update #original
set monthyear=replace(monthyear, '-', '-0') where  len(monthyear)=6

select * into _original from #original

Next I'll create a Type called ColumnNames:
create type ColumnNames AS table
(Columnnames varchar(max))

Finally I will create a stored proc with the following 3 caveats:
1.  The proc will take a required parameter @tablename that defines the name of the table you are deleting from in your database.
2.  The proc has an optional parameter @columns that you can use to define the fields that make up the desired primary key that you are deleting against.  If this field is left blank, it is assumed that all the fields besides the identity column make up the desired primary key.
3.  When duplicate records are deleted, the record with the lowest value in it's identity column will be maintained.
Here is my delete_dupes stored proc:
 create proc delete_dupes (@tablename varchar(max), @columns columnnames readonly)
 as
 begin

declare @table table (iterator int, name varchar(max), is_identity int)
declare @tablepartition table (idx int identity, type varchar(max), value varchar(max))
declare @partitionby varchar(max)
declare @iterator int= 1

if exists (select 1 from @columns)  begin
declare @columns1 table (iterator int, columnnames varchar(max))
insert @columns1
select 1, columnnames from @columns
set @partitionby = (select distinct
                substring((Select ', '+t1.columnnames
                From @columns1 t1
                Where T1.iterator = T2.iterator
                ORDER BY T1.iterator
                For XML PATH ('')),2, 1000)  partition
From @columns1 T2 )

end

insert @table
select 1, a.name, is_identity from sys.all_columns a join sys.all_objects b on a.object_id=b.object_id
where b.name = @tablename

declare @identity varchar(max)= (select name from @table where is_identity=1)

while @iterator>=0 begin
insert @tablepartition
Select          distinct case when @iterator=1 then 'order by' else 'over (partition by' end ,
                substring((Select ', '+t1.name
                From @table t1
                Where T1.iterator = T2.iterator and is_identity=@iterator
                ORDER BY T1.iterator
                For XML PATH ('')),2, 5000)  partition
From @table T2
set @iterator=@iterator-1
end

declare @originalpartition varchar(max)

if @partitionby is null begin
select @originalpartition  = replace(b.value+','+a.type+a.value ,'over (partition by','')  from @tablepartition a cross join @tablepartition b where a.idx=2 and b.idx=1
select @partitionby = a.type+a.value+' '+b.type+a.value+','+b.value+') rownum' from @tablepartition a cross join @tablepartition b where a.idx=2 and b.idx=1
 end
 else
 begin
 select @originalpartition=b.value +','+ @partitionby from @tablepartition a cross join @tablepartition b where a.idx=2 and b.idx=1
 set @partitionby = (select 'OVER (partition by'+ @partitionby  + ' ORDER BY'+ @partitionby + ','+b.value +') rownum'
 from @tablepartition a cross join @tablepartition b where a.idx=2 and b.idx=1)
 end

exec('select row_number() ' + @partitionby +', '+@originalpartition+' into ##temp from '+ @tablename+'')

exec(
'delete a from _original a
left join ##temp b on a.'+@identity+'=b.'+@identity+' and rownum=1
where b.rownum is null')

drop table ##temp

end

Once this is complied, you can delete all your duplicate records by running the proc. To delete dupes without defining a desired primary key use this call:
exec delete_dupes '_original'

To delete dupes based on a defined desired primary key use this call:
declare @table1 as columnnames
insert @table1
values ('salesrepid'),('sale')
exec delete_dupes '_original' , @table1


text:
Q: GAE/J This application does not exist (app_id=u'app-id') I'm having this problem that I can't deploy to GAE cloud. I am using the appcfg.sh script.
I have already did this:
./appcfg.sh update "/path/to/war" --no_cookies

And still getting the error. What am I missing?


text:
Q: mediawiki run an extension(ClipUpload) only in specific pages I have a mediawiki for my team up and running.
Extension:ClipUpload is a useful extension which allows users to upload images in clipboard by simple copy&paste.
However, it sometimes causes unwanted uploading of clipboard (e.g. text copied from excel or other MS office softwares)
So what I want is making a specific page so that I use the ClipUpload extension in specific pages.
Here's what I have done but failed:

*

*created a page: http://my.domain/wiki/index.php/UploadFromClipboard

*when I enter the edit page: http://my.domain/wiki/index.php?title=UploadFromClipboard&action=edit

*I wanted to run the extension so added a line in LocalSettings.php
if ( preg_match("/(Clipboard)/i", $wgArticlePath) ) require_once("$IP/extensions/ClipUpload/ClipUpload.php");

*This type of solution did not work. The problem is I can't parse page title in query.
Could you please suggest some solutions that I can try?

A: LocalSettings.php is loaded before MediaWiki parses the URL and there are enough edge cases that you shouldn't want to do it yourself.
One option is to use something that runs early but after basic variables have been set up (like BeforeInitialize) and disable the extension there based on the title (something like $wgHooks['EditPage::showEditForm:initial'] = array_diff( $wgHooks['EditPage::showEditForm:initial'], [ 'ClipSetup' ] );.
Or you might try to fix the extension / file a bug (discarding clipboard content that's not an image seems pretty trivial).


text:
Q: Custom coordinate operation in GeoServer I'm trying to create custom Coordinate Operation in GeoServer version 2.22.0, but I get this error in the geoserver.log:

WARN   [referencing.factory] - Error creating transformation: CONCAT_MT[ INVERSE_MT[ PARAM_MT["NADCON", PARAMETER["Latitude difference file", "Slovakia_JTSK03_to_JTSK.LAS"], PARAMETER["Longitude difference file", "Slovakia_JTSK03_to_JTSK.LOS"]]], PARAM_MT["Coordinate Frame rotation (geog2D domain)", PARAMETER["X-axis translation", 485.021], PARAMETER["Y-axis translation", 169.465], PARAMETER["Z-axis translation", 483.839], PARAMETER["X-axis rotation", -7.786342], PARAMETER["Y-axis rotation", -4.397554], PARAMETER["Z-axis rotation", -4.102655], PARAMETER["Scale difference", 0]]]

Unfortunately the log doesn't contain anything other relevant to the transformation. I have tried to set the logging level to GEOSERVER_DEVELOPER_LOGGING, GEOTOOLS_DEVELOPER_LOGGING and VERBOSE_LOGGING, but I did not find anything more.
This is the content of epsg_operations.properties file:
4156,4326=CONCAT_MT[ \
  INVERSE_MT[ \
    PARAM_MT["NADCON", \
      PARAMETER["Latitude difference file", "Slovakia_JTSK03_to_JTSK.LAS"], \
      PARAMETER["Longitude difference file", "Slovakia_JTSK03_to_JTSK.LOS"]]], \
  PARAM_MT["Coordinate Frame rotation (geog2D domain)", \
    PARAMETER["X-axis translation", 485.021], \
    PARAMETER["Y-axis translation", 169.465], \
    PARAMETER["Z-axis translation", 483.839], \
    PARAMETER["X-axis rotation", -7.786342], \
    PARAMETER["Y-axis rotation", -4.397554], \
    PARAMETER["Z-axis rotation", -4.102655], \
    PARAMETER["Scale difference", 0]]]

When I remove the "NADCON" transformation or the "Coordinate Frame rotation (geog2D domain)" transformation, then it works. So the syntax for these transformations should be correct.
I have also tried to combine the "NADCON" transformation with "Molodenski" transformation from GeoServer examples and that also works.
Is there some limitation to what transformations you can chain together?


text:
Q: Write numbers from 1 to 10, set cursor position to the beginning and restart the writing I just came to a strange behavior which I can't explain. I have a console application that writes numbers from 1 to 9 and then sets the cursor to the beginning of the console window again. After that, the loop goes on and restarts writing the numbers from 1 to 10. The problem is that the numbers written before get overwritten instead of moved forward.
My code for better understanding:
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int counter = 0; counter < 10; counter++)
{
    foreach (int number in numbers)
    {
        Console.Write(number + " ");
        Thread.Sleep(5);
    }
    Console.SetCursorPosition(0, 0);
}

When I add the line Console.Write("Test"); below Console.SetCursorPosition(0, 0);, I get the following output:

Test1 2 3 4 5 6 7 8 9

What I didn't expect: When adding Console.Write(1); below, I get

1 2 3 4 5 6 7 8 9

With my code I wanted to achieve the following:

1 2 3 4 5 6 7 8 9 [now setting cursor position to the beginning and moving the consisting numbers forward] 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 [and so on]

Why isn't the program behaving like this?

A: Obviously when you set the cursor of the console to 0,0 you will start overwriting previous values, because of that this happen. You can do this easily with strings concatenation, but I advice you to use StringBuilder because it is muttable.
    public static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();

        int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        for (int counter = 0; counter < 10; counter++)
        {
            StringBuilder numberBuilder = new StringBuilder();
            foreach (int number in numbers)
            {
                numberBuilder.Append(number + " ");
            }

            sb.Insert(0, numberBuilder.ToString());
        }

        Console.WriteLine(sb.ToString());
    }

Here dotnet fiddle example

A: The console is like a canvas, once something is written to it the text is "painted on" till something paints over it or erases it.
When you move the cursor to the start you start overwriting the old text, letter by letter. See this example
Console.Write("This is some long text");
Console.SetCursorPosition(0, 0);
for(int i = 0; i < 30; i++)
{
    Console.Write("z");
    Thread.Sleep(1000);
}

You can see the text written over slowly, one letter per second.
To get the effect you are looking for you need to keep a buffer in memory of the entire string and edit that string buffer, after you update the buffer you have to write out the entire line again. A easy way to to this is using a StringBuilder to act as the buffer (UPDATE: See mybirthname's answer for example usage)


text:
Q: Restore hierarchical column index when using groupby in pandas I am using groupby in pandas to compute some aggregates statistics in pandas on data where columns in a data frame are organized with a hierarchical index.
For the computed statistics I want to get back to a table form in the end, where the groups are reconverted to columns with the group values, e.g. like:
index = pd.MultiIndex.from_tuples([('A', 'a'), ('B', 'b')])
df = pd.DataFrame(np.random.randn(8,2), columns=index)

which results in e.g. this data frame
          A         B
          a         b
0  0.511157  0.334748
1  0.031113 -0.477456
2  0.288080 -0.258238
3  0.138467 -0.955547
4 -0.087873  0.017494
5 -0.667393  1.190039
6 -0.068245 -1.282864
7 -0.996982  0.589667

Now I compute the statistics using groupby and reset the index to recreate a flat data frame:
df.groupby([('A','a')]).mean().reset_index()
     (A, a)         B
                    b
0 -0.996982  0.589667
1 -0.667393  1.190039
2 -0.087873  0.017494
3 -0.068245 -1.282864
4  0.031113 -0.477456
5  0.138467 -0.955547
6  0.288080 -0.258238
7  0.511157  0.334748

How can I achieve that ('A', 'a') becomes a part of the multi index again, hopefully in an automatic fashion? Or stated otherwise: is there a way to preserve the hierarchical column structure during the groupby operation.

A: For me work add parameter as_index=False to groupby:
print df.groupby([('A','a')], as_index=False).mean()
          A         B
          a         b
0 -0.765088 -0.556601
1 -0.628040  2.074559
2 -0.516396 -2.028387
3 -0.152027  0.389853
4  0.450218  1.474989
5  0.718040 -0.882018
6  1.932556 -0.977316
7  2.028468 -0.875167

A: The simplest thing to do is reassign back the original columns:
In [182]:
df1 = df.groupby([('A','a')]).mean().reset_index()
df1.columns = df.columns
df1

Out[182]:
          A         B
          a         b
0 -0.857465 -0.761948
1 -0.263677  0.538251
2  0.067710 -1.038906
3  0.345584 -0.425514
4  0.478200  0.119345
5  0.639305  0.047526
6  1.528260  1.956677
7  3.114834 -0.532462


text:
Q: WCF service stream byte array size issue I have a WCF service that returns a stream object. But for some reason i get a corrupt zip file back which i am streaming. All the code is below Please advise
Contract Code
[ServiceContract(Namespace = "http://schemas.acme.it/2009/04/01")]
public interface IFileTransferService
{
    [OperationContract(IsOneWay = false)]
    FileDownloadReturnMessage DownloadFile(FileDownloadMessage request);

    [OperationContract()]
    string HellowWorld(string name);

}

[MessageContract]
public class FileDownloadMessage
{
    [MessageHeader(MustUnderstand = true)]
    public FileMetaData FileMetaData;
}

[MessageContract]
public class FileDownloadReturnMessage
{
    public FileDownloadReturnMessage(FileMetaData metaData, Stream stream)
    {
        this.DownloadedFileMetadata = metaData;
        this.FileByteStream = stream;
    }

    [MessageHeader(MustUnderstand = true)]
    public FileMetaData DownloadedFileMetadata;
    [MessageBodyMember(Order = 1)]
    public Stream FileByteStream;
}

[DataContract(Namespace = "http://schemas.acme.it/2009/04/01")]
public class FileMetaData
{
    public FileMetaData(string [] productIDs, string authenticationKey)
    {
        this.ids = productIDs;
     this.authenticationKey= authenticationKey;
    }

    [DataMember(Name = "ProductIDsArray", Order = 1, IsRequired = true)]
    public string[] ids;
    [DataMember(Name = "AuthenticationKey", Order = 2, IsRequired = true)]
    public string authenticationKey;
}

SVC file code
 public class DownloadCoverScan : IFileTransferService
    {
        public FileDownloadReturnMessage DownloadFile(FileDownloadMessage request)
        {
            FileStream stream = new FileStream(@"C:\Pictures.zip", FileMode.Open, FileAccess.Read);
            FileMetaData metaData= new FileMetaData(new string[] { "1", "2" },"asd");
            FileDownloadReturnMessage returnMessage = new FileDownloadReturnMessage(metaData,stream);
            return returnMessage;
        }
        public string HellowWorld(string name)
        {
            return "Hello " + name;
        }

    }

Config code
 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="DownloadCoverScanBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true" httpHelpPageEnabled="true" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="DownloadCoverScanBehavior" name="DownloadService.DownloadCoverScan">
        <endpoint address="" name="basicHttpStream" binding="basicHttpBinding" bindingConfiguration="httpLargeMessageStream"
                  contract="DownloadService.IFileTransferService" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="httpLargeMessageStream" maxReceivedMessageSize="2147483647" transferMode="Streamed"  messageEncoding="Mtom" />
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>

Client Code
        FileMetaData metaData = new FileMetaData();
        metaData.ProductIDsArray = new string[] { "1", "2" };
        metaData.AuthenticationKey = "test";
        FileDownloadMessage inputParam = new FileDownloadMessage(metaData);
        FileTransferServiceClient obj = new FileTransferServiceClient();
        FileDownloadReturnMessage outputMessage = obj.DownloadFile(inputParam);
        Byte[] buffer = new Byte[8192];
        int byteRead = outputMessage.FileByteStream.Read(buffer, 0, buffer.Length);
        Response.Buffer = false;
        Response.ContentType = "application/zip";
        Response.AppendHeader("content-length", buffer.Length.ToString());
        Response.AddHeader("Content-disposition", "attachment; filename=testFile.zip");
        Stream outStream = Response.OutputStream;
        while (byteRead > 0)
        {
            outStream.Write(buffer, 0, byteRead);
            byteRead = outputMessage.FileByteStream.Read(buffer, 0, buffer.Length);
        }
        outputMessage.FileByteStream.Close();
        outStream.Close();

A: The buffer size doesn't matter much, just pick a reasonable size, like:
Byte[] buffer = new Byte[8192];

There is also an error in your code, where you write the contents of the buffer:
outStream.Write(buffer, 0, buffer.Length);

should be:
outStream.Write(buffer, 0, byteRead);

Otherwise you will always write the entire buffer even if it's only partially filled with data.


text:
Q: Strange issue when calling same piece of code in multiple places in one template I am facing a strange issue. I have two method in a model. get_delivery_taxes and get_subtotal_taxes as shown below:
def get_delivery_taxes(self):
    delivery_tax_list = []
    if self.modifiers:
        if self.modifiers.get('Taxation', None):
            for tax in self.modifiers.get('Taxation'):
                if tax.get('delivery_tax', None):
                    delivery_tax_dict = tax.get('delivery_tax')

                    delivery_tax_amount = delivery_tax_dict['amount']
                    delivery_tax_dict['amount'] = Money(delivery_tax_amount, settings.DEFAULT_CURRENCY)

                    delivery_tax_list.append(delivery_tax_dict)
    return delivery_tax_list

def get_subtotal_taxes(self):
    subtotal_tax_list = []

    if self.modifiers:
        if self.modifiers.get('Taxation', None):
            for tax in self.modifiers.get('Taxation'):
                subtotal_tax_dict = None
                if tax.get('subtotal_tax', None):
                    subtotal_tax_dict = tax.get('subtotal_tax')

                    subtotal_tax_amount = subtotal_tax_dict['amount']

                    subtotal_tax_dict['amount'] = Money(subtotal_tax_amount, settings.DEFAULT_CURRENCY)

                    subtotal_tax_list.append(subtotal_tax_dict)
    return subtotal_tax_list

Those two methods are then used by these below methods to calculate their totals.
def get_subtotal_tax_price(self):
    subtotal_tax_price = 0
    for sub_tax_price in self.get_subtotal_taxes():
        subtotal_tax_price = subtotal_tax_price + sub_tax_price['amount']
    return subtotal_tax_price

def get_delivery_tax_price(self):
    delvry_tax_amount = 0
    for del_tax_price in self.get_delivery_taxes():
        delvry_tax_amount = delvry_tax_amount + del_tax_price['amount']
    return delvry_tax_amount

A final total is calculated using above two methods as below.
def get_order_final_total(self):
        subtotal = self.get_order_subtotal_price()
        subtotal_taxes = self.get_subtotal_tax_price()

        devilery_charges = self.get_order_delivery_charges_price()

        devilery_charges_taxes = self.get_delivery_tax_price()

        order_total = subtotal + subtotal_taxes + devilery_charges + devilery_charges_taxes
        return order_total

In my template, I use them as below:
{% for tax_dict in object.get_delivery_taxes %}
...
{% endfor %}

{% for tax_dict in object.get_subtotal_taxes %}
...
{% endfor %}

{{object.get_order_final_total}}

Doing this was working fine until I made changes to first two methods( get_delivery_taxes and get_subtotal_taxes). I added:
subtotal_tax_amount = subtotal_tax_dict['amount']

subtotal_tax_dict['amount'] = Money(subtotal_tax_amount, settings.DEFAULT_CURRENCY)

And:
subtotal_tax_amount = subtotal_tax_dict['amount']

subtotal_tax_dict['amount'] = Money(subtotal_tax_amount, settings.DEFAULT_CURRENCY)

I get this error:
File ".............\models.py", line 1251, in get_order_final_total
    devilery_charges_taxes = self.get_delivery_tax_price()
  File ".............\models.py", line 1240, in get_delivery_tax_price
    for del_tax_price in self.get_delivery_taxes():
  File ".............\models.py", line 1180, in get_delivery_taxes
    delivery_tax_dict['amount'] = Money(delivery_tax_amount, settings.DEFAULT_CURRENCY)
  File "C:\Users\user\Envs\myproj_py_38\lib\site-packages\moneyed\classes.py", line 83, in __init__
    amount = Decimal(str(amount))
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

But when I remove
{% for tax_dict in object.get_delivery_taxes %} ... {% endfor %}
AND
{% for tax_dict in object.get_subtotal_taxes %} ... {% endfor %}
OR
{{object.get_order_final_total}}
It no longer throws the error.
That Money() is from from moneyed import Money
Can anyone please point out what is going on.

A: After spending some hours on this I finally found the cause of this error.
As two methods access same code and try to change same dictionary it gives error since one the calls has already made a change(in this case, converting string 'amount' to Money()). The second call tries to update the same dict value assuming it is a string while it is actually Money().
So the solution is to copy dictionary and make changes to that like this below:
if tax.get('subtotal_tax', None):
    subtotal_tax_dict = tax.get('subtotal_tax')
    subtotal_tax_dict_copy = subtotal_tax_dict.copy()

    subtotal_tax_dict_copy['amount'] = Money(subtotal_tax_dict_copy['amount'], settings.DEFAULT_CURRENCY)

    subtotal_tax_list.append(subtotal_tax_dict_copy)

This gives you a new dictionary and then you can make changes to its value without affecting the original dict.


text:
Q: How do I center a link with other text next to it? I have pagination at the bottom of a page and I'd like to keep the "Page 1 of 2" centered and just have the "Older" and "Newer" buttons wrap to it, even if there is only one of the two buttons present.
Here's what I currently have:

.wrapper {
  background-color: #aaa;
  width: 540px;
  margin: 0 auto;
  text-align: center;
}
.links {} .page {}

  Older
  Page 1 of 2

How do I keep "Page 1 of 2" centered in the div and just put the "Older" or "Newer" link adjacent to the left or right side of the span?

A: .wrapper {
  background-color: #aaa;
  width: 100%;
  margin: 0 auto;
}
.items {
    position: relative;
    text-align: center;
}
.item {
    margin: 0 5px;
}
.always-left, .always-right {
    position: absolute;
    top: 0;
}

.always-left {
    left: 0;
}

.always-right {
    right: 0;
}

  Older

Page 1 of 2

  Older

A:

.wrapper {
  width: 540px;
  background: #CCC;
  margin: 0 auto;
  text-align: center;
}
.links {
  float: left;
}
.newer {
  float: right;
}

  Older
  Page 1 of 2
  Newer

In order to have the links stick to the left (and right), you need to remove the links from the normal flow, using float.
View it here.
CSS
.links{
  float:left;
}
.newer{
  float:right;
}

HTML

  Older
  Page 1 of 2
    Newer

A: Here's one way to do it

.wrapper {
    background-color: #aaa;
    width: 540px;
    position: relative;
}
.links {
    position: absolute;
    /* half width of the container - width of "Page 1 of 2" - 10px margin */
    left: calc(50% - 73px - 10px);
}
.page {
    display: table;
    margin: auto;
}

    Older
    Page 1 of 2


text:
Q: Heroku automatic db backup via cron job Is it possible to backup Heroku database using cron jobs?
I tried putting the following line into cron.rake:
heroku pgbackups:capture --expire

However it didn't work. The line works when I run it from Terminal.
Can you help?

A: Check out the heroku_s3_backup gem, which packages up the code necessary to do this in a neat way.

A: The gem heroku_backup_task integrates directly with the free PG Backups add-on for Heroku.


text:
Q: насколько опасно установить opensuse rpm пакет на centos 6? В связи с тем, что под centos package не существует в сети нашёлся этот же rpm пакет но для дистрибутива opensuse
Интересует какие проблемы могут возникнуть если его установить на centos 6 (собрав из исходников или установив уже собранный пакет)


text:
Q: How to display correctly Treeview with QML Qt 5.5 I'm trying to create a correct Treeview with Qml Qt 5.5.
I succeed to have a Treeview with a global root.
But impossible to find how to add child for row item.
For the moment I got something like that :
    TreeView {
        id:listTree
        anchors.fill: parent
        anchors.leftMargin: 1
        headerVisible: false
        backgroundVisible: false

        selection: ItemSelectionModel {
            model: myModel
        }
        TableViewColumn {
            role: "name"
        }

        itemDelegate: Item {
            Text {
                anchors.verticalCenter: parent.verticalCenter
                color: styleData.textColor
                elide: styleData.elideMode
                text: styleData.value
            }
        }

        Component.onCompleted: {
            model.append({"name":"Never"})
            model.append({"name":"gonna"})
            model.append({"name":"give"})
            model.append({"name":"you"})
            model.append({"name":"up"})
            model.append({"name":"Never"})
            model.append({"name":"gonna"})
            model.append({"name":"let"})
            model.append({"name":"you"})
            model.append({"name":"dow"})
        }
    }

And I would like something like that :

How can I do it ?

A: You can also create a TreeModel class that extends QStandardItemModel and overrides roleNames(), like done here. To add children to nodes in your tree, just use appendRow().
TreeModel::TreeModel(QObject *parent) : QStandardItemModel(parent)
{
    QStandardItem *root = new QStandardItem("root");
    QStandardItem *child = new QStandardItem("child");
    this->appendRow(root);
    root->appendRow(child);
}

A: Your model doesn't have any parent child relationships which is why its displayed like a list.
You'll want your "TreeModel" to be a collection of TreeItems. Each TreeItem will have knowledge of their own children and their parent item.
You can follow a fully implemented Qt example found here http://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html. You'll want to (in C++) make a class for TreeItem, and a separate class for your TreeModel.
That example is working code, you can just copy and paste it and get a working model for your TreeView.
The part you'll be particularly interested in is the implementation of the method setupModelData(). That's where you'll want to parse through your wonderful dataset of 80's lyrics and assign each of them a TreeItem.
Each TreeItem (one for every row of data) should be given knowledge of its parent upon creation (in its constructor). Then as soon as its children are created, call parentTreeItem.appendChild(childTreeItem)
When your model is completed, you can assign it to your qml view in a few ways, registering it with qmlRegisterType is what I prefer (http://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterType)
Once registered, it can be created in qml as though it were a ListView or any other qml object.
NOTE: You'll have this rootItem. This is something that isn't usable by the view, but all your "first indentation" parents are children of the rootItem.
Good luck!
Can you provide a code snippet of what line is causing your about failing to make a shortcut for QAbstractItemModel?


text:
Q: Influence compile order of form_alter I've got multiple form_alters in my D7 website. One contrib and one custom. I need the custom module to overwrite the contrib module. But for some reason, the custom module is committing second...
How can I change the processing order of the hook_alters in Drupal?

A: You just need to pop into the system table in your database and change the status column for your module. If you want your hooks to run before another particular module's then change status to a smaller number than the other module's status in the table. If you want them to run after, change the status to a greater number.
You'll need to clear Drupal's cache once you've made the change in the table so it gets picked up.
See How to update a module's weight for a fuller explanation.


text:
Q: Uima Ruta Rule for Below Regex I need to annotate below cases. I have block of texts & need to get sub blocks of texts which contains banks.For example below is a complete text block i need to annotate Bank of America as Bank Name.

*

*hereinafter described and hereinafter referred to as Owner and Bank
of America  NA,successor in interest from
There could be many cases for bank name

*

*Bank of America [Bank in starting]

*Royal Bank of Scotland  [Bank in middle]

*Yes Bank [Bank in end]
etc.

So text need to be annotate totally depends on bank
I'm not able to write generic rule to cover all cases so far i've tried below rules
 - Rule 1

     W[0,3] BankNameKeyWord W[0,3] {-> MARK(BANKNAME,1,3)};(looking around bank for 3 words)

 - Rule 2

       W? W? W? BankNameKeyWord W? W? W? {-> MARK(BANKNAME,1,7)};

I'm looking for generic approach to cover all cases.

A: You could maybe apply a rule like:
(CW[0,3] @BankNameKeyWord SW.ct=="of"? CW[0,3]) {-> MARK(BANKNAME,1,3)};

but this does not solve your problem. As the commnets note, you need some linguistic preprocessing like a chunker. If it's just bank names, you could consider a dictionary.
DISCLAIMER: I am a developer of UIMA Ruta


text:
Q: Remove duplicates conditional on dummy variable I have a data frame with partly duplicated IDs and a dummy variable. I want to remove all rows with duplicate IDs, but only if the dummy variable is equal to 1.
Consider the following example data:
# Example data
df <- data.frame(id = c(1, 2, 3, 3, 4, 4, 5, 5, 5),
                 values = c(0, 1, 1, 0, 0, 0, 1, 0, 0))

The output should look as follows
# Expected output
df_expected <- df[- c(3, 7), ]

How coul I remove all duplicates where values is equal to 1?

A: We can create a logical condition with duplicated on the 'id' column and those where 'values' is 1
i1 <- (duplicated(df$id)|duplicated(df$id, fromLast = TRUE)) & df$values == 1
df[!i1, ]
#  id values
#1  1      0
#2  2      1
#4  3      0
#5  4      0
#6  4      0
#8  5      0
#9  5      0

or with filter from dplyr
library(dplyr)
df %>%
   group_by(id) %>%
   filter(!values|n() == 1)


text:
Q: Retrieve data from a For XML subquery I am creating a table as follows:
CREATE TABLE dbo.Test
(
  A int,
  B int
)

GO

INSERT INTO Test VALUES (1, 11)
GO

INSERT INTO Test VALUES (5, 55)
GO

INSERT INTO Test VALUES (4, 44)
GO

I have a query which converts this into XML as :
  SELECT A,B
  FROM Test
  ORDER BY A
  FOR XML AUTO, ROOT ('myroot'), ELEMENTS

I need to use the above query as a subquery to get the following result:
A           B
1           11
4           44
5           55

I am trying a query like this but it gives an error:
SELECT Z.Value('@A', 'INT'),
   Z.Value('@B', 'INT')
FROM (SELECT A, B
  FROM Test
  ORDER BY A
  FOR XML AUTO,Elements, ROOT ('myroot')) Doc(Z)

Msg 4121, Level 16, State 1, Line 1
  Cannot find either column "Z" or the user-defined function or aggregate "Z.Value", or the > name is ambiguous.

I can write a simple query like below to get the result but the requirement is that I have to convert it into XMl and then retrieve the same result from it using the subquery.
Select * from test order by A
I know that I can insert the records returned by For XML in a table variable and then use Cross apply to fetch the result but as said above, I am looking to get this done in a single query without any temporary table or temporary variable.

A: There're a several issues here. First, your xml looks like this:
<myroot>
    <Test>
         111
    </Test>
    <Test>
         444
    </Test>
    <Test>
         555
    </Test>
</myroot>

And you're trying to fetch data as attributes (@A, @B). You need to fetch it as elements (A[1] or (A/text())[1]).
Second, you have to use type keyword if you want your xml to be xml type.
Third, to split data by rows you need nodes() function. So your query becomes:
select
   D.Z.value('(A/text())[1]', 'int'),
   D.Z.value('(B/text())[1]', 'int')
from (
   select A, B
   from Test
   order by A
   for xml auto, elements, root('myroot'), type
) as Doc(Z)
    outer apply Doc.Z.nodes('myroot/Test') as D(Z)

BTW, I'd better to use attributes, like this:
select
   D.Z.value('@A', 'int'),
   D.Z.value('@B', 'int')
from (
   select A, B
   from Test
   order by A
   for xml raw('Test'), root('myroot'), type
) as Doc(Z)
    outer apply Doc.Z.nodes('myroot/Test') as D(Z)

sql fiddle demo

A: You forgot TYPE mode (without it you get nvarchar instead of xml) and value keyword should be in lower-case.
Try this:
SELECT Z.Z.value('@A', 'INT'),
    Z.Z.value('@B', 'INT')
FROM (
    SELECT A, B
    FROM Test
    ORDER BY A
    FOR XML AUTO, ROOT ('myroot'), TYPE
) Doc(Doc)
CROSS APPLY Doc.nodes('/myroot/Test')Z(Z)

But I would prefer generating XML without AUTO mode (your query would break down if you write dbo.Test instead of Test), in more declaretive way using PATH keyword:
SELECT Z.Z.value('@A', 'INT'),
    Z.Z.value('@B', 'INT')
FROM (
    SELECT A AS '@A', B AS '@B'
    FROM dbo.Test
    ORDER BY A
    FOR XML PATH('Test'), ROOT ('myroot'), TYPE
) Doc(Doc)
CROSS APPLY Doc.nodes('/myroot/Test')Z(Z)


text:
Q: Cannot update nor insert data to datetime field I was trying to insert data through one web application I am developing and I could not insert data, while I was troubleshooting what the problem is, I saw that I can not neither edit datetime field even directly through Microsoft SQL Server Management Studio.
I am trying to update a datetime field in SQL Server 2014 but i am getting this weird error

I am trying to make the first row same as the second one and I am getting the above error:

I have full-permission user and I also can edit all other columns except of datetime type columns!
Any help in this regard would be more then welcome.
Here is the column definition:

A: This has nothing to do with a permissions issue.
The error message clearly states:

Conversion failed when converting the varchar value 'Receive' to data type int

So you typed the varchar value 'Receive' in another column of data type int, and it most likely has nothing to do with the datetime column.


text:
Q: Outlook 365 does not automatically add shared mailbox Each user here has a personal mailbox e.g.: personA@company.com.
Some users also have Full Access and Send As rights to a shared mailbox e.g.: shared@company.com.
In Outlook 365 the user's personal mailbox and the shared mailbox show up.
However, we are not able to send an email from the shared mailbox or set up a default signature as the shared mailbox does not show up in the list of mailboxes.
We know we can add the shared mailbox in the "From" field when composing a new email. However, when using this methode the mail is sent out from the user's personal mailbox (although to the receiver it looks like it's being sent from the shared mailbox).
Is it possible to have the shared mailbox just show up automatically when composing a new e-mail and to also have it in the list of signatures?

A: When using a shared mailbox, Outlook treats it as a secondary mailbox; this means that, unless you explicitly tell it (by setting the "From:" field) that you want to send a message from the shared mailbox, Outlook will default to using your main one. The same is true for signatures, which are stored in the main mailbox.
If you want Outlook to behave like the shared mailbox was the main one, you need to add it to Outlook as an actual Exchange account; but for this you need an user mailbox (a shared mailbox can't be directly accessed).

About "when using this method the mail is sent out from the user's personal mailbox": I'm assuming you are talking about the "Sent Items" folder where the sent messages are saved; this defaults to the main mailbox even when sending from a shared one. There are workarounds for this: https://docs.microsoft.com/en-us/exchange/troubleshoot/shared-mailboxes/sent-mail-is-not-saved.


text:
Q: Adding border to group of buttons in swift I am trying to add a border to a group of buttons that are all within the same stack view. I want the buttons to share the same leading and trailing borders, and the edges of the group of buttons to be rounded.
I tried embedding the buttons in a stack view, then embedding the buttons in views within the stack view, but still have not been able to get it right.

A: First apply layoutMargins with UIEdgeInsets to have spacing, then for each button in stackView, change cornerRadius
    stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) // change 20 with your value.
    // then for each of subviews in stackview, if it is a button, apply corner radius
    stackView.subviews.forEach { view in
        if view is UIButton {
            view.layer.cornerRadius = 5 // replace it with your value.
        }
    }


text:
Q: No errors shown rendering an included file in Django/GAE Usually an error message is shown in browser if any error occured processing a Django/GAE template. But once such error is contained in an included file, then none message is shown - the "include" tag produces just blank output making development difficult.
Is there a way to show all errors?

A: Write a unit test in tests.py, where you render the template using django.templates.Template. Check there whether it renders to something else than None or "" or white space.
Once that unit test succeeds, you can proceed with the next one:
Use self.client to render the template using the full stack. If the problem is here and not in the previous unit test, something is probably wrong with your view function.
If you don't enclose your code under test in try-catch, you get the full stack trace when something goes wrong. If there is no stack trace, but your test fails, you know you did something wrong.
In my opinion, unit tests in Django are real time-savers.


text:
Q: What syntax am i missing out on regarding char arrays and pointers to them I was doing some testing for a program of mine and was wondering why the program was crashing when entering my function. Don't mind the logic of the program, since i was still in the phase of making sure i understood how to use my tools at hand.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Constants */
#define HEX_CAPITAL_LETTERS_BEGIN 65
#define HEX_CAPITAL_LETTERS_END 90
#define HEX_NUMBERS_BEGIN 48
#define HEX_NUMBERS_END 57
#define EXIT_SUCCES 0

/* Prototypes */
void codeToField(char *charArray, int i, int hexFloor, int hexCeil, char *outputArray);

/* Main Function */
int main(void) {
  char *code, warehouse, product, qualifiers;
  int i = 0;

  printf("Enter a MMOC product code: ");
  scanf("%s", &code);

  codeToField(code, i, HEX_CAPITAL_LETTERS_BEGIN, HEX_CAPITAL_LETTERS_END, &warehouse);
  codeToField(code, i , HEX_NUMBERS_BEGIN, HEX_NUMBERS_END, &product);

  strcpy(&qualifiers, code + i);

  printf("\n\nWarehouse: %s\nProduct: %s\nQualifiers: %s\n", &warehouse, &product, &qualifiers);

  return EXIT_SUCCES;
}

void codeToField(char *charArray, int i, int hexFloor, int hexCeil, char *outputArray) {
  int j = 0;
  while (charArray[i] >= hexFloor && charArray[i] <= hexCeil) {
    outputArray[j] = charArray[i];
    i++;
    j++;
  }
}

Thanks in advance.

A: First, this does not do what you want:
char *code, warehouse, product, qualifiers;

The only pointer is code, the other are just a single char. You're printing them as strings with printf, and you use warehouse and product as outputArray in your function. They need to be pointers (or arrays) too:
char *code, *warehouse, *product, *qualifiers;

Then you need memory. The pointers are still uninitialized, so any reading from them is undefined behavior.
You can either allocate memory with automatic storage duration (on the stack) or dynamically (on the heap).
Stack:
char codestr[100];
code = codestr;

but then, you could also just have declared code as
char code[100];

to avoid to have two variables.
If you want to allocate the memory dynamically, you would use malloc:
code = malloc(100);

Don't forget to free the memory again:
free(code);

warehouse, product, qualifiers all need memory too. Some of the array sizes could be deduced form the defined constants.

A: The reason is because code has no memory allocated to it. It is an uninitialized pointer. Try this instead:
// ...
char myString[16], *code, warehouse, product, qualifiers;
code = &myString[0];
int i = 0;

printf("Enter a MMOC product code: ");
scanf("%15s", code);
// ...

A:   char *code, warehouse, product, qualifiers;
  int i = 0;

  printf("Enter a MMOC product code: ");
  scanf("%s", &code);

Here, code is an uninitialized pointer to memory so once you do the scanf call, your program is hosed.
I think you want something more like
char code[100];
printf ("Enter a MMOC product code: ");
scanf ("%s", code);


text:
Q: Removing <![CDATA[//> from HTML I am  trying to remove [CDATA[ from  HTML file but  it is not working
This is the code I got
from bs4 import BeautifulSoup

def stripIt(string, tag):
    soup = BeautifulSoup(string)
    data = open("tet.txt",'a')
    rmtags = soup.findAll(tag)
    for t in rmtags:
        string = string.replace(str(t), '')
        data.write(string)
    return string

testhtml = '''

<![CDATA[//><!]]>

അവഹേളനപരവും വ്യക്തിപരമായ അധിക്ഷേപങ്ങളും അശ്‌ളീല പദപ്രയോഗങ്ങളും ദയവായി ഒഴിവാക്കുക. അഭിപ്രായങ്ങള് മലയാളത്തിലോ ഇംഗ്ലീഷിലോ എഴുതുക. മംഗ്ലീഷില് എഴുതുന്ന അഭിപ്രായങ്ങള് പോസ്റ്റ് ചെയ്യുന്നതല്ല.
ഇംഗ്ലീഷില് ടൈപ് ചെയ്ത് മലയാളമാക്കാനുള്ള സംവിധാനം ഏര്‍പ്പെടുത്തിയിട്ടുണ്ട്  ടൈപ്പ് ചെയ്യാന് ഇവിടെ ക്ലിക്ക് ചെയ്യുകബൈക്കില് കാട്ടുപന്നിയിടിച്ച് മറിഞ്ഞു: അച്‌ഛനും മകനും പരുക്ക്‌പുല്‍പ്പള്ളി: ഓടിക്കൊണ്ടിരുന്ന ബൈക്കിലേക്ക് കാട്ടുപന്നി... കര്‍ഷക വഞ്ചനക്ക് തെരഞ്ഞെടുപ്പില് തിരിച്ചടി നല്‍കാന് ഹരിതസേന തയാറെടുക്കുന്നുമാനന്തവാടി: ആസന്നമായ പൊതുതെരഞ്ഞെടുപ്പ് ലക്ഷ്യമാക്കി കര്‍ഷക ക്ഷേമ... കോളനി വികസനത്തിന് രണ്ട് കോടിയുടെ ഭരണാനുമതികല്‍പ്പറ്റ: പടിഞ്ഞാറത്തറ പഞ്ചായത്തിലെ പാറനിരപ്പുകുന്ന്, ചെമ്പകമൂല... ടെക്‌ഫെസ്‌റ്റ്: മത്സര വിജയികള്‍ക്ക് കാല്‍ലക്ഷത്തിലേറെ തുക സമ്മാനംകല്‍പ്പറ്റ: നൂതനങ്ങളായ സാങ്കേതിക ഉല്‍പന്നങ്ങളെയും പദ്ധതികളേയും... ബത്തേരി സമ്പൂര്‍ണ പെന്‍ഷന് പഞ്ചായത്തായിബത്തേരി: സമ്പൂര്‍ണ പെന്‍ഷന് പദ്ധതി നയത്തിന്റെ ഭാഗമായി ബത്തേരി... ബത്തേരി ഉപജില്ലാ കലോത്സവം: മീനങ്ങാടി ജി.എച്ച്.എസ്. ചാമ്പ്യന്‍മാര്‍പുല്‍പ്പള്ളി: വിജയ എച്ച്.എസ്.എസില് നടന്ന 54 -ാമത് ബത്തേരി... പുകയില ഉപയോഗത്തിനെതിരേ സൈക്കിള് യാത്രകല്‍പ്പറ്റ: പുകയില ഉത്‌പന്നങ്ങളുടെ ഉപയോഗം ഉപേക്ഷിക്കണമെന്ന... അഞ്ചു വര്‍ഷത്തിനിടെ വയനാടിന് നഷ്‌ടമായത് അഞ്ചര കോടി രൂപകല്‍പ്പറ്റ: സര്‍ക്കാര് സ്‌കൂളുകളില് ചിത്രകലാ അധ്യാപകരുടെയും... പാരലല് കോളേജ് ജില്ലാ കായികമേള: ബത്തേരി മലബാര് കോളേജിന് ഒന്നാം സ്‌ഥാനംകല്‍പ്പറ്റ: എസ്.കെ.എം.ജെ. ഹയര്‍സെക്കന്‍ഡറി സ്‌കൂള് ഗ്രൗണ്ടില്... ക്രിസ്‌മസ്, പുതുവത്സര ആഘോഷങ്ങള് മദ്യവിമുക്‌തമാക്കണംമാനന്തവാടി: ക്രിസ്‌മസ്, പുതുവത്സര ആഘോഷങ്ങള് മദ്യവിമുക്... ക്രിസ്‌തുമസ്-പുതുവത്സരാഘോഷം: വ്യാജമദ്യ ഉല്‍പ്പാദനം തടയുന്നതിന് കണ്‍ട്രോള് റൂംകല്‍പ്പറ്റ: ക്രിസ്‌തുമസ്-പുതുവത്സര ആഘോഷത്തോടനുബന്ധിച്ച്... സ്‌റ്റേഡിയം ഉദ്‌ഘാടനം: റോഡ്‌ഷോ നടത്തികല്‍പ്പറ്റ:  ഈ മാസം 17-ാം തീയതി ഉദ്‌ഘാടനം ചെയ്യപ്പെടുന്ന കൃഷ്...

 സെന്‍സെക്‌സ് 200 പോയന്റ് ഇടിഞ്ഞു

 പാകിസ്താനില് മിസൈല് ആക്രമണം: 16 മരണം

 സച്ചിന് രാജ്യസഭാംഗമായി സത്യപ്രതിജ്ഞ ചെയ്തു

 സെന്‍സെക്‌സ് 200 പോയന്റ് ഇടിഞ്ഞു

 പാകിസ്താനില് മിസൈല് ആക്രമണം: 16 മരണം

 സച്ചിന് രാജ്യസഭാംഗമായി സത്യപ്രതിജ്ഞ ചെയ്തു

'''
#print  stripIt(testhtml, 'li')

How to fix it?

A: You can remove CDATA from the entire string like this:
from bs4 import CData

soup = BeautifulSoup.BeautifulSoup(testhtml)
for cd in soup.findAll(text=True):
  if isinstance(cd, CData):
    cd.replaceWith('')

A: This code uses a regular expression to find [CDATA[ - and can be customised to remove any string you would like to remove.
import re
string = '<![CDATA[//><!]]>'
first = re.search('\[CDATA\[', string)
string = string[:first.span()[0]]+string[first.span()[1]:]

If there are multiple versions of [CDATA[ (or any other string) to remove, you could use the following:
import re
string = '<![CDATA[//><!]]>, [CDATA['
first = re.finditer('\[CDATA\[', string)
for element in first:
    print element.span()
    string = string[:element.span()[0]]+string[element.span()[1]:]
print string


text:
Q: How to get authenticated users from firebase database? I'm creating app where I will be using Firebase messaging service. Messaging is  working fine, but now I wish to make it happen between two users.
I believe I need to provide a authentication  for each user then search for their connections(their friends  via their social network connections or their mail ids).
I managed to create Google+ authentication in my app using Auth.GOOGLE_SIGN_IN_API and AppInvite.API, but connecting to other users in firebase had no clue, then I went through these links Udacity tutorial and Codelabs tutorial and the Firebase  guides. (The tutorials explained the same thing and every one authenticated using the email provider, and not via the Google+ signin. And as a matter fact when I initially tried Google+ signin via these procedures, it didnt work, but email provider is working.)
Anyways email provider is also good for me as of now but still don't have a clue how to connect two users thriugh Firebase. I connected two users, its showing in my Firebase authentication console but how to connect two user one to one?
Any clues??

A: To make a connection between two users in a social network, typically one of them has to enter some "secret" details about the other user. Most common is that you have to enter the email address of your friend and then the system will show you that it has a record matching that email address.
You could implement such a system on Firebase by having a list of email addresses with their corresponding uid:
userLookup
  "ari@stackoverflow,com": "uidOfAri"
  "puf@stackoverflow.com": "uidOfPuf"

Now when I type your email address, I can find your UID (and thus connect with you).
To secure the above, you'd only grant read access on specific users:
{
  "rules": {
    "userLookup": {
      "$user": {
        ".read": true
      }
    }
  }
}

With this structure you can read each specific user, but you cannot search the list of users. So I can only find your uid (and thus connect) if I know your complete email address.


text:
Q: Boundary effect in a wavelet multi resolution analysis What are the methods to minimize the effect of boundaries in a wavelet decomposition?
I use R and the package waveslim.
I have found for instance the function
?brick.wall

but

*

*I am not too use how to use it.

*I am not sure the best solution is to remove some coefficient. I have read somewhere that it exists some wavelets that are not the same everywhere and their shape change at the boudaries.
Any ideas?

A: I think this is a good question and I don't kown much about implementations. Since wavelet is 'mutli-resolution' you have two types of solutions (which are somehow connected):

*

*Modify your signal for example extend you signal over the actual boundary to have meaningfull coefficients.
Exemples of that are :

*

*periodic wavelet on the interval

*Zero padding (extend the signal by zero outside ist domain

*finer prodecure are extensions of zero padding with smoothness condition at the boundary.

*Modify the wavelet (somehow equivalent to threshold or lower wavelet coefficient that are near the boundary). More generally, there are procedures I know there have been many work  since that of A Cohen I Daubechies et P Vial   1993. For example, in (Monasse and Perrier, 1995), wavelet that forms a basis adapted to conditions such as Dirichlet or Neumann are constructed. I guess some are implemented ? If you found implementations, I am interested.
References:
Monasse and Perrier : 1995 CRAS Ondelettes sur lintervalle pour la prise en compte de conditions aux limites
A Cohen  I Daubechies et P Vial  Wavelets on the interval and fast wavelet transforms    Appl Comp Harmonic Analysis  (1993)


text:
Q: filter objects in two seperate subject foreach if I have a question. I am trying to filter a match game.
In the match game I want to filter the players ...but because there is a home and away team ....I want to seperate them. How is this possible.
my structure
Name    Type
Id  string
MatchNumber int
Date    string
Time    string
ClockDirection  string
TrueStartTime   string
TrueEndTime string
DepartmentId    string
DepartmentCode  string
DepartmentName  string
HomeTeamId  string
HomeClubId  string
HomeTeam    string
AwayTeamId  string
AwayClubId  string
AwayTeam    string
PoolId  string
PoolName    string
ResultHome  int
ResultGuest int
PeriodStandings MatchReportPeriodStandingsItem[]
Actions MatchReportActionsItem[]
Players MatchReportPlayersItem[]
Coaches MatchReportCoachesItem[]
Referees    MatchReportRefereesItem[]
Officials   MatchReportOfficialsItem[]

for the players info it's like this
MatchReportPlayersItem

Properties

Name    Type
Id  string
Cap string
Name    string
Captain boolean
Team    string

If I want to show a list of players It's like this
$Players = [];
                    foreach($Match->Players as $playerItem) {
                    $Players[] = $playerItem->Name . ' ' . $playerItem->Team;
                }

resulting in
De Craemer H, Van Der Linden H, Baeckelandt H, Christiaens H, Degryse H, Devos H, Dumoulin H, Gevaert H, Gheysen H, Louage H, Mestdag H, Monballieu H, Peremans H, Stieperaere H, Van Den Berghe H, Van Hoestenberghe H, Verschelde H, Verschelde H, Bekar G, Benabdelouahed G, Bochet G, Bourgeois G, Brahim G, Brismee G, Brismee G, Broutard G, Carin G

where the H and G ...stands for Home and Guest ....I want it in two separate list/table ...how am I gonna accomplish this.
So far I got this.
$Players = [];
                    foreach($Match->Players as $playerItem) {
                    $Players[] = $playerItem->Name . ' ' . $playerItem->Team;
                }
         if ($playerItem->Team == "G"){
        echo implode(', ', $Players); }
        else {
    echo " ";
}

can someone help me on this subject thanx!

A: You can do like this:
<?php

class Match {

    public $Players;

    public function __construct($players) {
        $this->Players = $players;
    }

}

class Player {

    public $Name;
    public $Team;

    public function __construct($name, $team) {
        $this->Name = $name;
        $this->Team = $team;
    }

}

$Match = new Match(
        array(
            new Player("John", "Gremio"),
            new Player("Mike", "Gremio"),
            new Player("Tom", "Inter"),
            new Player("Silva", "Inter")
        )
    );

$Players = [];
foreach ($Match->Players as $playerItem) {
    $Players[$playerItem->Team][] = $playerItem->Name;
}

var_dump($Players);

This output:
array(2) {
  'Gremio' =>
  array(2) {
    [0] =>
    string(4) "John"
    [1] =>
    string(4) "Mike"
  }
  'Inter' =>
  array(2) {
    [0] =>
    string(3) "Tom"
    [1] =>
    string(5) "Silva"
  }
}

EDITED (new solution):
<?php

class Match {

    public $Players;

    public function __construct($players) {
        $this->Players = $players;
    }

}

class Player {

    public $Name;
    public $Team;

    public function __construct($name, $team) {
        $this->Name = $name;
        $this->Team = $team;
    }

}

function getPlayersFromTeam($team, $players) {
    $Players = array();
    foreach ($players as $playerItem) {
        if ($playerItem->Team == $team) {
            $Players[$playerItem->Team][] = $playerItem->Name;
        }
    }
    return $Players;
}

$Match = new Match(
        array(
    new Player("John", "Gremio"),
    new Player("Mike", "Gremio"),
    new Player("Tom", "Inter"),
    new Player("Silva", "Inter")
        )
);

var_dump(getPlayersFromTeam("Gremio", $Match->Players));
var_dump(getPlayersFromTeam("Inter", $Match->Players));


text:
Q: How to extract content from webpage as seen from browser using python I am trying to extract the data that is on this website "https://www.ncbi.nlm.nih.gov/nucleotide/209750423?report=genbank#". When I use urllib to extract the content, I am able to extract data that which I get by choosing 'view page source' after right-clicking on browser, but what I want is the actual sequence 'atggctgaga tgaaaaacct gaaaattgag gtggtgcgct ataacccgga....' to be extracted which is visible by right-clicking on browser and selecting 'inspect element' but not through 'view page source'
The code which I am using is
f = open('out.html', 'w')
response = urllib.urlopen("https://www.ncbi.nlm.nih.gov/nucleotide/209750423?report=genbank")
f.write(response.read())
f.close()

A: Data are loaded by js so you can get the data below:
import requests
from pyquery import PyQuery

r = requests.get("https://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?val=209750423&db=nuccore&dopt=genbank&extrafeat=976&fmt_mask=0&retmode=html&withmarkup=on&log$=seqview&maxplex=3&maxdownloadsize=1000000")
pq = PyQuery(r.content)
div = pq(".ff_line")

data = []
for d in div:
    data.append(d.text)

print data

A: You should take the time to actually look at the page you want to scrape. It's just a page that loads some JS application. The application then loads the actual data from another place.
https://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?val=209750423&db=nuccore&dopt=genbank&retmode=text
By the way, be sure to check copyright issues before scraping online content.