Q:

Multiplication division using DFSORT utility in Mainframe

There are two files FILE1.DATA and FILE2.DATA
To calculate percentage (Number of records in FILE1/Number of records in FILE2)*100 using DFSORT in Mainframe. And setting Return Code if it crossing a threshold (90%).
//********Extracting Unique records data*****************
//SORTT000 EXEC PGM=SORT
//SYSOUT   DD  SYSOUT=*
//SORTIN   DD  DSN=SAMPLE.DATA1,DISP=SHR
//SORTOUT  DD  DSN=FILE1.DATA,
//             SPACE=(2790,(5376,1075),RLSE),
//             UNIT=TSTSF,
//             DCB=(RECFM=FB,LRECL=05,BLKSIZE=0),
//             DISP=(NEW,CATLG,DELETE)
//SYSIN    DD  *
 SORT FIELDS=(10,5,CH,A)
 OUTREC FIELDS=(1:10,5)
 SUM FIELDS=NONE
/*
//************Getting count of records*****************
//STEP001  EXEC PGM=ICETOOL
//TOOLMSG  DD SYSOUT=*
//DFSMSG   DD SYSOUT=*
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//IN1      DD DISP=SHR,DSN=FILE1.DATA
//IN2      DD DISP=SHR,DSN=FILE2.DATA
//OUT1     DD DSN=FILE1.DATA.COUNT,
//            SPACE=(2790,(5376,1075),RLSE),
//            UNIT=TSTSF,
//            DCB=(RECFM=FB,LRECL=06,BLKSIZE=0),
//            DISP=(NEW,CATLG,DELETE)
//OUT2     DD DSN=FILE2.DATA.COUNT,
//            SPACE=(2790,(5376,1075),RLSE),
//            UNIT=TSTSF,
//            DCB=(RECFM=FB,LRECL=06,BLKSIZE=0),
//            DISP=(NEW,CATLG,DELETE)
//TOOLIN   DD *
   COUNT FROM(IN1)  WRITE(OUT1) DIGITS(6)
   COUNT FROM(IN2)  WRITE(OUT2) DIGITS(6)
/*
//*******Calculating percentage and if above 90% setting RC 04*****
//STEP002  EXEC PGM=SORT
//SYSOUT   DD SYSOUT=*
//SORTIN   DD DSN=FILE2.DATA.COUNT,DISP=SHR
//         DD DSN=FILE1.DATA.COUNT,DISP=SHR
//SORTOUT  DD DSN=FILE.DATA.COUNT.OUT,
//            SPACE=(2790,(5376,1075),RLSE),
//            UNIT=TSTSF,
//            DCB=(RECFM=FB,LRECL=80,BLKSIZE=0),
//            DISP=(NEW,CATLG,DELETE)
//SETRC    DD SYSOUT=*
//SYSIN    DD *
  INREC IFTHEN=(WHEN=INIT,BUILD=(1,6,X,6X'00',SEQNUM,1,ZD,80:X)),
  IFTHEN=(WHEN=(14,1,ZD,EQ,2),OVERLAY=(8:1,6))
  SORT FIELDS=(7,1,CH,A),EQUALS
  SUM FIELDS=(8,4,BI,12,2,BI)
  OUTREC OVERLAY=(15:X,1,6,ZD,DIV,+2,M11,LENGTH=6,X,
                 (8,6,ZD,MUL,+100),DIV,1,6,ZD,MUL,+100,EDIT=(TTT.TT))

  OUTFIL FNAMES=SETRC,NULLOFL=RC4,INCLUDE=(23,6,CH,GT,C'090.00')
  OUTFIL BUILD=(05:C'TOTAL NUMBER RECRODS IN FILE2        : ',1,6,/,
                05:C'TOTAL NUMBER RECRODS IN FILE1        : ',8,6,/,
                05:C'PERCENTAGE                           : ',23,6,/,
               80:X)
//*

The problem I am facing is datasets FILE1.DATA.COUNT and FILE1.DATA.COUNT  are getting created of 15 record length despite mentioning LRECL 6. (note, this was the question that existed when the first answer was written and does not relate now to the above code).
Can we merge both steps into one?
What does this, (15:X,1,6,ZD,DIV,+2,M11,LENGTH=6,X, (8,6,ZD,MUL,+100),DIV,1,6,ZD,MUL,+100,EDIT=(TTT.TT)), mean specifically?

A:

The answer to your first question is simply that you did not tell
ICETOOL's COUNT operator how long you wanted the output data to be, so
it came up with its own figure.
This is from the DFSORT Application Programming Guide:

WRITE(countdd) Specifies the ddname of the count data set to be
  produced by ICETOOL for this operation. A countdd DD statement must be
  present. ICETOOL sets the attributes of the count data set as follows:
v RECFM is set to FB.
v LRECL is set to one of the following:
– If WIDTH(n) is specified, LRECL is set to n. Use WIDTH(n) if your count
  record length and LRECL must be set to a particular value (for
  example, 80), or if you want to ensure that the count record length
  does not exceed a specific maximum (for example, 20 bytes).
– If WIDTH(n) is not specified, LRECL is set to the calculated required
  record length. If your LRECL does not need to be set to a particular
  value, you can let ICETOOL determine and set the appropriate LRECL
  value by not specifying WIDTH(n).

And:

DIGITS(d)
Specifies d digits for the count in the output record, overriding the
  default of 15 digits. d can be 1 to 15. The count is written as d
  decimal digits with leading zeros. DIGITS can only be specified if
  WRITE(countdd) is specified.
If you know that your count requires less than 15 digits, you can use
  a lower number of digits (d) instead by specifying DIGITS(d). For
  example, if DIGITS(10) is specified, 10 digits are used instead of 15.
If you use DIGITS(d) and the count overflows the number of digits
  used, ICETOOL terminates the operation. You can prevent the overflow
  by specifying an appropriately higher d value for DIGITS(d). For
  example, if DIGITS(5) results in overflow, you can use DIGITS(6)
  instead.

And:

WIDTH(n)
Specifies the record length and LRECL you want ICETOOL to use for the
  count data set. n can be from 1 to 32760. WIDTH can only be specified
  if WRITE(countdd) is specified. ICETOOL always calculates the record
  length required to write the count record and uses it as follows:
v If WIDTH(n) is specified and the calculated record length is less
  than or equal to n, ICETOOL sets the record length and LRECL to n.
  ICETOOL pads the count record on the right with blanks to the record
  length.
v If WIDTH(n) is specified and the calculated record length is greater
  than n, ICETOOL issues an error message and terminates the operation.
v If WIDTH(n) is not specified, ICETOOL sets the record length and
  LRECL to the calculated record length.
Use WIDTH(n) if your count record length and LRECL must be set to a
  particular value (for example, 80), or if you want to ensure that the
  count record length does not exceed a specific maximum (for example,
  20 bytes). Otherwise, you can let ICETOOL calculate and set the
  appropriate record length and LRECL by not specifying WIDTH(n).

For your second question, yes it can be done in one step, and greatly simplified.
The thing is, it can be further simplified by doing something else. Exactly what else depends on your actual task, which we don't know, we only know of the solution you have chosen for your task.
For instance, you want to know when one file is within 10% of the size of the other. One way, if on-the-dot accuracy is not required, is to talk to the technical staff who manage your storage. Tell them what you want to do, and they probably already have something you can use to do it with (when discussing this, bear in mind that these are technically data sets, not files).
Alternatively, something has already previously read or written those files. If the last program to do so does not already produce counts of what it has read/written (to my mind, standard good practice, with the program reconciling as well) then amend the programs to do so now. There. Magic. You have your counts.
Arrange for those counts to be in a data set of their own (preferably with record-types, headers/trailers, more standard good practice).
One step to take the larger (expectation) of the two counts, "work out" what 00% would be (doesn't need anything but a simple subtraction, with the right data) and generate a SYMNAMES format file (fixed-length 80-byte records) with a SORT-symbol for a constant with that value.
Second step which uses INCLUDE/OMIT with the symbol in comparison to the second record-count, using NULLOUT or NULLOFL.
The advantage of the above types of solution is that they basically use very few resources. On the Mainframe, the client pays for resources. Your client may not be so happy at the end of the year to find that they've paid for reading and "counting" 7.3m records just so that you can set an RC.
OK, perhaps 7.3m is not so large, but, when you have your "solution", the next person along is going to do it with 100,000 records, the next with 1,000,000 records. All to set an RC. Any one run of which (even with the 10,000-record example) will outweigh the costs of a "Mainframe" solution running every day for the next 15+ years.
For your third question:
 OUTREC OVERLAY=(15:X,1,6,ZD,DIV,+2,M11,LENGTH=6,X,
                (8,6,ZD,MUL,+100),DIV,1,6,ZD,MUL,+100,EDIT=(TTT.TT))

OUTREC is processed after SORT/MERGE and SUM (if present) otherwise after INREC. Note, the physical order in which these are specified in the JCL does not affect the order they are processed in.
OVERLAY says "update the information in the current record with these data-manipulations (BUILD always creates a new copy of the current record).
15: is "column 15" (position 15) on the record.
X inserts a blank.
1,6,ZD means "the information, at this moment, at start-position one for a length of six, which is a zoned-decimal format".
DIV is divde.
+2 is a numeric constant.
1,6,ZD,DIV,+2 means "take the six-digit number starting at position one, and divide it by two, giving a 'result', which will be placed at the next available position (16 in your case).
M11 is a built-in edit-mask. For details of what that mask is, look it up in the manual, as you will discover other useful pre-defined masks at the time. Use that to format the result.
LENGTH=6 limits the result to six digits.
So far, the number in the first six positions will be divided by two, treated (by the mask) as an unsigned zoned-decimal of six digits, starting from position 16.
The remaining elements of the statement are similar. Brackets affect the "precedence" of numeric operators in a normal way (consult the manual to be familiar with the precedence rules).
EDIT=(TTT.TT) is a used-defined edit mask, in this case inserting a decimal point, truncating the otherwise existing left-most digit, and having significant leading zeros when necessary.


Q:

Very Simple usage of ngModel

I have this very simple table body that generates a table based on the activityDays and for each clientType creates columns with some inputs.
It works well.

  {{day+1}}

      <input class='text-center field' value='0' type='number' min='0' required />

My problem now is how do I retrieve the data from this inputs?
I want for example
ClientType1 , Day 1 , 20 clients

ClientType2 , Day 1 , 10 clients

etc...
I made a class but I don't know how to apply this.
export class Client {
  day:number;
  type:string;
  amount:number;
}

And then when I submit my form i just want to show the objects on the log for now.
 clients:Client[];

 create() {
  console.log(this.clients);
 }

A:

You could do something like this:
Component.ts:
export class Component  {
  clientTypes = ['','','',''];
  clientTypesInputs = [];
}

Component.html:

        <input value="0" type="number" min="0" required [(ngModel)]="clientTypesInputs[in]"  />

{{clientTypeInput}}

clientTypesInputs is going to have the inputs at the index that they need to be acording to clientTypes array position.
Here is a working example:
https://stackblitz.com/edit/angular-artq8x


Q:

Display array elements JavaScript

I wanna diaplay username which means name + surname somewhere.
I've got a function:
function getData(count) {
    names = ["Michał", "Jan", "Katarzyna", "Andrzej", "Józef", "Bartek", "Mikołaj", "Tomasz", "Julian", "Brajan", "Dżesika"];////////////// bez var
    var surnames = ["Noga", "Kowalski", "Nowak", "Pazura", "Duda", "Komorowski", "Tomczyk", "Józefowicz", "Lechicki", "Goldberg"];
    var result = [];

    for (var i = 0; i < count; i++) {
        var randomNameIndex = Math.floor(Math.random() * names.length);
        var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
        name = names[randomNameIndex];
        var surname = surnames[randomSurnameIndex];
        result.push({
            name: name,
            surname: surname
        });
    }
    return result
}

Then I wanna display a result so I have another function:
function textDisplay() {
    //var username = name;
    //var username = names[1];
    //var username = getData(3);
    //$(username) = names[1];
    $("#nameDisplay").html(username);
}

And no one of lines in comments works.
How can I display these arrays elements properly?

A:

getData() returns an array of objects. You need to loop over them to get all the names.

function textDisplay() {
  var data = getData(3);
  var html = "";
  $.each(data, function(i, {name, surname}) {
    html += `Name: ${name} ${surname}<br>`;
  });
  $("#nameDisplay").html(html);
}

function getData(count) {
  names = ["Michał", "Jan", "Katarzyna", "Andrzej", "Józef", "Bartek", "Mikołaj", "Tomasz", "Julian", "Brajan", "Dżesika"]; ////////////// bez var
  var surnames = ["Noga", "Kowalski", "Nowak", "Pazura", "Duda", "Komorowski", "Tomczyk", "Józefowicz", "Lechicki", "Goldberg"];
  var result = [];

  for (var i = 0; i < count; i++) {
    var randomNameIndex = Math.floor(Math.random() * names.length);
    var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
    name = names[randomNameIndex];
    var surname = surnames[randomSurnameIndex];
    result.push({
      name: name,
      surname: surname
    });
  }
  return result
}

textDisplay();


Q:

algorithm for finding all substrings from a specific alphabet in a string in O(m+n) time

Given a string S . Find all maximal substrings that contains chars from alphabet A in O(|S|+|A|) time. "Maixmal susbstring" is a substring of S, surrounded by chars that are not in alphabet A, or string boundaries.
example:
S = rerwmkwerewkekbvverqwewevbvrewqwmkwe

A = {w,r,e}

answer: rerw, werew, e, er, wewe, rew, w, we
Can you help?

A:

Mapping your input to the output that you've provided here is one way to do it.

Just take the string characters one at a time and keep matching it to the alphabets in A.
Use a binary hash-table having 26 values based on alphabet.
Note: If capitals are included too hash them to their small letter counterparts for case-insensitivity and and double the hash table size for case-sensitivity.
If a value matches move on and concatenate this to previous sub-string.
If there is a miss, then break the sub-string, save it and start fresh with the next match.

Without the hash-table it would take O(m*n) time but now it'll take O(m) for hashing plus O(n) for traversing that is O(m+n) time.


Q:

C++ constructor definition

All of the constructors methods here do the same thing. I mostly use method2 but saw method3 for the first time today. Have seen method1 in some places but dont know what are the exact differences between them ?
Which one is the best way to define constructors and why ? Is there any performance issues involved ?
  1 class Test
  2 {
  3     private:
  4         int a;
  5         char *b;
  6     public:
  7         Test(){};
  8
  9         // method 1
 10         Test(int &vara, char *& varb) : a(vara), b(varb){}
 11
 12         // method 2
 13         Test(int &vara, char *& varb)
 14         {
 15             a = vara;
 16             b = varb;
 17         }
 18
 19         //method 3
 20         Test(int &vara, char *& varb)
 21         {
 22             this->a = vara;
 23             this->b = varb;
 24         }
 25
 26         ~Test(){}
 27 };

I have here used simple fields int and char*,what will happen if I have many fields or complex types like struct ??
Thanks

A:

For the types you use, there will probably be no difference in performance. However for non-POD data (classes with constructors) the form:
Test(int &vara, char *& varb) : a(vara), b(varb){}

will be the most efficient. This is because non-POD data will be initialised whther you provide an initialisation list or not. The other forms, which use assignment, will take the hit for initialisation, and then another hit for assignment.

A:

Probably not a HUGE difference in terms of performance, but in method 1, you're constructing a and b using a copy constructor. In method 2, you're constructing a and b automatically, THEN using the assignment operator. That could be slower for more complex types than int and char*.
Method 3 is exactly the same thing as method 2.

A:

There is absolutely no difference between Methods 2 and 3. Within a member function (including constructors and destructors) a member variable x is synonymous with this->x. The only time this makes a difference is if there is another variable named x in a nearer scope. For example:
int Foo::memberFunc() {
  return x; // Returns member variable x. Same as return this->x.
}

int Foo::memberFunc(int x) {
  return x; // Returns the argument x. Need to say return this->x to return member x
}

Method 1 is normally the preferred way of initializing member variables because it makes it explicit that that is what you are doing.
In your case, it is also identical to methods 2 and 3, but in some cases it is not. In particular, if any of your member variables are constants, references, or objects without default constructors, then Method1 is the only way you can initialize them.
Another small difference of Method 1 is that if any of your member variables are objects, using Methods 2 or 3 they will be constructed with their default constructors first and then modified or assigned to int he constructor code, while with Method 1 you can create them with a constructor other than the default in the first place.


Q:

How to check if a string is contained in another list of strings?

I have a list of folders in which I contain a list of languages that I want to be processed:
eng_US
spa_ES

etc...
I have a list of directories containing subfolders for each language it has. They can be more than the ones defined in my languages list. It can look like this:
ja-JP
eng_US
spa_Es
fr_FR

I list the directories in that specific folder like this:
string[] directories = Directory.GetDirectories(path);

I want to get with Linq all that folders that are inside my private language list.
I tried something similar to this:
string[] directories = Directory.GetDirectories(path).Where(x => x.Contains(languageList.Value));

But, obviously is bad :(
How can I get only the folders which are also listed in my private language list?
So, how can I check if my resulting path is contained inside another string list with Linq?
Thanks!
NOTE:
My language list is saved in a Dictionary.
IDictionary<int, string> languages;

A:

You're pretty close - Remember languageList is a list of names you care about and your Linq statement will return one string value at a time to put through your Where clause, so you'd want it to look as follows:
string[] directories = Directory.GetDirectories(path).Where(x => languageList.Contains(x)).ToArray();

Basically saying Give me back and returned value that is contained in languageList
Hope that makes sense.


Q:

Dict values to array, sorted by key

I have a dictionary:
test_dict = {"1": "one", "3": "three", "2": "two"}

I'd like to create an array of values, but sorted by key, to get something like this:
test_array = ["one", "two", "three"]

Normally, I retrieve values by using test_dict.values(), but since dictionaries are unordered, it messes up my array.

A:

You can try this:
test_dict = {"1": "one", "3": "three", "2": "two"}

print([x[1] for x in sorted(test_dict.items(), key=lambda x: int(x[0]))])
# ['one', 'two', 'three']


Q:

New variable for each group - pandas

I love R. But now I need pandas.
In R I can do:
data %>% group_by(sym) %>% mutate(s = mean(price))

Its not aggregation ! Its a new variable different for each group.
I try everything in pandas - "group by" want to aggregate or split my data ! I only want to calculate new variable.

A:

We can try
import pandas as pd
data['s'] = data['price'].groupby(data['sym']).transform('mean')
print(data)
#   price sym           s
#0    125   A  129.000000
#1    133   A  129.000000
#2     50   B   77.333333
#3     62   B   77.333333
#4    120   B   77.333333

Or as @MaxU mentioned
data['s'] = data.groupby('sym')['price'].transform('mean')

data
data = pd.DataFrame({'sym': ['A', 'A', 'B', 'B', 'B'], 'price': [125, 133, 50, 62, 120]})


Q:

Why the "de" in "d'entre eux"?

In the expressions certains d'entre eux, aucun d'entre eux, etc., is there an explanation why there is a "de"? The meaning seems to be just "some of them" and "none of them", so I'm not sure why it is necessary to place a "de" in front of the preposition.

A:

As underlined @oldergod, without "de" those expressions would not have the same meaning :

certains / aucun  = some / none
de = of
entre = between
eux = them

So without "de" you have no link between the quantity (some/none) and the fact that this quantity is taken inside the group (of them).
You would be understood because it is not a big word missing, but it will appear as strange and incorrect - you will probably be corrected.


Q:

How many Stored Procedures created everyday ( problem in converting Datetime )?

I make a query that return to me the count of Stored Procedure that created everyday as follow
SELECT  convert(varchar, crdate, 103) as Date,Count(*) as Counter
FROM    sysobjects
WHERE   (xtype = 'p') AND (name NOT LIKE 'dt%')
Group by  convert(varchar, crdate, 103)

and its already work but dates appear in string format that i can't order it such as below
01/03/2010  3
01/04/2008  4
01/05/2010  5
01/11/2008  1
01/12/2008  4
02/03/2008  1
02/03/2010  2
02/04/2008  4
02/05/2010  2
02/11/2008  2
02/11/2009  2
02/12/2008  4
03/01/2010  1
03/02/2010  2
03/03/2010  2
03/04/2008  2
03/04/2010  2
03/05/2008  1
03/05/2010  2

I want to make that in which date is in datetime format that i can make order by successfully, i tried  convert(datetime, crdate, 103) but it show Full date
any idea of how to do ?

A:

To get a sortable date you need year, then month, then date.  use format "112".
SELECT  convert(varchar, crdate, 112) as Date,Count(*) as Counter
FROM    sysobjects
WHERE   (xtype = 'p') AND (name NOT LIKE 'dt%')
Group by  convert(varchar, crdate, 112)
order by  Date

which gives this:
Date        Counter
20040711    124
20040713    1
20040725    1
20040726    2
20040803    6

If you want to get the right sort order but a differently formatted date, then you can use a subquery like this.
select CONVERT(varchar, GroupDate, 103) Date, Counter
FROM (
    SELECT  MIN(crdate) as GroupDate,Count(*) as Counter
    FROM    sysobjects
    WHERE   (xtype = 'p') AND (name NOT LIKE 'dt%')
    Group by  convert(varchar, crdate, 112)
) A
order by  GroupDate

which yields
Date        Counter
11/07/2004  124
13/07/2004  1
25/07/2004  1
26/07/2004  2
03/08/2004  6


Q:

XSLT - Remove full parent node if child contains specific text

I just need to transform one XML file to another XML file with the wanted data.
The transformation remove every parent nodes if child nodes doesn't contain the correct category.
Input XML:
    <SHOP>
    <SHOPITEM>
        <ITEM_ID>142</ITEM_ID>
        <PRODUCT>Mora MV 1251</PRODUCT>
        <DESCRIPTION>XXXXX</DESCRIPTION>
        <URL>http://www.xxx.sk/o</URL>
        <IMGURL>http://xxx.jpg</IMGURL>
        <PRICE>6.74</PRICE>
        <PRICE_VAT>8.10</PRICE_VAT>
        <VAT>0.20</VAT>
        <MANUFACTURER>Mora</MANUFACTURER>
        <CATEGORYTEXT>Accessories / Mobile</CATEGORYTEXT>
        <EAN>8590371028526</EAN>
        <PRODUCTNO></PRODUCTNO>
        <WARRANTY>24</WARRANTY>
        <DELIVERY_DATE>24</DELIVERY_DATE>
    </SHOPITEM>

    <SHOPITEM>
       <ITEM_ID>XXX</ITEM_ID>
       <PRODUCT>Hyundai LLF 22924 DVDR</PRODUCT>
       <DESCRIPTION>XXXXX</DESCRIPTION>
       <URL>http://www.xxx.sk/t</URL>
       <IMGURL>http://xxx.jpg</IMGURL>
       <PRICE>173.35</PRICE>
       <PRICE_VAT>208.00</PRICE_VAT>
       <VAT>0.20</VAT>
       <MANUFACTURER>Hyundai</MANUFACTURER>
       <CATEGORYTEXT>Main category / TVs</CATEGORYTEXT>
       <EAN>xxxxx</EAN>
       <PRODUCTNO/>
       <WARRANTY>24</WARRANTY>
       <DELIVERY_DATE>99999</DELIVERY_DATE>
    </SHOPITEM>
    </SHOP>

I need to remove every SHOPITEM nodes where the CATEGORYTEXT is not Main category / TVs
I have the below XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

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

 <xsl:template match="CATEGORYTEXT[not(text() = 'Main category / TVs')]"/>
</xsl:stylesheet>

But this only removes the CATEGORYTEXT node, not the full SHOPITEM node.
Can anyone help me please? :)
I'm new too XSLT, every help is appreciated.
Desired output is:
       <SHOP>
         <SHOPITEM>
           <ITEM_ID>XXX</ITEM_ID>
           <PRODUCT>Hyundai LLF 22924 DVDR</PRODUCT>
           <DESCRIPTION>XXXXX</DESCRIPTION>
           <URL>http://www.xxx.sk/t</URL>
           <IMGURL>http://xxx.jpg</IMGURL>
           <PRICE>173.35</PRICE>
           <PRICE_VAT>208.00</PRICE_VAT>
           <VAT>0.20</VAT>
           <MANUFACTURER>Hyundai</MANUFACTURER>
           <CATEGORYTEXT>Main category / TVs</CATEGORYTEXT>
           <EAN>xxxxx</EAN>
           <PRODUCTNO/>
           <WARRANTY>24</WARRANTY>
           <DELIVERY_DATE>99999</DELIVERY_DATE>
         </SHOPITEM>
       </SHOP>

A:

Replace this
<xsl:template match="CATEGORYTEXT[not(text() = 'Main category / TVs')]"/>

with this:
<xsl:template match="SHOPITEM[not(CATEGORYTEXT = 'Main category / TVs')]"/>

Your current template filters CATEGORYTEXT elements based on the value of their text node children, whereas what you need is to filter SHOPITEM elements based on the value of their CATEGORYTEXT element children.
Note that it is only very rarely that you actually need to use text() in an XPath expression - text() gives you a set of all the individual text nodes that are direct children of the element you're dealing with, whereas usually what you care about is the complete string value of the element itself (which is, by definition, the concatenation of all its descendant text nodes)


Q:

svn directory as webroot

What I would like to do is point the webroot from my dev webserver to some dir that is in some way linked to svn so when I commit changes they will be automatically visible on my dev webserver.
Any clue how I can do this?
EDIT
i'm creating a django project so i'm justing the Django development server

A:

You can make your wwwroot a working copy of the svn repository, by checking it out from the server. To get the automatic updates working, you'll either have to look into a post-commit hook or have a cron job (or similar) run a task to update the wwwroot every X minutes or so.


Q:

Equation display in Source Mode in Overleaf

It seems that overleaf displays some equations automatically in the Source text, as shown below:

(I am referring to the second and fourth lines). How can I have everything displayed in terms of $$ ?
** Update:
I just want to say that I am not in Rich mode text (I never use it). I am in source mode and lately (perhaps I changed some setting), I get my equations displayed in the source mode text.

In addition, when I am editing the 'faulty' lines, I do get everything in LATEX code, but for a brief period of time (it then switches back to the displayed version).

A:

A LATEX chrome extension was the cause of the issue as it was automatically displaying equations in LATEX form with the source text. By deactivating or deleting it from chrome://extensions/ should fix the problem.


Q:

Broken string in exception?

I am throwing some parse exceptions. But an exception takes broken string..?
//Parse exception
class ParseException : public exception {
public:
    //Constructor
    //Arguments:
    //  Str: Message
    //  Pos: Position
    ParseException(string Str, int Pos) {
        msg = Str;
        pos = Pos;
    }

    //Get what happened(From exception)
    //Returns:
    //  Message with position
    virtual const char* what() const throw() {
        string str = msg;
        str += " at " + to_string(pos);
        return str.c_str();
    }
private:
    string msg; //Message
    int pos;    //Position
};

This is exception class. And I throwed this exception like this:
throw ParseException("Mismatched bracket", P.Pos);

This exception is thrown and goes to:
try {
    Parse(p);
}
catch (ParseException e) { // <<< Here
    cerr << "ParseException: " << e.what() << endl;
}

And what I get is:
ParseException: ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌

Is there a problem with my code? Or problem of Visual Studio(or Compiler)?

A:

As noted in the comments, you can't return the c_str of a local string without creating undefined behavior. It might make sense to store a string cache of the what value on the exception itself; the char* returned by what needs to live as long as the exception object, so caching on the exception is reasonable.
class ParseException : public exception {
public:
    //Constructor
    //Arguments:
    //  Str: Message
    //  Pos: Position
    ParseException(string Str, int Pos) : msg(std::move(Str)), pos(Pos) {}

    //Get what happened(From exception)
    //Returns:
    //  Message with position
    virtual const char* what() const throw() {
        // Lazily populate what so it's not populated until called
        if (_what.empty()) {
            _what = msg + " at " + to_string(pos);
        }
        return _what.c_str();
    }
private:
    string msg; //Message
    int pos;    //Position
    string _what;
};

Alternatively, you compute the value in the constructor so what remains nothrow compatible (matching the C++ standard library exceptions).


Q:

jQuery prepend() not working, what is wrong

I'm confused my append() not showing up in the HTML. Can you guys tell me what is wrong in the following code:

      Password:
     <input type="password" class="form-control" id="input-password" placeholder="Password" value="" name="password"/>

my js:

A:

Assuming the focusout event is triggered, the problem is you are using .text() after .prepend() which will remove the content added with .prepend()
$('input[name="password"]').focusout(function () {
    if ($(this).val() == "") {
        $('#password').attr('class', 'form-group has-error');
        $('#password .control-label').text(' Input your new password!');
        $('#password .control-label').prepend("");
    }
});

Demo: Fiddle

So
jQuery(function($){
    $('input[name="password"]').focusout(function () {
        if ($(this).val() == "") {
            $('#password').attr('class', 'form-group has-error');
            $('#password .control-label').text(' Input your new password!').prepend("");
            //$('#password .control-label').html(' Input your new password!');
        }
    });
});


Q:

IE CSS is not implementing box-shadow when deployed to server

I am using some css to add a corner radius and box shadow to a div in my asp.net project
.DesktopContainerDiv
{
    background-color:#C4D5E9;
    box-shadow: 10px 10px 5px #888;
    border-radius: 10px;
    border-collapse: separate;
    padding:10px;
    width:60%;
    min-width:800px;
    margin: 20px auto;
    text-align:center;
    min-height:200px
}

This works fine when I run through the Visual Studio IDE (Hitting F5). But when I deploy it to my web server, if I load a page using IE9 is doesn't display the box shadow and radius (Firefox and Chrome both show it correctly).
I have tried using UltiDev and IIS web servers and both behave the same so that eliminates that.
IE must be picking up the sytlesheet because it is turning the background blue so I can't understand what the difference is between running in IDE and web server is.

A:

This happened to me once before and the problem was solved by making sure the compatability mode was set to IE9
You can force this by putting
<meta http-equiv="X-UA-Compatible" content="IE=9" />

into your <head>
Edit: Or try:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />


Q:

set multiple column values to NaN based on condition

I'm trying to set values in 2 columns of my dataframe to null based on condition applied to one of the columns.
I know how to set the value of 1 column to null based on condition. I do that in the following example with col3. My question is how can I also set the value in col2 of the same row to null?
df = pd.DataFrame([['a',1, 10],
                   ['b',2, 20],
                   ['c',3, 30],
                   ['d',4, 40],
                   ['e',5, 50]], columns=['col1','col2','col3'])

df
Out[121]:
  col1  col2  col3
0    a     1    10
1    b     2    20
2    c     3    30
3    d     4    40
4    e     5    50

df['col3'].mask(df['col3']<30,inplace=True)

df
Out[123]:
  col1  col2  col3
0    a     1   NaN
1    b     2   NaN
2    c     3  30.0
3    d     4  40.0
4    e     5  50.0

Tried the following and it doesn't work
df['col2','col3'].mask(df['col3']<30,inplace=True)

My desired output is
  col1  col2  col3
0    a   NaN   NaN
1    b   NaN   NaN
2    c     3  30.0
3    d     4  40.0
4    e     5  50.0

A:

You can try df.loc found here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html.
This way you can state a condition to select the rows, and a list of columns that you want to apply the change to.
Using the constant NaN from numpy: https://docs.scipy.org/doc/numpy/reference/constants.html?highlight=nan#numpy.nan.
df.loc[df['col3']<30,['col2','col3']] = np.nan

The resulting df will be.
  col1  col2  col3
0    a   NaN   NaN
1    b   NaN   NaN
2    c   3.0  30.0
3    d   4.0  40.0
4    e   5.0  50.0


Q:

how to post URL with Image on facebook by ShareKit

I am using sharekit in my iPhone app to share url link on facebook. However, it seems to me that it is not possible to share url with image with sharekit. Do you guys know how to do it? Thanks a lot.

A:

Please have a look to the code I just made my own Send method in SHKFacebook.m/h files, I think  it will help you.
  -(BOOL) sendWithImage :(NSString*)creativeUrl
   {
            self.pendingFacebookAction = SHKFacebookPendingStatus;

        SHKFBStreamDialog* dialog = [[[SHKFBStreamDialog alloc] init] autorelease];
        dialog.delegate = self;
        dialog.userMessagePrompt = SHKLocalizedString(@"Enter your message:");
        dialog.attachment = [NSString stringWithFormat:
                             @"{\
                             \"name\":\"%@\",\
                             \"href\":\"%@\",\
                             \"media\":[{\"type\":\"image\",\"src\":\"%@\",\"href\":\"%@\"}]\
                             }",
                            item.title == nil ? SHKEncodeURL(item.URL) : SHKEncode(item.title),
                            SHKEncodeURL(item.URL),
                            creativeUrl,
                            SHKEncodeURL(item.URL)

                        ];
    dialog.defaultStatus = item.text;
    dialog.actionLinks = [NSString stringWithFormat:@"[{\"text\":\"Get %@\",\"href\":\"%@\"}]",
                            SHKEncode(SHKMyAppName),
                            SHKEncode(SHKMyAppURL)];
    [dialog show];
    return YES;

}

Here is How I Use it
SHKFacebook *fb =[[SHKFacebook alloc]init];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@iphone/photo?id=%d",[SplashViewController getBaseURL],[photoId intValue]]];
    fb.item = [SHKItem URL:url title:[dicResult valueForKey:@"Caption"]];
    //fb.shareType = SHKShareTypeURL;
    fb.quiet = YES;
    [TedryUITabBarController updateProgress:10 totalByteToSent:11 message:@"Sharing on facebook"];
    [fb sendWithImage:[dicResult valueForKey:@"CreativeURL"] :@""];

A:

This may be slightly simpler, I hope, for those having problems with other answers here (although basically the same in principle).
Add the custom values to your item, such as:
[item setCustomValue:@"Your caption" forKey:@"caption"];
[item setCustomValue:@"Your description" forKey:@"description"];
[item setCustomValue:@"Your image URL" forKey:@"mediaSrc"];
[item setCustomValue:@"Your image link" forKey:@"mediaHREF"];

Note the two values needed for the image at the bottom: the source URL and the link URL. You then need to modify the "send" method in SHKFacebook.m to use those values, as follows:
// ...
if (item.shareType == SHKShareTypeURL)
{
    self.pendingFacebookAction = SHKFacebookPendingStatus;

    SHKFBStreamDialog* dialog = [[[SHKFBStreamDialog alloc] init] autorelease];
    dialog.delegate = self;
    dialog.userMessagePrompt = SHKLocalizedString(@"Enter your message:");

    // with image...
    dialog.attachment = [NSString stringWithFormat:
                         @"{\
                         \"name\":\"%@\",\
                         \"href\":\"%@\",\
                         \"caption\":\"%@\",\
                         \"description\":\"%@\",\
                         \"media\":[\
                            {\
                                \"type\": \"image\",\
                                \"src\": \"%@\",\
                                \"href\": \"%@\"\
                            }]\
                         }",
                         item.title == nil ? SHKEncodeURL(item.URL) : SHKEncode(item.title),
                         SHKEncodeURL(item.URL),
                         [item customValueForKey:@"caption"],
                         [item customValueForKey:@"description"],
                         [item customValueForKey:@"mediaSrc"],
                         [item customValueForKey:@"mediaHREF"]
                         ];

    dialog.defaultStatus = item.text;
    dialog.actionLinks = [NSString stringWithFormat:@"[{\"text\":\"Get %@\",\"href\":\"%@\"}]",
                          SHKEncode(SHKMyAppName),
                          SHKEncode(SHKMyAppURL)];
    [dialog show];

}
// ...

And the link given by jumponadoughnut is the definitive list of fields you can use (I could not vote his up because my rep is not high enough): http://developers.facebook.com/docs/guides/attachments

A:

I'm using the latest sharekit from github. Actually, you just set the url as the custom value of the link, with key "picture"
NSString *urlImage = @"http://someurl.com/someimage.jpg";
[linkItem setCustomValue:urlImage forKey:@"picture"];

It works for me.


Q:

See all breakpoints in Visual Studio 2010+

Is there a window in Visual Studio 2010 and newer where I can see all the breakpoints that I have in my project or solution?

A:

Try Debug -> Windows -> Breakpoints.

A:

Default Shortcuts:
To open the break point window:
Ctrl+D, B
If you wanted to delete all breakpoints:
Ctrl+F9

A:

Ctrl+Alt+B in Visual Studio 2010.


Q:

How to parse milliseconds?

How do I use strptime or any other functions to parse time stamps with milliseconds in R?
time[1]
# [1] "2010-01-15 13:55:23.975"
strptime(time[1], format="%Y-%m-%d %H:%M:%S.%f")
# [1] NA
strptime(time[1], format="%Y-%m-%d %H:%M:%S")
# [1] "2010-01-15 13:55:23"`

A:

Courtesy of the ?strptime help file (with the example changed to your value):
 z <- strptime("2010-01-15 13:55:23.975", "%Y-%m-%d %H:%M:%OS")
 z # prints without fractional seconds
 op <- options(digits.secs=3)
 z
 options(op) #reset options

A:

You can also use strptime(time[1], "%OSn") where 0 <= n <= 6, without having to set digits.secs.
The documentation states "Which of these are supported is OS-dependent." so YMMV.


Q:

How can I specify my ui elements to be situated above the navigation bar in android?

in my app I am using a full screen layout, meaning that the screen goes beyond the on screen buttons (like the ones on the nexus devices).
If I now put buttons and other elements at the bottom of my layout, they will interfere with the navigation bar.
How can I make this not happen? Is there any way to specify that my ui elements are put above the on screen buttons while maintaining the full screen experience?

A:

As noted in the Translucent System Bars, you can add android:fitsSystemWindows="true" (documentation) to ensure that those elements are not placed over system navigation areas.


Q:

Solr multiple filter tagging / excluding

I am trying to apply filter tagging for Solr search Tagging_and_excluding_Filters.
The challenge is to apply multiple tagging at the same time (for multiple select options on a single page). e.g.
q=mainquery&fq=status:public&fq={!tag=dt}doctype:pdf&fq={!tag=doc}document:1&facet=on&facet.field={!ex=dt}doctype&facet.field={!ex=doc}document
But for some reason excluding works only for one filter and other gets unnoticed. Is there any problem with my syntax? Can anyone suggest a better method?

A:

I'm having a similiar problem to solve and it seemed to work by just using a comma to seperate excluded tags:
From: http://wiki.apache.org/solr/SimpleFacetParameters#facet.field

Filter exclusion is supported for all types of facets. Both the tag
  and ex local params may specify multiple values by separating them
  with commas.

So I guess you'd use it like: {!ex=doc,dt}


Q:

Combing 3 arrays into one array

I have the following Arrays:
$front = array("front_first","front_second");
$inside = array("inside_first", "inside_second", "inside_third");
$back = array("back_first", "back_second", "back_third","back_fourth");

what I need to do is combine it so that an output would look like this for the above situation.  The output order is always to put them in order back, front, inside:
$final = array(
"back_first",
"front_first",
"inside_first",
"back_second",
"front_second",
"inside_second",
"back_third",
"front_second",
"inside_third",
"back_fourth",
"front_second",
"inside_third"
);

So basically it looks at the three arrays, and whichever array has less values it will reuse the last value multiple times until it loops through the remaining keys in the longer arrays.
Is there a way to do this?  I am stumped/

A:

$front = array("front_first","front_second");
$inside = array("inside_first", "inside_second", "inside_third");
$back = array("back_first", "back_second", "back_third","back_fourth");

function foo() {
  $args = func_get_args();
  $max = max(array_map('sizeof', $args)); // credits to hakre ;)
  $result = array();

  for ($i = 0; $i < $max; $i += 1) {
    foreach ($args as $arg) {
      $result[] = isset($arg[$i]) ? $arg[$i] : end($arg);
    }
  }

  return $result;
}

$final = foo($back, $front, $inside);
print_r($final);

demo: http://codepad.viper-7.com/RFmGYW


Q:

PHP how to move the children up to each parent

I've been stuck on this for a while now, internet has helped but I can't get it right.  I have an array listed below and I've been trying to create a new array from this one with the children in each odd number moved up to the corresponding parent.  I came close with a $new array and a counter checking if the index was odd or even and then if the odd number is true reassign the children to the current parent.
Here's the array.
Array
(
   [0] => hair-and-beauty
   [1] => Array
    (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [2] => hair-colouring
   [3] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [4] => hair-styling
   [5] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

)

I need to get the kids like this.
 Array
  (
       [0] => hair-and-beauty  => Array
         (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     [1] => hair-colouring => Array
          (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

        [2] => hair-styling  => Array
           (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     )

My php code isn't working out right for me :(
    $new = array();
    $number = 0;
     foreach($menu as $current){
         //If number is even
         if ($number % 2 == 0) {
            array_push($new[$current]);
        }else{
            //number isnt even so go for children and add them to parent
            $new[$value['index']] = $current;
        }
        ++$number;
     }
     unset($menu);
    usort($new);

    $x = $new;
    $json=$x;

The main array is called $menu.
Any help appreciated.
I'm steering in the direction of an array_merge
Var export :
array (
  0 => 'hair-and-beauty',
  1 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  2 => 'hair-colouring',
  3 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  4 => 'hair-styling',
  5 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
)null

A:

Let $input be the array posted in the question.
This simple piece of code does the job:
$output = array();
foreach (array_chunk($input, 2) as $i) {
    $output[$i[0]] = array_filter($i[1]);
}

The calls to array_filter() remove the empty entries from the arrays on even positions (the new children). Its purpose is to remove the key 0 from them (it is not present in the expected output) but it also removes other keys whose values are equivalent to FALSE.
If you want to keep all the string keys and get rid only of 0 then you can write it as:
$output = array();
foreach (array_chunk($input, 2) as $i) {
    unset($i[1][0]);
    $output[$i[0]] = $i[1];
}

If you use PHP 5.5 or newer you can write it nicer:
$output = array();
foreach (array_chunk($input, 2) as list($k, $v)) {
    unset($v[0]);
    $output[$k] = $v;
}


Q:

LNK2001: unresolved external symbol public: static class std::vector

I'm trying to something very simple and can't figure out why I'm getting this error:
mainwindow.obj:-1: error: LNK2001: unresolved external symbol "public: static class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > const MazeBuilder::algorithms" (?algorithms@MazeBuilder@@2V?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@B)

I want to have a vector of strings that I access with my enums so I have a nice way to write out what I'm grabbing, and all my other classes can use it.
Here is a shortened version of my code:
MainWindow.cpp
#include "MainWindow.h"
#include "MazeBuilder.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow (QWidget* parent) : QMainWindow (parent), ui (new Ui::MainWindow)
{
    ui->setupUi (this);

    //Add available algorithms to the combo box
    for (size_t i = 0; i < MazeBuilder::algorithms.size(); i++)
    {
        ui->algorithmBox->addItem(MazeBuilder::algorithms.at(i).c_str());
    }
}

MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget* parent = nullptr);

private:
    Ui::MainWindow* ui;

};

#endif // MAINWINDOW_H

MazeBuilder.cpp
#include "MazeBuilder.h"

//Binds to MazeBuilder::MazeAlgorithm
//const static std::vector<std::string> algorithms = {"Prim's"};
const std::vector<std::string> MazeBuilder::algorithms = {"Prim's"};

MazeBuilder::MazeBuilder()
{

}

MazeBuilder.h
#ifndef MAZEBUILDER_H
#define MAZEBUILDER_H

#include <string>
#include <vector>

class MazeBuilder
{

public:
    enum MazeAlgorithm
    {
        PRIM = 0
    };
    const static std::vector<std::string> algorithms;

    MazeBuilder();
};

#endif // MAZEBUILDER_H

ENTIRE PROJECT (SMALL) HERE: https://mega.nz/#!ruoRCZbQ!Jk79ATSO0POb9J_xkaAeNIy9ycVTnHkp1iT4Vq5XFoM

A:

You have a scoping issue. Since algorithms is declared as a static member of MazeBuilder it needs to be defined as such, too. Change its definition in MazeBuilder.cpp to
const std::vector<std::string> MazeBuilder::algorithms = {"Prim's"};

Otherwise, you're just defining a static variable algorithms in the global scope.
The following minimal code compiles and links just fine for me
#include <iostream>
#include <string>
#include <vector>

class MazeBuilder {
public:
  const static std::vector<std::string> algorithms;

  MazeBuilder();
};

const std::vector<std::string> MazeBuilder::algorithms = {"Prim's"};
MazeBuilder::MazeBuilder() {
}

int main(int argc, char** argv) {

  for(std::string s : MazeBuilder::algorithms) {
    std::cout << s << std::endl;
  }

  return 0;
}


Q:

What does $\sum_{n\in\mathbb N}\frac{n^x}{x^n}$ converge to when $x\in\mathbb R^+$ and $x>1$?

What does $\sum_{n\in\mathbb N}\frac{n^x}{x^n}$ converge to when $x\in\mathbb R^+$ and $x>1$?

I'm looking for a hint of how to tackle this problem.

A:

From the definition of the polylogarithm this is :
$$\sum_{n\in\mathbb N^{*}}\frac{n^x}{x^n}=\sum_{n\in\mathbb N^{*}}\frac{\left(\frac 1x\right)^n}{n^{-x}}=\operatorname{Li}_{-x}\left(\frac 1x\right)$$
This simplifies for non negative integer values of $x$ (and $-1$) as seen here.


Q:

What parts of the Z3 C++ API are still supported?

I see some of the Z3 API is marked deprecated.  I also see some comments by Leonardo that more of the API was retired in 2012 (related: contexts are in maintenance mode).  What parts of the API should I be using?
Is this page a good guide to the active parts of the C API?  Same for this page and C++?
I think I'm just looking for two yes's from someone in the know, but if it's more nuanced then I'm all ears.

A:

Yes, some parts of the C API were marked as deprecated. They are listed in this page.
Two relevant groups are: the theory plugin API, and the old solver API.


Q:

Why does django community encourage the use of Postgres over Mysql?

Django community seems to encourage the use of Postgres, I understand that in a big project you probably don't want to use SQLite or such, but i don't know why they don't like Mysql that much.
just a quick example - Djangobook page 9:

We’re quite fond of PostgreSQL ourselves, for reasons outside the scope of this book, so we mention it first. However, all those engines will work equally well with Django.

Postgres name is always associated with Django - just like Mysql is always associated with php

A:

Best answer might be given to this quiestion is from those who writes the Framework...
But from what you can get from documentation is:

By default, Django starts a transaction when a database connection is first used and commits the result at the end of the request/response handling. The PostgreSQL backends normally operate the same as any other Django backend in this respect.

Django have a strong Transection control, and using a powerful free DBMS that have strong transection control is a plus...
Also,  previous versions of Mysql (before mysql 5.0), MySql have some integrity problems. Also MySql's fast storage engine MyISAM do not support foreign keys and transections. So using MyISAM have important minuses that its pluses...
And a wiki for why Postgres is better than Mysql. Its quite old but it is good.


Q:

Change element's background color with gradient to background color without gradient

I have a table with two columns and multiple rows. When you click on any cell (and you keep the click down) except the ones that are heading, the background color changes from very light gray to light blue, and when you release the click it goes back to its original color. (Please check the code and click a cell, now). So far it's perfect.

table {
  margin-right: 1px;
  font-family: Arial, sans-serif;
}
table td {
  width: 100px;
  padding: 11px 16px;
  text-align: center;
  background: gray;
  /* Old browsers */
  background: linear-gradient(to left, #EEE 50%, #1F7DE2 50%);
  background-size: 200% 100%;
  background-position: right bottom;
  margin-left: 10px;
  transition: all 0.3s ease-in;
}
table td:active {
  background-position: left bottom;
  color: white;
}

    Column 1
    Column 2

    Content 1
    Content 2

    Content 1
    Content 2

    Content 1
    Content 2

    Column 1
    Column 2

    Content 1
    Content 2

    Content 1
    Content 2

    Content 1
    Content 2

  The background should actually be like this

