text:
Q: Error while copying records from table1 to table 2. sqlite constraint exception error code 19 constraint failed I'm copying  all the records (back up) from table1 to table2 in the same database. This is my first database application.
Here is the table 1 structure :
private static final String CREATE_SELECTED_CAND_TABLE = " CREATE TABLE if not exists "
        + TABLE_SELECTED_CAND
        + "("
        + KEY_ID
        + " integer PRIMARY KEY autoincrement,"
        + KEY_NAME1
        + " TEXT,"
        + KEY_NAME2
        + " TEXT,"
        + KEY_NAME3
        + " TEXT,"
        + KEY_NAME4
        + " TEXT," + KEY_NAME5 + " TEXT" + ")";

Table2 Structure :
private static final String CREATE_SELECTED_CAND_RECOUNT1 = " CREATE TABLE if not exists "
        + TABLE_RECOUNT1
        + "("
        + KEY_ID
        + " integer PRIMARY KEY autoincrement,"
        + KEY_NAME1
        + " TEXT,"
        + KEY_NAME2
        + " TEXT,"
        + KEY_NAME3
        + " TEXT,"
        + KEY_NAME4
        + " TEXT," + KEY_NAME5 + " TEXT" + ")";

and I am copying like this :
    mDb.execSQL(" INSERT INTO " + TABLE_RECOUNT1 + " SELECT * FROM "
            + TABLE_SELECTED_CAND);

Now the problem is, It is copying only if all the columns are not null  I have some columns as null, but I want to copy them also. How do I achieve this.?  Any help would be highly appreciable..!
These are the stack traces :

E/AndroidRuntime(30294):
     android.database.sqlite.SQLiteConstraintException: error code 19:
     constraint failed
  E/AndroidRuntime(30294):    at  android.database.sqlite.SQLiteStatement.native_execute(Native Method)
  E/AndroidRuntime(30294):    at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:92)
  E/AndroidRuntime(30294):    at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:2028)
  E/AndroidRuntime(30294):    at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1968)
  E/AndroidRuntime(30294):    at com.dana.db.SelectedCandidatesDB.copyToRecount1(SelectedCandidatesDB.java:257)
  E/AndroidRuntime(30294):    at com.dana.votecount.VoteRecount.fetchAllFromRecount1(VoteRecount.java:161)   E/AndroidRuntime(30294):     at com.dana.votecount.VoteRecount.access$1(VoteRecount.java:158)
  E/AndroidRuntime(30294):    at com.dana.votecount.VoteRecount$2$1.onClick(VoteRecount.java:107)

A: the error is due to the autoincrement because you can not or assign give value to column which is autoincrement you should assign null or change in the query
mDb.execSQL(" INSERT INTO " + TABLE_RECOUNT1 + " SELECT * FROM "
            + TABLE_SELECTED_CAND);
replce * with column names not mention autoincrement column name and also for table1 in the same query

A: It is actually possible to set autoincrement columns to a specific value, but only if that value does not yet exist.
It is likely that the records already exist in the RECOUNT1 table.
To ensure that there are no old records, delete them before inserting:
mDb.execSQL("DELETE FROM " + TABLE_RECOUNT1);
mDb.execSQL("INSERT INTO " + TABLE_RECOUNT1 + " SELECT ...");

Alternatively, if you know that none of the records have changed, you can use the INSERT OR IGNORE command to insert only those records whose IDs do not yet exist in the target table:
mDb.execSQL("INSERT OR IGNORE INTO " + TABLE_RECOUNT1 + " SELECT ...");


text:
Q: Error: Invalid Token for push notifications to App loaded through iTunes When I load the APP using Xcode, push notifications work nicely, if I load it on the device using iTunes, push notifications do not work: I always receive a "[1] Invalid token" error when trying to sent a push notification to the device from backend.
I noticed the pushId app receives in the two cases (loaded through Xcode/loaded though iTunes) are different.
Perhaps when loading the app through iTunes it automatically receives a production pushId? If this is the case, is it possible to load the app through iTunes so that is has a development pushId?

A: Possibly resolved: XCode 6 contains a bug, exporting the .ipa file with the incorrect provisioning profile, so the pushId generated is invalid.
How to export with the correct provisioning profile is described here:
Xcode 6 - How to pick signing certificate/provisioning profile for Ad-Hoc distribution?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift macOS how to print with NSPrintInfo and NSAttributedString I want to print out a list in my App.
However if the list is too large to fit on one page there is a problem with
the last and the first line on a page.
e.g. the last line on a page is cropped and some parts are shown on top of next page.

Screenshot of bottom of page 1

Screenshot of top of page 2
How can I manage to set up my print job that the text is set up correctly on every page?
Currently I have the following code snippet:
   func makePDF(markup: String, amount: Int) {
    let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let printOpts: [NSPrintInfo.AttributeKey: Any] = [NSPrintInfo.AttributeKey.jobDisposition: NSPrintInfo.JobDisposition.save, NSPrintInfo.AttributeKey.jobSavingURL: directoryURL]
    let printInfo = NSPrintInfo(dictionary: printOpts)
    printInfo.horizontalPagination = NSPrintInfo.PaginationMode.autoPagination
    printInfo.verticalPagination = NSPrintInfo.PaginationMode.autoPagination
    printInfo.topMargin = 20.0
    printInfo.leftMargin = 20.0
    printInfo.rightMargin = 20.0
    printInfo.bottomMargin = 20.0

    let view = NSView(frame: NSRect(x: 0, y: 0, width: 560, height: (60 + 36 * amount)))

    if let htmlData = markup.data(using: String.Encoding.utf8) {
        let attrStr = NSAttributedString(html: htmlData, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:
            String.Encoding.utf8.rawValue], documentAttributes: nil)

        let frameRect = NSRect(x: 0, y: 0, width: 560, height: (60 + 36 * amount))
        let textField = NSTextField(frame: frameRect)
        textField.attributedStringValue = attrStr!
        view.addSubview(textField)

        let printOperation = NSPrintOperation(view: view, printInfo: printInfo)
        printOperation.showsPrintPanel = true
        printOperation.showsProgressPanel = true
        printOperation.run()

    }
}


text:
Q: Loop through lines in text file, search for delimiter and add to associative array I have some text as such:
     $string = "———version1———
                item1-result1
                item2-result2
                item3-result3
                ———version2———
                Item1-result4
                Item2-result5
                Item3-result6
                ———version3———
                Item1-result7
                Item2-result8
                Item3-result9"

I need to loop through the lines and explode the lines that contain the hyphen delimiter (-) and add to an associative array but group by version, so the values would map to each other like so:
The desired result I need is something like:
   array = [
    Version1_item1 => result1,
    Version1_item2=>result2
    …
    …
    Version2_item1=>result4
    etc
    ]

I could use explode, and the add the item values to one array and the results to another and then use array_combine but I can't seem to get the code right.
 $final_result = array();
foreach (explode('\n', $string) as $piece) {
    $result = array();
    $result[] = explode('-', $piece);

Can anyone help?

A: The main issue is that you are using '\n' but, into single quotes, it doesn't represent a newline. You should use "\n", into double quotes.
You should use trim() to remove extra spaces before and after the text on each line.
Finally, you are appending to $result the array of your explode, instead of assign to it:
$string = "This is the text file
        item1-result1
        item2-result2
        item3-result3
        End of text file";

$final_result = array();
foreach (explode("\n", $string) as $piece) {
    $piece = trim($piece);
    $result = explode('-', $piece);
    if (count($result) == 2) {
        $final_result[ $result[0] ] = $result[1];
    }
}
print_r($final_result);

Outputs:
Array
(
    [item1] => result1
    [item2] => result2
    [item3] => result3
)

EDIT
$string = "———version1———
           item1-result1
           item2-result2
           item3-result3
           ———version2———
           Item1-result4
           Item2-result5
           Item3-result6
           ———version3———
           Item1-result7
           Item2-result8
           Item3-result9";

$final_result = array();
$current_version = '';
foreach (explode("\n", $string) as $piece) {
    $piece = trim($piece);
    if (strpos($piece, '———') === 0) $current_version = trim($piece,'—');
    $result = explode('-', $piece);
    if (count($result) == 2) {
        $final_result[ $current_version . '_' . $result[0] ] = $result[1];
    }
}
print_r($final_result);

Outputs:
Array
(
    [version1_item1] => result1
    [version1_item2] => result2
    [version1_item3] => result3
    [version2_Item1] => result4
    [version2_Item2] => result5
    [version2_Item3] => result6
    [version3_Item1] => result7
    [version3_Item2] => result8
    [version3_Item3] => result9
)

A: Your approach is right, so just modified newline which is in single qoutes. Also remember the best practice for newline is to use the PHP constant PHP_EOL which represents the current system's EOL (End Of Line).
foreach (explode(PHP_EOL, $string) as $piece) {

}


text:
Q: How to get the response of bounced mail when working with google mail smtp (smtp.googlemail.com) I am working on making newsletters. I have bulk of 1200 emails but it's not verified. I am using google mail smtp for verification in codeigniter framework. Mail is properly sending but when I tested it for wrong email then also it shows send mail status. I want to ask that how to get the response of bounced mail when working with google mail smtp.
$check is containing array of emails :
 $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => '465',
            'smtp_user' => 'mymail@gmail.com',
            'smtp_pass' => 'mypass',
            'mailtype'  => 'html',
            'charset'   => 'iso-8859-1',
            'send_multipart' => FALSE
        );
        $this->email->initialize($config);
        $this->load->library('email', $config);

        foreach($_POST['chk'] as $check)
        {
                    $this->email->clear();
                    $data = array(
                     'userName'=> 'Myname'
                         );
                   $this->email->set_newline("\r\n");
                   $this->load->library('email',$config);

                   $this->email->from("mymail@gmail.com","Myname");

                    //echo $row->email;
                    $this->email->to($check);
                    $this->email->subject("THIS IS AN EMAIL TEST");
                    $gett = $this->load->view('home_test.php',$data,TRUE);
                    $this->email->message($gett);
                    $this->email->set_mailtype("html");
                    if($this->email->send())
                    {
                        echo "Your Mail send";
                    }
                    else
                    {
                        show_error($this->email->print_debugger());
                        exit();
                    }
        }

Its always showing Your Mail send although if I provide fake email id. How to track this bounced mail in PHP.

A: You will not get status of the bounced emails immediately after sent. What you can do is, specify return path email as third parameter of $this->email->from("mymail@gmail.com","Myname");.
Change this line
$this->email->from("mymail@gmail.com","Myname");
to
$this->email->from("mymail@gmail.com","Myname", 'yourreturnemail@gmail.com');
For more details see codigniter's email documentation here
This way all bounced emails will come to the return path email address. Then you can create a cron or something to read and parse this emails.  php's imap extension can be installed and use for read email bounced status.


