text:
Q: Create nested list from Multidimensional Array with sveral keys i need create list from this array
 [records] => Array
    (
        [0] => Array
            (
                [id] => 665
                [productGroupID] => 665
                [name] => AUDIO/VIDEO VALDKOND
                [showInWebshop] => 1
                [positionNo] => 619
                [added] => 1362673935
                [lastModified] => 1364198793
                [subGroups] => Array
                    (
                        [0] => Array
                            (
                                [id] => 557
                                [productGroupID] => 557
                                [name] => VIDEO
                                [showInWebshop] => 1
                                [positionNo] => 1229
                                [added] => 1361340146
                                [lastModified] => 1362131355
                                [subGroups] => Array
                                    (
                                        [0] => Array
                                            (
                                                [id] => 565
                                                [productGroupID] => 565
                                                [name] => TELERID
                                                [showInWebshop] => 1
                                                [positionNo] => 642
                                                [added] => 1361340916
                                                [lastModified] => 1397208602
                                                [subGroups] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [id] => 269
                                                                [productGroupID] => 269
                                                                [name] => Teler kuni 15"
                                                                [showInWebshop] => 1
                                                                [positionNo] => 1454
                                                                [added] => 1361281340
                                                                [lastModified] => 1363594045
                                                                [subGroups] => Array
                                                                    (
                                                                    )

                                                            )

                                                        [1] => Array
                                                            (
                                                                [id] => 500
                                                                [productGroupID] => 500
                                                                [name] => Teler 19-29"
                                                                [showInWebshop] => 1
                                                                [positionNo] => 1459
                                                                [added] => 1361284369
                                                                [lastModified] => 1379684581
                                                                [subGroups] => Array
                                                                    (
                                                                    )

                                                            )

                                                        [2] => Array
                                                            (
                                                                [id] => 509
                                                                [productGroupID] => 509
                                                                [name] => Teler 32"
                                                                [showInWebshop] => 1
                                                                [positionNo] => 1460
                                                                [added] => 1361284370
                                                                [lastModified] => 1363594480
                                                                [subGroups] => Array
                                                                    (
                                                                    )

                                                            )

                                                    )

                                            )

how can i remove all values beside productGroupID and name?
what i made sofar
function list($element){
    foreach($element as $value){
        if(!is_array($value)){
            echo "
";
            echo $value;
        }else{
            echo "
";
            r($value);
            echo "
";
            echo "
";
        }
    }
}

echo "
";
echo list($output['records']).";
echo "
";

this prints all values. i cant figure out, how print only 2 needed values of each sub-array

A: You have to iterate over arrays of arrays. Then all what you have to do is printing informations which you need and check if there is not empty subarray. If it is, call recursively again listing function. Below is a working code example. You still pass $output['records'] to this function as argument.
function list_elements($elements) {
    echo '
';
    foreach ($elements as $element) {
        echo '
';
        echo $element['productGroupID'] . ':' . $element['name'];
        if (!empty($element['subGroups'])) {
            list_elements($element['subGroups']);
        }
        echo '
';
    }
    echo '
';
}


text:
Q: getting nhl standings with python I wrote a function using python and selenium to use BeautifulSoup on a url:
def get_soup(url):
    d = webdriver.Chrome()
    d.get(url)
    result = d.page_source
    soup = BeautifulSoup(result, 'html.parser')
    return soup

I'm trying to scrape the current NHL standings from this url: https://www.nhl.com/standings/league
I am running into 2 issues that I don't know how to get around:
1) If you follow this url, it takes you to the "league" tab, but the scraping doesn't distinguish between this tab and the others.
2) The three elements in the "National Hockey League" column (ranking, logo, name) are three separate things, but they are in a single column.
I'd like to pull this data into a pandas dataframe.

A: I took a look at the source code of the website, and found the internal NHL API. You can scrape the rankings here. The only thing that this listing doesn't have is a logo, but it has the other things you're looking for. Just note that since this doesn't appear to be public, the URL can change at any time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I fix my `itoa` implementation so it doesn't print reversed output? I want to convert an integer into a string of numeric characters in C.
I've tried using itoa, but it's non-standard and not provided by my C library.
I tried to implement my own itoa, but it's not working properly:
#include <stdlib.h>
#include <stdio.h>

char *itoa(int val, char *buf, int base)
{
    size_t ctr = 0;
    for( ; val; val /= base )
    {
        buf[ctr++] = '0' + (val % base);
    }
    buf[ctr] = 0;
    return buf;
}

int main(void)
{
    unsigned char c = 201;
    char *buf = malloc(sizeof(c)*8+1);
    itoa(c, buf, 2);
    puts(buf);
    free(buf);
}

It gives reversed output.
For example, if c is 'A' and base is 2, the output is this: 0101101
The output I want it to be is this: 1011010
How do I fix this issue?

Similar questions

I've already seen this question: Is there a printf converter to print in binary format?
I do not want a printf format specifier to print an integer as binary, I want to convert the binary to a string.
I've already seen this question: Print an int in binary representation using C
Although the answer does convert an integer into a string of binary digits, that's the only thing it can do.

Restrictions

I want itoa to be able to work with other bases, such as 10, 8, etc. and print correctly (i.e. 12345 translates to "12345" and not to "11000000111001").
I do not want to use printf or sprintf to do this.
I do not care about the length of the string as long is the result is correct.
I do not want to convert the integer into ASCII characters other than numeric ones, with the exception of bases greater than 10, in which case the characters may be alphanumeric.
The answer must fit this prototype exactly:
char *itoa(int val, char *buf, int base);

There may be a function called nitoa that has this prototype and returns the number of characters required to hold the result of itoa:
size_t nitoa(int val, int base);

A:
How do I fix my itoa implementation so it doesn't print reversed output?

Rather than reverse the string, form it right-to-left.  #4 of @user3386109

I recommend the helper function also receives in a size.
#include <limits.h>

char* itostr(char *dest, size_t size, int a, int base) {
  // Max text needs occur with itostr(dest, size, INT_MIN, 2)
  char buffer[sizeof a * CHAR_BIT + 1 + 1];
  static const char digits[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  if (base < 2 || base > 36) {
    fprintf(stderr, "Invalid base");
    return NULL;
  }

  // Start filling from the end
  char* p = &buffer[sizeof buffer - 1];
  *p = '\0';

  // Work with negative `int`
  int an = a < 0 ? a : -a;

  do {
    *(--p) = digits[-(an % base)];
    an /= base;
  } while (an);

  if (a < 0) {
    *(--p) = '-';
  }

  size_t size_used = &buffer[sizeof(buffer)] - p;
  if (size_used > size) {
    fprintf(stderr, "Scant buffer %zu > %zu", size_used , size);
    return NULL;
  }
  return memcpy(dest, p, size_used);
}

Then to provide memory, use a compound literal.
// compound literal C99 or later
#define INT_STR_SIZE (sizeof(int)*CHAR_BIT + 2)
#define MY_ITOA(x, base) itostr((char [INT_STR_SIZE]){""}, INT_STR_SIZE, (x), (base))

Now you can call it multiple times.
int main(void) {
  printf("%s %s %s %s\n", MY_ITOA(INT_MIN,10), MY_ITOA(-1,10), MY_ITOA(0,10), MY_ITOA(INT_MAX,10));
  printf("%s %s\n", MY_ITOA(INT_MIN,2), MY_ITOA(INT_MIN,36));
  return (0);
}

Output
-2147483648 -1 0 2147483647
-10000000000000000000000000000000 -ZIK0ZK

Note: sizeof(c)*8+1 is one too small for INT_MIN, base 2.

A: This solution works for me:
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#define itoa lltoa
#define utoa ulltoa
#define ltoa lltoa
#define ultoa ulltoa
#define nitoa nlltoa
#define nutoa nulltoa
#define nltoa nlltoa
#define nultoa nulltoa

#define BASE_BIN 2
#define BASE_OCT 8
#define BASE_DEC 10
#define BASE_HEX 16
#define BASE_02Z 36

__extension__
char *ulltoa(unsigned long long val, char *buf, int base)
{
    int remainder;
    char c, *tmp = buf;

    if(base < BASE_BIN)
    {
        errno = EINVAL;
        return NULL;
    }

    do {
        remainder = val % base;
        if(remainder >= BASE_DEC) c = 'a' - BASE_DEC;
        else c = '0';
        *tmp++ = remainder + c;
        val /= base;
    } while(val);

    *tmp = 0;
    return strrev(buf);
}

__extension__
size_t nulltoa(unsigned long long val, int base)
{
    size_t size = 0;

    if(base < BASE_BIN)
    {
        errno = EINVAL;
        return 0;
    }

    if(!val) size++;

    for( ; val; val /= base, size++ );

    return size;
}

__extension__
char *lltoa(long long val, char *buf, int base)
{
    if(val < 0 && base > BASE_BIN)
    {
         val = -val;
         *buf++ = '-';
    }

    return ulltoa(val, buf, base);
}

__extension__
size_t nlltoa(long long val, int base)
{
    size_t size = 0;

    if(val < 0 && base > BASE_BIN)
    {
        val = -val;
        size++;
    }

    return size + nulltoa(val, base);
}


text:
Q: Connect-MsolService error after importing MSOnline module I'm receive the following error when I run Connect-MsolService -

Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown.
      + CategoryInfo          : OperationStopped: (:) [Connect-MsolService], MicrosoftOnlineException
      + FullyQualifiedErrorId : 0x80090345,Microsoft.Online.Administration.Automation.ConnectMsolService
      + PSComputerName        : xxxxx

Background -
I am using powershell to manage Active Directory, Exchange and Sharepoint Online user data.  I have an SSIS package that dynamically builds arguments passed to powershell scripts for creating new and updating existing AD user data, adding/updating necessary security and distribution groups for each user, enabling exchange mailboxes, and passing custom attribute data to Sharepoint online user profiles.
In effort to maintain the purity of the SQL server running the SSIS package, dynamic sessions are created to servers having the modules necessary for import.  This allows me to do all of the things mentioned above without having to install the different modules on my SQL server.
My final hurdle is automating the Office 365 licensing.  To script licensing assignments I create a session to our server having the necessary MSOnline module and import it giving me access to the Cmdlets, like Set-MsolUserLicense.  However, before I can use the Cmdlets I have to connect to the MSOLService.
When I run Connect-MsolService, the credentials modal pops as expected, the appropriate credentials are entered (which have been verified a thousand times over), and I receive the error shown above.
These commands all work fine when I run them from the server where the MSOnline cmdlets are installed, but return the error when run post successful import-module on my SQL server.
Here are the commands used for establishing the session and importing the MSOnline module -
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $securePassword

$outputSession = $Null
foreach($session in Get-PSSession){
    if(($session.ComputerName -eq $Server) -and ($session.Availability -eq "Available")){
        $outputSession = $session
    }
}
if ($outputSession -eq $Null){
    $outputSession = New-PSSession -ComputerName $Server -Credential $cred -Name 'MSOnline'
    Invoke-Command -Session $outputSession -ScriptBlock {Import-Module MSOnline}
    Import-PSSession -session $outputSession -module MSOnline -AllowClobber
}

Connect-MSOLService is the only Cmdlet giving me an issues using these methods.  Any help you can provide will be appreciated.

A: Sigh. This appears to be a bug with single sign on assistant and MSOL module. I have had this issue reproduced reliably and had it reported to Office 365 support. It went nowhere. To state it simply, Connect-MSOnline works only in local sessions.
Mind you, MSOL module is a very strange beast, it is not using PSSession to maintain connection with Azure but uses some internal mechanisms that must rely on single sign-on assistant. This may be why in remote session MSOL commandlet cannot connect to Azure AD.
It was a dead end for me, and the only way to work around it is to write an application that runs on the server using MSOL module and accepts commands from the client or is invoked on server directly via service or scheduled task.


text:
Q: How to read and view a disc file in a webix application I am absolutely new into webix development and not finding much documentation/help about my current challenge.
In my webix application, I want to have button (name say 'View Report') clicking which will link to a disc file in my local disc and show its content in a popup window.
I am including the snippet of code which I could write so far :
mytoolbar =
  {             id:'tb',
                view: 'toolbar',
                height: rowHeight,
                type: 'clean',
                cols: [
{view:"button", id:"showfile",  type:"icon", icon:"external-link", label:"View Report", width:buttonWidth, tooltip: "click to view report", on: {onItemClick:function(){viewReportFile()}} },

]

And the viewReportFile function looks as below (taken from
http://docs.webix.com/desktop__window.html )
function viewReportFile(){
     webix.ui( {
        view:"window",
        height:250,
        width:300,
        left:50, top:50,
        move:true,
        resize: true,
        head:"This window can be resized",
        body:{
            template:"Some text"
        }
    }).show();

})
}

Clicking the button should read a file residing in my directory (lets say at C:\Users\myname\Desktop\report.txt") and display that file content in the modal window. It could be any popup window to display the file content with a close button. Can anybody help me with the implementation ? I apologize for not being able to put much code here as I am new to it.
I am also including an working code which lets the user pick a file from his directory and shows its content in the textarea.
<html>

<input type="file" onchange="onFileSelected(event)">
<br>
<textarea id="result" rows="10" cols="50"></textarea>
<script>
function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var result = document.getElementById("result");

  reader.onload = function(event) {
    result.innerHTML = event.target.result;
  };

  reader.readAsText(selectedFile);
}

</script>
</html>

Thanks.

A: Here a sample, but keep in mind that there is many way to perform this and this sample shouldn't be best suited for your specific case :
http://webix.com/snippet/36341f3c
function loadReport() {
  return "My report string";
}

function viewReportFile() {
  $$('myContent').define('template', loadReport());
  $$('myPopup').show();
}

webix.ui({
        id: 'myPopup',
        view:"window",
        height:250,
        width:300,
        left:50,
        top:50,
        move:true,
        resize: true,
        head:"This window can be resized",
        body:{
            id: 'myContent',
            template: "Some text"
        }
    });


text:
Q: Parameter for IN query oracle SELECT * FROM EMPLOYEE
WHERE EMP_NAME IN (:EMP_NAME);

This is my query and now the EMP_NAME parameter I would like to send it as a list of strings.
When I run this query in SQL developer it is asked to send the EMP_NAME as a parameter, Now I want to send 'Kiran','Joshi' (Basically, I want to fetch the details of the employee with employee name either Kiran or Joshi. How should I pass the value during the execution of the query?
It works when I use the value Kiran alone, but when I concatenate with any other string it won't work. Any pointers in this?
I tried the one below
'Kiran','Joshi'
The above way doesn't work as understood this is a single parameter it tries the employee with the name as 'Kiran',Joshi' which won't come. Understandable, but in order to achieve this thing, how can I go ahead?
Any help would be really appreciated.

A: Thanks to the people who helped me in solving this problem.
I could get the solution using the way proposed, below is the approach
SELECT * FROM EMPLOYEE WHERE EMP_NAME IN (&EMP_NAME)

I have tried in this way and following are the scenarios which I have tested and they are working fine.
Scenario 1:
To fetch details of only "Kiran", then in this case the value of EMP_NAME when sql developer prompts is given as Kiran. It worked.
Scenario 2:
To fetch details of either "Kiran" or "Joshi", then the value of EMP_NAME is sent as
Kiran','Joshi

It worked in this case also.
Thanks Kedarnath for helping me in achieving the solution :)

A: IN clause would be implicitly converted into multiple OR conditions.. and the limit is 1000.. Also query with bind variable means, the execution plan will be reused..  Supporting bind variables for IN clause will hence affect the bind variable's basic usage, and hence oracle limits it at syntax level itself.
Only way is like name in (:1,:2) and bind the other values..
for this, you might dynamic SQL constructing the in clause bind variables in a loop.
Other way is, calling a procedure or function(pl/sql)
DECLARE
    v_mystring VARCHAR(50);
    v_my_ref_cursor sys_refcursor;
    in_string varchar2='''Kiran'',''Joshi''';
    id2 varchar2(10):='123'; --- if some other value you have to compare
        myrecord tablename%rowtype;
  BEGIN

    v_mystring := 'SELECT a.*... from tablename a where name= :id2 and
                    id in('||in_string||')';

    OPEN v_my_ref_cursor FOR v_mystring USING id2;

    LOOP
      FETCH v_my_ref_cursor INTO myrecord;
      EXIT WHEN v_my_ref_cursor%NOTFOUND;
        ..
      -- your processing
    END LOOP;
    CLOSE v_my_ref_cursor;

  END;

IN clause supports maximum of 1000 items. You can always use a table to join instead. That table might be a Global Temporary Table(GTT) whose data is visible to thats particular session.
Still you can use a nested table also for it(like PL/SQL table)
TABLE() will convert a PL/Sql table as a SQL understandable table object(an object actually)
A simple example of it below.
CREATE TYPE pr AS OBJECT
           (pr  NUMBER);
/
CREATE TYPE prList AS TABLE OF pr;
/

declare
  myPrList prList := prList ();
  cursor lc is
    select *
      from (select a.*
              from yourtable a
                   TABLE(CAST(myPrList as prList)) my_list
             where
                   a.pr = my_list.pr
             order by a.pr desc) ;
  rec lc%ROWTYPE;

BEGIN
  /*Populate the Nested Table, with whatever collection you have */
  myPrList := prList ( pr(91),
                       pr(80));
  /*
     Sample code: for populating from your TABLE OF NUMBER type

     FOR I IN 1..your_input_array.COUNT
     LOOP
          myPrList.EXTEND;
          myPrList(I) := pr(your_input_array(I));
     END LOOP;
  */
  open lc;
  loop
    FETCH lc into rec;
    exit when lc%NOTFOUND; -- Your Exit WHEN condition should be checked afte FETCH iyself!
    dbms_output.put_line(rec.pr);
  end loop;
  close lc;
END;
/


text:
Q: Concatenating dataframes read from multiple aws s3 bucket generate NoneType error I have a bunch of csv files I need to read and group into one single dataframe. These files re in an aws s3 bucket and a subfolder of it. Reading the files is not really an issue. The problem is that I get an error message when doing this, but I cannot figure out what I am doing wrong:
bucket = s3.Bucket('mybucket')
import io
prefix_objs = bucket.objects.filter(Prefix="folder/file_prefix")

df = pd.DataFrame()

for obj in prefix_objs:
    key = obj.key
    body = obj.get()['Body'].read()
    temp = pd.read_csv(io.BytesIO(body), sep=",",encoding='utf8')
    frame =[df,temp]
    df = pd.concat(frame)

So, my idea is starting with an empty df, to use read_csv only on files with a given prefix in a given bucket folder.
Now, I get the error
AttributeError: 'NoneType' object has no attribute 'items'

but at the same time i do get info that indicates I'm not completely far off:
            id       date  success      on     off  quota  errors
0         130  2020-12-09     True     0.0     0.0  1.000     NaN
1         433  2020-12-09    False     NaN     NaN    NaN     NaN
2         810  2020-12-09     True     0.0     0.0  1.000     NaN
3        2889  2020-12-09     True  1653.0  1707.0  0.968     NaN
4        5410  2020-12-09    False     NaN     NaN    NaN     NaN
..        ...         ...      ...     ...     ...    ...     ...
2         810  2021-01-12     True    50.0    47.0  1.064     NaN
3        2889  2021-01-12     True   190.0   179.0  1.061     NaN
4        5410  2021-01-12     True     0.0     0.0  1.000     NaN
5        6069  2021-01-12     True  1736.0  1779.0  0.976     NaN
6        6128  2021-01-12     True     0.0     0.0  1.000     NaN

[232 rows x 7 columns]

What in my code is wrong so that it would generate that error? Any help would be appreciated.
Another alternative, if it isn't possible to answer this:
If I change the code to
bucket = s3.Bucket('my bucket')
import io
prefix_objs = bucket.objects.filter(Prefix="folder/prefix")

df = []

for obj in prefix_objs:
    key = obj.key
    body = obj.get()['Body'].read()
    temp = pd.read_csv(io.BytesIO(body), encoding='utf8',sep=",")
    df.append(temp)

How can I make
[          Id        date  success      on     off  quota  errors
 0        130  2020-12-09     True     0.0     0.0  1.000     NaN
 1        433  2020-12-09    False     NaN     NaN    NaN     NaN
 2        810  2020-12-09     True     0.0     0.0  1.000     NaN
 3       2889  2020-12-09     True  1653.0  1707.0  0.968     NaN
 4       5410  2020-12-09    False     NaN     NaN    NaN     NaN
 5       6069  2020-12-09     True     0.0     0.0  1.000     NaN
 6       6128  2020-12-09     True  2202.0  2182.0  1.009     NaN,
           id        date  success      on     off  quota  errors
 0        130  2020-12-10     True   634.0   556.0  1.140     NaN
 1        433  2020-12-10    False     NaN     NaN    NaN     NaN
 2        810  2020-12-10     True   464.0   442.0  1.050     NaN
 3       2889  2020-12-10     True   940.0   915.0  1.027     NaN
 4       5410  2020-12-10    False     NaN     NaN    NaN     NaN
 5       6069  2020-12-10     True  2926.0  2879.0  1.016     NaN
 6       6128  2020-12-10     True    32.0    32.0  1.000     NaN,
           id        date  success      on     off  quota  errors
 0        130  2020-12-11     True   366.0   341.0  1.073     NaN
 1        433  2020-12-11    False     NaN     NaN    NaN     NaN
 2        810  2020-12-11     True   204.0   201.0  1.015     NaN
 3       2889  2020-12-11     True   359.0   362.0  0.992     NaN
 4       5410  2020-12-11    False     NaN     NaN    NaN     NaN
 5       6069  2020-12-11     True  1601.0  1588.0  1.008     NaN
 6       6128  2020-12-11     True   703.0   705.0  0.997     NaN,
           id        date  success     on    off  quota  errors
 0        130  2020-12-12     True  162.0  153.0  1.059     NaN
 1        433  2020-12-12    False    NaN    NaN    NaN     NaN
 2        810  2020-12-12     True  153.0  147.0  1.041     NaN
 3       2889  2020-12-12    False    NaN    NaN    NaN     NaN
 4       5410  2020-12-12    False    NaN    NaN    NaN     NaN
 5       6069  2020-12-12     True  690.0  701.0  0.984     NaN
 6       6128  2020-12-12     True    0.0    0.0  1.000     NaN]

into a dataframe? I tried DF = pd.DataFrame(df) but it is obviously wrong.
 EDIT: Reproducible Data
All the csv files in the bucket are of this form
Id,date,success,on,off,quota,errors
130,2020-12-09,True,0.0,0.0,1.000,
433,2020-12-09,False,,,,
810,2020-12-09,True,0.0,0.0,1.000,
2889,2020-12-09,True,1653.0,1707.0,0.968,
5410,2020-12-09,False,,,,
6069,2020-12-09,True,0.0,0.0,1.000,
6128,2020-12-09,True,2202.0,2182.0,1.009,

Here is a second example
Id,date,success,on,off,quota,errors
130,2020-12-11,True,366.0,341.0,1.073,
433,2020-12-11,False,,,,
810,2020-12-11,True,204.0,201.0,1.015,
2889,2020-12-11,True,359.0,362.0,0.992,
5410,2020-12-11,False,,,,
6069,2020-12-11,True,1601.0,1588.0,1.008,
6128,2020-12-11,True,703.0,705.0,0.997,

All the missing value a left blank.

A: The code below runs fine.
import pandas as pd

csv1 ="""Id,date,success,on,off,quota,errors
130,2020-12-09,True,0.0,0.0,1.000,
433,2020-12-09,False,,,,
810,2020-12-09,True,0.0,0.0,1.000,
2889,2020-12-09,True,1653.0,1707.0,0.968,
5410,2020-12-09,False,,,,
6069,2020-12-09,True,0.0,0.0,1.000,
6128,2020-12-09,True,2202.0,2182.0,1.009,"""

csv2="""Id,date,success,on,off,quota,errors
130,2020-12-11,True,366.0,341.0,1.073,
433,2020-12-11,False,,,,
810,2020-12-11,True,204.0,201.0,1.015,
2889,2020-12-11,True,359.0,362.0,0.992,
5410,2020-12-11,False,,,,
6069,2020-12-11,True,1601.0,1588.0,1.008,
6128,2020-12-11,True,703.0,705.0,0.997,"""

df1 = pd.read_csv(io.StringIO(csv1))
df2 = pd.read_csv(io.StringIO(csv2))

df = pd.concat([df1, df2])
df.to_csv('aws_toy.csv')
print(df, '\n')

avg_quota = df.groupby('date').agg(avg_quota=('quota', 'mean')).reset_index()
print(avg_quota, '\n')

select_quota = df.filter(['on'])
print(select_quota, '\n')

Ouput:
     Id        date  success      on     off  quota  errors
0   130  2020-12-09     True     0.0     0.0  1.000     NaN
1   433  2020-12-09    False     NaN     NaN    NaN     NaN
2   810  2020-12-09     True     0.0     0.0  1.000     NaN
3  2889  2020-12-09     True  1653.0  1707.0  0.968     NaN
4  5410  2020-12-09    False     NaN     NaN    NaN     NaN
5  6069  2020-12-09     True     0.0     0.0  1.000     NaN
6  6128  2020-12-09     True  2202.0  2182.0  1.009     NaN
0   130  2020-12-11     True   366.0   341.0  1.073     NaN
1   433  2020-12-11    False     NaN     NaN    NaN     NaN
2   810  2020-12-11     True   204.0   201.0  1.015     NaN
3  2889  2020-12-11     True   359.0   362.0  0.992     NaN
4  5410  2020-12-11    False     NaN     NaN    NaN     NaN
5  6069  2020-12-11     True  1601.0  1588.0  1.008     NaN
6  6128  2020-12-11     True   703.0   705.0  0.997     NaN

         date  avg_quota
0  2020-12-09     0.9954
1  2020-12-11     1.0170

       on
0     0.0
1     NaN
2     0.0
3  1653.0
4     NaN
5     0.0
6  2202.0
0   366.0
1     NaN
2   204.0
3   359.0
4     NaN
5  1601.0
6   703.0


text:
Q: error: expression list treated as compound expression in initializer [-fpermissive] I'm entirely stuck. I keep getting this message when I attempt to compile...
"[mkiss117@kuvapcsitrd01 csc135]$ g++ test4.cpp
test4.cpp: In function 'int main()':
test4.cpp:39:51: error: expression list treated as compound expression in initializer [-fpermissive]
float CalculateIt (Sales,counter, AverageArray);
^
test4.cpp:39:51: error: cannot convert 'float*' to 'float' in initialization
"
I am lost and feeling in over my head as how to fix this.
#include <iostream> // includes the iostream library
#include <math.h>   // handles math in the script
#include <iomanip>  // manipulates text display.
#include <string>
#include <fstream>
using namespace std;
#define MAXDEPT 10
#define MAXMONTHS 12

void ExplainIt();
bool OpenIt (ifstream &, string &);
void DisplayIt (string[12], float[12],float[12]);
bool ReadIt (ifstream &, string &, float[12], float);
float CalculateIt (float[12], int &, float[10]);

int main(){
 string Months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"};
 float Goals[12] = {23.0, 33.1, 20.5, 23.5, 54.0, 33.3, 34.8, 45.0, 56.3, 44.6, 34.0, 56.0};
 float Sales[12];
 int counter=0;
 float AverageArray[10];
    ifstream ins;
    string FileName;
    float Department;

        //This prints the instructions.
        ExplainIt();

        if(!OpenIt(ins, FileName)){return 1;}
        //This reads each order, one at a time, and loads the values
        while(!ins.eof()) {
        int Departments=0;
          while(!ReadIt(ins, FileName, Sales, Departments)){

          float CalculateIt (Sales,counter, AverageArray);
counter++;

        }

        }
        DisplayIt(Months,Goals,Sales);
}
////////////////////////////////////////////////////////////////////////
//
//   Function name:    ExplainIt
//   Description:      output instructions for operator to use the script
//   Parameters:       None
//   Return Value:     None
//
////////////////////////////////////////////////////////////////////////

void ExplainIt () {
    cout << "This program collects a file name from the user. It then opens that file." << endl;
    cout << "It records one line of information on sales at a time, and stores the " << endl;
    cout << "information. It takes this information and calculates the average over" << endl;
    cout << "the course of the year. It also tells how many months that each department" << endl;
    cout << "met their goal and how many months they missed it. Finally it reports if" << endl;
    cout << "the department was able to satisfy 8 or more monthly goals and reports" << endl;
    cout << "a satisfied or unsatisfied performance rating." << endl;
}
//End ExplainIt Function/////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//
//   Function name:    OpenIt
//   Description:
//   Parameters:
//   Return Value:
////////////////////////////////////////////////////////////////////////
bool OpenIt (ifstream &ins, string &FileName){
    cout << "Enter the name of the file you would like to open: ";
    cin  >> FileName;
    ins.open(FileName);
        if (ins.fail()) {
            cout << "ERROR opening file: " << FileName << "." << endl;
            return 0;
        }
    return !ins.fail();
}
//End OpenIt Function///////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//
//   Function name:    ReadIt
//   Description:
//   Parameters:
//   Return Value:
//
//
////////////////////////////////////////////////////////////////////////
bool ReadIt(ifstream &ins,string &FileName, float Sales[12], float Departments ){
    for(int D=0; D<12; D++){
        if(ins.fail()) {
        cout << "Debug1" << endl;
            return true;
        }else {
            ins >> Sales[D];
            if(ins.fail()){
            cout << "Debug2" << endl;
                return true;
            }
        }
    }
    cout << "Debug3" << endl;
    return false;
}
//End ReadIt Function///////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//
//   Function name:    CalculateIt
//   Description:
//   Parameters:
//   Return Value:
//
////////////////////////////////////////////////////////////////////////
float CalculateIt (float sales[12], int &counter,float AverageArray[10]){
float sum=0;
float avg;
    for(int i=0; i<12; i++){
    sum+=sales[i];
    }
avg=sum/12;
AverageArray[counter]=avg;
return 1;
}
//End CalculateIt Function//////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//
//   Function name:    DisplayIt
//   Description:
//   Parameters:
//   Return Value:
//
////////////////////////////////////////////////////////////////////////
void DisplayIt(string Months[12], float Goals[12], float Sales [12]){
cout << endl;
        for(int i=0; i<12; i++){
        cout << setw(6)<< left << Months[i] << " ";
        }
        cout << endl;
        for(int q=0; q<12; q++){
        cout << setw(6)<< left << Goals[q] << " ";
        }
cout << endl;
cout << "---------------------------------------------------------------------------------" << endl;
        for(int p=0; p<12; p++){
        cout << setw(6)<< left << Sales[p] << " ";
        }
cout << endl;
}
//End DisplayIt Function////////////////////////////////////////////////


text:
Q: Is there a way to use a Random Forest model on Android to make predictions? I've been looking at primarily Weka to do machine learning testing, and I've found that Random Forest models have the best results for my purposes. I wanted to save this model and implement it on Android to predict new values, but these days it seems nigh-impossible to implement Weka on Android (all the available sources are super out-dated).
Are there any ways to train a Random Forest model, and then implement that model on an Android app to predict new values?

A: In addition to Weka, you can train Random Forest (RF) models also with R, Scikit-Learn or Apache Spark ML. You can export/convert RF models from their native representation into the standardized PMML representation using R2PMML, SkLearn2PMML or JPMML-SparkML-Package tools, respectively, and then import and score such models using Java PMML scoring engines such as JPMML-Evaluator. The latter has a direct Android integration available.

A: In addition to the answer of user1808924, you can convert Weka Random Forest to PMML using the following tool:
https://github.com/AlbertoCasasOrtiz/weka-to-pmml
And then proceed to load the PMML models in Android.


text:
Q: Playbook where item.stat.exist not working I have created playbook which will run on a remote host and check whether the files exist or not. I want to extract the only files which are not present on the remote host. But my playbook giving all paths whether they are present or not.
Playbook:-
- name: Playbook for files not present on remote hosts
  hosts: source
  gather_facts: false
  vars:
     Filepath: /opt/webapps/obiee/oracle_common/inventory/ContentsXML/comps.xml
  tasks:
    - name: Getting files location path
      shell:  grep -i "COMP NAME" {{ Filepath }} |sed 's/^.*INST_LOC="//'|cut -f1 -d'"' | sed '/^$/d;s/[[:blank:]]//g' // extract files from comps.xml
      register: get_element_attribute

    - name: check path present or not
      stat:
        path: "{{ item }}"
      with_items:
         - "{{ get_element_attribute.stdout_lines }}"
      register: path_output

    - name: path exists or not
      set_fact:
         path_item: "{{ item }}" # here i am getting the output as expected that's files not present on remote host
      with_items: "{{ path_output.results }}"
      register: final_output
      when:  item.stat.exists == False

    - debug:
        var: final_output  #  giving both output i.e. files present and absent

    - name: Create a fact list
      set_fact:
       paths: "{{ final_output.results |  map(attribute='item.item') | list }}" # i have add this condition  " item.stat.exists == False' inside this stmt

    - name:  Print Fact
      debug:
        var: paths

A: The issue  resolved by using below command:
- name: Create a fact list
  set_fact:
    paths: "{{ final_output.results | selectattr('item.stat.exists', 'equalto', false) | map(attribute='item.item') |  list }}"
  register: config_facts

A: The following query should get all the file names which don't exsist on the remote host and store them in the fact 'paths':
- name: Create a fact list
  set_fact:
    paths: "{{ final_output | json_query(query)}}"
  vars:
    query: "results[?(@._ansible_item_label.stat.exists==`false`)]._ansible_item_label.item"


text:
Q: Does a micro-HDMI (type D) cable with an adapter work normally for computer-monitor connection? I'm considering using a micro-HDMI (type D) to HDMI cable with an adapter on the micro-HDMI end to connect my computer to my monitor. I want to use micro-HDMI because I'm passing the cable through a conduit in the wall and I don't want the hole in the wall to be huge.
Specifically, I want to know if a micro-HDMI cable would be different (apart from the size) or have some limitation compared to regular HDMI. I want to output 1080p to two monitors. My graphics card has got two outputs.
So, can I use an adapter with a micro-HDMI to HDMI cable to connect my computer to my monitors?

A: Wikipedia has the following to say about micro-HDMI (emphasis mine):

A Micro connector ... keeps the standard 19 pins of types A and C but shrinks the connector size to something resembling a micro-USB connector. ... The pin assignment is different from Type A or C.

Since the only thing that changes from HDMI to micro-HDMI is the pin assignments and not the number of pins, it's reasonable to conclude that connecting an HDMI device (with an appropriate adapter) through a micro-HDMI to HDMI cable would work.


text:
Q: lookup task (ssis) I just need the confirmation.
Tell me if I am wrong.
A package consists of an oledb source editor which consists of a query followed by three lookups. If I do a preview on each task, every task (oledb source, and the first two lookups) except for the last lookup has values in the respective tables. So, my claim is: if there is no data in the last lookup table the final resultset that comes out of the last look up should be empty.
Help appreciated.

A: Depending on how you handle errors it will either throw an error (red component) or be redirected/ignored. So you are somewhat correct with your assumption.


text:
Q: how to do this query in rails to get search two columns from one table and one column from another table I have the following association:
class Resource < ActiveRecord::Base
 belongs_to :author
 def self.search(search)
     where('title ILIKE ? OR description ILIKE ?', "%#{search}%","%#{search}%")
 end

I need to search for the author name as in the following:
 where('title ILIKE ? OR description ILIKE ? OR author_name ILIKE ?', "%#{search}%","%#{search}%","%#{search}%" )

end
This obviously won't work as I have the author_id in the Resource table and not the author name field.
I'm a NOOB so any help appreciated
Thanks

A: You can use the joins method to join the authors table.  See example below:
def self.search(search)
 joins(:author).where('title ILIKE ? OR description ILIKE ? OR authors.name ILIKE ?', "%#{search}%","%#{search}%","%#{search}%")
end


text:
Q: Pug HTML Rendering With MongoDB ObjectID I have a HTML rendering problem on pug, I am sending the mongodb objectId to the .pug files and its not rendering properly.
My Pug Code :
 input(type='text', value=transaction._id, name='transaction_id')

HTML Rendered Code :
<input type="text" value=""576c0bb18716a46c0c41508e"" name="transaction_id"/>

Its automatically adding " I tried to change the objectId as string, but it didn't works.

A: This one should work :
 input(type='text', value='#{transaction._id}', name='transaction_id')


text:
Q: selecting an element in xml using linq extension methods I am little new to linq and was wondering how i can select the application in the following xml based on the application name using Extension Methods (not using the query expression)
<applicationlist>
<application>
    <name>test1</name>
    <ele1>852</ele1
    <ele2>http://localhost/test1</ele2>
</application>

<application>
    <name>test2</name>
    <ele1>456</ele1
    <ele2>http://localhost/test2</ele2>
</application>
</applicationlist>

A: Assuming that by "the SQL way of selecting" you mean "using a query expression", let's start off with your query expression:
var v = from b in root.Descendants("application")
      where b.Element("name").Value.Trim().ToLower() == appName.Trim().ToLower()
      select b;

With extension methods, this would just be:
var v = root.Descendants("application")
            .Where(b => b.Element("name").Value.Trim().ToLower() ==
                        appName.Trim().ToLower());

I would recommend against making case-insensitive comparisons this way though - it has cultural problems. Use something like this instead:
var v = root.Descendants("application")
            .Where(b => b.Element("name").Value.Trim().Equals(appName.Trim(),
                                     StringComparison.CurrentCultureIgnoreCase);

(or one of the other StringComparison options - or an instance of StringComparer).
You might also want to trim appName once rather than for every comparison...


text:
Q: Android kSOAP2: Namespace inexplicably added within XML parameter on server side I'm trying to send some XML as a parameter within a SOAP request from an Android app I'm developing. The problem is that despite the fact that the request dump looks to be exactly what I require, it appears that the namespace for the upper-level method is being added into one of the inner tags of the XML parameter when the request is received on the server side:
The Java code:
public String uploadOpRecordsV2(Cursor op) throws IOException {
    SoapObject resultsRequestSOAP = null;
    SoapSerializationEnvelope envelope = null;
    HttpTransportSE androidHttpTransport = null;

    try {

        SoapObject request = new SoapObject("[website url]", "UploadOpRecordsV2");
        request.addProperty("username", sharedprefs.getString("Username", "none"));
        request.addProperty("password", "sharedprefs.getString("Password", "none")");
        request.addProperty("clientid", sharedprefs.getString("ClientID", "none"));
        SoapObject records = new SoapObject("", "records");
        SoapObject newRecords = new SoapObject("", "NewRecords");

        LocalDBHandler database = LocalDBHandler.getInstance(context);
        op = db.getEntireTable("thin_client_operations");
        op.moveToFirst();

        while (!op.isAfterLast()) {
            SoapObject db = new SoapObject("", "db");
            db.addAttribute("type", 1);
            db.addProperty("ID", database.getStringColumnValueNoClose(op, "id"));
            db.addProperty("PA", database.getStringColumnValueNoClose(op, "patientage"));
            db.addProperty("SP", sharedprefs.getString("Specialty", "none"));
            db.addProperty("OD", database.getStringColumnValueNoClose(op, "operationdate"));
            db.addProperty("HN", Validation.decrypt(database.getStringColumnValueNoClose(op, "hospitalnumber")));
            db.addProperty("PV", (database.getIntColumnValueNoClose(op, "id") == 1));
            db.addProperty("BT", "");
            db.addProperty("AG", database.getStringColumnValueNoClose(op, "asagrade"));
            db.addProperty("OC", database.getStringColumnValueNoClose(op, "operationcode"));
            db.addProperty("HC", database.getStringColumnValueNoClose(op, "hospitalcode"));
            db.addProperty("CO", "6130249");
            db.addProperty("SU", database.getStringColumnValueNoClose(op, "supervision"));
            db.addProperty("CE", database.getStringColumnValueNoClose(op, "cepod"));
            db.addProperty("NT", database.getStringColumnValueNoClose(op, "notes"));
            db.addProperty("CM", "Complications");
            db.addProperty("CP", "False");

            newRecords.addSoapObject(db);
            op.moveToNext();
        }
        records.addSoapObject(newRecords);
        request.addSoapObject(records);
        request.addProperty("src", "rcsedApp");
        op.close();

        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.implicitTypes = true;
        envelope.setAddAdornments(false);
        envelope.xsd = "http://www.w3.org/2001/XMLSchema";
        envelope.xsi = "http://www.w3.org/2001/XMLSchema-instance";
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        androidHttpTransport = new HttpTransportSE("[webservice url]");
        androidHttpTransport.debug = true;
        androidHttpTransport.call("[websiteurl/UploadOpRecordsV2]", envelope);
        resultsRequestSOAP = (SoapObject) envelope.bodyIn;

        Log.e("Request", androidHttpTransport.requestDump);
        Log.e("Response", androidHttpTransport.responseDump);
        return androidHttpTransport.responseDump;
    }

    catch (XmlPullParserException e) {
        return null;
    }
}

The log from the request dump, everything appears fine:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <UploadOpRecordsV2 xmlns="[websiteurl]">
      <username>string</username>
      <password>string</password>
      <clientid>string</clientid>
      <records>
        <NewRecords>
            <db type="1">
                <ID>df8aaba5-5784-42dc-93a7-b37f50610e38</ID>
                <PA>28</PA>
                <SP>CardiacSur</SP>
                <OD>08/07/2014 00:00:00</OD>
                <HN>23456</HN>
                <PV>false</PV>
                <BT></BT>
                <AG>2</AG>
                <OC>139</OC>
                <HC>160</HC>
                <CO>6130249</CO>
                <SU>4</SU>
                <CE>1</CE>
                <NT></NT>
                <CM>Complications</CM>
                <CP>False</CP></db>
            </db>
        </NewRecords>
        </records>
      <src>srcname</src>
    </UploadOpRecordsV2>
  </soap:Body>
</soap:Envelope>

The XML section of the request received by the server, sent to me by the technicians for the website:
NewRecords  <db type="1" xmlns="[websiteurl]"><ID>df8aaba5-5784-42dc-93a7-b37f50610e38</ID>
<PA>28</PA><SP>CardiacSur</SP><OD>08/07/2014 00:00:00</OD><HN>23456</HN>
<PV>false</PV><BT></BT><AG>2</AG><OC>139</OC><HC>160</HC><CO>6130249</CO>
<SU>4</SU><CE>1</CE><NT></NT><CM>Complications</CM><CP>False</CP></db>

Is it even possible for me to stop the namespace appearing in the db tag on the server side and if so how would I go about it? All the other posters with this problem solved it by setting "" as the namespace but it won't work here...
Any help would be massively appreciated.


text:
Q: TSQL Help (SQL Server 2005) I have been playing around with a quite complex SQL Statement for a few days, and have gotten most of it working correctly.
I am having trouble with one last part, and was wondering if anyone could shed some light on the issue, as I have no idea why it isnt working:
INSERT INTO ExistingClientsAccounts_IMPORT
SELECT DISTINCT
cca.AccountID, cca.SKBranch, cca.SKAccount, cca.SKName, cca.SKBase,
cca.SyncStatus, cca.SKCCY, cca.ClientType, cca.GFCID, cca.GFPID, cca.SyncInput,
cca.SyncUpdate, cca.LastUpdatedBy, cca.Deleted, cca.Branch_Account, cca.AccountTypeID
FROM         ClientsAccounts AS cca
INNER JOIN
(SELECT DISTINCT ClientAccount, SKAccount, SKDesc,
    SKBase, SKBranch, ClientType, SKStatus, GFCID,
    GFPID, Account_Open_Date, Account_Update
FROM          ClientsAccounts_IMPORT) AS ccai
ON cca.Branch_Account = ccai.ClientAccount

Table definitions follow:
CREATE TABLE [dbo].[ExistingClientsAccounts_IMPORT](
    [AccountID] [int] NOT NULL,
    [SKBranch] [varchar](2) NOT NULL,
    [SKAccount] [varchar](12) NOT NULL,
    [SKName] [varchar](255) NULL,
    [SKBase] [varchar](16) NULL,
    [SyncStatus] [varchar](50) NULL,
    [SKCCY] [varchar](5) NULL,
    [ClientType] [varchar](50) NULL,
    [GFCID] [varchar](10) NULL,
    [GFPID] [varchar](10) NULL,
    [SyncInput] [smalldatetime] NULL,
    [SyncUpdate] [smalldatetime] NULL,
    [LastUpdatedBy] [varchar](50) NOT NULL,
    [Deleted] [tinyint] NOT NULL,
    [Branch_Account] [varchar](16) NOT NULL,
    [AccountTypeID] [int] NOT NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[ClientsAccounts_IMPORT](
    [NEWClientIndex] [bigint] NOT NULL,
    [ClientGroup] [varchar](255) NOT NULL,
    [ClientAccount] [varchar](255) NOT NULL,
    [SKAccount] [varchar](255) NOT NULL,
    [SKDesc] [varchar](255) NOT NULL,
    [SKBase] [varchar](10) NULL,
    [SKBranch] [varchar](2) NOT NULL,
    [ClientType] [varchar](255) NOT NULL,
    [SKStatus] [varchar](255) NOT NULL,
    [GFCID] [varchar](255) NULL,
    [GFPID] [varchar](255) NULL,
    [Account_Open_Date] [smalldatetime] NULL,
    [Account_Update] [smalldatetime] NULL,
    [SKType] [varchar](255) NOT NULL
) ON [PRIMARY]

The error message I get is:
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.

A: The error is because you are trying to insert data into a column in ExistingClientsAccounts_IMPORT where the column size is smaller than the length of data attempting to be inserted into it.
e.g.
SKAccount column is VARCHAR(12) in the ExistingClientsAccounts_IMPORT table but is VARCHAR(255) in ClientsAccounts_IMPORT.
So if ClientsAccounts_IMPORT contains any rows where that field is longer than 12 characters, you will get that error as obv. e.g. 100 characters will not fit into a 12 character field.
You need to make sure all the columns in the table you are inserting into, are big enough - make sure each column definition matches the source table.

A: Check the field definitions. You can see some are smaller than the original ones. Now run a query on the old data - you will find some of the larger fields were used, so the insert is not possible without losing data.
Example: SKAccount - from 255 length to 12.

A: The third column of your SELECT column list means that ExistingClientsAccounts_IMPORT.SKAccount is populated from ClientsAccounts.SKAccount - however, the source is up to 255 characters, while the destination has a capacity of 12. If there's any data that wouldn't fit, you'll get this message.
I haven't gone through all the other columns.

A: You are trying to insert values which are greater than tha max length specified for a column. Use a profiler to check the data being passed to this query and verify the length of data against the permissible length for all columns.
There is a clear mismatch in the column lenghts of common columns of these two tables.
ClientsAccounts_IMPORT.SKBase is 10 whereas it is 16 in the other table.


text:
Q: ¿Cómo puedo obtener el GET del editor desde una URL amigable? No logro detectar el identificador de editor desde las URL amigables.
Mis URL amigables constan con varias categorías, no existe un número exacto, unas pueden tener más otras pueden tener menos categorías.
Ejemplo:
http://sitio.com/categoria1/categoría2/cat/cat/url-del-contenido-final/

Al darle al usuario su código de editor pub-1374077Q para registrar las referencia que fue promocionado desde su identificador, de la siguiente manera:
http://sitio.com/categoria1/categoría2/cat/cat/url-del-contenido-final/?publishers=pub-1374077Q

Pero no me imprime su identificador desde la URL amigable
$publishers = $_GET['publishers'];
echo $publishers;

Desde una URL normal:
http://sitio.com/index.php?publishers=pub-1374077Q

Ahí me imprime su identificador pub-1374077Q
¿Pero como puedo obtener el identificador del editor desde las URL amigables?

A: Primeramente debemos obtener la URL completa:
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

Luego la mejor manera de obtener lo que deseas es hacerlo mediante explode para eliminar cierta parte de la url, en este caso el /?publishers= y mediante array_pop para obtener el último elemento del final, del array pub-1374077Q.
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$url = explode('/?publishers=', $url);
$lastPart = array_pop($url);
echo $lastPart;


text:
Q: Error build android apk while using facebook plugins in ionic3 The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
        at build_6jy1i81bonl94r9ffpxyja5iq.run(E:\avtar\All Project Latest code\MindfulScholar\platforms\android\build.gradle:141)
The JavaCompile.setDependencyCacheDir() method has been deprecated and is scheduled to be removed in Gradle 4.0.
Incremental java compilation is an incubating feature.
The TaskInputs.source(Object) method has been deprecated and is scheduled to be removed in Gradle 4.0. Please use TaskInputs.file(Object).skipWhenEmpty() instead.


text:
Q: Why Does BackgroundWorker Throw An Exception While My Plain Thread Solution Doesn't? We're looking to avoid unresponsiveness on our UI for a potentially intensive database call.  I've been experimenting with different ways to reach the following scenario.

*

*User invokes the functionality.

*A thread is forked that executes the functionality.

*The user has the option of canceling the functionality.

*a. If the user does not cancel, the thread works with independent data and spawns some other, unrelated UI.

*b. If the user does cancel, cancel the thread's processing and cancel any related activity (such as the SQL stored procedure we'll be calling -- irrelevant for the purposes of this question).

Being a low-level, C++ kinda guy myself, I first tried a straight Thread solution.  Then, I tried looking into .NET's BackgroundWorker solution (C#).
Here's the code that I use to simulate that potentially-intensive operation that the thread is to handle.
    /// <summary>
    /// Simulates the processing for a query that is pretty much
    /// unresponsive after it's been invoked.
    /// </summary>
    public void SimulateSuperLongQuery ()
    {
        // Pass the time, for a very long time...
        for (int i=0; i < int.MaxValue; i++)
            SimulateSuperLongQuery();

        _completed = true;
    }

Peculiarly...

*

*My plain Thread solution works fine when calling that method.

*The BackgroundWorker solution throws a StackOverflowException when calling that method!

Does anyone have any idea why the BackgroundWorker causes an exception?

Code, in case it helps.  Here's a bit of the BackgroundWorker code.  It's straight off of the MSDN website.
        BackgroundWorker bw = new BackgroundWorker();
        bw.WorkerSupportsCancellation = true;
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);

        if (bw.IsBusy != true)
        {
            bw.RunWorkerAsync();
        }

        // ...

    private void bw_DoWork (object sender, DoWorkEventArgs e)
    {
        QuerySimulator query = new QuerySimulator();
        query.SimulateSuperLongQuery();
    }

Here's a bit of my plain vanilla code.
        // Fire up a thread to run a query
        QuerySimulator query = new QuerySimulator();
        Thread queryThread = new Thread(query.SimulateSuperLongQuery);

A: As people have already spotted, it is clear that you will run into a Stackoverflow, thread or not - just that in the single-threaded case I suspect that the CLR was able to do tail-call optimization.
If you want to simulate blocking thread, do just that: block it.
Thread.Sleep(TimeSpan.FromSeconds(5));

A: Without seeing all the code it's kind of hard to tell for sure, but I'm almost certain your SimulateSuperLongQuery code will cause a StackOverflowException no matter what. It's calling itself recursively forever (or trying to, anyway).
How long does your plain Thread solution take to run? If you're not seeing an exception in that version, it may just be getting swallowed somewhere.


text:
Q: Exact sequence and flasque sheaves What is an easy example of an exact sequence of sheaves (of modules or abelian groups if you prefer)
$$0\rightarrow \mathcal F \rightarrow \mathcal G \rightarrow \mathcal H \rightarrow 0$$
such that $\mathcal G$ is flasque (also called flabby) but $\mathcal H$ is not flasque?
In Harthshorne II.1 exercises if $\mathcal F$ and $\mathcal G$ are flasque then $\mathcal H$ would necessarily be so. And one uses $\mathcal F$ is flasque to show that on the level of sections we have exactness as well. I was wondering to what extent this would fail (and this is best explained by an example) if we don't have this.

A: Any sheaf $\mathcal{F}$ admits an injection $\mathcal{F\to G}$ into a flasque sheaf $\mathcal{G}$. Take $\mathcal{H}$ the cokernel. By the long exact sequence in cohomology, we have isomorphisms $H^i(X,\mathcal{H})\simeq H^{i+1}(X,\mathcal{F})$ for any $i>0$. Take $\mathcal{F}$ a sheaf with a non vanishing $H^2$ (for example), then $\mathcal{H}$ has a non vanishing $H^1$ and thus is not flasque.

A: As a complement, let me give a simple example where we have an exact sequence of sheaves of abelian groups
$$0\rightarrow \mathcal F \rightarrow \mathcal G \rightarrow \mathcal H \rightarrow 0$$ with $\mathcal G , \mathcal H $ both flasque but with $\mathcal F$ not flasque.
Take for $X=\mathbb A^1(\mathbb C)$ the complex affine line seen as an algebraic variety endowed with its Zariski topology.
We have an exact sequence of sheaves of abelian groups
$$0\rightarrow \mathcal O_X^* \rightarrow \mathcal K^*_X \rightarrow \mathcal Div_X\rightarrow 0$$ where $\mathcal K^*_X$ is the sheaf of non-zero rational functions and $\mathcal Div_X$ the sheaf of divisors on $X$.
Concretely, for an open subset $U\subset X$ the group $\mathcal Div_X(U)=\oplus_{P\in U} \mathbb  Z \cdot P $ is the free group on the points in $U$.
The map $\mathcal K^*_X(U)\rightarrow \mathcal Div_X(U)$ associates to the rational function $\phi$ the difference $Z(\phi)-P(\phi)$ of its zero set and its pole set, both counted with multiplicities.
The sheaf $\mathcal K^*_X$ is well known to be flasque ( more or less by definition)  while $\mathcal Div_X$ is trivially flasque because any finite sum $\Sigma_{P\in U} n_P \cdot P \in \mathcal Div_X(U)$ can be extended to  the sum   $\Sigma_{P\in X} n_P \cdot P \in \mathcal Div_X(X)$ with $n_P=0 $ for $P\in X\setminus U$.
However the sheaf $\mathcal O_X^*$ is not flasque, as witnessed by the section $z \in \mathcal O_X^*(X\setminus \{O\})$, not extendable to $\mathcal O_X^*(X)=\mathbb C^*$.

A: $\newcommand\N{\mathbb{N}} \newcommand\Z{\mathbb{Z}}$This is NOT an answer to my question. It is just to clarify with Jean Billie that you cannot assume the constant sheaf to be flasque if your topology is arbitrary. I would suggest Jean Billie to post this as a question in another thread. Meanwhile I write it here because it is too long for a comment:
Here is a case where you don't have flasque: Let $\beta\N$ be the (Alexandroff) one-point compactification of $\N$ (with discrete topology). Take your group to be $(\Z,+)$. $\N$ is an open and discrete subset of $\beta\N$. Since $\N$ is discrete, from the sheafification of the constant presheaf $\Z$ over $\beta\N$ you can define a section in $s\in \underline{\Z}(\N)$ by
$$s:\N\rightarrow \bigcup_{x\in \N} {\Z_x} \qquad s(i) = i$$
where the  $\Z_x$ is just a copy of $\Z$ (it is the stalk at $x\in \N$). There is no global section that restricts to $s$ because otherwise this section restricted to a small enough neighbourhood of $\infty$ (that extra point that compactifies $\N$) coincides with a section of the constant presheaf. But we know that all open sets containing $\infty$ must be cofinite. So, such a global section must be constant over all but finite number of elements in $\N$ but $s(i)$ is different for every $i$. So you have a contradiction.
For an irreducible topology you cannot do this. So you need some kind of reducibility or discreteness to make such an example.


text:
Q: How to make Pull Requests on a wordpress.org plugin? How can I submit pull request to other's plugin, which is hosted at wordpress.org?

A: WordPress.org repository uses SVN, not Git, so there are no pull requests.
Only users with contributor status can access plugins to commit changes. Each plugin has one contributor by default, but more contributors can be allowed to each plugin.
Some plugins are developed on GitHub, and only released on WordPress.org when ready.

A: No, the wordpres.org SVN repositories are not for development and there are no plans to change this. So you either have to ask on support forum, or if the plugin is on an open GIT repository search for it on GitHub.


text:
Q: Bash How to delete record from destination file which matches with source up to 17th pipe My source file is a pipe delimited one
QWER|RTYUI||12345678|09/07/1994|DFGHJK||PHOENIX|AZ||85044|123456|QQ|4567890|10/06/2017|12/31/9999|N||1|1234567|QQ|4567890876

and so is my destination file (destination files will be in date partitioned folders)
QWER|RTYUI||12345678|09/07/1994|DFGHJK||PHOENIX|AZ||85044|123456|QQ|4567890|10/06/2017|12/31/9999|N|QQQ|NOMATCH

I should be able to pick a record from source file and loop through all of files in destination folders and remove the record from destination file, point to be noted is I only need to match data up to 17th pipe in both of the files because after that data mismatches.
Example
BEFORE:
Source file
QWER|RTYUI||12345678|09/07/1994|DFGHJK||PHOENIX|AZ||85044|123456|QQ|4567890|10/06/2017|12/31/9999|N||1|1234567|QQ|4567890876

Destination file
QWER|RTYUI||12345678|09/07/1994|DFGHJK||PHOENIX|AZ||85044|123456|QQ|4567890|10/06/2017|12/31/9999|N|QQQ|NOMATCH
QWER|RTYUI||98765432|09/07/1921|FGHJKJK||VBNM|AZ||85044|123456|QQ|4567890|10/06/2017|12/31/9999|N|QQQ|NOMATCH

AFTER:
Destination file
QWER|RTYUI||98765432|09/07/1921|FGHJKJK||VBNM|AZ||85044|123456|QQ|4567890|10/06/2017|12/31/9999|N|QQQ|NOMATCH

The first record should be deleted from destination file because it is matching the data with source file up to 17th pipe.

A: One cut and one grep should be enough
cut -d'|' -f1-17 source | grep -vFf- destination > new_destination

A: Following awk should be able to help you in same.
awk -F"|" 'FNR==NR{a[$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17];next} !(($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17) in a)' Source_file  Destination_file  > temp_file && mv temp_file  Destination_file

Adding a non-one line form for solution too now.
awk -F"|" '
FNR==NR{
  a[$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17];
  next
}
!(($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17) in a)
'   Source_file  Destination_file  > temp_file && mv temp_file  Destination_file


text:
Q: Cannot stat during kernel compilation error I am trying to compile kernel version 4.10.1 in Ubuntu 14.04 the way described here.
It worked up until 4.9.x version.
When 4.10.x came out, I keep getting the following error:
install -p    -o root -g root  -m  644 CREDITS /usr/src/linux-4.10.1/debian/linux-headers-4.10.1/usr/share/doc/linux-headers-4.10.1/
install -p    -o root -g root  -m  644 MAINTAINERS /usr/src/linux-4.10.1/debian/linux-headers-4.10.1/usr/share/doc/linux-headers-4.10.1/
install -p    -o root -g root  -m  644 REPORTING-BUGS /usr/src/linux-4.10.1/debian/linux-headers-4.10.1/usr/share/doc/linux-headers-4.10.1/
install: cannot stat 'REPORTING-BUGS': No such file or directory
make[1]: *** [debian/stamp/install/linux-headers-4.10.1] Error 1
make[1]: Leaving directory `/usr/src/linux-4.10.1'
make: *** [kernel_headers] Error 2

A: The reason is that the kernel developers removed the REPORTING-BUGS file from the kernel source and the Ubuntu tool you used to compile the kernel expects the file to be there.
Apparently most kernel developers don't use make-kpkg, so they either didn't notice or didn't care about the fact that they broke the building of the kernel-headers package with make-kpkg. make-kpkg is after all just the tool of a specific Linux distro and the kernel developers might feel that they never made a promise to always have a documentation file with that path in the source tree.
As a workaround you can just copy the file from the 4.9 kernel sources into your tree to make it compile.


text:
Q: How can I use mod_rewrite to remove the query string from my URL? I am new at mod_rewrite and need some help if is possible.
this is my old url
www.mysite.com/web/page.php?c=categoryname

I need to change it at:
www.mysite.com/web/page/categoryname.html

I am using this code but it doesn't work:
    RewriteEngine on
    RewriteBase /web/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^/([^/]+)/?$ page.php?c=$1 [L]

How can I fix the above code to correctly rewrite my URLs?
EDIT:
Thanks to Ulrich Palha
i manage to redirect the html files, but css,js etc are not redirect and the website looks rly bad, this is the code i am using now, till i will get the one who will redirect css too
 RewriteEngine On
    RewriteBase /web/

    #redirect www.mysite.com/web/page.php?c=categoryname to
    #www.mysite.com/web/page/categoryname.html
    #prevent internal redirect
    RewriteCond %{ENV:REDIRECT_STATUS} !200
    RewriteCond %{QUERY_STRING} (^|&)c=([^&]+)(&|$) [NC]
    RewriteRule ^(page)\.php$ $1/%2.html? [NC,L,R=301]

    #rewrite www.mysite.com/web/page/categoryname.html to
    #www.mysite.com/web/page.php?c=categoryname
    RewriteRule ^(page)/([-a-zA-Z0-9]+)\.html$ $1.php?c=$2 [L,NC]

BUMP ANY HELP PLEASE?

A: Your regex in the rule is wrong — you are missing /page, adding an optional final slash that you shouldn't be, and forgetting to remove the .html part. Also your RewriteBase shouldn't have a final slash and your rule shouldn't have a leading slash.
It total, it should be this:
RewriteEngine on
RewriteBase /web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^page/([^/]+)\.html$ page.php?c=$1 [L]

A: Add the following to the .htaccess file in the web directory of your site, replacing the rules you have above.
RewriteEngine On
RewriteBase /web/

#do not process css/js etc
RewriteCond %{REQUEST_URI} \.(css|js|jpg|png) [NC]
#alternatively you could skip all existing files. Comment previous line and uncomment next to do so
#RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

#redirect www.mysite.com/web/page.php?c=categoryname to
#www.mysite.com/web/page/categoryname.html
#prevent internal redirect
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteCond %{QUERY_STRING} (^|&)c=([^&]+)(&|$) [NC]
RewriteRule ^(page)\.php$ $1/%2.html? [NC,L,R=301]

#rewrite www.mysite.com/web/page/categoryname.html to
#www.mysite.com/web/page.php?c=categoryname
RewriteRule ^(page)/([-a-zA-Z0-9]+)\.html$ $1.php?c=$2 [L,NC]


text:
Q: PHP-5.3.16 Apache crash on image upload / resize I am using simple image upload / resize function. Once image is uploaded Apache shows "Send Error Report" / "Don't Send" Alert.
Uploaded images are .jpeg and apache crashes on imagecreatefromjpeg line.
I am using : PHP-5.3.16
Upload Works with : PHP-5.2.17 version, but I have to use higher version because of code features.
Does anyone know how to fix this error, or how to make it work with PHP-5.3.x?
P.S : I tried to use PHP-5.4.6 but it also shows this error.
Here is Apache Error Log :
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:43 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:43 2012] [warn] Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Fri Aug 31 22:36:43 2012] [notice] Apache/2.2.22 (Win32) mod_ssl/2.2.22 OpenSSL/0.9.8u configured -- resuming normal operations
[Fri Aug 31 22:36:43 2012] [notice] Server built: Mar 19 2012 19:56:33
[Fri Aug 31 22:36:43 2012] [notice] Parent: Created child process 728
[Fri Aug 31 22:36:43 2012] [notice] Disabled use of AcceptEx() WinSock2 API
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:44 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:44 2012] [warn] Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Fri Aug 31 22:36:45 2012] [warn] RSA server certificate CommonName (CN) `openserver' does NOT match server name!?
[Fri Aug 31 22:36:45 2012] [warn] Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Fri Aug 31 22:36:46 2012] [notice] Child 728: Child process is running
[Fri Aug 31 22:36:46 2012] [notice] Child 728: Acquired the start mutex.
[Fri Aug 31 22:36:46 2012] [notice] Child 728: Starting 32 worker threads.
[Fri Aug 31 22:36:46 2012] [notice] Child 728: Listening on port 443.
[Fri Aug 31 22:36:46 2012] [notice] Child 728: Listening on port 80.


text:
Q: Magento call jquery-ui progressbar after prototype ajax request successfull I have done ajax add to cart product from product page, I am able to update the top cart contents successfully on Prototype ajax request success, but when I try to initialize the jquery progressbar(which is already included in top cart) from the success event of the prototype ajax request, then it doesn't work at all.
Progress bar works fine if I do a page reload (document ready).
Below is my code.
function updatetopcart() {
    var ajxformurl = $('ajaxTLUrl').getValue();
    new Ajax.Request(ajxformurl, {
    onSuccess: function(response) {
        var transport = response.responseText.evalJSON(true);
        var toplinkcontent = transport.content;
        //alert(toplinkcontent);
        $$('#minicart').invoke('replace', toplinkcontent);
        //Reset top cart hover flap
        resetFlaps();
        //Reset free delivery progress bar
        resetFDBar();
        return true;
    },
    onException: function(request,e){
        //console.log(e.message);
        alert(e.message);
    }
    });
}
function resetFlaps() {
    $('minicart').observe('mouseover', function(e) {
        $('minicart-panel').setStyle({backgroundColor: '#FFFFFF'});
        $('minicart-panel').show();
    });
    $('minicart').observe('mouseout', function(e) {
        $('minicart-panel').hide();
    });

    $('minicart_mobile').observe('mouseover', function(e) {
        $('minicart-panel_mobile').setStyle({backgroundColor: '#FFFFFF'});
        $('minicart-panel_mobile').show();
    });
    $('minicart_mobile').observe('mouseout', function(e) {
        $('minicart-panel_mobile').hide();
    });
    return true;
}

function resetFDBar() {
    (function($) {
        jQuery("#free_delivery").progressbar({
            max: Number(jQuery('#maxPriceVal').val()),
            value: Number(jQuery('#currPriceVal').val())
        });
    })(jQuery);
    return true;
}


text:
Q: Error with Amazon S3 for WordPress I am using a great Wordpress to store files on Amazon S3 called "Amazon S3 for WordPress" it seems to have a bug with version 3.0+ of Wordpress.
The error I am getting is:

Warning: strpos() expects parameter 1
  to be string, array given in
  /home/dir/public_html/www.site.com/wp-admin/includes/media.php
  on line 310

Here is the code in media.php around line 310:

wp_enqueue_style( 'global' );
wp_enqueue_style( 'wp-admin' );
wp_enqueue_style( 'colors' );
// Check callback name for 'media'
if ( ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) ) || 0 === strpos( $content_func, 'media' ) )
    wp_enqueue_style( 'media' );