However, if you look at the method I used to change that background color was by actually using a linear-gradient. So, the cells already have the blue background, it's just it isn't visible, until you click them, which changes the background-position, pushing the gray background (and giving instead the idea that it's changing).
If you look at the end of the code, you can see there's an additional p element, with the background liner gradient colors I want the cells to have (two colors, up to bottom).
The problem is, with my method I guess you can't change the background: linear-gradient to a background-color (solid, with no gradient).

A:

Use two gradients one under the other like so:
table td {
    width:100px;
    padding: 11px 16px;
    text-align:center;
    background: grey;
    /* Old browsers */
    background-image:
      linear-gradient(to left,transparent 50%, #1F7DE2 50%),
      linear-gradient(#F7f7f7, #EEE);
    background-size: 200% 100%;
    background-position:right bottom;
    margin-left:10px;
    transition:all 0.3s ease-in;
}

table {
    margin-right: 1px;
    font-family: Arial, sans-serif;
}
table td {
    width:100px;
    padding: 11px 16px;
    text-align:center;
    background: grey;
    /* Old browsers */
    background-image:
      linear-gradient(to left,transparent 50%, #1F7DE2 50%),
      linear-gradient(#F7f7f7, #EEE);
    background-size: 200% 100%;
    background-position:right bottom;
    margin-left:10px;
    transition:all 0.3s ease-in;
}
table td:active {
    background-position:left bottom;
    color: white;
}

        Column 1
        Column 2

      Content 1
      Content 2

      Content 1
      Content 2

      Content 1
      Content 2

        Column 1
        Column 2

      Content 1
      Content 2

      Content 1
      Content 2

      Content 1
      Content 2


Q:

Is the "cfgrid form field is corrupt" error after submit solved for HTML-type cfgrids in Adobe Coldfusion 11?

I'm using cfgrid with format="html" to edit data after submission on Adobe's coldfusion-11 Update 4 (11,0,04,293328) and jQuery 1.8.3 (on java version 1.7.0_55 on IIS7 on Windows Server 2008 R2 64bit) and get a "submitted cfgrid form field is corrupt" error using the below cfform and cfgrid code, with these details:
 The submitted cfgrid form field is corrupt (name:
 __CFGRID__AFORM__OneGrid value:
 ,__CFGRID__EDIT__=4�field1�Y�field2�Y�field3�Y�is_expected�Y
 �1�U�Detail 1�Detail 1�Category 3�Details, details, details�D
 etails, details, details�No�No)
ColdFusion cannot determine the line of the template that caused this
error. This is often caused by an error in the exception handling
subsystem.

The coldfusion source code is:
<cfform name="aform" action="" method="post">
    <cfgrid name="OneGrid"
        query="rsDetails"
        format="html"
        selectmode="edit"
        selectcolor="blue"
        insert="true"
        insertbutton="Click here to insert"
        delete="true"
        deletebutton="Click here to delete"
        colheaderbold="true"
        bgcolor="##E3F2FF"
        striperowcolor="##BDE0FF"
        striperows="true"
        rowHeight="20"
    >
    <cfgridcolumn name="field1" type="combobox"
        header="Field 1"
        width="200"
        valuesdelimiter=","
        values="#lstField1Values#"
        valuesdisplay="#lstField1Values#" select="true" >
    <cfgridcolumn name="field2" type="combobox"
        header="Field 2"
        width="150"
        valuesdelimiter=","
        values="#lstField2Values#"
        valuesdisplay="#lstField2Values#"
    >
    <cfgridcolumn
        name="field3"
        header="Field 3**"
        type="string_noCase"
        width="300">
    <cfgridcolumn name="is_expected" type="Boolean"
        header="Is this what you expected?"
        width="50"
    >
    </cfgrid>
</cfform>

This error has been reported by other developers here (last update on March 13th), but as one can see, no response by adobe has been given.
Has anybody found a solution?

A:

Few days ago I found that Jamie Martin reported on June 25, 2015 that adobe has mailing out fixes to individuals about this fix. I've not tried it yet but instead replaced the server-side cfgrid with a client-side solution: jqgrid. Here comes Jamie's report:

«
Seems Adobe is mailing out fixes to individuals. I received a fix (some data redacted due to security). Would be nice if they'd just make the fix public at this point.
Adobe response follows
We have got a new fix for the cfgrid issues, you are facing. This fix covers Bug# 3842284 (The submitted cfgrid form field is corrupt), Bug# 3945554 (cfgridupdate) and Bug# 3741324 (dropdown listbox outside the confines of the grid control). You can apply CF11 Update 5 first and then this fix on top of it. Please try the following steps:-

Stop ColdFusion 11 Application Service
Download the hotfix from ftp://XXXXXXXX@sjftp.adobe.com/ColdFusion/hf1100-3842284.jar. Alternatively, you can download the fix from https://www.dropbox.com/s/XXXXXXX/hf1100-3842284.jar as well.
Place this hf1100-3842284.jar at the location -- \ColdFusion11\cfusion\lib\updates\
Take a backup of cfgrid.js at \CFIDE\scripts\ajax\package\ and delete it.
Download the cfgrid.js from ftp://XXXXXXXXX@sjftp.adobe.com/ColdFusion/cfgrid.js and place it at the above location. Alternatively, you can download the fix from https://www.dropbox.com/s/XXXXXXXX/cfgrid.js, as well.
Start ColdFusion 11 Application Service.

»


Q:

Parse.com Local data store

how does the parse local data store work with respect to updating. If I call they query and then pin it to my local data store for the second time, would it only pin the new objects or would it pin all of them again?
Thanks

A:

If you are querying an item and then modifying it and saving it again it will update the current item in the data base. If you are querying an item and creating a new Item with the information of the old item it will create a second item on the database.


Q:

"bad variable name" using "read var"

I am getting confused about Linux shells. It may be that I oversee something obvious as a Linux noob.
All I want is the following script to run:
#!/bin/bash
echo "Type some Text:"
read var
echo "You entered: "$var

Here is the situation:

Installed Ubuntu Server 14.04 in a VirtualBox on windows
Installed it with this packages
A SAMBA mounted on /media/buff
The script is on /media/buff/ShellScript/test.sh
made executable by "sudo chmod a+x /media/buff/ShellScript/test.sh"
The rest is default
I am using PSPad on windows to edit the script file

I read about the dash but I'm not getting it.
Here are some variations:
Using sh to launch
user@Ubuntu:/media/buff/ShellScript$ sh test.sh
Type some Text:
:bad variable nameread var
You entered:

Using bash to launch:
user@Ubuntu:/media/buff/ShellScript$ bash test.sh
Type some Text:
': Ist kein gültiger Bezeichner.var (means no valid identifyier)
You entered:

Changed the Shebang in the script to "#!/bin/sh", Using sh to launch
user@Ubuntu:/media/buff/ShellScript$ sh test.sh
Type some Text:
:bad variable nameread var
You entered:

I searched across the Internet for hours now and I assume, that the script itself is ok, but there are missing some environment settings.
I used "sudo dpkg-reconfigure dash" to set dash as default shell (which I think is ubuntu default anyway)
sadface panda :)

A:

There are most probably carriage returns (CR, '\r') at the end of your lines in the shell script, so the variable is trying to be read into var\r instead of var. This is why your error message is meaningless. A similar error should look like this:
run.sh: 3: export: [... the variable name]: bad variable name

In your case bash throws an error because var\r is illegal for a variable name due to the carriage return, so it prints
test.sh: 3: read: var\r: bad variable name

but the \r jumps to the beginning of the line, overwriting the start of the error message.
Remove the carriage returns fom the ends of lines, possibly by using the dos2unix utility.


Q:

Router neighbour config discovery

I am new to the whole networking world and I apologize if this is a re-post of a question.
What I want to know is that is there a mechanism for routers to discover its environment. NOT what a dynamic routing table does. but more than that. for example an intelligent system that would discover its environment such as what are the supporting routing and security protocols each neighboring routers are using. more like an advanced routing table which stores more than what a dynamic routing table holds. any references would be of great help :)
I directed this question to you experts cause i do not have the knowledge or know the keywords to search online on this subject matter.

A:

CDP & LLDP permits the sharing of some very basic information, but that's really not enough to do something like you ask.
From a network operation point of view, you normally want a Known State, not dynamic configuration.  Just look at all the problem that VTP can cause (a single switch newly connected can bring down the whole network in certain circumstances).
Troubleshooting Dynamic configuration stuff is always harder, because you have to validate the dynamic protocols first to see if they have done their job and to understand their current state, check if it's a "correct" state, then try to find the issue you're looking for, instead of simply having to look out for something that is not how it was configured (interfaces states/trunking/forwarding, VLAN propagation, etc)
And for security reason, it would not be a good idea to have such mechanism either, as it would makes it easier for someone to connect/break your network

A:

Converting my comments to an answer...
Configuration discovery is a complicated task that involves both seeing and interpreting device configs.  This task is manual today... there is no comprehensive automation for it.


Q:

Query column from one .csv file against column from a second .csv file. Print queried column to new file and annotate with File 2 row where match

I have two .csv files and I would like to query column 3 from File 1 against column 3 from File 2. The output file should consist of column 3 from File 1, and if the entry exists in File 2, print the entire corresponding row from File 2. If no match in File 2, print File 1 column 3 and leave rest blank (see below).
File 1:
...   ...   a   ...
...   ...   e   ...
...   ...   b   ...
...   ...   c   ...

File 2:
...   ...   a   a-info-1   a-info-2   a-info-n
...   ...   c   c-info-1   c-info-2   c-info-n
...   ...   d   d-info-1   d-info-2   d-info-n
...   ...   e   e-info-1   e-info-2   e-info-n
...   ...   f   f-info-1   f-info-2   f-info-n

Desired output:
a   ...   ...   a-info-1   a-info-2   a-info-n
e   ...   ...   e-info-1   e-info-2   e-info-n
b
c   ...   ...   c-info-1   c-info-2   c-info-n

I have tried to accomplish this in both R and bash. I thought I should be able to figure this out by referencing this thread: awk compare 2 files, 2 fields different order in the file, print or merge match and non match lines, but I am very much new to all things programming and can't seem to figure out how to transcribe the solution to my case.
My best try:
awk -F"," 'NR==FNR{a[$3]=$3;next}{if ($3 in a)print a[$3]","$0;}' file1.csv file2.csv  > output.csv

The problem with this code is that it does not print the entries from File 1 that do not have entries in File 2.
If your solutions could be overly explanatory, I would very much appreciate it!

A:

From your example, I understand that you want to lookup the rows in second file by the values in the third column of first file.
Assuming your data frames are named df1 and df2, let df1 and df2 be
> df1
  col1 col2 col3
1   48   39    a
2   26   42    e
3   45   30    b
4   40   46    c

> df2
  col1 col2 col3   col4    col5
1   49   47    a info a info2 a
2   27   45    b info b info2 b
3   28   37    c info c info2 c
4   37   26    e info e info2 e
5   25   40    f info f info2 f

The first step is to identify the rows in the second file,
rn <-  match(df1$col3, df2$col3)

This will create the vector of the row names, based on which the file 2 can be filtered
out <- cbind(df1[3], df2[rn,][-3])

Here, the column from first data frame is combined with the all the columns except third of the looked-up rows of second data frame.
The new data frame will have the row names from the vector which we had created earlier. Also, if there are some unidentified rows it will create NA in the data frame which can be replaced with an empty character.
rownames(out) <- rownames(df1)
out[is.na(out)] <- ""

The output will be like this:
> out
  col3 col1 col2   col4    col5
1    a   49   47 info a info2 a
2    e   37   26 info e info2 e
3    b
4    c   28   37 info c info2 c


Q:

TableLayoutPane missing in Visual Studio 17

Ive been using TableLayoutPane in Visual Studio 2015 to create form designs and recently upgraded to Visual Studio 2017. But the TableLayoutPane has been missing in the newer version!! What is the solution here?

A:

Solved the problem myself guys. What I did is :

Right click on container(or any other) tab inside the Toolbox an click on "Choose items..."
Then a dialogue pops up and under .NET components search for TableLayoutPane and check it to make it visible in Toolbox


Q:

Apache Pig - ERROR 2229: Couldn't find matching uid -1 for project

I've got the following exception when running a Pig script.

ERROR 2229: Couldn't find matching uid -1 for project (Name: Project
  Type: bytearray Uid: -1 Input: 0 Column: 12)

org.apache.pig.impl.logicalLayer.FrontendException: ERROR 2000: Error processing rule ColumnMapKeyPrune. Try -t ColumnMapKeyPrune
    at org.apache.pig.newplan.optimizer.PlanOptimizer.optimize(PlanOptimizer.java:122)
    at org.apache.pig.backend.hadoop.executionengine.HExecutionEngine.compile(HExecutionEngine.java:274)
    at org.apache.pig.PigServer.compilePp(PigServer.java:1324)
    at org.apache.pig.PigServer.executeCompiledLogicalPlan(PigServer.java:1249)
    at org.apache.pig.PigServer.execute(PigServer.java:1241)
    at org.apache.pig.PigServer.executeBatch(PigServer.java:335)
    at org.apache.pig.tools.grunt.GruntParser.executeBatch(GruntParser.java:137)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:198)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:170)
    at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:84)
    at org.apache.pig.Main.run(Main.java:604)
    at org.apache.pig.Main.main(Main.java:157)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:208)