text:
Q: Accessing a file dialog inside an iframe I have an inline jsp page which has the code for the  html type: file. The below displayed IFRAME tag is in the main jsp. I want to pass on the file name and submit this file dialog using the web driver. Basically want to do something like:
WebElement elem = driver.findElement(By.id("attachmentfile"));
elem.sendKeys("C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg");

However, am not able to get a hold of the attachmentfile id. Any help would be appreciated. Thanks.
Main Jsp:

</FORM>

The fileupload.jsp is as below:

    <form name="frm_fileUpload" ENCTYPE="multipart/form-data"><%

        <input type="file" name="attachmentfile"
        id="attachmentfile" onChange="uploadFile   ();" />
        <input type="button" name="uploadbutton" id="uploadbutton"
        value="Upload" class="button" />

   </form>


text:
Q: Please explain JSONP in jQuery I can't understand the doc of the jQuery.ajax, specifically two options: jsonp and jsonpCallback, so can somebody be so pleasant to explain?
What I do understand is that jsonp is a name of a GET parameter which server expects (usually 'callback') and jsonpCallback is a name of a function to wrap a response. Seems simple.
But the explanation at the jQuery.ajax doc makes this a bit complicated. I would like to cite the complete text for jsonp option here and mark with bold what is obscure to me:

jsonp
Override the callback function name in a jsonp request. This value
  will be used instead of 'callback' in the 'callback=?' part of the
  query string in the url. So {jsonp:'onJSONPLoad'} would result in
  'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
  jsonp option to false prevents jQuery from adding the "?callback"
  string to the URL or attempting to use "=?" for transformation. In
  this case, you should also explicitly set the jsonpCallback setting.
  For example, { jsonp: false, jsonpCallback: "callbackName" }

So the questions are:
1.What does it mean "=?" or 'callback=?' (extra question mark)? When I perform a JSONP AJAX-request like here:
 $.ajax('http://fake.com',{
     dataType: 'jsonp',
     success: function(data) {console.log(data);}
 });

The URL looks like this, there is no such question mark:
http://fake.com/?callback=jQuery18104830878316494931_1352981996209&_=1352981999411

2.What is the extra parameter (underscore) _=1352981999411?
3.What do the words In this case, you should also explicitly set the jsonpCallback setting mean? I can't see any interrelationship. If I set { jsonp: false, jsonpCallback: "callbackName" }, as it is said in the doc the query will look like this:
http://fake.com/?_=1352981999411

There is no use of the "callbackName" at all so why to specify it?
My appreciation.

A: The callback name is optional, if you don't supply one it uses a default one. Hence, if you leave out onJsonLoad you just get callback.
What happens is the JSON is wrapped with a function, because JSONP works through the <script> tag, so your normal JSON:
{prop: value}

Becomes:
callback({prop: value});

When the script tag is loaded jQuery can then call this function and get back the JSON data.
The _=123456788 is just a Date.getTime() to stop the request from caching.

A: The idea behind JSONP is the following:
Because of the Cross domain policy, it is not allowed to request data for an external source. Let's say my server has a function that return the name of a person if you enter his phone number.
YOUR website, which is not on my domain, is not allowed to perform an ajax call to my server and receive the data Flater.
There is one exception to this rule, and that is with using scripts that are externally loaded. I can load a jQuery.js file hosted on another server etc. I cannot request data from an external server, but I can request javascript.
So it would impossible for you to receive this result:
Flater

But it is possible to put this on your page:
<script src="http://externalserver.com/script.js">

and you will receive regular javascript, e.g.
<script>
    function doSomething(value) {
        alert(value);
    }

    doSomething("First");
    doSomething("Second");
</script>