wp_enqueue_style( 'ie' );

I would love some clue as to what is going on.
Thanks

A: Actually, I think you've found a bug in WordPress. The line of code that's throwing the error is this:
if ( ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) ) || 0 === strpos( $content_func, 'media' ) )

If you look at that, the second scenario assumes $content_func is a string and passes it through strpos
Maybe something like
if ( ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) ) || ( is_string( $content_func ) && 0 === strpos( (string)$content_func, 'media' ) ) )

Would work better.


text:
Q: Execute PowerShell on Azure VM from TFS via AzureRM I have a number of VMs provisioned in my Azure subscription, protected by an NSG, so I don't have WinRM available remotely.
I'd like to execute a PowerShell script on these VMs as part of my TFS release definition.
Is there any way to execute arbitrary PowerShell scripts on Azure VM resources?
I'm aware of the Custom Script extension for Azure VM resources, but I don't know if this is what I'm after, or if it plays nicely with TFS.

A: Custom Script Extension would work fine for running scripts on the VM - but it would have to be done as part of "adding" the extension.  Meaning you'd have to deploy the extension to the VM to trigger running the script.  So you'd do it when the VM is provisioned or submit another deployment to run the script after it's provision.
Either is doable from TFS/VSTS...


text:
Q: Null value passed with select2 field type My Product model has a code foreign key which points to a Code model, which also has a code coulmn but as a primary key. In the Create view of Product's CRUD, I created a dropdown field that allows me to choose from all the already existing Codes using the Select2 field type.
[
    'label'     => 'Code',
    'type'      => 'select2',
    'name'      => 'code',             // the foreign key
    'entity'    => 'productCode',      // the relationship's method
    'model'     => 'App\Models\Code',
    'attribute' => 'code',             // attribute that is shown in the dropdown
]