Caused by: org.apache.pig.impl.logicalLayer.FrontendException: ERROR 2229: Couldn't find matching uid -1 for project (Name: Project Type: bytearray Uid: -1 Input: 0 Column: 12)
    at org.apache.pig.newplan.logical.optimizer.ProjectionPatcher$ProjectionRewriter.visit(ProjectionPatcher.java:91)
    at org.apache.pig.newplan.logical.expression.ProjectExpression.accept(ProjectExpression.java:207)
    at org.apache.pig.newplan.DepthFirstWalker.depthFirst(DepthFirstWalker.java:64)
    at org.apache.pig.newplan.DepthFirstWalker.walk(DepthFirstWalker.java:53)
    at org.apache.pig.newplan.PlanVisitor.visit(PlanVisitor.java:52)
    at org.apache.pig.newplan.logical.optimizer.AllExpressionVisitor.visitAll(AllExpressionVisitor.java:72)
    at org.apache.pig.newplan.logical.optimizer.AllExpressionVisitor.visit(AllExpressionVisitor.java:95)
    at org.apache.pig.newplan.logical.relational.LOJoin.accept(LOJoin.java:174)
    at org.apache.pig.newplan.DependencyOrderWalker.walk(DependencyOrderWalker.java:75)
    at org.apache.pig.newplan.PlanVisitor.visit(PlanVisitor.java:52)
    at org.apache.pig.newplan.logical.optimizer.ProjectionPatcher.transformed(ProjectionPatcher.java:48)
    at org.apache.pig.newplan.optimizer.PlanOptimizer.optimize(PlanOptimizer.java:113)
    ... 16 more