Which means (and here's the important part) that you could also receive the following javascript:
<script>
    doSomething("Flater");
</script>

Suppose you already defined a function doSomething() on your page. This would be perfactly valid javascript because it calls an existing function, event though the server where this snippet originated (http://externalserver.com/script.js) has no clue what happens in the function doSomething.
So technically, you were able to retrieve the data you wanted in the beginning (i used a string as example but JSON would've been just as valid), and the javascript around it is merely used as window dressing (the 'padding').
Now what most JSONP enabled sites let you do is CHOOSE the name of the function. For example:
<script src="http://externalserver.com/script.js?callback=doSomething">
<script src="http://externalserver.com/script.js?callback=banana">
<script src="http://externalserver.com/script.js?callback=Process_Name">

would return
<script>
    doSomething("Flater");
</script>
<script>
    banana("Flater");
</script>
<script>
    Process_Name("Flater");
</script>

Wich means that if you've defined the function name you are using as the callback parameter, you can effectively tell the external server which function it needs to pass the JSON to.
Which is very handy if you have multiple functions that all need to work.
I hope I was able to clear up the intended use of JSONP? If you have questions, just ask :-)
UPDATE
By the way, I used script tags in the example. Like you already mentioned, jQuery has progressed to the point where it basically looks like an ajax call (as it should). However, I assumed it would be easier to explain to you the core principles at play.

A: callback=?
Jquery will autogenerate the callback name when it sees the ?
In some API's you need to provide a specific callback as outlined by the API.
In most cases server simply uses $_GET['callback'] using php as example. In your case it would send back
jQuery18104830878316494931_1352981996209( /* json string*/)

jQuery18104830878316494931_1352981996209 is the callback.
To better understand, inspect a jsonp request in browser console Net or Network tab. You can see the params that jQuery sends, and see the full response


text:
Q: Division rings arising from the endomorphism ring of a simple module I was reading about Schur's Lemma and I immediately asked myself: is every skew-field the endomorphism ring of some simple module?
The page on division rings on Wikipedia states the following:

In general, if R is a ring and S is a simple module over R, then, by
  Schur's lemma, the endomorphism ring of S is a division ring; every
  division ring arises in this fashion from some simple module.

How can the latter statement be proven?
Thank you

A: If $D$ is a division ring, then it is naturally an $\operatorname{End}_D(D)$-module where multiplication is given by evaluation:
$$\phi .d := \phi(d).$$
Every element $d \in D$ defines a map "left multiplication by $d$"
$$m_d: D \to D, x \mapsto dx$$
which commutes with all $\phi \in \operatorname{End}_D(D)$, i.e. $m_d$ is an endomorphism of $D$ as an $\operatorname{End}_D(D)$-module. Now it easy to show that
\begin{align*}
\alpha: D &\longrightarrow \operatorname{End}_{\operatorname{End}_D(D)}(D),\\
d &\longmapsto m_d
\end{align*}
is an isomorphism of rings (the inverse sends $\theta$ to $\theta(1)$). So $D$ is the endomorphism ring of some module. We just have to show that $D$ is simple as an $\operatorname{End}_D(D)$-module. This is where we use that $D$ is a division ring. Suppose $E \subseteq D$ is a non-trivial $\operatorname{End}_D(D)$-submodule of $D$, i.e. $\phi(E) \subseteq E$ for all $\phi \in \operatorname{End}_D(D)$. Pick an $0 \neq e \in E$. Then for every $d \in D$ right multiplication by $e^{-1}d$
$$D \to D, x \mapsto xe^{-1}d$$
is an $D$-endomorphism of $D$ and its image contains $d = ee^{-1}d$. So in fact $E =D$.

A: Let $D$ be a division ring and consider $D$ as a right module over itself. Now consider the endomorphism ring of this module. If $s$ is some endomorphism, then $s(1) = a = a1$ for some $a\in D$ so the map $x \mapsto s(x) - ax$ is a morphism with non-trivial kernel, and hence $0$. This means that $s$ is simply multiplication by $a$ from the left, and we get that the endomorphism ring of $D$ as a module over itself is isomorphic to $D$.


text:
Q: How to make this code more simple? I have a small problem with this code
if    3 <= y <  7: self.draw_y -= 2
elif  7 <= y < 13: self.draw_y -= 3
elif 13 <= y < 17: self.draw_y -= 4
elif 17 <= y < 23: self.draw_y -= 5
elif 23 <= y < 27: self.draw_y -= 6
elif 27 <= y < 33: self.draw_y -= 7
elif 33 <= y < 37: self.draw_y -= 8
elif 37 <= y < 43: self.draw_y -= 9
elif 43 <= y < 47: self.draw_y -= 10
....

Could you help me to make this code simpler?

A: Not efficient, but cleaner:
if y >= 3:
    self.draw_y -= 2
    delta = 6
    while y >= 7:
        self.draw_y -= 1
        y -= delta
        delta = 6 if delta == 4 else 4

A: Maybe something like this would help:
from bisect import bisect_right

def drawshift(x, l=[3,7,13,17,23,27,33,37,43,47]):
    return bisect_right(l, x) + 1

print(drawshift(2)) # 1
print(drawshift(3)) # 2
print(drawshift(4)) # 2
print(drawshift(7)) # 3
print(drawshift(43)) # 10
print(drawshift(47)) # 11

The documentation for the module I have used can be found here. It uses a bisection algorithm (basically, binary search) which has O(log n) lookup time.
The edge cases like x < 3 or x >= 47 can be handled pretty simply with conditional statements. For example note that bisect_right(x) where x is lower than all elements of the list will return 0 and that bisect_right(x) where x is greater than or equal to the highest element in the list will give you len(l) + 1.

A: Another solution to this problem, it uses simple arithmetic (division and modulo) and can be easily adapted for vectorization in case you're ever looking into that:
def range_selector(num):
    q, r = divmod(num - 3, 10)
    return 2*q + 2 + (r>=4)

Example, using numpy:
>>> import numpy as np
>>> y = np.array([3,6,7,13,14,47])
>>> range_selector(y)
array([ 2,  2,  3,  4,  4, 11])


text:
Q: could not configure a c compiler I am trying to compile some libraries using gcc 4.7 (which i just upgraded from 4.6.3, somehow it complain about c compiler:
/home/rtbkit/platform-deps/node/wscript:263: error: could not configure a c compiler!
make[1]: Entering directory `/home/rtbkit/platform-deps/node'
Project not configured (run 'waf configure' first)
make[1]: *** [program] Error 1
make[1]: Target `all' not remade because of errors.
make[1]: Leaving directory `/home/rtbkit/platform-deps/node'
make[1]: Entering directory `/home/rtbkit/platform-deps/node'
Project not configured (run 'waf configure' first)
make[1]: *** [program] Error 1
make[1]: Target `all' not remade because of errors.
make[1]: Leaving directory `/home/rtbkit/platform-deps/node'
make[1]: Entering directory `/home/rtbkit/platform-deps/node'
Project not configured (run 'waf configure' first)
make[1]: *** [program] Error 1
make[1]: Leaving directory `/home/rtbkit/platform-deps/node'

installing
make[1]: Entering directory `/home/rtbkit/platform-deps/node'
Project not configured (run 'waf configure' first)
make[1]: *** [install] Error 1
make[1]: Leaving directory `/home/rtbkit/platform-deps/node'
cp: target `/home/rtbkit/local/include/node' is not a directory
make: *** [install_node] Error 1

A: gcc-4.7 may not be set as the auto default.  Depending on your OS version you may need to get the 4.7 version from another archive like PPA. This is for Ubuntu:
Install the python tools for adding an archive to apt-get:
root@bidder:~# apt-get install python-software-properties

Then add the ppa archive:
root@bidder:~# add-apt-repository ppa:ubuntu-toolchain-r/test

Make sure there are no existing linking:
root@bidder:~# update-alternatives --remove-all gcc
root@bidder:~# update-alternatives --remove-all g++

Update list of packages from all archives:
root@bidder:~# apt-get update

Install the 4.7 versions of gcc and g++ :
root@bidder:~# apt-get install gcc-4.7
root@bidder:~# apt-get -f install
root@bidder:~# apt-get install g++-4.7

Add default links to the new versions:
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 20
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.7 20
root@bidder:~# update-alternatives --config gcc
root@bidder:~# update-alternatives --config g++

Confirm the versions and defaults:
root@bidder:~# apt-cache policy gcc

Mostly referenced from https://askubuntu.com/questions/26498/choose-gcc-and-g-version/26518#26518 and personal experience on Ubuntu 12.04.


text:
Q: What causes horizontal scrolling bar to appear I control the layout of each page of my website(8-12 pages) with the following three divs:
.left, .right{

width:25%;
height:2300px;
float:left;
}

.left {
clear:both;
}

.middle {
width:50%;
height:2300px;
float:left;
}

This works successfully to maintain all of my HTML within the horizontal layout , except on one page where the horizontal scroll bar appears and I am able to scroll beyond the leftmost div.  I do not have any elements, hidden or otherwise, beyond the leftmost div, so I am not sure what I should be looking at to fix this.
HTML

All Posts

    <li  class="show" id="user" data="<?php echo $_SESSION['Userid']; ?>">My Posts

Following

      <li class="species" id="breed" data-breed="<?php echo $_SESSION['Breed']; ?>">

All

Arthritis

Cancer

Cardiac

Diabetes

Obesity

Other

Now Showing:

<?php echo $_SESSION['Breed']; ?>

 Post Count

A: I can not see any problem in this code,but you can add overflow-x:hidden; to disable horizontal scroll bar.
body{
    overflow-x:hidden;
}


text:
Q: Postgres ODBC Connection String error from PowerShell The ODBC connection is ok from the ODBC Data Source Administrator (see below image) but failed from PowerShell.
I got the below exception.
Exception setting "ConnectionString": "Format of the initialization string does not conform to specification start
ing at index 0." from
what is wrong with the connection string?
Here is the code
$Query = "select distinct name, friendly_name from _users order by name"
$DWServer = "MyServer"
$DWUser = "readonly"
$DWPwd = "readonly"
$DWDatabase = "workgroup"
$Port = 8060

#$ConnectionString = "Driver={PostgreSQL35W}:Server=$DWServer;Port=$Port;Database=$DWDatabase;Uid=$DWUser;Pwd=$DWPwd;"
$ConnectionString = "Driver={PostgreSQL UNICODE(x64)}:Server=$DWServer;Port=$Port;Database=$DWDatabase;Uid=$DWUser;Pwd=$DWPwd;"
try
{
    # 1. Connect to DB

$Conn = New-Object System.Data.Odbc.OdbcConnection;
    $Conn.ConnectionString = $ConnectionString
    $Conn.Open()
    $Command = $Conn.CreateCommand()
    $Command.CommandText  = $Query
    $Result = $Command.ExecuteReader()

    $DocCount = 0

    while ($Result.Read())
    {
        try
        {
            $ADId = $Result.GetValue(0)
            $FullName = $Result.GetValue(1)

            $DocCount = $DocCount + 1
            $LicenseName = $ADId  +" " + $FullName

            Write-Output " ********** $DocCount ---  $LicenseName"

        } # end of try
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName

            Write-Output  "*** Exception while catch for $LicenseName ----- $ErrorMessage from $FailedItem"
        } # end of catch

    }  # end of  while
}  # end of outer try
catch
{
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName

    Write-Output "*** Exception  Outer Catch for $LicenseName ----- $ErrorMessage from $FailedItem"
} # end of outer try
finally
{
    $Conn.close()
}


text:
Q: Leaks not caused by application code - Will it get approved? Another memory question on iPhone - When running the leaks application I see a number of leaks get identified, but are caused by NSFoundation or similar, rather than my application code. Where my application name is mentioned, I have obviously resolved the leak.
I assume I can ignore these and that my app will be approved, or am I reading the data incorrectly?
Also - does the application have to have zero memory leaks before it is approved?
Cheers

A: Memory leaks will not cause your application to be rejected unless they contribute to general instability - e.g. a leak while moving forwards/backwards between views will eventually cause your app to crash.
Thats said, there are few actual leaks in the SDK libraries so be sure to check the leak are not actually a result of something your code is doing.

A: Any leaks that apple finds in testing of its own stuff will get fixed (and Apple does definitely test for leaks).  The frameworks are not completely leak free, but it's dangerous to assume that a problem is in the frameworks.  Here are a couple things to keep in mind:
(1) If you leak an object, the entire tree of objects hanging off it will also be reported as leaks. Suppose an object of class NSPrivateWhosit that you've never heard is leaked.  Does that necessarily make it Apple's problem?  No, it might be something used by an instance of NSPublicClass that you leaked.
(2) If an object is allocated in Foundation and passed to you, and you retain it, then you can leak it.  The backtrace of the allocation doesn't matter.  What matters is the backtrace of the unbalanced retain.

A: Your application will get approved even with memory leaks (at least my buggy application did get approved).


text:
Q: Why T in "K <: T" can't be covariance? Scala code:
class Cat[T] {
    def meow[K <: T] = ""
}

class Cat[-T] {
    def meow[K <: T] = ""
}

They can be compiled.
But when T is covariance, the following code can't be compiled:
class Cat[+T] {
    def meow[K <: T] = ""
}

The compiler prints:
error: covariant type T occurs in contravariant position in type  <: T of type K
       def meow[K <: T] = ""
                ^

The type on the right of <: must not be covariant? And why?

A: That would be unsound
with Jazz <: Music, Classical <: Music, but no relation between Jazz and Classical,
meow[K <: T] means that a Cat[Music] can meow in Jazz, Classical, or any choice of genre.
On the other hand, a Cat[Classical] meow cannot be Jazz.
But if you have covariant Cat[+T], then a Cat[Classical] <: Cat[Music] , so a Cat[Classical], being an eclectic Cat[Music] too, should be able to meow Jazz.
Contradiction.


text:
Q: Loop through a parent collection in firestore
I have a parent collection 'chats' on firestore with different ids which I am sending from the app. Each id also have a 'messages' collection.
The major thing I want to achieve is iterating through the documents of the parent (i.e 'chats') collection and checking if the document contains an id (e.g 31) then do something with the message collection of that document.
await FirebaseFirestore.instance.collection('chats').get().then((value){
      print('value Size: ${value.size}'); //value.size here is returning 0
      for (var element in value.docs) {
        if (element.id.contains('31')) {
          //Do something with the messages collection.
FirebaseFirestore.instance.collection('chats/${element.id}/messages').get().then((value){
      for (var message in value.docs) {
        // Do something with the message data
      }
    });
        }
      }
    });

The value.size is returning 0.
However, I don't have issues when I want to perform the same operation on the 'messages' collection.
Please, how can I acheive this??? Thank you in advance.

A: Take a close look at the documents listed under "chats".  They are all greyed out and in italics.  That means there are no actual documents there.  What you have are subcollections nested under the document IDs that don't exist.
If you have no documents in a collection like this, then your query on "chats" will not find anything - your code is working exactly as I would expect.
If you want to be able to list those IDs where there are no documents, you won't be able to do that from your client web app.  You can do this in your backend code, though.  Please read: How to find Firestore collections which don't have parent documents?
See also:

*

*Firebase query won't return all documents

*Firestore query returns no documents even though they are shown in the console in italics


text:
Q: How do I recreate a "settings application"-like tableview inside my application? I want to add a view to my application that allows the user to change several (many) settings. It should look like the built in "Settings Application" (see here) but it has to be within my app itself. At the moment I just have a tableview and I manually add different cell objects (corresponding to switches, sliders, etc). Is there a smarter of doing that? I have the feeling that I'm reinventing the wheel.

A: No, that's the way, returning individual cells in the tableView:cellForRowAtIndexPath: method. Just remember that a UITableViewCell has useful properties such an accessory mark (a detail discolsure button, a disclosure indicator or a checkmark) and an image at the left side.

A: Here's some code I used to set up a preferences page:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case (0):
            return 3;
            break;
        case (1):
            return 2;
            break;
        case (2):
            return 1;
            break;
    }
    return 0;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    switch (section) {
        case (0):
            return @"Numbers";
            break;
        case (1):
            return @"Randomize";
            break;
        case (2):
            return @"About";
            break;
    }
    return nil;
}

The switch statement sets up 3 sections:  Numbers, Randomize, and Versions.  You can fill in the sections with whatever controls you need

A: This is an old question by internet standards, but I've found an amazing way to do this that requires very little effort. I was pulling my hair out trying to build a 2nd table view in another nib before i found these guys: InAppSettingsKit
Basically they've got all the views and the backend stuff done, all you do is add the files to your project and implement a few delegate methods in the class you're calling the settings page from (along with a button in your UI to open the settings panel, etc), and it takes care of the NSUserDefaults stuff. The UI and the settings values and keys are all generated from the same Settings.bundle used for the real settings app, which means your settings can be altered by the user in both places, in the app AND in the settings app. I found this much easier than messing with the delegate methods for a custom table view, and now i don't actually have to choose between Settings.app and something in-app because it does both.
All that's left is to pull the values you need for each settings key later on in your app when you need them, with [[NSUserDefaults standardUserDefaults] objectForKey:@"key"].

A: If you're really gung ho, you can simply use the same format Apple uses to describe settings that would normally go into the settings bundle - but instead parse them yourself, and dynamically build a table based on the settings types.
It's a lot of work, but then again half the work has already been done for you as Apple has a very well though out plist schema for how you define settings.
That also gives you the advantage of extending the settings format to include some extra abilities the Settings app would not have...


text:
Q: Powershell: bulk parametr set am trying to bulk edit "UsageLocation" for a list of users. Running against one UPN is working fine, but bulk not :-/
CSV example
UPN
user1@company.smt
user2@compamy.smt
user3@company.smt

Import users from CSV
$userlist = Import-Csv .\users.csv

Set usagelocation before adding a license
Set-MsolUser -UserPrincipalName "user@company.com" -UsageLocation "XY"

Set UsageLocation for users from CSV
$userlist.foreach(
    {
        Set-MsolUser -UserPrincipalName $_.UPN -UsageLocation "XY"
    }
)

Error returned
Set-MsolUser : User Not Found.  User: .
At line:3 char:9
+         Set-MsolUser -UserPrincipalName $_.UPN -UsageLocation "XY"
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [Set-MsolUser], MicrosoftOnlineException
    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.UserNotFoundException,Microsoft.Online.Administration.Automation.SetUser

Set-MsolUser : Invalid value for parameter.  Parameter Name: UsageLocation.
At line:3 char:9
+         Set-MsolUser -UserPrincipalName $_.UPN -UsageLocation "XY"
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [Set-MsolUser], MicrosoftOnlineException
    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.PropertyValidationException,Microsoft.Online.Administration.Automation.SetUser

Any ideas, please? :-(
Thanks a lot.


text:
Q: I have an issue with a NullPointerException upon resuming my Android app and rendering the canvas my app currently crashes when you press the home or back button saying "Unfortunately, Rocks has crashed". I have narrowed it down to the line of code that reads:
// draws the canvas on the panel
this.gamePanel.render(canvas);

in this context:
package com.background.rocks;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

public class MainThread extends Thread {

    private static final String TAG = MainThread.class.getSimpleName();

    // desired fps
    private final static int MAX_FPS = 50;
    // maximum number of frames to be skipped
    private final static int MAX_FRAME_SKIPS = 5;
    // the frame period
    private final static int FRAME_PERIOD = 1000 / MAX_FPS;

    // Surface holder that can access the physical surface
    private SurfaceHolder surfaceHolder;
    // The actual view that handles inputs
    // and draws to the surface
    private Graphics gamePanel;

    // flag to hold game state
    private boolean running;

    public void setRunning(boolean running) {
        this.running = running;
    }

    public MainThread(SurfaceHolder surfaceHolder, Graphics gamePanel) {
        super();
        this.surfaceHolder = surfaceHolder;
        this.gamePanel = gamePanel;
    }

@Override
public void run() {
    Canvas canvas;
    Log.d(TAG, "Starting game loop");

    long beginTime; // the time when the cycle begun
    long timeDiff; // the time it took for the cycle to execute
    int sleepTime; // ms to sleep (<0 if we're behind)
    int framesSkipped; // number of frames being skipped

    sleepTime = 0;

    while (running) {
        canvas = null;
        // try locking the canvas for exclusive pixel editing
        // in the surface
        try {
            canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                beginTime = System.currentTimeMillis();
                framesSkipped = 0; // resetting the frames skipped
                // update game state
                this.gamePanel.update();
                // render state to the screen
                // draws the canvas on the panel
                this.gamePanel.render(canvas);
                // calculate how long did the cycle take
                timeDiff = System.currentTimeMillis() - beginTime;
                // calculate sleep time
                sleepTime = (int) (FRAME_PERIOD - timeDiff);

                if (sleepTime > 0) {
                    // if sleepTime > 0 we're OK
                    try {
                        // send the thread to sleep for a short period
                        // very useful for battery saving
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                    }
                }

                while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
                    // we need to catch up
                    this.gamePanel.update(); // update without rendering
                    sleepTime += FRAME_PERIOD; // add frame period to check if in next frame
                    framesSkipped++;
                }
            }
        } finally {
            // in case of an exception the surface is not left in
            // an inconsistent state
            if (canvas != null) {
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        } // end finally
    }
}

}
But I'm new to using canvas so I don't know how to fix it. It creates a NullPointerException so I'm assuming it's to do with when resuming the app or pausing the app the canvas isn't stored properly.
Edit: Graphics class (without imports):
package com.background.rocks;

public class Graphics extends SurfaceView implements SurfaceHolder.Callback {

private static final String TAG = Graphics.class.getSimpleName();

private MainThread thread;
private Player player;
private ArrayList<Rock> rocks = new ArrayList<Rock>();
private Random random = new Random();
private CountDownTimer countdown;

public Graphics(Context context) {
    super(context);
    // adding the callback (this) to the surface holder to intercept events
    getHolder().addCallback(this);

    // create shape and load bitmap
    player = new Player(BitmapFactory.decodeResource(getResources(), R.drawable.player_orange), 540, 1500);

    // create the game loop thread
    thread = new MainThread(getHolder(), this);

    // make the GamePanel focusable so it can handle events
    setFocusable(true);

    timer();
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    // at this point the surface is created and
    // we can safely start the game loop
    thread.setRunning(true);
    thread.start();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    Log.d(TAG, "Surface is being destroyed");
    // tell the thread to shut down and wait for it to finish
    // this is a clean shutdown
    boolean retry = true;
    while (retry) {
        try {
            thread.join();
            retry = false;
        } catch (InterruptedException e) {
            // try again shutting down the thread
        }
    }
    Log.d(TAG, "Thread was shut down cleanly");
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        // delegating event handling to the shape
        player.handleActionDown((int) event.getX(), (int) event.getY());

        // check if in the lower part of the screen we exit
        if (event.getY() > getHeight() - 50) {
            thread.setRunning(false);
            ((Activity) getContext()).finish();
        } else {
            Log.d(TAG, "Coords: x=" + event.getX() + ",y=" + event.getY());
        }
    }
    if (event.getAction() == MotionEvent.ACTION_MOVE) {
        // the gestures
        if (player.isTouched()) {
            // the shape was picked up and is being dragged
            player.setX((int) event.getX());
            player.setY((int) event.getY());
        }
    }
    if (event.getAction() == MotionEvent.ACTION_UP) {
        // touch was released
        if (player.isTouched()) {
            player.setTouched(false);
        }
    }
    return true;
}

**public void render(Canvas canvas) {
    if (canvas != null) {
        canvas.drawColor(Color.WHITE);
        player.draw(canvas);
        Rock[] rockArray = rocks.toArray(new Rock[0]);
        for (Rock rock : rockArray) {
            rock.draw(canvas);
        }
    }
}**

/**
 * This is the game update method. It iterates through all the objects and
 * calls their update method if they have one or calls specific engine's
 * update method.
 */
public void update() {
    Rock[] rockArray = rocks.toArray(new Rock[0]);
    for (Rock rock : rocks) {
        rock.update();
    }
}

public void timer() {
    if (countdown != null) {
        countdown.cancel();
    }
    countdown = new CountDownTimer(30000, 800) {

        public void onTick(long millisUntilFinished) {
            rocks.add(new Rock(BitmapFactory.decodeResource(getResources(), R.drawable.rock), random.nextInt(1080 - 1) + 1, 0));
        }

        public void onFinish() {
            countdown.start();
        }
    }.start();
}

 }

Edit 2: So I managed to change my Render method in Graphics and so the app doesn't crash now when you press home or back, however when I try and resume the app I get a black screen. I'm assuming because it hasn't loaded the canvas back in, but I'm not sure how to do this, any help?

A: Start running the thread once the surface gets created. i.e. when you get a callback surfaceCreated(), start the thread.
Code Snippet
public void surfaceCreated(SurfaceHolder holder) {
    thread.setRunning(true);
    thread.start();
}

A: This might be too late but what I did to fix it was I put a n if statement to test whether the canvas is still their before rendering and updating. Should look like this:
If (canvas != null){
    this.gamePanel.render (canvas);
    this.gamePanel.update ();
}

I think I followed the same tutorial as you, you will probobly encounter another issue after this on is solved. Im still looking for an answer to that issue. Hope this helps!


text:
Q: Can this be formalized in terms of mixed-integer linear programming? I am trying to solve a problem where there are a group of objects that need to move between various points at specific times.
I have been able to formalize most of the constraints in terms of linear programming, i.e.:
object1FirstDepartureTime > X
object1FirstArrivalTime < Y
object1FirstArrivalTime - object1FirstDepartureTime > Z
object1SecondDepartureTime - object1FirstArrivalTime > A

And so forth and so on for all the objects and all of their arrivals/departures.  The objective function will be to spend either the least or most possible time in transit.
The problem I'm having is with one additional constraint: certain objects need to be accompanied for the duration of their trip by other objects.  For example, object1 could be accompanied by object2, object3, or object4.  These objects themselves have certain arrival or departure constraints.  I'd like to make my (perhaps mixed-integer) linear program take care of the picking of the accompanying object.  But while trying to formalize this, I can't figure out a way to keep it linear.  I have thought of mixed-integer constraints like
object2GoWIthObject1 + object3GoWithObject1 + object4GoWithObject1 < 2
object2GoWIthObject1, object3GoWithObject1, object4GoWithObject1 are all less than 2
object2GoWIthObject1, object3GoWithObject1, object4GoWithObject1 are all integers

But I can't figure out how to express constraints like "If object 2 accompanies object 1, it will depart at time X with object 1 and arrive at time Y."  This seems non-linear, as I'd be multiplying the boolean variable (if object 2 accompanies object 1) by the time of travel.
Of course, I could just create different linear problems for every "if...then..." statement, but with 60ish accompanied paths and 10ish accompanying objects, this'd lead to 10^60 linear programs to solve, which is not good.
If anyone has any intuition as to how to formalize this linear programming problem so that the decisions of "will X accompany Y?" can be expressed in the problem itself, I'd be much obliged!

A: Yes, you can modify the formulation to handle your constraints. There are many standard tricks involving the "Big-M" and new 0-1 to accomplish this. (Han's response rightly suggests this.)
In order to accommodate your specific non-linear constraints, you would introduce new 0-1 variables (like your "GoWith" variables) and then add extra linear constraints in your formulation.
Let's take your stated requirement: If object 2 accompanies object 1, it will depart at time X with object 1 and arrive at time Y
Start1 >= X
Arrive1 <= Y

are constraints that you already have for Object 1.
Let's introduce the binary variable Z12 which is 1 if Object2 travels with Object1, Z12 = 0 otherwise.
So,
If Z12 = 1, then Start2 > X
If Z12 = 1 then Arrive2 < Y

We can rewrite this as:
Start2 - X >= 0 if Z12 =1
Start2 - X >= -M if Z12 =0, where M is a large number.

Combine them into one linear constraint:
Start2 - X >= M(Z12-1)

This constraint is binding when Z12 is 1, and is trivially satisfied otherwise.
Likewise, for the arrival of Object2 to match the arrival of Object1, you would write:
Arrive2 < Y if Z12=1
Arrive2 < M if Z12=0

Which becomes
Arrive2 < Y + M(1-Z12), a linear constraint.

By similarly introducing binary variables Z13, Z14 etc. you can take care of all your constraints in just one linear formulation.
More "tricks" to use in IP formulation can be found at:
http://agecon2.tamu.edu/people/faculty/mccarl-bruce/mccspr/new15.pdf

A: One way would be to use the big-M method like this:
object1FirstDepartureTime - object2FirstDepartureTime > -M * object2GoWIthObject1
object1FirstDepartureTime - object2FirstDepartureTime < M * object2GoWIthObject1

M is a sufficiently large constant.  The problem with the big-M approach is that it leads to a poor LP relaxation.


text:
Q: Woocommerce Product Vendors change "sold by" If anyone is familiar with the Woocommerce Product Vendors plugin, I'm trying to do something that I thought would be fairly simple. I'm not highly proficient in PHP but can wrap my head around some of it.
I'm trying to change where the output says, "Sold by vendorname". All I want to do is change "Sold by" to something else.
I changed it in the code, knowing that if there was an update, my change would go away. So, I'm assuming I need to put it in my Child Theme functions.php file. That's where I'm stuck.
Help greatly appreciate.

A: Dug around the code and look at some additional documentation to give me some inspiration. I was able to update the text with the following:
/* update vendor sold by text */
add_filter( 'wcpv_sold_by_text', 'sold_by_text' );
function sold_by_text() {
  return 'Artist:';
}


text:
Q: getXDomainRequest not working on IE but works anywhere else I have this function which returns some XML datas from a foreign website :
function sendData()
{
        var dev_statut = jQuery("select[name='statut']").val();
        var dev_fdpaysid = jQuery("select[name='pays']").val();
        var dev_fddeffet = jQuery("input[name='date_effet']").val();
        var dev_fdnbadu = jQuery('select[name="nb_adultes"]').val();
        var dev_fdnbenf = jQuery('select[name="nb_enfants"]').val();

        var date_naiss_a_val = jQuery("input[name^=date_naissance_a]").map(function() {
        var dev_date_naiss_a = 'dev_fadnaiss_';
        return dev_date_naiss_a + this.id + '=' + this.value;
        }).get().join('&');

         var date_naiss_e_val = jQuery("input[name^=date_naissance_e]").map(function() {
         var dev_date_naiss_e = 'dev_fadnaiss_';
         return dev_date_naiss_e + this.id + '=' + this.value;
         }).get().join('&');

        var xdr = getXDomainRequest();
        xdr.onload = function()
        {
                alert(xdr.responseXML);

                var xml = xdr.responseXML;
                var prod = xml.documentElement.getElementsByTagName("produit");

                var proddata = [];

                proddata.push('
');

                var len = prod.length;
                for (var i = 0; i < len; i++) {

                var nomprod = xml.getElementsByTagName('nomprod')[i].firstChild.nodeValue;
                var url = xml.getElementsByTagName('url')[i].firstChild.nodeValue;
                var desc = xml.getElementsByTagName('desc')[i].firstChild.nodeValue;
                var texte = xml.getElementsByTagName('texte')[i].firstChild.nodeValue;

                proddata.push("

" + "
" + nomprod + "
" + "
" + desc + "
" + "
" + texte + "
" + "Faire un devis" + "

");
                }

                proddata.push('
');
                jQuery('#mydiv2').append(proddata.join("\n"));

                jQuery('.resultat_produit a').click(function(e)
                {
                        e.preventDefault();

                        var href = jQuery(this).attr('href');

                        jQuery('#myDiv').empty();
                        jQuery('#myDiv').append('');
                });
        }
        xdr.open("GET", "http://www.MYURL.fr/page.php?dev_statut="+ dev_statut +"&dev_fdpaysid="+ dev_fdpaysid +"&dev_fddeffet="+ dev_fddeffet +"&dev_fdnbadu="+ dev_fdnbadu +"&dev_fdnbenf="+ dev_fdnbenf +"&"+ date_naiss_a_val +"&"+ date_naiss_e_val +"");
        xdr.send();
}

It works fine on any major browsers (Chrome, FF, etc) but not on ... IE ! I've opened the console and it says : "DocumentElement is undefined ..."
I'm tired and can't fix that, any help will be very very appreciated !!


text: Q: Transforming the explanatory variables What are the considerations that we need to take into account if we need to transform just the explanatory variables (not the dependent variable). I have data on assets and liabilities and I need to use assets-liabilities or net worth as the explanatory variable. I can't use logarithm because net worth can be negative or zero or positive. In addition, if I just use the amount of networth (raw data) the maximum likelihood estimator doesn't achieve convergence. But, with the Inverse hyperbolic sine (IHS) transformation, the convergence is achieved. My first question is if it is safe to say that we are using the IHS transformation just because we don't have convergence. Are there any other considerations that we need to look into in this regard? Second question is how do we find the scale parameter (theta) in IHS transformation. ?


text:
Q: Why doesn't my fragment with custom layout check the given checkedItem I have a DialogFragment which shows single choice items with radio buttons.
Here is my code:

   SimpleAdapter simpleAdapter = new SimpleAdapter(
    getActivity(),
    listItem, //this is a hashmap
    R.layout.my_custom_list_item,
    new String[] { "id", "name", "status" },
    new int[] { R.id.textview_ID, R.id.textview_name, R.id.textview_status });
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Title").setSingleChoiceItems(simpleAdapter, 0, //check the first item
    new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInteface,int position) {
            //do something
        }
        }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog,int id) {
            //do something
        }
    });

I use ArrayAdapter with android.R.layout.simple_list_item_single_choice on a different place and it checks the first item. Note that i already gave 0 to the checkedItem parameter. I think there is a problem with my custom layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="10sp"
    android:paddingRight="10sp"
    android:paddingTop="2sp" >

        <RadioButton
            android:id="@+id/selected_cert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginRight="15dp" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textview_ID"
                android:layout_width="fill_parent"
                android:layout_height="29dp"
                android:layout_marginTop="5dp"
                android:textSize="16sp"
                android:textStyle="bold"
                android:typeface="sans" >
            </TextView>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="28dp" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Name :"
                    android:textSize="13sp"
                    android:textStyle="bold" >
                </TextView>

                <TextView
                    android:id="@+id/textview_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="13sp" >
                </TextView>
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="30dp" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Satatus:"
                    android:textSize="13sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/textview_qualifiedstatus"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="13sp" />
            </LinearLayout>
        </LinearLayout>
</LinearLayout>

How do i make the first custom item selected when user opens the dialog fragment.

A: I found out that i needed to create a custom LinearLayout and implement Checkable interface. Then use it as root view of my list item.
My custom LinearLayout:

public class CheckableLinearLayout extends LinearLayout implements Checkable {
    RadioButton mRadioButton;

    public CheckableLinearLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CheckableLinearLayout(Context context) {
        super(context);
    }

    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        findCheckableView(this);
    }

    //finds RadioButton recursively (comment if you know a better way to do that)
    void findCheckableView(ViewGroup parent) {
        for (int i = 0; i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                findCheckableView((ViewGroup) child);
            } else if (child != null) {
                if (child instanceof RadioButton) {
                    mRadioButton = (RadioButton) child;
                }
            }
        }
    }

    @Override
    public void setChecked(boolean checked) {
        if (mRadioButton != null) {
            mRadioButton.setChecked(checked);
        }
    }

    @Override
    public boolean isChecked() {
        return mRadioButton != null ? mRadioButton.isChecked() : false;
    }

    @Override
    public void toggle() {
        if (mRadioButton != null) {
            mRadioButton.toggle();
        }
    }
}

My List item
<com.foo.customViews.CheckableLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="10sp"
    android:paddingRight="10sp"
    android:paddingTop="2sp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="87dp"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radio"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginRight="15dp" />

            <TextView
                android:id="@+id/tv"
                android:layout_width="fill_parent"
                android:layout_height="29dp"
                android:layout_marginTop="5dp"
                android:textSize="16sp"
                android:textStyle="bold"
                android:typeface="sans" >
            </TextView>
    </LinearLayout>
    <!-- some more views -->
</com.foo.customViews.CheckableLinearLayout>

Here is the article which helped me:
http://tokudu.com/post/50023900640/android-checkable-linear-layout


text:
Q: text_field com where para busca em rails Estou começando a estudar rails e estou tentando buscar por nome e data em uma lista.
Gostaria de apresentar na tela dentro da página show essa busca por nome e data
aonde estou tentando criar o formulario na view
<form>
<%= text_field(@fees_by_name , "") %>
<%= select_date(@my_date, start_year: Date.today.year - 100, end_year: Date.today.year + 5, order: [:month, :year]) %>
<%= button_to 'Search' %>
</form>

def no Controller pra pegar as variaveis globais
def show
@my_date = params[:date].nil? ? Date.today : DateTime.new(params[:date][:year].to_i, params[:date][:month].to_i)
@fees = @condominium.fees
end


text:
Q: MySql ssl connection with self signed certificate Hey I want to connect to mySql db using ssl secure connection. I did the following:
Create self signed certificates (resource: https://dev.mysql.com/doc/refman/5.6/en/creating-ssl-files-using-openssl.html):
#server
openssl genrsa 2048 > ca-key.pem

openssl req -new -x509 -nodes -days 3600 -key ca-key.pem -out ca.pem

openssl req -newkey rsa:2048 -days 3600 nodes -keyout server-key.pem -out server-req.pem

openssl rsa -in server-key.pem -out server-key.pem

openssl x509 -req -in server-req.pem -days 3600 -CA ca.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.pem

#client

openssl req -newkey rsa:2048 -days 3600 -nodes -keyout client-key.pem -out client-req.pem

openssl rsa -in client-key.pem -out client-key.pem

openssl x509 -req -in client-req.pem -days 3600 -CA ca.pem -CAkey ca-key.pem -set_serial 01 -out client-cert.pem

#signing

openssl verify -CAfile ca.pem server-cert.pem client-cert.pem

Created the my.cnf  file in C:\Program Files\MySQL\MySQL Server X.Y (since it didn't exists) and added this lines (resource: https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-ssl.html)
ssl-ca=c:/certs/ca.pem
ssl-cert=c:/certs/server-cert.pem
ssl-key=c:/certs/server-key.pem

Then connected to mysql using root and created the sslclient user :
CREATE USER 'sslclient'@'localhost';

Now when I'm trying to connect to mySql db using ssl :
 mysql -h localhost -u sslclient -p --ssl=1 --ssl-cert=client-cert.pem --ssl-key=client-key.pem --ssl-ca=ca.cert

I get the following exception:
 SSL connection error: SSL is required but the server doesn't support it

I tried it also as the root user and also tried to change the ssl settings through MySQl Workbench > right click on my connection > edit connection > connection> ssl and filled the relevant fields.
EDIT : I found out that the .cnf can be the .ini file (located at C:\ProgramData\MySQL\MySQL Server X.Y), so I added the ssl-x lines to it, but now I'm getting this error :
 SSL connection error: ASN: bad other signature confirmation


text:
Q: C - scanf to pull a number in quotes only after a specific sequence of characters Say I have a string like this:
Hello World - this is a line of textCOLOR="4"

and this string is stored in buf[1000]
As you can see this string has a color tag in the format of COLOR="n". The number is what needs to be pulled (it can be between 1 and 56) and assigned to an int variable. I'd like for this tag to be able to be anywhere in the string.
I can run the following code to extract the color value:
int colorNumber = 1; //default value
if (scanf(buf, "%*[^\"]\"%2d[^\"]\"", &colorNumber)) {
    // work with number
}

and that works fine, but if the string were to contain a number or quote in it then the scanf would fail to produce the number.
I've tried a few variations of my second scanf argument, but those didn't work. I tried "%*[^\"]COLOR=\"%2d[^\"]\"" but that doesn't seem to work at all.
I've looked through the man pages for scanf, but I couldn't find what I was looking for in there either.
Perhaps scanf is not the right tool for this? I'm willing to try other libraries/functions if necessary.

A: try
if (sscanf(buf, "%*[^C]COLOR=\"%d", &colorNUM) == 1)

The reason your attempted "%*[^\"]COLOR"... format didn't work is that the %*[\"] matches everything up to the ", skipping past the COLOR, so will then fail to match COLOR.  The above will fail if there's another C somwhere else in the string before COLOR, however.  To avoid that you're probably better off using strstr, possibly in a loop if COLOR might appear multiple places.
for (const char *p = buf; p = strstr(p, "COLOR"); ++p) {
    if (sscanf(p, "COLOR=\"%d", &colorNum) == 1) {
        // found a color number

Note also, trying to match characters after the %d is pointless as regardelss of whether they match or not, the returned values will be the same, so there's no way to tell.  If you want to ensure there's a " after the number, you need something like
int end = 0;
if (sscanf(p, "COLOR=\"%d\"%n", &colorNum, &end), end > 0)

by checking that %n wrote something to end, you're also checking that everything before the %n matched correctly.


text:
Q: Apache: .htaccess ErrorDocument up one level? my site structure like this:
- pages
    404.php
    403.php
- app
    /css
    /-script
    index.php
    .htaccess

in my .htaccess
if I type ErrorDocument 403 /403.php
and put 403.php inside /app and it works
but I need to do something like ErrorDocument 403 ../pages/403.php
how can I achieve that?

A: I believe that this is not possible. In order to retrieve a document above the root, you would need to create a script that fetches it's content.
The ErrorDocument instruction can only see below it's location, not above.
So, if you were to create an error.php file in the app directory that fetches the file from the pages directory (according to the parameter ?error=404), it would work.
ErrorDocument 404 /error.php?error=404

A: Another option would be to place the .htaccess file a folder up.
.htaccess files are being read (and "used") for any folder "under" the .htaccess as long there is not one in the specific folder "overriding" the .htaccess most upward.
All this depends on your setup, though. (DocumentRoot, etc.)


text:
Q: How to deal with empty array to be sent as json in swift? I'm trying to encode data but struggling to deal with empty array with no type as the API's I am working with needs me to send [] if there is no entry.
[
    {
        "RequestId": "5B6E36D9-8759-41BB-A0C0-EDFB116DFBB7",
        "DataSources": ["5B6E36D9-8759-41BB-A0C0-EDFB116DFBB7"],
        "GroupBy": [],
        "Filters": []
    }
]

above is the object json which I have to send.
struct ResponseElement: Encodable {
    let requestID: String
    let dataSources: [String]
    let groupBy: []
    let filters: []

    enum CodingKeys: String, CodingKey {
        case requestID = "RequestId"
        case dataSources = "DataSources"
        case groupBy = "GroupBy"
        case filters = "Filters"
    }
}

let data = ResponseElement(requestID: "5B6E36D9-8759-41BB-A0C0-EDFB116DFBB7",
                           dataSources: ["5B6E36D9-8759-41BB-A0C0-EDFB116DFBB7", ["5B6E36D9-8759-41BB-A0C0-EDFB116DFBB7]"],
                           groupBy: [],
                           filters: [])

let jsonEncoder = JSONEncoder()
let data = try! jsonEncoder.encode(data)

please note while creating data variable I have to pass groupBy, filters as empty array [], I have tried with [nil] which goes as [null] after encoding but it doesn't work in my case, it has to be []
how do I solve this please?

A: If you know that the array will always be empty, the type of that is [Never]. A Never is a type that cannot be instantiated, so this array is necessarily empty.
Unfortunately, Never does not conform to Encodable. It should. It should conform to every protocol automatically (that would make Never a "bottom type," which is a good feature in a type system). That said, it's straightforward to provide the conformance:
extension Never: Encodable {
    public func encode(to encoder: Encoder) throws {
        // This line of code can never, ever run. It's impossible to
        // create a Never, so it's impossible to run its instance methods.
        fatalError()
    }
}

struct ResponseElement: Encodable {
    let requestID: String
    let dataSources: [String]
    let groupBy: [Never]
    let filters: [Never]

    ...
}

You may rightly feel uncomfortable extending a stdlib type to conform with a stdlib protocol. This is kind of fragile, since stdlib might create the conformance in the future, or some other package might do it, and  there'd be a conflict. So you can do this explicitly by creating a type of your own that encodes an empty unkeyed container:
struct EmptyArray: Encodable {
    func encode(to encoder: Encoder) throws {
        encoder.unkeyedContainer()
    }
}

struct ResponseElement: Encodable {
    let requestID: String
    let dataSources: [String]
    let groupBy: EmptyArray
    let filters: EmptyArray
    ...
}

And finally, you can perform the encoding by hand and get rid of the unnecessary properties (this is how I'd do it myself):
struct ResponseElement: Encodable {
    let requestID: String
    let dataSources: [String]

    enum CodingKeys: String, CodingKey {
        case requestID = "RequestId"
        case dataSources = "DataSources"
        case groupBy = "GroupBy"
        case filters = "Filters"
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(requestID, forKey: .requestID)
        try container.encode(dataSources, forKey: .dataSources)
        container.nestedUnkeyedContainer(forKey: .groupBy)
        container.nestedUnkeyedContainer(forKey: .filters )
    }
}

A: If this is just for encoding data and you never have to provide anything for this properties you could use any type you want for your property:
e.g.
struct ResponseElement: Encodable {
    let requestID: String
    let dataSources: [String]
    let groupBy: [String] = []
    let filters: [String] = []

    enum CodingKeys: String, CodingKey {
        case requestID = "RequestId"
        case dataSources = "DataSources"
        case groupBy = "GroupBy"
        case filters = "Filters"
    }
}

Result:
{
    "RequestId": "1",
    "GroupBy": [],
    "Filters": [],
    "DataSources": [
        "1",
        "2"
    ]
}


text:
Q: Azure DevOps user migration After a couple companies merge, we had to build up an AZ DevOps solution from scratch for the new business entity. Unfortunately, at that time we added some users from various companies under their original email addresses (reason: reuse of their VS subscriptions).
Now we need to migrate these users in Azure DevOps from their old bill.smith@oldcompany.com to their new bill.smith@newcompany.com without losing their work and settings. Afterwards the users should be able to log in with their new emails and see everything as if they would log in with their old addresses.
Any ideas how to solve this problem?

A: You need to open a support case and they can help you out. You get a excel file to map users between the domains and they can map them over in one go.

A: jessehouwing is right, if you want to migrate data to new Azure DevOps users, you need submit a support ticket here.
But there are something you need pay attention and get ready first:

*

*Do not add them (bill.smith@newcompany.com)  to Azure DevOps Service or let them logon to Azure DevOps Service. At this point
Azure DevOps Service support needs to migrate/transfer the users.

*Provide a mapping list of users (old user > new user) to Azure DevOps
Service Support.

Azure DevOps Service will transfer identities to the new users. This should add the new account to Azure DevOps Service, assign work items to the new account, assign the Azure DevOps Service license to the new account , and remove the old account from Azure DevOps Service.


text:
Q: Python Call function within a function and reset one of the argument I want to call a Python function y within another function x by passing on the arguments for function y, and then dynamically reset one of the parameters of function y during execution. How can I do it? Below is an example of what I'm trying to do.
def functiony(p,q,r):
    return (p+q)*r

def functionx(functiony,loopvalue):
    for i in loopvalue:
        <<code to reset the 'r' argument of function y, keeping other arguments the same>>
        print(functiony)

functionx(functiony(2,3,4),loopvalue=[10,20,30])

A: Instead of passing functiony into functionx, just pass functiony's args into functionx
def functiony(p,q,r):
    return (p+q)*r

def functionx(functiony_args,loopvalue):
    for i in loopvalue:
        functiony_args[1] = i
        print(functiony(*functiony_args))

functionx([2,3,4],loopvalue=[10,20,30])


text:
Q: Alternative to groupBy on several columns in spark dataframe I have a spark data frame with columns like so:
df
--------------------------
A     B     C    D    E    F   amt
"A1"  "B1" "C1" "D1" "E1"  "F1"  1
"A2"  "B2" "C2" "D2" "E2"  "F2"  2

I would like to perform groupBy with column combinations
(A, B, sum(amt))
(A, C, sum(amt))
(A, D, sum(amt))
(A, E, sum(amt))
(A, F, sum(amt))

such that the resulting data frame looks like:
df_grouped
----------------------
A     field    value   amt
"A1"    "B"     "B1"    1
"A2"    "B"     "B2"    2
"A1"    "C"     "C1"    1
"A2"    "C"     "C2"    2
"A1"    "D"     "D1"    1
"A2"    "D"     "D2"    2

My attempt at this was the following:
val cols = Vector("B","C","D","E","F")
//code for creating empty data frame with structs for the cols A, field, value and act
for (col <- cols){
   empty_df = empty_df.union (df.groupBy($"A",col)
  .agg(sum(amt).as(amt)
  .withColumn("field",lit(col)
  .withColumnRenamed(col, "value"))
}

I feel that the usage "for" or "foreach" may be clumsy for a distributed env such as spark. Are there any alternatives with map functionality for what I am doing? In my mind, aggregateByKey and collect_list may work; however, I am unable to imagine a complete solution. Please advise.

A: foldLeft is very powerful function devised in Scala if you know how to play with it. I am suggesting you to use foldLeft function ( I have commented for clarity in the code and for explanation)
//selecting the columns without A and amt
val columnsForAggregation = df.columns.tail.toSet - "amt"

//creating an empty dataframe (format for final output
val finalDF = Seq(("empty", "empty", "empty", 0.0)).toDF("A", "field", "value", "amt")

//using foldLeft for the aggregation and merging each aggreted results
import org.apache.spark.sql.functions._
val (originaldf, transformeddf) = columnsForAggregation.foldLeft((df, finalDF)){(tempdf, column) => {
  //aggregation on the dataframe with A and one of the column and finally selecting as required in the outptu
  val aggregatedf = tempdf._1.groupBy("A", column).agg(sum("amt").as("amt"))
    .select(col("A"), lit(column).as("field"), col(column).as("value"), col("amt"))
  //union the aggregated results and transferring dataframes for next loop
  (df, tempdf._2.union(aggregatedf))
}
}

//finally removing the dummy row created
transformeddf.filter(col("A") =!= "empty")
  .show(false)

You should have the dataframe you desire
+---+-----+-----+---+
|A  |field|value|amt|
+---+-----+-----+---+
|A1 |E    |E1   |1.0|
|A2 |E    |E2   |2.0|
|A1 |F    |F1   |1.0|
|A2 |F    |F2   |2.0|
|A2 |B    |B2   |2.0|
|A1 |B    |B1   |1.0|
|A2 |C    |C2   |2.0|
|A1 |C    |C1   |1.0|
|A1 |D    |D1   |1.0|
|A2 |D    |D2   |2.0|
+---+-----+-----+---+

I hope the answer is helpful
Concised form of above foldLeft function is
import org.apache.spark.sql.functions._
val (originaldf, transformeddf) = columnsForAggregation.foldLeft((df, finalDF)){(tempdf, column) =>
  (df, tempdf._2.union(tempdf._1.groupBy("A", column).agg(sum("amt").as("amt")).select(col("A"), lit(column).as("field"), col(column).as("value"), col("amt"))))
}


text:
Q: How to call a class, Java - Eclipse I'm making a text based gladiator combat game. The problem I'm having is that it's not going into the other class when I try to call it. This is what I have.
Main Class
if (fill.equals("1")) {
    arena = true;
    while (arena == true) {
        System.out.println("You travel to the arena.");
        fill = scan.next();
        System.out.println("Vanguard: Welcome!");
        System.out.println("1) Enter the arena.");
        System.out.println("2) Exit the arena.");
        fill = scan.next();
        if (fill.equals("1")) {
            System.out.println("Vanguard: These are the available matches:");
            if (rank == "Rookie") {
                System.out.println("1) Snow");
                System.out.println("2) Blaze");
                System.out.println("3) Ember");
                fill = scan.next();

                if (fill.equals("1")) {
                    System.out.println("You with to battle Snow? Y/N");
                    fill = scan.next();
                    fill = fill.toLowerCase();
                    if (fill.equals("y")) {
                        enemy = "Snow";
                        enemyhealth = 35;
                        enemydamage = enemydamrn.nextInt((7 - 5) + 1) + 5;
                        System.out.println("You go to the arena to prepare with snow.");

                        Battle Battle = new Battle();
                    }
                }
            }
        }
    }
}

When I type "y" into the scanner, it will just restart at the while statement, instead of going to the class.
I would appreciate any help I can get with this. I'm pretty new to java, I've been coding with it for about 1.5 months and I would like to be able to find out this issue. I hope any of you could help me! ^_^/

A: When you say
Battle Battle = new Battle();

you construct a new instance of Battle with a really unfortunate name. I suggest you try
Battle battle = new Battle();

and then (unless you do everything in the Battle constructor, which I would not recommend) you need to call the method you want to execute on your Battle instance like
battle.someMethod();

Also,
if (rank == "Rookie") {

is not going to work for comparing String(s). That's reference equality (not value). You need to test String equality like
if (rank.equals("Rookie")) {


text:
Q: error while running python 2.7 code for deepwalk #! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import random
from io import open
from argparse import ArgumentParser, FileType, ArgumentDefaultsHelpFormatter
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
import logging

from deepwalk import graph
from deepwalk import walks as serialized_walks
from walks import WalksCorpus
from gensim.models import Word2Vec
from deepwalk.skipgram import Skipgram
from six import text_type as unicode
from six import iteritems
from six.moves import range

import psutil
from multiprocessing import cpu_count

p = psutil.Process(os.getpid())
try:
    p.set_cpu_affinity(list(range(cpu_count())))
except AttributeError:
    try:
        p.cpu_affinity(list(range(cpu_count())))
    except AttributeError:
        pass

logger = logging.getLogger(__name__)
LOGFORMAT = "%(asctime).19s %(levelname)s %(filename)s: %(lineno)s %(message)s"

def debug(type_, value, tb):
  if hasattr(sys, 'ps1') or not sys.stderr.isatty():
    sys.__excepthook__(type_, value, tb)
  else:
    import traceback
    import pdb
    traceback.print_exception(type_, value, tb)
    print(u"\n")
    pdb.pm()

def process(args):

  if args.format == "adjlist":
    G = graph.load_adjacencylist(args.input, undirected=args.undirected)
  elif args.format == "edgelist":
    G = graph.load_edgelist(args.input, undirected=args.undirected)
  elif args.format == "mat":
    G = graph.load_matfile(args.input, variable_name=args.matfile_variable_name, undirected=args.undirected)
  else:
    raise Exception("Unknown file format: '%s'.  Valid formats: 'adjlist', 'edgelist', 'mat'" % args.format)

  print("Number of nodes: {}".format(len(G.nodes())))

  num_walks = len(G.nodes()) * args.number_walks

  print("Number of walks: {}".format(num_walks))

  data_size = num_walks * args.walk_length

  print("Data size (walks*length): {}".format(data_size))

  if data_size < args.max_memory_data_size:
    print("Walking...")
    walks = graph.build_deepwalk_corpus(G, num_paths=args.number_walks,
                                        path_length=args.walk_length, alpha=0, rand=random.Random(args.seed))
    print("Training...")
    model = Word2Vec(walks, size=args.representation_size, window=args.window_size, min_count=0, sg=1, hs=1, workers=args.workers)
  else:
    print("Data size {} is larger than limit (max-memory-data-size: {}).  Dumping walks to disk.".format(data_size, args.max_memory_data_size))
    print("Walking...")

    walks_filebase = args.output + ".walks"
    walk_files = serialized_walks.write_walks_to_disk(G, walks_filebase, num_paths=args.number_walks,
                                         path_length=args.walk_length, alpha=0, rand=random.Random(args.seed),
                                         num_workers=args.workers)

    print("Counting vertex frequency...")
    if not args.vertex_freq_degree:
      vertex_counts = serialized_walks.count_textfiles(walk_files, args.workers)
    else:
      # use degree distribution for frequency in tree
      vertex_counts = G.degree(nodes=G.iterkeys())

    print("Training...")
    walks_corpus = serialized_walks.WalksCorpus(walk_files)
    model = Skipgram(sentences=walks_corpus, vocabulary_counts=vertex_counts,
                     size=args.representation_size,
                     window=args.window_size, min_count=0, trim_rule=None, workers=args.workers)

  model.wv.save_word2vec_format(args.output)

def main():
  parser = ArgumentParser("deepwalk",
                          formatter_class=ArgumentDefaultsHelpFormatter,
                          conflict_handler='resolve')

  parser.add_argument("--debug", dest="debug", action='store_true', default=False,
                      help="drop a debugger if an exception is raised.")

  parser.add_argument('--format', default='adjlist',
                      help='File format of input file')

  parser.add_argument('--input', nargs='?', required=True,
                      help='Input graph file')

  parser.add_argument("-l", "--log", dest="log", default="INFO",
                      help="log verbosity level")

  parser.add_argument('--matfile-variable-name', default='network',
                      help='variable name of adjacency matrix inside a .mat file.')

  parser.add_argument('--max-memory-data-size', default=1000000000, type=int,
                      help='Size to start dumping walks to disk, instead of keeping them in memory.')

  parser.add_argument('--number-walks', default=10, type=int,
                      help='Number of random walks to start at each node')

  parser.add_argument('--output', required=True,
                      help='Output representation file')

  parser.add_argument('--representation-size', default=64, type=int,
                      help='Number of latent dimensions to learn for each node.')

  parser.add_argument('--seed', default=0, type=int,
                      help='Seed for random walk generator.')

  parser.add_argument('--undirected', default=True, type=bool,
                      help='Treat graph as undirected.')

  parser.add_argument('--vertex-freq-degree', default=False, action='store_true',
                      help='Use vertex degree to estimate the frequency of nodes '
                           'in the random walks. This option is faster than '
                           'calculating the vocabulary.')

  parser.add_argument('--walk-length', default=40, type=int,
                      help='Length of the random walk started at each node')

  parser.add_argument('--window-size', default=5, type=int,
                      help='Window size of skipgram model.')

  parser.add_argument('--workers', default=1, type=int,
                      help='Number of parallel processes.')

  args = parser.parse_args()
  numeric_level = getattr(logging, args.log.upper(), None)
  logging.basicConfig(format=LOGFORMAT)
  logger.setLevel(numeric_level)

  if args.debug:
   sys.excepthook = debug

  process(args)

if __name__ == "__main__":
  sys.exit(main())

Error:

Traceback (most recent call last):   File "main.py", line 165, in      sys.exit(main())   File "main.py", line 162, in main     process(args)   File "main.py", line 93, in process     walks_corpus = serialized_walks.WalksCorpus(walk_files) AttributeError: 'module' object has no attribute 'WalksCorpus'

Why do I get this error?

A: It looks as though you are importing WalksCorpus on its own from walks with from walks import WalksCorpus.  Then when you try to use WalksCorpus method you are looking for it with in serialized_walks which I assume does not have the WalksCorpus method in it.
Try changing this line.
walks_corpus = serialized_walks.WalksCorpus(walk_files)

To:
walks_corpus = WalksCorpus(walk_files)


text:
Q: Delegate not working in iOS I feel frustrated with this problem, I my delegate doesn't work, Here's the code snippet below. I'm just using xib in this application.
//classA.h file
    ClassA.h
#import "ClassB.h"

@interface ClassA : UIViewController< ClassBDelegate >

//classA.m file
**ClassA.m**

-(void)didSuccessPreview:(ClassB *)controller andLog:(NSString *)log{
    NSLog(@"%@", log);
}

//classB.h file
**ClassB.h**

#import <UIKit/UIKit.h>

@class ClassB;

@protocol ClassBDelegate <NSObject>

- (void)didSuccessPreview:(ClassB *)controller andLog:(NSString *)log;

@end

@interface ClassB : UIViewController

@property (weak, nonatomic) id< ClassBDelegate >delegate;

//classB.m file
**ClassB.m**

I add this code below inside view did load

[self.delegate didSuccessPreview:self andLog:@"zz"];

I have other delegate inside my application same as the code above, but it works but this one is not, I don't know why. Inside my classA I have a button then when i click it it goes to classB, then when it goes to viewdidload in ClassB, the delegate doesn't fired.

A: Depending on where you assign the delegate, your code might need to look like this:
ClassB viewController = [ClassB new];
ClassA delegateStrongRef = [ClassA new]

viewController.delegate = delegateStrongRef; // <-- you are missing this now;
// Fixed: the ClassA object must be referenced strongly somewhere else
// besides the (weak)delegate property, otherwise it will be deallocated.

(The code above is the part where you create the instance of ClassB, the view controller. It might be inside the AppDelegate, another viewController's implementation, anything - depending on how your app is structured).
Then, in the view controller's -viewDidload method, you can have the delegate execute a method like this:
- (void)viewDidLoad
{
    [self.delegate didSuccessPreview:self andLog:@"zz"];
}

so, at some point after instantiating your view controller, you need to assign an object of type ClassA (the class that adopts the delegate protocol) to its delegate property, otherwise it will be nil and any messages sent to it will be ignored (no method executed).
Properties and instance variables of object type are not allocated automatically, but initialized to nil (ints, floats etc, are initialized to 0, 0.0f, etc.)
EDIT: If you are assigning the delegate from ClassA's code, then it might look like this:
ClassA.m:
- (void) someMethodOfClassA
{
    ClassB viewController = [ClassB new];
    viewController.delegate = self;

    // e.g., Do something with the view controller...
    [navigationController pushViewController:viewController animated:YES];
}

Since the delegate property is defined as a weak reference, before calling any method of the delegate make sure it has not been deallocated and its reference set back to nil (use NSLog or set a breakpoint).


text:
Q: How do I view an app running in Heroku's staging environment? When I push my app to the staging environment do I get a different main URL?
I inherited an app someone else built and deployed on Heroku. I'd like to test some
drastic changes that current users won't run into. It looks fine on my local machine,
but the app has some quirks that keep it from running on my own nginx/passenger-based
server. So Heroku it is.
Thanks for any advice.

A: Heroku apps don't inherently have a staging environment. It's likely pushing to a second Heroku app the original developer was using as a staging environment. Read more about managing multiple environments on Heroku here:
https://devcenter.heroku.com/articles/multiple-environments


text:
Q: pdo_mysql extension is not installed error on magento2 I'm facing this type of extension error on local machine. I also Checked pdo_mysql extension install on my server.It show enable status during execuate commond .
which is :
 php -i|grep PDO
It Shows PDO support => enabled
But execuate Some indexing commond it seems error.
I h've attched Screen Shot on my terminal Captured.
I'm using php 5.6.20 and mysql v5.6+

A: Have you installed the extension?
sudo apt-get install php5.6-pdo-mysql


text:
Q: strange behavior on removing items from a bound collection i have a ListView which is data-bound to an OservableCollection.. i need to make a button that removes items from the collection depending on the selected items of the ListView of the UI.
my XAML :
<ListView Name="MyListView"
          ItemsSource="{Binding}"
          SelectionMode="Multiple"/>

<Button Name="RemoveButton"
        Click="RemoveButton_Click" />

my C# :
 private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        MyListView.DataContext = this.ItemsCollection;
      // ItemsCollection is the ObservableCollection
    }

  private void RemoveButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in MyListView.SelectedItems)
        {
            ItemsCollection.Remove((Item)item);
        }
    }

now what happens is whenever i click the RemoveButton the first selected item is removed but the one after it is not removed and so on, for example if my ListView shows this :
item 1
item 2
item 3
item 4
item 5
item 6
then selecting all items and hitting Remove makes the ListView shows this :
item 2
item 4
item 6
and with repeating the select and remove shows this :
item 4
so you can see it removes an item and leaves the next .. why this weird behavior ? what am i missing ?

A: This will work..
private void RemoveButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in MyListView.SelectedItems.Cast<object>().ToList())
        {
            ItemsCollection.Remove((Item)item);
        }
    }

You can see the fullcode here:
public partial class MainWindow : Window
{
    public ObservableCollection<Person> _personList { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        _personList = new ObservableCollection<Person>();
        _personList.Add(new Person() { Name = "Person1" });
        _personList.Add(new Person() { Name = "Person2" });
        _personList.Add(new Person() { Name = "Person3" });
        _personList.Add(new Person() { Name = "Person4" });
        _personList.Add(new Person() { Name = "Person5" });
        _personList.Add(new Person() { Name = "Person6" });

        MyListView.DataContext = this._personList;
    }

    private void RemoveButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in MyListView.SelectedItems.Cast<object>().ToList())
        {
            _personList.Remove((Person)item);
        }
    }
}

public class Person
{
    public string Name { get; set; }
}

<Window x:Class="ListView.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ListView"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
    <ListView Background="DarkCyan" Foreground="White" Name="MyListView"
      ItemsSource="{Binding}" Height="200" DisplayMemberPath="Name"
      SelectionMode="Multiple"/>

    <Button Name="RemoveButton"
    Click="RemoveButton_Click" Height="100" Width="100" />
    </StackPanel>
</Grid>


text:
Q: deleting row from JTable and database I want to delete Selected row data from Jtable  and database.
My Code :
 try {

        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.removeRow(jTable1.getSelectedRow());

        Class.forName("org.sqlite.JDBC");
        Connection con = DriverManager.getConnection("jdbc:sqlite:C:\\management.db");
        Statement st = con.createStatement();
        int id = jTable1.getSelectedRow();
        Object number =  jTable1.getValueAt(id-1,0);
        String sql = "delete  from emp_details where id ="+number;
        int res = st.executeUpdate(sql);
        if(res == 1) {
                JOptionPane.showMessageDialog(this, "Deleted", "Emp Details", WIDTH);
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Empsearch.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(Empsearch.class.getName()).log(Level.SEVERE, null, ex);
    }

When I run the program get the following exception:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -2

A: When removeRow() gets called, any row selection is undone, so the subsequent call to getSelectedRow() returns -1, thus setting id to -1. This results in getValueAt having id-1 (i.e. -2) as its first parameter, which of course is an invalid row index, hence the exception.
Perhaps try executing the SQL update and then deleting the table row?


text:
Q: iPhone Device 3.1 SDK Breaks vertical alignment of UITableViewCellStyleValue1 textLabel Can anyone provide an explanation for the following phenomenon?
As of the iPhone Device 3.1 SDK, I've found that if a UITableViewCell is of style UITableViewCellStyleValue1 and its detailTextLabel.text is unassigned, then the textLabel does not display in the center of the cell as would be expected.
One notable caveat is that this only happens for me when I'm testing on the Device – the iPhone Simulator 3.1 SDK displays the cells correctly. Also, this is not a problem when using the iPhone Device 3.0 SDK.
Below is a simple UITableViewController subclass implementation that demonstrates the problem.
@implementation BuggyTableViewController

#pragma mark Table view methods

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }

    switch (indexPath.row) {
  case 0:
   cell.textLabel.text = @"detailTextLabel.text unassigned";
   break;
  case 1:
   cell.textLabel.text = @"detailTextLabel.text = @\"\"";
   cell.detailTextLabel.text = @"";
   break;
  case 2:
   cell.textLabel.text = @"detailTextLabel.text = @\"A\"";
   cell.detailTextLabel.text = @"A";
   break;
  default:
   break;
 }

    return cell;
}

@end

A: instead of
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];

try using
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

A: I also had the same problem. The cell looked fine in the simulator but when i ran the app on the device the cell text was not centered vertically. Using UITableViewCellStyleDefault solved my vertical alignment centering problems. Fortunately my cell does not have a subtitle.


text:
Q: Normalization of Slater Determinant and Antisymmetry Consider a system consisting of two electrons with Slater-Determinant $\vert\chi_1\chi_2\rangle$, where $\chi_1$ and $\chi_2$ are one-electron orbitals (spin-orbitals). The Slater Determinant is normalized, i.e, $\langle\chi_1\chi_2\vert\chi_1\chi_2\rangle=1$. Further, the antisymmetry of $\vert\chi_1\chi_2\rangle$ manifests as
$$\vert\chi_2\chi_1\rangle=-\vert\chi_1\chi_2\rangle.$$
Project now the latter relation on $\langle\chi_1\chi_2\vert$, i.e.,
$$\langle\chi_1\chi_2\vert\chi_2\chi_1\rangle=-\langle\chi_1\chi_2\vert\chi_1\chi_2\rangle=-1.$$
My Question: What does the relation $\langle\chi_1\chi_2\vert\chi_2\chi_1\rangle=-1$ mean?

A: Let $|\psi\rangle$ and $|\phi\rangle$ be two arbitrary normalized states. If $\langle\psi|\phi\rangle = 0$, then the states are orthogonal. If $\langle\psi|\phi\rangle = 1$, then the states are the same. If $\langle\psi|\phi\rangle = e^{i\theta}$, for some $\theta\in\mathbb{R}$, then the states are the same up to a global phase. Since the global phase has no bearing on the physics of the system, when $\langle\psi|\phi\rangle = e^{i\theta}$, the states are the same.
So for single Slater determinants, exchange of electrons has no bearing on the physics of the system, meaning that $|\chi_1\chi_2\rangle$ and $|\chi_2\chi_1\rangle$ are the same state. However, the antisymmetry property is important when you consider linear combinations of Slater determinants. For example, the state
$$ \frac{1}{\sqrt{2}}\big(|\chi_1\chi_2\rangle + |\chi_1\chi_3\rangle\big)$$
is a different state from
$$ \frac{1}{\sqrt{2}}\big(|\chi_1\chi_2\rangle + |\chi_3\chi_1\rangle\big)$$
because the antisymmetry property of Slater determinants now manifests as a change in the relative phase between two Slater determinants in superposition:
$$ \frac{1}{\sqrt{2}}\big(|\chi_1\chi_2\rangle +|\chi_3\chi_1\rangle\big) = \frac{1}{\sqrt{2}}\big(|\chi_1\chi_2\rangle - |\chi_1\chi_3\rangle\big) \not=\frac{1}{\sqrt{2}}\big(|\chi_1\chi_2\rangle + |\chi_1\chi_3\rangle\big).$$