The codes are shown correctly in the dropdown, but when I save the new product the code field is stored in the request as a null value. Anyone knows what the issue could be? Or if I'm getting some of this wrong?
This is the relationship in the Product model:
public function productCode() {
    return $this->belongsTo('App\Models\Code', 'code', 'code');
}

A: A primaryKey property is required on a model when your primary key is not the typical "id" column, and keyType property is required  if that primary key is not an integer column:
Adding the below to your App\Models\Code model should fix the problem:
/**
 * The primary key for the model.
 *
 * @var  string
 */
 protected $primaryKey = 'code';

/**
 * The "type" of the primary key
 *
 * @var  string
 */
protected $keyType = 'string';


text:
Q: Does a sequence of pairwise disjoint event converge to the empy set, $\emptyset$? Let $(A_n)$ be any sequence of pairwise disjoint events, is
$$
\lim_{n \to \infty} A_n = \emptyset.
$$
always true?
Conceptually I would say yes, since if we partition $\Omega$ an infinite amount of times, I guess that the events would get smaller and smaller.

A: One can say that a sequence of sets $(A_n)_{n\geqslant 1}$ converges to $A$ if
$\limsup_{n\to\infty}A_n=\liminf_{n\to\infty}A_n=A$, where
$$
\limsup_{n\to\infty}A_n=\bigcap_{N\geqslant 1}\bigcup_{n\geqslant N}A_n
$$
and $$
\liminf_{n\to\infty}A_n=\bigcup_{N\geqslant 1}\bigcap_{n\geqslant N}A_n.
$$
One can show that $\omega$ belongs to $\limsup_{n\to\infty}A_n$ if and only if the set $\{n\in\mathbb N, \omega\in A_n\}$ is infinite and that $\omega$ belongs to $\liminf_{n\to\infty}A_n$ if and only if there exists an integer $N$ such that $\omega\in A_n$ for all $n\geqslant N$.
The inclusion $\liminf_{n\to\infty}A_n\subset \limsup_{n\to\infty}A_n$ always hold. In the particular case where $(A_n)_{n\geqslant 1}$ is pairwise disjoint, $\limsup_{n\to\infty}A_n$ is empty, because no $\omega$ belongs to more than one $A_n$.