What could be the reason? I've looked at the expanded and substituted version of the script and I don't see anything wrong from a syntax point of view.

A:

Its a bug in Pig Optimizer in version 0.11.1 (CDH 4.3). It seems to be related to the attempt at optimizing the following simplified script
LOAD A  -- Primary Driver Table
LOAD B
LOAD C
J1 = JOIN A LEFT, B
J2 = JOIN J2 LEFT, C
LOAD D
J3 = JOIN J2, D -- Inner Join

Ideally if A was joined with D earlier, then the data flowing through joins J1 AND J2 could reduce and therefore speed up things.
I guess this optimization attempt is failing.
One way to do away with this bug is to identify how you can "promote" join J3 (inner join) to happen earlier in your script.


Q:

Defining the complexification of a representation

I am reading a paper and do not really understand the following.
The setting is $G$ is a compact connected Lie group and $\mathbb{R}^n$ a representation of $G$. Later on in the paper the authors mention the "complexified action of $G$ on $\mathbb{C}^n$". Could someone please explain to me what this means?
If we write the representation as $\pi:G\to GL(n;\mathbb{R})$, is the complexification referring to the Lie group (see https://en.wikipedia.org/wiki/Complexification_(Lie_group)), or is it referring to the ambient space $\mathbb{R}^n$ (so the image of the representation becomes $GL(n;\mathbb{C})$), or is it both?
What would be the proper definition of this complexification?
Comment: I do not think $G$ gets complexified because they use the Peter-Weyl theorem later on in the paper, which is a result for compact Lie groups, and the complexification of $G$ is not compact (see https://en.wikipedia.org/wiki/Complex_Lie_group, the final example).
Any help will be very appreciated! Thanks!

A:

A summary of the discussion in the comments:

It's simply the composition of your $\pi:G\rightarrow \operatorname{GL}(n, \Bbb R)$ with the canonical embedding $\operatorname{GL}(n, \Bbb R)\hookrightarrow\operatorname{GL}(n, \Bbb C)$.
If you prefer group action language, then it's the formula $\rho(g)(v_1 + iv_2) = \pi(g)(v_1) + i\pi_g(v_2)$, but with $v_1, v_2\in \Bbb R^n$.
Note that the canonical $\Bbb R$-basis of $\Bbb R^n$ is also a canonical $\Bbb C$-basis of $\Bbb C^n$, thus under that basis, the matrix of $\rho(g)$ is exactly the same as the matrix of $\pi(g)$, just viewed as complex matrix. Hence it's tautologically in $\operatorname{GL}(n, \Bbb C)$.
In other words, it's simply multiplying a real matrix with complex vectors.


Q:

Is there any solution for git - error: bad signature without losing (non-committed) data

I was working on a branch and it was working fine. After some work, when I type git status this happens:
mac-mini:production_designs jithinraj$ git status
error: bad signature
fatal: index file corrupt

Now I can't commit or do anything on my branch. Any solution for this without losing my data that was not committed?

A:

I fixed my issue without loosing my data -

Deleted the index file manually.
After that, I used the command git reset --keep
Then used the command git status(it will take some time) magically all my changed files were there for me to commit.

Thank you for your time guys. Really appreciate it.

A:

Try to reset your git.
it may be because of any index or file got corrupted.
Once I also faced the same problem.
Got fixed with below command:
rm -f .git/index

git reset .

I hope this resolve that issue.


Q:

Python Programmatically Change Console font size

I found the code below which is supposed to programmatically change the console font size. I'm on Windows 10.
However, whatever values I tweak, I can't seem to get any control over the font size, and also for some reason the console which gets opened when I run this script is very wide.
I have no idea how ctypes works - all I want is to modify the size of the console font from inside Python.
Any actual working solutions?
import ctypes

LF_FACESIZE = 32
STD_OUTPUT_HANDLE = -11

class COORD(ctypes.Structure):
    _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)]