text: Q: Is there a way to force a request to cache in Google Chrome devtools? I'm developing a ui for a call that takes a long time to respond. Is there any way to have Chrome return the last result without actually creating and waiting for the request?


text:
Q: Bypass spring security with java URL connection I am using Spring MVC in my project and while mapping user request to a URI, I was unable to bypass it. I get the 403 error as the url is intercepted. But i was able to access it through browser.
Updated

I removed the interception in security.xml and when i try to hit i get the following error.
Request method 'POST' not supported

http://49.205.88.200:5080/Batasariservice/groupview.htm
username :  userx@bat
password :  123456

Updated:
My Rest Controller:
 @RestController
public class AuthenticateDeviceRestWS {

    @Autowired
    ManageDeviceWSBusiness manageDeviceWSBusiness;

    @RequestMapping(value = "authAndRegDevice.htm", method = RequestMethod.POST)
    public @ResponseBody String authenticateAndRegisterDevice(
            @RequestBody String notificationJsonRequest)
            throws BatasariWSException {
        WSDeviceAuthenticateRequest wsDeviceAuthenticateRequest = (WSDeviceAuthenticateRequest) UserAccessManagementUtil
                .convertToJava(notificationJsonRequest,
                        WSDeviceAuthenticateRequest.class);

        WSDeviceAuthenticateResponse wsDeviceAuthenticateResponse = manageDeviceWSBusiness
                .authAndRegisterDevice(wsDeviceAuthenticateRequest);

        return UserAccessManagementUtil
                .convertToJson(wsDeviceAuthenticateResponse);
    }

}

Updated
Java Main class i.e., tested with
public class AuthURLConnection {
static String URL = "http://localhost:5080/Batasariservice/authAndRegDevice.htm";

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String json = "{ " + "\"deviceID\":\"Test\", "
            + "\"deviceName\":\"Test Device\",  "
            + "\"phoneNumber\":\"testnumber\",   "
            + "\"companyIdentifier\":\"bat\",   "
            + "\"userIdentifier\":\"Test\",   " + "\"addtionalInfo\":\"\""
            + "}";
    wsRequest(json);

}

private static void wsRequest(String jsonInput) {

    try {

        URL targetUrl = new URL(URL);
        HttpURLConnection httpConnection = (HttpURLConnection) targetUrl
                .openConnection();

        httpConnection.setDoOutput(true);
        httpConnection.setRequestMethod("POST");
        httpConnection.setRequestProperty("Content-Type",
                "application/json");

        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(jsonInput.getBytes());
        outputStream.flush();

        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + httpConnection.getResponseCode() + ":"
                    + httpConnection.getResponseMessage());
        }

        BufferedReader responseBuffer = new BufferedReader(
                new InputStreamReader(httpConnection.getInputStream()));

        String output;
        StringBuffer sb = new StringBuffer();
        while ((output = responseBuffer.readLine()) != null) {
            sb.append(output);
        }

        httpConnection.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

}
Updated
my spring-security.xml file
<http auto-config="true" use-expressions="true">
        <intercept-url pattern="/userLogin*" access="permitAll" />
        <intercept-url pattern="/authAndRegDevice.htm" access="permitAll" />
        <intercept-url pattern="/css/**" access="permitAll" />
        <intercept-url pattern="/**" access="hasRole('DefaultRole')" />

        <!-- access denied page -->
        <access-denied-handler error-page="/403" />

        <form-login login-page="/userLogin.htm" default-target-url="/groupview.htm"
            authentication-failure-url="/userLogin.htm?error" username-parameter="username"
            password-parameter="password" authentication-success-handler-ref="authSuccessHandler" />

        <csrf />
    </http>

    <beans:bean id="authSuccessHandler"
        class="com.pathfinder.filter.AuthenticationSuccessHandlerImpl" />
    <beans:bean id="encoder"
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

        <authentication-manager>
            <authentication-provider>
                <password-encoder ref="encoder" />
                <jdbc-user-service data-source-ref="dataSource"
                    users-by-username-query="select username,password, status from users where username=?"
                    authorities-by-username-query="select username, 'DefaultRole' as role from userrolesview where username =?  " />
            </authentication-provider>
        </authentication-manager>