class CONSOLE_FONT_INFOEX(ctypes.Structure):
    _fields_ = [("cbSize", ctypes.c_ulong),
                ("nFont", ctypes.c_ulong),
                ("dwFontSize", COORD),
                ("FontFamily", ctypes.c_uint),
                ("FontWeight", ctypes.c_uint),
                ("FaceName", ctypes.c_wchar * LF_FACESIZE)]

font = CONSOLE_FONT_INFOEX()
font.cbSize = ctypes.sizeof(CONSOLE_FONT_INFOEX)
font.nFont = 12
font.dwFontSize.X = 11
font.dwFontSize.Y = 18
font.FontFamily = 54
font.FontWeight = 400
font.FaceName = "Lucida Console"

handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
ctypes.windll.kernel32.SetCurrentConsoleFontEx(
        handle, ctypes.c_long(False), ctypes.pointer(font))

print("Foo")

A:

I want to start by pointing out [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer) which describes a problem that most CTypes users run into.
The CTypes home page (also listed in the above URL): [Python.Docs]: ctypes - A foreign function library for Python
I changed your code "a bit".
code.py:
#!/usr/bin/env python

import sys
from ctypes import POINTER, WinDLL, Structure, sizeof, byref
from ctypes.wintypes import BOOL, SHORT, WCHAR, UINT, ULONG, DWORD, HANDLE