text:
Q: ESXi - Forward port to virtual machine? For example, i have a ESXi Host with a router vm and a intern network.
Could i use the host ip for other things except ESXi?
I mean: On a virtual machine is a webserver (port 80).
Could i route the port 80 from esxi host to the Virtual Machine Port 80?
Image:
http://www.abload.de/image.php?img=esxinhxgi.jpg

A: I needed a second ip adress. Then i created a router vm in a subnetwork and then i could give different machines different ports...


text:
Q: On class update, SVG image as background in CSS does not appear in IE11 Problem:
On page load, for a button, SVG which is being called in CSS background appears. On some event, I apply a class and to it call another SVG in CSS background. However that new SVG does not appear. If in debugger, I try to toggle the background, it then starts appearing.
What am I missing to get this working in IE11?
In Below picture, we are using <button> tag. On some event, the background SVG is changed.
CSS Code
.buttonIcons{
 .svgicon-fields-add{ background-image:url('../assets/themes/svg/arrow_active.svg');
 width: 16px;
 height: 16px;
}

On disabled state, below is the CSS
.buttonIcons.disabled{
 .svgicon-fields-add{ background-image:url('../assets/themes/svg/arrow_disabled.svg');
  width: 16px;
  height: 16px;
}

So initially all buttons are disabled, but if you see the first button needs to show active svg image, but it is not appearing. I can see it in IE11 console, and if in console, I toggle the property, it starts appearing.
The code works fine in Chrome
Thanks in advance for all the suggestions.

SVG file code
<?xml version="1.0" encoding="utf-8"?>
<svg width="16" height="16" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 16 16" enable-background="new 0 0 16 16" xml:space="preserve">
<g>
    <polygon fill="#00a6a0" points="7.6,1.6 6.7,2.4 12.3,8 6.7,13.6 7.6,14.4 14,8   "/>
    <polygon fill="#00a6a0" points="2.6,1.6 1.7,2.4 7.3,8 1.7,13.6 2.6,14.4 9,8     "/>
</g>
</svg>

A: Based on the small number of views, this is an esoteric case, but I'm having the same problem. I've been on it for days. I also had a double problem where IE would not display the background on toggling the style in developer tools.
I thought it was initially a memory issue, where IE was allocating memory for the icon but not actually putting anything there.
So I applied the SVG as an xml-encoded string directly in the class itself. This solved one instance of an SVG background not appearing, but it didn't solve the problem mentioned here. Furthermore, this allowed me to see the toggle event you mentioned.
So I now believe that it is NOT a memory issue, but an issue with IE10/11's SVG rendering engine. The fact that this problem only happens with certain SVG's reinforces the idea that the IE rendering engine is crapping the bed with certain inputs. It also only happens when a CSS SVG background is being overridden by another class's SVG background.
I thus tried setting the object to display:none, then display:block in the hopes of forcing a re-render of the element. This didn't help. I destroyed the element then rebuilt it and appended it back where it was supposed to go. That didn't work.
To make things even more confusing, I was never able to replicate the problem locally. It would only ever manifest in certain environments, leading me to believe that it is a combination of the browser and some server settings. I have no idea what.
Regardless, the point is that IE is remarkably resilient it not re-rendering what it has rendered. And since the SVG engine is apparently separate from the DOM rendering engine, screwing around with the DOM will have no effect on what the SVG renderer has stored. You have to give it quantifiably different data to force the SVG engine to re-render.
The only solution I found was to have my two CSS classes then give IE different image data than what it found on page load.
.Class1 {
   background-image: url("data:image/svg+xml,image-data...");
}
.Class2 {
   background-image: url("data:image/svg+xml,image-data...");
}

These classes allow default page load states to be covered. Then when JS events change the appearance, instead of changing the class, assign an in-line CSS style with the XML-ified SVG image data with a slight difference. Anything will work. I used an extra space.
onclick="function(){
   element.style.backgroundImage = "url(\"data:image/svg+xml,slightly-different-data...\")"
}

To reiterate, it is an SVG rendering problem that occurs on page load. You can force SVG to re-render the image by giving it slightly different data in-line. I would imagine that you could do the same thing with a third class that contains a reference to a slightly different SVG file from the initial one, but I didn't do this.

A: Make sure the SVG file has the width and height property.
And if there's a 'responsive' option in it, you should remove it.
The option resets the CSS width and height.


text:
Q: Could you identify the mistake here? This program is supposed to show the different types of characters in a string entered by the user but for some unknown reason it doesn't show the number of vowels in a string even when there are a bunch of them in it. If someone could identify the mistake it would be great!
str=input("Enter a string: ")
upper   = 0
lower   = 0
num     = 0
vowel   = 0
special = 0
for i in range(len(str)):
  if(str[i].isupper()):
     upper+=1
  elif(str[i].islower()):
     lower+=1
  elif(str[i].isdigit()):
      num+=1
  elif(str[i] == "a"or"e"or"i"or"o"or"u"or"A"or"E"or"I"or"O"or"U"):
      vowel = vowel+1
  else:
      special+=1
print("Upper Case Letters: ",upper)
print("lower case letters: ",lower)
print("Numbers: ",num)
print("Vowels: ",vowel)
print("Special Characters: ",special)

A: First you need to replace all elif's with if's, then:
Replace
elif(str[i] == "a"or"e"or"i"or"o"or"u"or"A"or"E"or"I"or"O"or"U"):

with:
if (str[i] in ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]):

A: Its because there is no space between the "or" and the next string, in python a r"" is considered a 'raw string'.


text:
Q: Adding users to Exchange admin role groups via API? Is it possible to add users/members to Exchange admin role groups via an API? The equivalent PowerShell cmdlet would be Add-RoleGroupMember and the specific group I wish to add to is View-only Organization Management.
Microsoft Graph has an endpoint to add to directory roles, however I can't seem to find a "View-only Organization Management" group listed in my tenant's DirectoryRoles or DirectoryRoleTemplates, so I suspect MS Graph hasn't got access to these Exchange role groups. Poking around the Outlook API has not revealed much in the form of user/member functions either.
Extra info added from further poking around
I ran this PowerShell cmdlet:

Add-RoleGroupMember
  -identity "View-only Organization Management"
  -member "user@domain.onmicrosoft.com"

Then ran:

Get-RoleGroupMember -identity "View-Only Organization Management"

To confirm that the user was in fact added to it. I then ran the following MS Graph call:

GET https://graph.microsoft.com/v1.0/users/user@domain.onmicrosoft.com/memberOf

And it returned zip:
{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects",
  "value": []
}

So it looks like this particular View-only Organization Management roleGroup is not accessible via MS Graph? Are there any other APIs that would allow me to add to this roleGroup?