LF_FACESIZE = 32
STD_OUTPUT_HANDLE = -11

class COORD(Structure):
    _fields_ = [
        ("X", SHORT),
        ("Y", SHORT),
    ]

class CONSOLE_FONT_INFOEX(Structure):
    _fields_ = [
        ("cbSize", ULONG),
        ("nFont", DWORD),
        ("dwFontSize", COORD),
        ("FontFamily", UINT),
        ("FontWeight", UINT),
        ("FaceName", WCHAR * LF_FACESIZE)
    ]

kernel32_dll = WinDLL("kernel32.dll")

get_last_error_func = kernel32_dll.GetLastError
get_last_error_func.argtypes = []
get_last_error_func.restype = DWORD

get_std_handle_func = kernel32_dll.GetStdHandle
get_std_handle_func.argtypes = [DWORD]
get_std_handle_func.restype = HANDLE

get_current_console_font_ex_func = kernel32_dll.GetCurrentConsoleFontEx
get_current_console_font_ex_func.argtypes = [HANDLE, BOOL, POINTER(CONSOLE_FONT_INFOEX)]
get_current_console_font_ex_func.restype = BOOL

set_current_console_font_ex_func = kernel32_dll.SetCurrentConsoleFontEx
set_current_console_font_ex_func.argtypes = [HANDLE, BOOL, POINTER(CONSOLE_FONT_INFOEX)]
set_current_console_font_ex_func.restype = BOOL

def main():
    # Get stdout handle
    stdout = get_std_handle_func(STD_OUTPUT_HANDLE)
    if not stdout:
        print("{:s} error: {:d}".format(get_std_handle_func.__name__, get_last_error_func()))
        return
    # Get current font characteristics
    font = CONSOLE_FONT_INFOEX()
    font.cbSize = sizeof(CONSOLE_FONT_INFOEX)
    res = get_current_console_font_ex_func(stdout, False, byref(font))
    if not res:
        print("{:s} error: {:d}".format(get_current_console_font_ex_func.__name__, get_last_error_func()))
        return
    # Display font information
    print("Console information for {:}".format(font))
    for field_name, _ in font._fields_:
        field_data = getattr(font, field_name)
        if field_name == "dwFontSize":
            print("    {:s}: {{X: {:d}, Y: {:d}}}".format(field_name, field_data.X, field_data.Y))
        else:
            print("    {:s}: {:}".format(field_name, field_data))
    while 1:
        try:
            height = int(input("\nEnter font height (invalid to exit): "))
        except:
            break
        # Alter font height
        font.dwFontSize.X = 10  # Changing X has no effect (at least on my machine)
        font.dwFontSize.Y = height
        # Apply changes
        res = set_current_console_font_ex_func(stdout, False, byref(font))
        if not res:
            print("{:s} error: {:d}".format(set_current_console_font_ex_func.__name__, get_last_error_func()))
            return
        print("OMG! The window changed :)")
        # Get current font characteristics again and display font size
        res = get_current_console_font_ex_func(stdout, False, byref(font))
        if not res:
            print("{:s} error: {:d}".format(get_current_console_font_ex_func.__name__, get_last_error_func()))
            return
        print("\nNew sizes    X: {:d}, Y: {:d}".format(font.dwFontSize.X, font.dwFontSize.Y))

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

Notes:

CTypes allows low level access similar to C (only the syntax is Python)

Code uses [MS.Docs]: SetConsoleTextAttribute function

In order to avoid setting invalid values, it's used in conjunction with its counterpart: [MS.Docs]: GetCurrentConsoleFontEx function. Call that function in order to populate the CONSOLE_FONT_INFOEX structure, then modify only the desired values
There are "simpler" functions (e.g. [MS.Docs]: GetCurrentConsoleFont function or [MS.Docs]: GetConsoleFontSize function), but unfortunately there are no corresponding setters

The ctypes.wintypes constants (which reference the standard CTypes types) are used (to give the code a Win like flavor)