A: So https://graph.microsoft.com/v1.0/directoryRoleTemplates lists the available out-of-the-box "Directory" roles that you can set.  I put Directory in quotes, because these roles do include Exchange, SharePoint and Skype service admins (as well as other roles).  The thing to note here is that only the "implicit" user role and the Company Administrator role are available from the get go.  The others need to be enabled/activated if you want them to show up and use them.  This is described here: https://graph.microsoft.io/en-us/docs/api-reference/v1.0/resources/directoryrole.
Once you've activated the "Exchange Service Admin" role, you should be able to assign users to this role using https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/directoryrole_post_members.
If you are looking to use Azure AD PowerShell, this capability is ALSO available. You can find info here for V2 Azure AD PowerShell https://learn.microsoft.com/en-us/powershell/azuread/v2/azureactivedirectory. In the search type "DirectoryRole" and you'll find all the DirectoryRole cmdlets.


text:
Q: Creating a directory in custom command after Monodevelop builds the project in Windows XP I'm developing a project using Monodevelop 4 in Windows XP and I need to copy some of the .dll library files into some folder after they are built. These libraries are plugins to a main project and so the main project is not depended on them and they need to be copied manually.
But as we are using computers nothing needs to actually be done manually, and so I turned to Monodevelop's Custom Commands in project settings. There I can type in any command I like (supposedly).
So here's what I did; First I added a command to make sure the destination folder exists:
mkdir "${SolutionDir}\MainProj\bin\${ProjectConfigName}\Plugins"

And then copied the library:
xcopy "${TargetFile}" "${SolutionDir}\MainProj\bin\${ProjectConfigName}\Plugins" /Y

But the thing is that the first command fails and so the second one never executes. To see the results of the first command I checked both of checkboxes named Run on external console and Pause console ouput and here's its output:
'"mkdir"' is not recognized as an internal or external command,
operable program or batch file.
Press any key to continue . . .

In IDE's output panel I can read mkdir "C:\Some\Path\MainProj\bin\Debug\Plugins" which is correct and when I paste it into a console creates the folder successfully so I have no idea why Monodevelop is unable to execute it!
Does anyone have any comment on this problem?

A: I found a solution myself. I created a batch file with mkdir command in it and called it in the project's Custom Commands.

A: I was able to resolve this in Xamarin Studio (ver 4.2.5) by using xcopy instead of copy and providing the full path to xcopy.exe:
"%systemroot%\system32\xcopy.EXE" /y "${ProjectDir}\myAppSettings.config" "${TargetDir}"

After some experimentation, it appears that Xamarin Studio/MonoDevelop:

*

*Wraps the entire custom command in double-quotes, and

*Includes logic to try to deal with you "improperly" including additional double-quotes. (I tried an injection technique to undo the quotation.)

This has the side effect of rendering internal shell commands unexecutable - because copy becomes "copy", which isn't a valid command. And it explains why moving everything to a batch file also resolves the issue - there is now a physical file (which a physical path) to execute.


text:
Q: How to find new client? I ran into one problem that I can not solve for 3 days already.
The problem is current, there is a database of two columns of date ("yyyy-mm") and the phone number is unique non-repeating. I want to find out how many new customers each month. Well, the formula is roughly current (the new client is the first month + the new client is the next month ....). If the customer meets the first month he is considered a new customer, then it is on the other month, he is missing a new customer.

A: try Something like this:
select year(f2.DateColumn) YearCol,  month(f2.DateColumn) MonthCol, count(f2.PhoneNumber) NbNewPhone
from (
        Select f1.*,  row_number() over(partition by f1.PhoneNumber order by f1.DateColumn) rang
        from yourTable f1
) f2
where f2.rang=1
group by year(f2.DateColumn),  month(f2.DateColumn)
order by 1, 2

or if you column is not a date :
select f2.DateColumn, count(f2.PhoneNumber) NbNewPhone
from (
        Select f1.*,  row_number() over(partition by f1.PhoneNumber order by f1.DateColumn) rang
        from yourTable f1
) f2
where f2.rang=1
group by f2.DateColumn
order by 1, 2

A: As per your example just below count is sufficient:
Select DateColumn, Count(PhoneNumber) from yourTable
    Group by DateColumn

If Datecolumn is real date as yyyy-mm-dd with date datatype you can query as below:
Select year(datecolumn), month(datecolumn), count(PhoneNumber) from yourTable
   group by year(datecolumn), month(datecolumn)