It is very (almost painfully) long (also because I've added proper error handling)

An alternative, as suggested in one of the answers of [SO]: Change console font in Windows (where you copied the code from), would be to install a 3rd-party module (e.g. [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions which is a Python wrapper over WINAPIs) which would require less code to write because the bridging between Python and C would be already implemented, and probably the above functionality could be accomplished in just a few lines

As I commented in the code, setting COORD.X seems to be ignored. But it's automatically set when setting COORD.Y (to a value close to COORD.Y // 2 - probably to preserve the aspect ratio). On my machine (Win 10 pc064) the default value is 16. You might want to set it back at the end, to avoid leaving the console in a "challenged" state (apparently, Win adjusts cmd window size, to be (sort of) in sync with the font size):


Q:

Using PyTest with hug and base_url

I have a an api that is setup with
import hug
API = hug.API(__name__).http.base_url='/api'

@hug.get('/hello-world', versions=1)
def hello_world(response):
    return hug.HTTP_200

and I'm trying to test it with PyTest.
I'm trying to test the route with
import pytest
import hug
from myapi import api

...

def test_hello_world_route(self):
    result = hug.test.get(myapp, 'v1/hello-world')
    assert result.status == hug.HTTP_200

How can I test hug routes that have http.base_url configured?
I get a 404 errors regardless of the route path. I've tried

/api/v1/hello-world
api/v1/hello-world
v1/hello-world
/v1/hello-world

If I remove the hug.API().http.base_url setting then v1/hello-world works fine but my requirement is to have a base_url setup.
I've reviewed the documentation on the official hug github repo and various online sources such as ProgramTalk but I haven't had much success.
any recommendations?

A:

You should send your module (myapp) as the first argument to hug.test.get().
Then you can use the full path /api/v1/hello-world as the second argument.
Here's a minimal working example:
# myapp.py

import hug

api = hug.API(__name__).http.base_url='/api'

@hug.get('/hello-world', versions=1)
def hello_world(response):
    return hug.HTTP_200

.
# tests.py

import hug
import myapp

def test_hello_world_route():
    result = hug.test.get(myapp, '/api/v1/hello-world')
    assert result.status == hug.HTTP_200

.
# run in shell
pytest tests.py


Q:

ffmpeg: re-encode a video, keeping settings similar

I'm dealing with some mp4 videos that were encoded on mobile phones and are pretty huge.
I think ffmpeg can do better.   I'm trying to figure out what flags to use to preserve fps, resolution, and keep the appearance the same (lossless or near lossless).
What flags should I use?

A:

Preserve settings
ffmpeg will automatically attempt to use many of the same parameters when encoding including: frame rate, width, height, pixel format, audio channel layout, audio sample rate, etc. So you usually don't have to do anything special.
Some settings may change if there are format or encoder restrictions.
Preserve quality
For H.264 video using the encoder libx264 use:

-crf 18
the slowest preset you have patience for

These options will output a lossy video, but it -crf 18 provides enough bits that it will likely be visually lossless or nearly so. If the output is still too big the general recommendation is to use the highest -crf value that still provides an acceptable quality.
You can change it to -crf 0 for true lossless, but the resulting output will be a huge file size–probably even bigger than the original.
Example:
ffmpeg -i input.mp4 -c:v libx264 -crf 18 -preset slow -c:a copy output.mp4

This example stream copies the audio instead of re-encoding it since the majority of the file size comes from video.
Development is very active, so make sure to use a recent build of ffmpeg. See the FFmpeg Download page for links to binaries.
Also see:

FFmpeg Wiki: H.264 Video


Q:

Oracle Index Sort Order and Joining

I have 2 tables that are a few millions of rows with indexes. I'm looking to convert one of the indexes to DESC order to optimize some operations. However, will that affect joinining speed or other optimizations?
For example:

Table A:
a_id (pk)
Table B:
b_id (pk)
a_id (fk)

If A.a_id is stored as DESC and B.a_id is stored ASC will I encounter any problems or slowness on joins? Will oracle be able to use the indexes for joining even though they have different sort orders? Do I have to make B.a_id DESC as well or create a second index that is DESC ? Obviously I'd like to try a simple experiment but I don't have DBA access or a spare oracle setup to work with.

A:

Will oracle be able to use the indexes
  for joining even though they have
  different sort orders?

Indexes are not used "for joining".  They're used to access data.  The row sources thus created are then joined.  The only reason I can think of that the sort order of the index would have any impact on joining would be if a merge join is occurring and the index is being used to avoid sorting.  In this case, the impact of changing to a descending index might be that the data needs to be sorted in memory after it is accessed; or it might not, if the optimizer is intelligent enough to simply walk through that data in reverse order when doing the merge.
If you have queries whose execution plans rely on using the index on A.A_ID to get the data in ascending order (either for purposes of a merge join or to meet your requested ordering of the results), then changing the index to descending order could have an impact.
Edit:  Just did a quick test on some sample data.  The optimizer does seem to have the capability to merge row sources sorting in opposite orders without resorting either of them.  So at the most obvious level, having one index ascending and the other descending should not cause serious performance problems.  However, it does look like the descending indexes can have other effects on the execution plan -- in my case, the ascending index was used for a fast full scan, while the descending one was used for a range scan.  This could cause changes in query performance -- good or bad -- but the only way to know for certain is to test it.


Q:

List index out of range error when getting column names from dict keys

I am trying to get some data from a site and keep encountering this error message
IndexError                                Traceback (most recent call last)
<ipython-input-119-2f759e4acc91> in <module>
----> 1 fights_df = fights(fighters)

<ipython-input-118-be5e1cad2fca> in fights(list_of_boxers)
     31
     32     #grab the column names from the dictionary keys of one event
---> 33     col_titles = r[0].keys()
     34
     35     # create a list of values (remove the keys from the dictionary of each instance)

IndexError: list index out of range

From what I understand this means that the length of the list I am using as argument should have a length matching what I defined in my function.
Here is my code:
def fights(list_of_boxers):
  dataframe = pd.DataFrame()
  for boxer in list_of_boxers:
    headers = {
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "en-US,en;q=0.9",
    "Connection": "keep-alive",
    "Content-Length": "28",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Host": "beta.compuboxdata.com",
    "Origin": "http://beta.compuboxdata.com.com",
    "Referer": "http://beta.compuboxdata.com/fighter",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest"
    }
    dataload = {"page": "0",
            "result": "100",
            "fighter": boxer}
    t0 = time.time()
    r = requests.post('http://beta.compuboxdata.com/front/fighter/search', headers = headers, data = dataload )
    r = r.json()

    #grab the column names from the dictionary keys of one event
    col_titles = r[0].keys()

    # create a list of values (remove the keys from the dictionary of each instance)
    event_values = [list(event.values()) for event in r]

    #create a dataframe from the list of values
    df = pd.concat([pd.DataFrame([i], columns = col_titles) for i in event_values], ignore_index = True)

    dataframe = dataframe.append(df)

    response_delay = time.time() - t0
    time.sleep(0.5*response_delay)
    fights_df = fights(fighters)

  return dataframe

The full length of fighters is 6151
Here is a sample
['6690',
 '5631',
 '7281',
 '2643',
 '7099',
 '4719',
 '2555',
 '7244',
 '6807',
 '4550']

This is what i get if I comment out everything prior to
col_titles = r[0].keys()

Output:
[{'tot': '1',
  'event_id': '5648',
  'event_name': 'CAMABD03292014',
  'event_date': '2014-03-29',
  'title': '',
  'fighter1': 'CAMPFORT WILKY',
  'fighter2': 'ABDULLAEV KHURSHID',
  'fighter1id': '4549',
  'fighter2id': '4550',
  'fighter1ln': 'CAMPFORT',
  'fighter2ln': 'ABDULLAEV',
  'result': 'PAST'}]

A:

I have done a small fix to your code, which is to check for length of the dictionary/list before you try to access the element "if len(r) > 0:". That is why you get the error "IndexError: list index out of range". Below is the working code
import pandas as pd
import requests
import time

def fights(list_of_boxers):
    dataframe = pd.DataFrame()
    for boxer in list_of_boxers:
      headers = {
          "Accept": "application/json, text/javascript, */*; q=0.01",
          "Accept-Encoding": "gzip, deflate",
          "Accept-Language": "en-US,en;q=0.9",
          "Connection": "keep-alive",
          "Content-Length": "28",
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
          "Host": "beta.compuboxdata.com",
          "Origin": "http://beta.compuboxdata.com.com",
          "Referer": "http://beta.compuboxdata.com/fighter",
          "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
          "X-Requested-With": "XMLHttpRequest"
      }
      dataload = {"page": "0",
                  "result": "100",
                  "fighter": boxer}
      t0 = time.time()
      r = requests.post('http://beta.compuboxdata.com/front/fighter/search', headers=headers, data=dataload)
      r = r.json()

      # grab the column names from the dictionary keys of one event
      if len(r) > 0:
          col_titles = r[0].keys()
          print(r)
          # create a list of values (remove the keys from the dictionary of each instance)
          event_values = [list(event.values()) for event in r]

          # create a dataframe from the list of values
          df = pd.concat([pd.DataFrame([i], columns=col_titles) for i in event_values], ignore_index=True)

          dataframe = dataframe.append(df)

          response_delay = time.time() - t0
          time.sleep(0.5 * response_delay)

    return dataframe

list_of_boxers = ['6690'
'5648',
'7281',
'2643',
'7099',
'4719',
'2555',
'7244',
'6807',
'4550']

fights(list_of_boxers)

and below is the screenshot of the code and the results


Q:

How to return image from AV Foundation still capture and add it to graphics context for a screenshot?

I have a camera preview which works great. I want to take a screenshot of it and everything on top of it. However, since the usual screenshot approach: CALayer's renderInContext does not render content from the camera, I need to add it separately.
I have this function in my view controller captures the image and saves it to the camera roll.
 @IBAction func snapStillImage(sender: AnyObject) {
        print("snapStillImage")
        (self.previewView.layer as! AVCaptureVideoPreviewLayer).connection.enabled=false;

        dispatch_async(self.sessionQueue, {
            // Update the orientation on the still image output video connection before capturing.

            let videoOrientation =  (self.previewView.layer as! AVCaptureVideoPreviewLayer).connection.videoOrientation

            self.stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = videoOrientation

            // Flash set to Auto for Still Capture
            ViewController.setFlashMode(AVCaptureFlashMode.Auto, device: self.videoDeviceInput!.device)

            self.stillImageOutput!.captureStillImageAsynchronouslyFromConnection(self.stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo), completionHandler: {
                (imageDataSampleBuffer: CMSampleBuffer!, error: NSError!) in

                if error == nil {
                    let data:NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                    let image:UIImage = UIImage( data: data)!

                    let libaray:ALAssetsLibrary = ALAssetsLibrary()
                    let orientation: ALAssetOrientation = ALAssetOrientation(rawValue: image.imageOrientation.rawValue)!
                    libaray.writeImageToSavedPhotosAlbum(image.CGImage, orientation: orientation, completionBlock: nil)

                    print("save to album")

                }else{
//                    print("Did not capture still image")
                    print(error)
                }

            })

        })
    }

I want to return the image defined with let image:UIImage = UIImage( data: data)!
so that it is accessible by the following function
@IBAction func downloadButton(sender: UIButton) {
    //Create the UIImage

    UIGraphicsBeginImageContextWithOptions(previewView.frame.size, false, 0.0)

    previewView.layer.renderInContext(UIGraphicsGetCurrentContext()!)

    //ALSO ADD image captured with captureStillImageAsynchronouslyFromConnection right here to the context.
    let image = UIGraphicsGetImageFromCurrentImageContext()

    //Save it to the camera roll

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

This would let my screenshot include the recently captured image as well as all the stuff on top that gets added with UIGraphicsGetCurrentContext()!
I have heard that you do this by including the image in the completion handler block already included in the captureStillImageAsynchronouslyFromConnection function but I am not quite sure how to do this. Any suggestions?

A:

You could add the captured still image as a UIImage as a subview of the previewView. Then make the call to renderInContext.
Assuming this code is all going on in the same class, you can make image a property like
class CameraViewController: UIViewController {
    var image: UIImage!
    ...

Then in captureStillImageAsynchronouslyFromConnection
instead of
let image:UIImage = UIImage( data: data)!

use
self.image = UIImage( data: data)!

Then in downloadButton use
var imageView = UIImageView(frame: previewView.frame)
imageView.image = self.image
previewView.addSubview(imageView)
previewView.layer.renderInContext(UIGraphicsGetCurrentContext()!)

You can then remove the imageView if you want
imageView.removeFromSuperview()

A:

You cannot render content from the camera because CALayer's renderInContext doesn't work.
Nonetheless you want to work that, the following link can help you.
Taking a screenshot when camera is on -iOS
https://developer.apple.com/library/ios/qa/qa1702/_index.html#//apple_ref/doc/uid/DTS40010192


Q:

Task on the number of iterations

There is a number N
every iteration it becomes equal to (N*2)-1
I need to find out how many steps the number will be a multiple of the original N;
( 1≤ N ≤ 2 · 10 9 )
For example:
N = 7; count = 0

N_ = 7*2-1 = 13; count = 1; N_ % N != 0

N_ = 13*2-1 = 25; count = 2; N_ % N != 0

N_ = 25*2-1 = 49; count = 3; N_ % N == 0

Answer is 3
if it is impossible to decompose in this way, then output -1
       #include <iostream>
       using namespace std;

       int main(){
           int N,M,c;
           cin >> N;
           if (N%2==0) {
               cout << -1;
               return 0;
           }
           M = N*2-1;
           c = 1;
           while (M%N!=0){
               c+=1;
               M=M*2-1;
           }
           cout << c;
           return 0;
       }

It does not fit during (1 second limit). How to optimize the algorithm?
P.S All the answers indicated are optimized, but they don’t fit in 1 second, because you need to change the algorithm in principle. The solution was to use Euler's theorem.

A:

The problem, as other answers have suggested, is equivalent to finding c such that pow(2, c) = 1 mod N. This is impossible if N is even, and possible otherwise (as your code suggests you know).
A linear-time approach is:
int c = 1;
uint64_t m = 2;
while (m != 1){
  c += 1;
  m = (2*m)%N;
}
printf("%d\n", c);

To solve this in 1 second, I don't think you can use a linear-time algorithm. The worst cases will be when N is prime and large. For example 1999999817 for which the above code runs in around 10 seconds on my laptop.
Instead, factor N into its prime factors. Solve 2^c = 1 mod p^k for each prime factor (where p^k appears in the prime factorization of N. Then combine the results using the Chinese Remainder theorem.
When finding the c for a given prime power, if k=1, the solution is c=p-1. When k is larger, the details are quite messy, but you can find a written solution here: https://math.stackexchange.com/questions/1863037/discrete-logarithm-modulo-powers-of-a-small-prime

A:

The problem is that you're overflowing, the int data type only has 32 bits, and overflows 2^31-1 , in this problem you don't need to keep the actual value of M, you can just keep the modulo of n.
 while (M%N!=0){
           c+=1;
           M=M*2-1;
           M%=N
       }

Edit:In addition, you don't actually need more than N iterations to check if a 0 mod exists, as there are only N different mods to N and it just keeps cycling. so you also need to keep that in mind in case there is no 0 mod.


Q:

iOS Update UIImage with other UIImage after allocating

Ok the case might sound simple, but i can't figure out how to do this:
        //
        CGImageRef ImagRef      = [self imageFromSampleBuffer:sampleBuffer];

        // Allocate m_pIMAGE at the first frame
        if(m_pIMAGE == NULL)
        {
            m_pIMAGE = [[UIImage alloc] initWithCGImage:(ImagRef)];
        }
        else
        {
            // Copy the frame image (ImagRef) into the m_pIMAGE

        }

        CGImageRelease( ImagRef );

How do i update my m_pIMAGE with ImageRef after it was allocated at the first frame?

A:

Image should be assigned in main thread...
CGImageRef ImagRef = CGBitmapContextCreateImage(context);

CFRetain(ImagRef);
// Create an image object from the Quartz image
if([NSThread isMainThread]) {
    if(m_pIMAGE == NULL) {
        m_pIMAGE = [[UIImage alloc] initWithCGImage:(ImagRef)];
    } else {
    }
    CFRelease(ImagRef);
} else {
    dispatch_async(dispatch_get_main_queue(), ^{
        if(m_pIMAGE == NULL) {
            m_pIMAGE = [[UIImage alloc] initWithCGImage:(ImagRef)];
        } else {
        }
        CFRelease(ImagRef);
    });
}
// Release the Quartz image
CGImageRelease(ImagRef);


Q:

Why a client and not an app?

I searched on the play store for a stack overflow app for my android. I found out there is a client that you can use, but I was wondering why they didn't make an official app? The GUI would be much better and the buttons would look as if they belong on a mobile device. So far it looks like the desktop view squeezed onto a mobile view.

A:

There actually is an app
https://play.google.com/store/apps/details?id=com.stackexchange.marvin&hl=en
It's not specifically or solely for stackoverflow, but stackoverflow is also in there.