Q:

Why do mana abilities not go on the stack?

Why this special treatment for mana-abilities? What are the design implications if they didn't go on the stack?

A:

I can think of three reasons:

It would force arbitrary actions to be reversed.
It would allow spells that haven't been fully cast to be countered.
There are already plenty of opportunities to react.

It would force arbitrary actions to be reversed
Consider this rule:

601.2 [...] If, at any point during the casting of a spell, a player is unable to comply with any of the steps listed below, the casting of the spell is illegal; the game returns to the moment before that spell started to be cast.

Players can obtain mana in the middle of casting a spell[1][2]. If mana abilities used the stack, that means players would be able to cast spells in response. If the spell were to become unable to be cast, one would have to rewind all direct and indirect effects of those spells. Someone could have revealed private information, shuffled their library or lost the game as a result. How do you undo those?
Not only that, it would also make it far more likely for a spell to become unable to be cast, something that should never happen.
For example, consider this scenario where responding to mana abilities would be allowed.

Alice only has a single creature on the 'field.
Starts casting Altar's Reap.
She activates a Swamp's ability.
In response, Nancy casts Beacon of Destruction
Nancy kills Alice's creature and shuffles her Beacon of Destruction into her library.
Alice can no longer complete the casting of her spell (because she can't pay the additional cost), so the game rewinds to the start of the casting of the spell. Nancy needs to unshuffle her library to match the game state.

It would allow spells that haven't been fully cast to be countered
Players can obtain mana in the middle of casting a spell[1]. This happens after placing the spell on the stack[2]. A spell is a card on the stack (or a copy of spell), so it could be the legitimate target of a Cancel cast in response to activating mana abilities. That means one could counter a spell that han't been (fully) cast yet. That's just too complicated and messy to allow.

There are already plenty of opportunities to react
Activating mana abilities is not something someone one normally does for its own sake. It's done as part of something else, such as casting a spell. Allowing this to be interrupted would be detrimental to the game flow and would add confusion. There are plenty of other points at which players can respond.
The earlier problems only surface when activating mana abilities when one would not have priority under the current rules. Could the game allow players to respond to the activation of mana abilities performed when a player has priority? Yes, but it would often be hard to distinguish whether an activation occurred before or during casting. It's far simpler to have mana abilities never use the stack rather that having the player try to figure out whether one can respond to a particular activation or not.

Notes

Or activating an ability. I'm only mentioning spells to keep it simple.
The steps to casting a spell[1] are:

601.2a) Place card on stack.
601.2b-d) Make choices, including targets.
601.2e) Determine total cost.
601.2f) Activate mana abilities.
601.2g) Pay the previously determined cost.

A:

There is some history behind the decision. Back in the dark ages of MtG rules, before sixth edition, there were a lot of rules that were unintuitive and confusing. With the release of Fifth Edition, a new type of ability was introduced,

Mana Sources: "Mana sources" are a new category of abilities. They include the ability of lands to be tapped for mana and all abilities that provide mana as interrupts. For example, Llanowar Elves's ability is now considered a mana source, but the ability of Ice Cauldron is not. Mana sources may be used whenever desired and may not be interrupted; there is no gap between playing the ability and resolving it. For example, you can't Rust a Mox; only continuous effects can stop a mana source from producing mana.

So, a Mana Source is anything that generated mana. Spells like Dark Ritual from earlier editions can be found with the card type Mana Source. Fifth Edition rules clarified that they may not be interrupted. This was necessary, because before the stack, Interrupts (depreciated, and later reclassified as Instants) were handled in batches

In the beginning, there was the batch. You played a spell, a flurry of "fast effects" were played in response, and then everything (well, everything except interrupts) resolved using the "last in, first out rule," with no chance of playing more spells in the middle. [...]
The timing issues presented by Red Elemental Blast and Blue Elemental Blast (and later, Hydroblast and Pyroblast) were particularly troublesome. Interrupts made sense when they targeted spells, but what happened when they began targeting permanents? Remember, removing the source of a fast effect does not remove the fast effect itself, but what about stopping the fast effect in response to it being played? [...]
Under the current rules, Mark taps his Prodigal Sorcerer in an attempt to deal 1 damage to Randy. In response, Randy plays Red Elemental Blast, targeting the Prodigal Sorcerer. This destroys the Sorcerer, but not before its "ping" effect goes onto the stack. That 1 damage is still dealt to Randy. Now, under the earliest Magic rules, Mark would announce the tapping of his Sorcerer, but Randy could say, "Hold on a minute! I want to interrupt your effect." This would stop the game, target the Sorcerer with Randy's Red Elemental Blast, and prevent the damage from ever being dealt. This created huge amounts of confusion over timing: The active player was supposed to have priority each turn, but interrupts being used this way seemed to contradict the rule. This problem, however, was corrected before interrupts were done away with entirely. The ruling said that if you targeted a permanent with an interrupt, the interrupt was played "as an instant."

So, under the pre-fifth edition rules, you could kill a Llanowar Elves or Interdict a land tapping for mana to prevent a player from generating enough mana to play a spell, and the game would have to backup to the point of the illegal action of casting a spell you couldn't pay the cost for. Sixth Edition rules and the stack did away with all this confusion. There are no longer batches and special timing rules for Interrupts/Instants, they all go on the Stack. Abilities that generate mana don't go on the stack, amd therefore cannot be responded to, removing the necessity to specify on the cards that they cannot target mana abilities.

A:

I think the simplest answer is that mana abilities are generally used while casting a spell to pay a cost. If they had to be put on the stack, then they could never be used while casting a spell because you would be taking another action before a previous action is complete.

601.2. To cast a spell is to take it from where it is (usually the hand), put it on the stack, and pay its costs, so that it will
  eventually resolve and have its effect. Casting a spell follows the
  steps listed below, in order. If, at any point during the casting of a
  spell, a player is unable to comply with any of the steps listed
  below, the casting of the spell is illegal; the game returns to the
  moment before that spell started to be cast (see rule 717, "Handling
  Illegal Actions"). Announcements and payments can't be altered after
  they've been made.
...
601.2h Once the steps described in 601.2a-g are completed, the spell becomes cast. Any abilities that trigger when a spell is cast or put
  onto the stack trigger at this time. If the spell's controller had
  priority before casting it, he or she gets priority.

If you follow 601.2 to it's conculsion you see that you could not activate the mana ability if it was not treated differently because you don't have priority while you are 'casting' a spell.
Yes you had priority when you started to cast the spell and you will have it again when you are done casting the spell, but while you are 'casting' it, (Paying its cost, choosing its targets etc) there is no passing of priority so no abilities or other spells can be used/cast.
So if it was treated like a normal ability, which you also can not activate while casting a spell, then you could never use them to pay a cost while casting a spell. they would always have to be used before you started paying the cost.


Q:

How you make procedure in C?

So I'm new to C, I'm trying to make procedure to swap value of 2 variables.
When I run this the swap didn't work.
#include <stdio.h>
#include <stdlib.h>

void swap(int A,int B)
{
    A = A + B;
    B = A - B;
    A = A - B;
}

int main(void){
    int num1,num2;
    printf("insert first number :\n");
    scanf("%d",&num1);
    printf("insert second number :\n");
    scanf("%d",&num2);
    swap(num1,num2);

    printf("%d %d\n",num1,num2);

    return 0;
}

A:

That is because arguments are passed by value and modifying them in callee won't affect caller's local variables. Use pointers to modify ones.
#include <stdio.h>
#include <stdlib.h>
void swap(int* A,int* B)
{
    *A = *A + *B;
    *B = *A - *B;
    *A = *A - *B;
}

int main(void){
    int num1=0,num2=0; /* initialize for in case scanf() fails */
    printf("insert first number :\n");
    scanf("%d",&num1);
    printf("insert second number :\n");
    scanf("%d",&num2);
    swap(&num1,&num2);

    printf("%d %d\n",num1,num2);

    return 0;
}


Q:

Variable number of arguments in C++ [Xcode]

I have a problem with variable number of arguments in C++. I write my code using Xcode.
Here is my code:
#include <iostream>

int sum(int n, ...)
{
    int *p = &n;
    p++;

    int res = 0;
    for(int i=0; i<n; i++){
        res+=(*p);
        p++;
    }

    return res;
}

int main(int argc, const char * argv[]) {

    std::cout << sum(4, 1, 2, 3, 4);

    return 0;
}

sum(4, 1, 2, 3, 4) should return a value of 10, but it returns 1606452732.

A:

In C++ you use a template metafunction to do that. It's pretty straight forward:
int sum(int u)
{return u;}  // Recursion-End

template<typename... Args>
int sum(int u, Args... rest)
{
    return u + sum(rest...);
}

Try it online!
However there is a, as I consider it, depreciated C-way using va_start and va_end. You need to include cstdarg and on function call you need to provide the total parameter count. It would look like this:
int sum(int argnum, ...)
{
    va_list arguments;
    int i;
    int sum = 0;

    va_start(arguments, argnum); /* Needs last known character to calculate
                                    the address of the other parameters */
    for(i = 0; i < argnum; ++i)
        sum += va_arg(arguments, int); /* use next argument */

    va_end(arguments);

    return sum;
}

Try it online!


Q:

NSAutoLayout standard space value

When using AutoLayout you can tick the "standard" box in Interface Builder or you can create it visually using... @"|-[someElement]-|"
Is there a constant that I can use to access the value that this "standard" represents?
I want to create an NSLayoutConstraint where the constant property is equal to this standard value.

A:

According to this answer to What constant can I use for the default Aqua space in Autolayout?, the standard Aqua space is

8.0 between sibling views, and 20.0 between a view and its superview.

There are no predefined constants so you'd have to define your own.


Q:

How do I reload this module?

from mypackage.pkg import mymodule
...
reload(mypackage.pkg.mymodule)

results in NameError: global name 'mypackage' is not defined.
How should mymodule be reloaded?

A:

from mypackage.pkg import mymodule

reload(mymodule)

or
import mypackage.pkg.mymodule
...
reload(mypackage.pkg.mymodule)


Q:

Make "object" delete at "distance", when "created"? C# programming

I'm a complete newb, working on a 2D RTS game. So far I've created an object "infantry" and can make it shoot a "bullet" in specified direction, and can only find the code to delete bullet once outside the room. I want the bullet to delete at a relative distance of 300pixels from the infantry. And need the code to be very clean, hence there will be a lot of bullets eventually. My question is: Should I make a rectangle around the infantry, to specify range and line of sight, and when bullet collides with range = delete? or Should the bullet class say "once created + distance traveled = 300 pixels = delete"?... Any code, or hints you can offer would be greatly appreciated.

A:

Simple method:

Store the origin point, where the projectile is created (at the gun barrel)
Each frame, use the distance formula to find out whether the projectile has exceeded the travel radius.
You can avoid the Math.Sqrt call in the distance formula, by comparing to the square of the radius.
var dx = xbullet - xorigin;
var dy = ybullet - yorigin;
if (dx*dx + dy*dy > range*range) delete bullet


Q:

Avoid having to qRegisterMetaType (pointer vs reference), concern about const

Given the signal:
void dbConnected(const QSqlDatabase &db);

I learned (from Qt Communication betwen threads, app design) how to avoid having to use
qRegisterMetaType<QSqlDatabase>("QSqlDatabase");

Just changing the signal to this form:
void dbConnected(QSqlDatabase *db);

And, in the slot side I'll use something like this:
void onDBConnected(QSqlDatabase * const db);

I'm concerned with the usage of db (as in the beginning I've made the reference const), so I make it const here (in the slot side). I've tried to do the same in the signal side with
void dbConnected(QSqlDatabase * const db);
But doing so I have the runtime error (mentioned in Qt Communication betwen threads, app design) back. So I tried another form, which seems to do the job:
void dbConnected(QSqlDatabase *db) const;

Am I in the right direction?

A:

Am I in the right direction?

Maybe. First, make sure that you know that you cannot pass the database to an object living in another thread. That was one of the major mistakes you did in the code in the other question. Don't do that anymore.
If you're passing an object via reference, it must be copyable. A QSqlDatabase is copyable after you open it. So you're OK here, too.
But you might not need to pass the database reference at all. QSqlDatabase assigns a name to each connection. Instead of passing the databases by value or by pointer, you can pass their connection names instead, and use QSqlDatabase::database to get a database object representing a given connection.
For example:
class Opener : public QObject {
  Q_OBJECT
  QSqlDatabase m_db;
public:
  Q_SIGNAL void dbOpened(const QString &);
  void open() {
    m_db.addDatabase("FOO", "cats");
    ...
    if (m_db.open()) emit dbOpened(m_db.connectionName());
  }
};

class DbUser : public QObject {
  Q_OBJECT
  QSqlDatabase m_db;
public:
  Q_SLOT void onDbOpened(const QString & conn) {
    m_db = QSqlDatabase::database(conn);
  }
  ...
};

As you can see, the dbOpened signal emits not a database, but a database connection name, and then the various objects that wish to use that connection can retrieve the database object (handle) by name.


Q:

code involving indexPath & NSIndexPath works - but why is it redundant?

I'm getting back to using CloudKit and in the project I'm revisiting, I have a query fetch performed and I am left with an array of CKRecords. I'm setting this array to be displayed via TableController.  Anyways, I have this one line of code (which works)... but I am just unsure why I am setting the indexPath as NSIndexPath.
 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "dining") as! table1cell
    let restaurant: CKRecord = categories[(indexPath as NSIndexPath).row]
    cell.Name.text = restaurant.value(forKey: "Name") as? String

    return cell

With my other non-CKRecord TableController projects, I know I don't have to set the indexPath to itself, in essence.  What am I missing here?

A:

The use of the cast to NSIndexPath is pointless. Simply change the line to:
let restaurant: CKRecord = categories[indexPath.row]


Q:

Hiding entire table resizes it

Having an HTML page with a simple table and js code to do show / hide on it:

    <title>title</title>

[click]

    s
    d
    a

What happens is that on Mozilla the table gets resized after you click twice(even with the table-layout: fixed css). IE works fine.

A:

Tables shouldn't be set to display: block.  Table rows and cells shouldn't either.  They have different display values.  My advice?  Don't do it this way.  Use a class:
.hidden {
  display: none;
}

and dynamically add it and remove it from the table to avoid problems of setting the right display type on an element that you show.
Edit: To clarify the comment as to why do it this way and what's going on.  Try this:

  Cell 1
  Cell 2

</table

It will (or should) screw up your table layout.  Why because a  element, by default, has display: table-cell not block.  Tables are the same.  They have display: table.
Unsetting CSS attributes is... problematic.
Thus you are best off using classes to set and unset attributes.  It's easier to change (the class resides in a CSS file and isn't code), avoids problems like setting the value back to the correct original value and generally provides a cleaner solution, especially when used with a library like jQuery.  In jQuery, you can do:
$("table").toggleClass("hidden");

Done.
Or you can use addClass() and removeClass() if that's more appropriate.  For example:
<input type="button" id="hide" value="Hide Table">
...

...

and
$(function() {
  $("#hide").click(function() {
    if ($("#mytable").is(".hidden")) {
      $("#hide").val("Hide Table");
      $("#mytable").removeClass("hidden");
    } else {
      $("#hide").val("Show Table");
      $("#mytable").addClass("hidden");
    }
  });
});

And there you have a robust, succinct and easy-to-understand solution (once you get your head around the jQuery syntax, which doesn't take that long).
Messing about with Javascript directly is so 2002. :-)


Q:

Writing CSV file using Spark and java - handling empty values and quotes

Initial data is in Dataset<Row> and I am trying to write to pipe delimited file and I want each non empty cell and non null values to be placed in quotes. Empty or null values should not contain quotes
result.coalesce(1).write()
            .option("delimiter", "|")
            .option("header", "true")
            .option("nullValue", "")
            .option("quoteAll", "false")
            .csv(Location);

Expected output:
"London"||"UK"
"Delhi"|"India"
"Moscow"|"Russia"

Current Output:
London||UK
Delhi|India
Moscow|Russia

If I change the "quoteAll" to "true", output I am getting is:
"London"|""|"UK"
"Delhi"|"India"
"Moscow"|"Russia"

Spark version is 2.3 and java version is java 8

A:

Java answer. CSV escape is not just adding " symbols around. You should handle " inside strings. So let's use  StringEscapeUtils and define UDF that will call it. Then just apply the UDF to each of the column.
import org.apache.commons.text.StringEscapeUtils;
import org.apache.spark.sql.Column;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import static org.apache.spark.sql.functions.*;
import org.apache.spark.sql.expressions.UserDefinedFunction;
import org.apache.spark.sql.types.DataTypes;

import java.util.Arrays;

public class Test {

    void test(Dataset<Row> result, String Location) {
        // define UDF
        UserDefinedFunction escape = udf(
            (String str) -> str.isEmpty()?"":StringEscapeUtils.escapeCsv(str), DataTypes.StringType
        );
        // call udf for each column
        Column columns[] = Arrays.stream(result.schema().fieldNames())
                .map(f -> escape.apply(col(f)).as(f))
                .toArray(Column[]::new);

         // save the result
        result.select(columns)
                .coalesce(1).write()
                .option("delimiter", "|")
                .option("header", "true")
                .option("nullValue", "")
                .option("quoteAll", "false")
                .csv(Location);
    }
}

Side note: coalesce(1) is a bad call. It collect all data on one executor. You can get executor OOM in production for huge dataset.


Q:

Обёртка в -col- лишняя?

Насколько корректно в bootstrap навешивать классы -col- на таблицу?
То есть вместо:

        ...

Сразу писать без обёртки в row и -col-:

        ...

Вроде бы в последних FF и Chrome работает как надо, но интересно вообще насколько корректно навешивать флексы (на них я так понимаю сделаны col в четвертом бутстрапе) на таблицу.

A:

Философский вопрос, так как можно сделать всё что угодно, и оно даже может работать. Но на мой взгляд это совершенно не корректно. col и row отвечают за сетку, и их не следует путать с другими элементами без надобности. Корректно было бы положить таблицу во внутрь col, ну или в ячейку положить row вместе c col. Сами бутстрап пишут, что весь контент должен оборачиваться в эти элементы, допустима любая вложенность. Не хочешь отступов - вешай no-gutters.
Если их совместить то как минимум, таблица вылезет за контент. Наглядный пример:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Контент

Контент, какой-то там контент...

            Таблица внутри col

            1
            2
            3
            4

            5
            6
            7
            8

                    row>col внутри ячейки

                    1

                    2

                    3

            10
            11
            12

          Таблица + col

          1
          2
          3
          4

          5
          6
          7
          8

          9
          10
          11
          12


Q:

Pandas DataFrame.to_csv() OSError: [Errno 22] Invalid argument and PermissionError: [Errno 13] Permission denied

I am writing a large number of financial time series datas to individual CSV files. In one instance I have found that the to_csv method repeatably fails but I cannot for the life of me figure out why. During the call to method to_csv everything just hangs for upwards of 10-15 minutes. Before crashing with the the error:

Traceback (most recent call last):   File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 172, in save
      self._save()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 274, in _save
      self._save_header()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 242, in _save_header
      writer.writerow(encoded_labels) OSError: [Errno 22] Invalid argument
During handling of the above exception, another exception occurred:
OSError: [Errno 22] Invalid argument
During handling of the above exception, another exception occurred:
Traceback (most recent call last):   File "securitiesArchives.py",
  line 1072, in
      out_df.to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None)     File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py",
  line 3020, in to_csv
      formatter.save()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 187, in save
      f.close() OSError: [Errno 22] Invalid argument

It seems to be hanging up while writing the header row of the csv file. I wrote the same frame to hdf, then loaded from hdf, and using the hdf loaded frame, reproduced the same (or very close to the same) failure:

Traceback (most recent call last):   File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 172, in save
      self._save()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 274, in _save
      self._save_header()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 242, in _save_header
      writer.writerow(encoded_labels) PermissionError: [Errno 13] Permission denied
During handling of the above exception, another exception occurred:
PermissionError: [Errno 13] Permission denied
During handling of the above exception, another exception occurred:
Traceback (most recent call last):   File "bad_archive.py", line 12,
  in
      #out_df.to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None)   File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py",
  line 3020, in to_csv
      formatter.save()   File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py",
  line 187, in save
      f.close() PermissionError: [Errno 13] Permission denied

Not sure why it changed from "OSError: [Errno 22] Invalid argument" to "PermissionError: [Errno 13] Permission denied" when moving from a larger code body to a small sample problem. I have searched for these errors in relation to the method to_csv and have seen that previous version of pandas may have had similar issues but this was supposed to be resolved in a later version. My pandas is:

INSTALLED VERSIONS
  ------------------ commit: None python: 3.7.3.final.0 python-bits: 64 OS: Windows OS-release: 10 machine: AMD64 processor: Intel64 Family 6
  Model 94 Stepping 3, GenuineIntel byteorder: little LC_ALL: None LANG:
  None LOCALE: None.None
pandas: 0.24.2 pytest: 5.0.1 pip: 19.1.1 setuptools: 41.0.1 Cython:
  0.29.12 numpy: 1.16.4 scipy: 1.2.1 pyarrow: None xarray: None IPython: 7.6.1 sphinx: 2.1.2 patsy: 0.5.1 dateutil: 2.8.0 pytz: 2019.1 blosc: None bottleneck: 1.2.1 tables: 3.5.2 numexpr: 2.6.9 feather: None
  matplotlib: 3.1.0 openpyxl: 2.6.2 xlrd: 1.2.0 xlwt: 1.3.0 xlsxwriter:
  1.1.8 lxml.etree: 4.3.4 bs4: 4.7.1 html5lib: 1.0.1 sqlalchemy: 1.3.5 pymysql: None psycopg2: None jinja2: 2.10.1 s3fs: None fastparquet:
  None pandas_gbq: None pandas_datareader: 0.8.1 gcsfs: None

I am on a win-10 64 bit machine using Anaconda Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
I have tried:

convert index to str to astype(str) prior to calling to_csv, same issue
dropna on index (rows) as there were a large number of NaN entries (originally this frame was part of a much larger multi index frame) problem persists
keyword arguments headers=False and index=False, neither changed the behavior.
Using .loc[] to slice first row only and perform to_csv on this

out_df.loc[out_df.index.values[0]].to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None)
which also failed. Even though this is now a series and no longer a frame as the following warning was produced

FutureWarning: The signature of Series.to_csv was aligned to that of
  DataFrame.to_csv, and argument 'header' will change its default
  value from False to True: please pass an explicit value to suppress this warning.

Tried again same method as above instead slicing the first two row to ensure it remained a frame and not converted to series

The entire two row DataFrame which refuses cooperation with to_csv
out_df.loc[out_df.index.values[0]:out_df.index.values[1]].to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None,index=False,header=False)
But this also failed as before. I was however, able to write the sequence of each column independently to its own CSV file without issue.
for col_name in out_df.columns:
   print('Writing '+col_name+' as CSV')
    out_df[col_name].to_csv(col_name.replace(' ','_')+"_PRN.csv",mode='w',encoding='UTF-8' ,compression=None)
    print('Done.')

Combined, the above success, and failure of the two row write attempt, makes me think this is not an issue related to specific columns values. Further, the tracebacks make me think this issues is related to writing the column headers. But the thing is I have 3000+ other DataFrames withe the exact same column labels and they write to csv using to_csv without issue. At this point I am out of my depth.
Failure occurs on this same set of data repeatedly whether I am using the data I wrote to hdf or using a fresh pull from yahoo using yfinance. The following code reliably recreates the issue on my system:
import pandas as pd
import yfinance as yf

good_df = yf.download(tickers='AAPL',interval='1m',period='7d')
bad_df = yf.download(tickers='PRN',interval='1m',period='7d')
print('Writing test case AAPL as CSV')
good_df.to_csv("AAPL.csv",mode='w',encoding='UTF-8' ,compression=None)
print('Writing test case PRN as CSV')
bad_df.to_csv("PRN.csv",mode='w',encoding='UTF-8' ,compression=None)

Anyone have any ideas?
PS - While re-reading I decided to check the column labels for equivalence and as far as a Boolean comparison is concerned those of the 'good' DataFrame and those of the 'bad' DataFrame as identical.
>>>print(good_df.columns)
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'], dtype='object')
>>>print(bad_df.columns)
Index(['Open', 'High', 'Low', 'Close', 'Adj Close','Volume'], dtype='object')
>>>print(good_df.columns == bad_df.columns)
[ True  True  True  True  True  True]

PPS - I also have tried removing all flags from to_csv though they should have been the default values. It was a carry-over from as used in other code and I was going through different values to see if it would work. The most basic to_csv call fails as before
import pandas as pd
import yfinance as yf

good_df = yf.download(tickers='AAPL',interval='1m',period='7d')
bad_df = yf.download(tickers='PRN',interval='1m',period='7d')
print('Writing test case AAPL as CSV')
good_df.to_csv("AAPL.csv")
print('Writing test case PRN as CSV')
bad_df.to_csv("PRN.csv")

Update In response to reply from Cheng
I can see no file in explorer or via dir in console. But to test this I used a new file name that was not the symbol "PRN" and lo'n'behold it works.
I did not think this was the issue as I already tried writing to a different destination folder, both in the larger parent code, and then in the toy problem. Neither worked.
It would seem that windows has an old reference to any old file named "PRN.csv" or something....how frustrating. Lets hope a simple restart fixes it.
Thanks!

A:

I literally had this same problem earlier today, but since I was working with much smaller data, the solution was easier to spot.
When a file is opened in another program, you cannot write or append to it. Check for places where you might have forgotten to close() or if it's open for viewing in Microsoft Excel.
Also generally it's better to use open('file', 'a') to write in case there's any previous data you stored there. If not, it will do the same as open('file','w') and create a new file.


Q:

Does consistency imply completeness?

A deductive theory is consistent if no two asserted statements of this theory contradict each other.
A theory is called complete if of any two contradictory sentences at least one sentence can be proved within this theory.
I could (I guess) rewrite the definition as:
"A theory is called complete ↔ if there are any two contradictory sentences, then at least one sentence can be proved within this theory."
So, by my understanding, if a theory is consistent then there are no statements that contradict each other, and if there are not statements that contradict each other, the antecedent of the conditional "if there are any two contradictory sentences, then at least one sentence can be proved within this theory" is false, which means that the sentence is true, which means that it is consistent. Is this correct?
if not how can a theory be consistent and incomplete?

A:

No.
Consider a silly theory which proves $\vdash p$ for every atomic propositional letter $p$ and nothing else.
Clearly, this theory is consistent, because without negative formulas, there is no way a contradiction could be derived.
However, it is also not complete, because we have e.g. neither $\vdash p \to p$ nor $\vdash \neg (p \to p)$, because there is no axiom or rule that allows to introduce complex formulas.

The definitions could be re-written as follows:

A theory is consistent
$\Leftrightarrow$ For any two contradictory
  statements of the language, not both are in the theory.
$\Leftrightarrow$  For any statement $\phi$, if $\vdash \phi$ then
  $\nvdash \neg \phi$ and if $\vdash \neg \phi$ then $\nvdash \phi$.
A theory is complete
$\Leftrightarrow$ For any two contradictory
  statements of the language, at least one is in the theory.
$\Leftrightarrow$ For any statement $\phi$, if $\nvdash \phi$ then
  $\vdash \neg \phi$ and if $\nvdash \neg \phi$ then $\vdash \phi$.

The first does not entail the second: "$\nvdash \phi$ and $\nvdash \neg \phi$" for some statement $\phi$ (such as $\phi := p \to p$ above) is compatible with consistency, but not completeness.

The problem with your reasoning is here:

"if there are any two contradictory sentences"

This means any two contradictory sentences in the language, not in the theory. The antecedent is not restricted to those statements that can already be proven -- then, if the theory is consistent, the implication would indeed be vacuously true -- but to all conceivable statements that are well-formed formulas of the language -- and there are infinitely many contradictory pairs of well-formed statements $\phi, \neg \phi$ that make the antecedent true.

There is the notion of maximal consistency

A theory is maximally consistent
$\Leftrightarrow$ the theory is consistent and every proper superset of the theory is inconsistent (i.o.w., adding any more statements to the theory would render it inconsistent)

which does entail completeness.


Q:

Mass Assignment Issue Rails 3

I've searched for an answer this this on SO and haven't found it. I'm getting this error: Can't mass-assign protected attributes: Brand, Details, Product, Code
I'm uploading csv data from a file into my rails db. Here is the import action from the upload page controller:
def import
     Item.import(params[:file])
     redirect_to root_url, notice: "Products imported."
end

The attr_accessible line from Item model:
attr_accessible :brand, :details, :img, :product, :code

I'm using Devise, not sure if that is part of the problem? Do I need to do something in my User model to make this work? Thanks in advance.
Here's the self.import method from Item:
  def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
    Item.create! row.to_hash
   end
  end

A:

This is a tip on general debugging — you could also for curiosity's sake take a look at what params is at this point or use pry
def import
  raise StandardError, params.inspect
end

I also recommend that you use Strong Parameters and I have detailed a clean approach on my blog that you may find useful: Bootstrapping Strong Parameters in Rails.


Q:

What are these dishes looking at?

In this CSA video CSA Astronaut Chris Hadfield describes the attitude control of the ISS and its importance for things like communication with Earth.
At 00:30 here is about a 2 second vignette of these four identical fixed dish antennas all apparently pointing in the same direction -- in the general direction of the Sun, which would be south if this is in North America.
Are these used to communicate or control the ISS, or is this just commercial stock footage of a cable tv station?

A:

It's stock footage. Here's the source: https://www.shutterstock.com/video/clip-3547922-stock-footage-satellite.html?src=search/j9qjEB4D-XcqsNoqfQWZrA:1:4/gg


Q:

Finding the number of two consecutive vowels in a string does not work

When two vowels come one after another then the count should increment.But i dont know why its incrementing it more than that.
#include<stdio.h>
#include<conio.h>
void main(void)
{
    int i,j,count=0;
    char string[80];
    printf("Enter a string:\n");
    gets(string);
    for(i=0; ;i++)
    {
        if(string[i]=='\0')
            break;
        if(string[i]=='a'||string[i]=='A'||string[i]=='e'||string[i]=='E'||string[i]=='i'||string[i]=='I'||string[i]=='o'||string[i]=='O'||string[i]=='u'||string[i]=='U')
        {
            if(string[i+1]=='a'||string[i]=='A'||string[i]=='e'||string[i]=='E'||string[i]=='i'||string[i]=='I'||string[i]=='o'||string[i]=='O'||string[i]=='u'||string[i]=='U')
            count++;
        }
    }
    printf("%d",count);
    getch();
}

A:

Looks like you have a typo here, your code:
if(string[i]=='a'||string[i]=='A'||string[i]=='e'||string[i]=='E'||string[i]=='i'||string[i]=='I'||string[i]=='o'||string[i]=='O'||string[i]=='u'||string[i]=='U')
{
    if(string[i+1]=='a'||string[i]=='A'||string[i]=='e'||string[i]=='E'||string[i]=='i'||string[i]=='I'||string[i]=='o'||string[i]=='O'||string[i]=='u'||string[i]=='U')
        count++;
}

Notice the second if statement there, everything except the first condition is checking string[i] instead of string[i+1].  So if you have 'A' in string[i], then this will increment count no matter what is in string[i+1].
You want:
if(string[i]=='a'||string[i]=='A'||string[i]=='e'||string[i]=='E'||string[i]=='i'||string[i]=='I'||string[i]=='o'||string[i]=='O'||string[i]=='u'||string[i]=='U')
{
    if(string[i+1]=='a'||string[i+1]=='A'||string[i+1]=='e'||string[i+1]=='E'||string[i+1]=='i'||string[i+1]=='I'||string[i+1]=='o'||string[i+1]=='O'||string[i+1]=='u'||string[i+1]=='U')
        count++;
}

I also recommend you look up the function tolower which will lower-case a character, meaning you need to do less comparisons which will make this code much easier to read and maintain.  Also you might consider using a switch or any array hereand probably writing a helper function.
I guess I just can't stand this code as it is, here's a better version:
int is_vowel(char ch)
{
    switch (tolower(ch))
    {
    case 'a': case 'e': case 'i': case 'o': case 'u':
        return 1;
    default:
        return 0;
    }
}

And then make your if statement:
if (is_vowel(string[i]) && is_vowel(string[i+1]))
    count++;

See, much cleaner and easier to read, don't you think?

A:

For once, be as lazy as you can. If you have to repeat a portion of code, ask yourself if you can't do it without repeating.
I would have gone for that :
#include <stdio.h>
#include <string.h>
#include <ctype.h>

const size_t MAX_LENGTH = 100;

//Counts the occurrences of two consecutive same characters
//in a string, without case
size_t cnt_doubled(char const * const str, int c) {
    size_t ret = 0;

    //A pointer browses the string until terminating char and
    //increments ret if the pointed char is the one seeked
    //two chars in a row
    for(char const *p = str ; *p != '\0' ; ++p) {
        ret += tolower(*p) == tolower(c) && tolower(*(p+1)) == tolower(c);
    }

    return ret;
}

//Explicit...
size_t cnt_doubled_vowels(char *str) {
    char const *vowels = "aeiouy";

    //A pointer browses the vowels and takes into account
    //the occurrences in the string of every char pointed
    size_t n_vowels = 0;
    for(char const *p = vowels ; *p != '\0' ; ++p) {
        n_vowels += cnt_doubled(str, *p);
    }

    return n_vowels;
}

int main(void) {
    //fgets returns a string terminated by a newline char (before
    //terminating char of course) but in your case it doesn't
    //matter
    char string[MAX_LENGTH] = "";
    fgets(string, MAX_LENGTH, stdin);

    printf("N : %d", cnt_doubled_vowels(string));

    return 0;
}


Q:

Trying to create a login screen With Adndoid SDK 2.3.3

I am Completely new to Android SDK and very new to writing code in general. I have been monkeying with the software and following a tutorial on how to make a login for my app but I just can't seem to get it to work. Below is my .Java Code. I can tell that the error is in line 32-42, I don't know why I it does not detect .settext or .SetOnClickListner. Any help would be great.
package com.example.inventory;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

private EditText User;
private EditText Password;
private TextView Info;
private Button Login;
private int counter = 5;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    User = (EditText) findViewById(R.id.etName);
    Password = (EditText) findViewById(R.id.etPassword);
    Info = (TextView) findViewById(R.id.tvInfo);
    Login = (Button) findViewById(R.id.btnLogin);
}

Info.setText("No of attemps remaining: 5");

Login.SetOnClickListener(new View.OnClickListener()

{
    @Override
    public void onClick (View view){
    validate(Name.getText().toString(), Password.getText().toString());
}
};

}
private void validate(String userName, String userPassword) {
    if ((userName.equals("Admin")) && (userPassword.equals("Pass"))) {
        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        startActivity(intent);
    }else{
        counter--;

        if (counter== 0){
            Login.setEnabled(false);
        }
    }
}

}

A:

Your .setText() code is outside of the onCreate method. There is not a process to call the .setText() method. Just move the code inside of the bracket above it. Same goes for your OnClickListeners. You were also missing a parenthesis at the close of your OnClickListener.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    User = (EditText) findViewById(R.id.etName);
    Password = (EditText) findViewById(R.id.etPassword);
    Info = (TextView) findViewById(R.id.tvInfo);
    Login = (Button) findViewById(R.id.btnLogin);

    Info.setText("No of attemps remaining: 5");

    Login.SetOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view){
        validate(Name.getText().toString(), Password.getText().toString());
        }
    });
}


Q:

How to set the pandas dataframe data left/right alignment?

I use pd.set_option("display.colheader_justify","right") to set the column header. But I can't find the option for data by pd.describe_option().
How to set the data within a dataframe display left or right alignment for each column? Or, is it possible to define a format template for the whole row data display?

A:

If you want to change the display in a Jupyter Notebook, you can use the Style feature.
# Test data
df = DataFrame({'text': ['foo', 'bar'],
                 'number': [1, 2]})

df.style.set_properties(**{'text-align': 'right'})

A:

The answer given by @Romain is great but I would like to summarize some comments:
# Test data
df = DataFrame({'text': ['foo', 'bar'],'number': [1, 2]})

dfStyler = df.style.set_properties(**{'text-align': 'left'})
dfStyler.set_table_styles([dict(selector='th', props=[('text-align', 'left')])])

will align all table text and the column headers as well.


Q:

Is there a max number of answers per day

The question pretty much says it all, Is there a max number of answers per day. While I'm at it is there a max number of questions.
If there isn't does anyone think it should be implemented.

A:

You can give as much answers as you like per day.
But you will only get max 200 rep from upvotes a day. After you reach that limit (called rep-cap) you will only get more rep for accepts and bounties.


Q:

How can I get UTM attributes in android?

I want to track UTM attributes to track the sources that are bringing users to my app and store them in database but after spending more than two days I have not found anything useful on google.

A:

You need to register a broadcast receiver which will automatically trigger on your app first open, you can use the below example to achieve this,
public class InstallTrackersReceiver extends BroadcastReceiver {
    private static final String KEY_REFERRER = "referrer";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Install Referrer", "onReceive");
        if (intent != null && !intent.getStringExtra(KEY_REFERRER).equalsIgnoreCase("")) {
            Log.i("Referrer", intent.getStringExtra(KEY_REFERRER));
        } else {
            Log.e("Install Referrer", "not found");
        }
    }
}

In your manifest, register your receiver like below,
        <receiver
            android:name="InstallTrackersReceiver"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.INSTALL_PACKAGES">
            <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
            </intent-filter>
        </receiver>

Updated
You can use the following adb command to test install referrer,
adb shell am broadcast -a com.android.vending.INSTALL_REFERRER -n <your.package>/.<path.up.until.your.InstallTrackersReceiver> --es "referrer" "utm_source=test_source\&utm_medium=test_medium\&utm_term=test_term\&utm_content=test_content\&utm_campaign=test_name"


Q:

Leads per Week For Last 10 Weeks Formula With Countif

I have a long list of dates (like below) that indicate Leads and I am trying to get number of leads per week for the last 10 weeks. I know I can get the current week number with MID(TEXT(Today(),"yyww"), 3, 2). I’ve researched and think countif and arrayformula might get me there but I don’t know how to apply them. Countif the week that a date corresponds to equals the current week, and the year is the current year. Seems simple enough but I can't quite figure out this countif.
These are the dates:
12/30/2013
12/9/2013
12/12/2013
12/23/2013
12/30/2013
12/5/2013
1/2/2014
1/2/2014
1/2/2014
1/6/2014
1/6/2014

A:

Perhaps in a helper column (say B assuming data is in A):
=if(year(A1)=year(now()),weeknum(A1),"")

to identify entries in the latest 10 weeks (by week number) by row and a table in rows1:10 of:
=weeknum(now())-10+ROW()

for one column (say E) and:
=countif(B:B,E1)

for another, with all formulae copied down to suit.


Q:

Scrollable PDF in Rails - ActiveStorage

I am building a Rails website where the a user can upload a paper and another user can review/read it.
I used ActiveStorage to save the PDF.
Thanks to ActiveStorage, a user can preview the PDF (showing the first page), open it in another browser tab and download it.
HOWEVER I would like the user to be able to scroll through the PDF (since each PDF is longer than I page). The Preview does not allow me to do so because it displays only the first page.
In my show.html.etb I have these two link_to:
<%= link_to "Open the paper", @paper.paper_pdf, target: :_blank, :class => "btn btn-warning" %>
<%= link_to image_tag(@paper.paper_pdf.preview(resize: "1000x1000")), @paper.paper_pdf, target: :_blank %>
<%= link_to "Download the PDF", rails_blob_path(@paper.paper_pdf, disposition: :attachment), :class => "btn btn-success" %>

What do you suggest to use to display the paper and make it scrollable?

A:

I solved it using iframe.
<iframe src=<%= url_for(@paper.paper_pdf) %>
 width="700" height="780" style="border: none;"></iframe>

With <%= url_for(@paper.paper_pdf) %> I get the URL of where my PDF is stored. It works on localhost, not sure if it works on a real server.


Q:

Windows Events for Remote Desktop logon failure

According to ref the logon types 10 and 3 in windows events are represnting
Logon Type 10 = RemoteInteractive Logon
&
Logon Type 3  = Network Logon
But when i tried to connect a Windows machine via "Remote Desktop Connection" with a wrong username and password, remote machine generating  events with logon type 3 instead of 10. I checked with a lot machines. But still this is happening.
Could you explain why this happening?
log another details : event all details
Screenshots

A:

You will get this logon type 3 when you are using NLA (Network Layer Authentication) as the authentication type since it will try and pre-authenticate you prior to giving you RDP access.
You can test this by changing the security layer to RDP Security Layer.  Instructions and detailed information on how to do so are found here: Configure Server Authentication and Encryption Levels -- You should then find when typing an invalid username/password combination that it now logs it as logon type 10.


Q:

How to decrease a value of a variable based on a user input?

I can usually find the answer to questions without posting but I'm completely stuck here so I appreciate any help.
I am creating a cost calculator using Javascript & jQuery which needs to be able to give discounts based on the number of licences entered. My costs for the calculator are as follows:

1-49 Licences = £50 per licence (this is nice and simple)
50 - 249 Licences = Starts at £49.90 per licence but the per licence cost will decrease by 0.10 for each additional licence. For example 50 licences would cost £49.90 per licence, 51 licences would cost 49.80 per licence and so on.
250+ Licences = No calculation, a message will be displayed to call.

My Question: I have created a LicenceCost variable to store the cost per licence which I can use for calculation. How can I set this variable to account for the 0.10 discount for each licence above 49?
All the articles I have read recommend to use multiple if...else statements which I don't think works well in my case as I would have 200 of them for a little calculator. I might have gone about this the wrong way so if I need to take a different approach I'm open to ideas and I will happily start again!
Thanks for any help, I have included a snippet below for reference.
Note: The cost calculator is not being used for any payments, it's just for illustration so I am not concerned about doing this client side.

$('#NumberOfLicencesInput').bind('input', function() {
  // Get number of selected licences
  var SelectedLicences = document.getElementById('NumberOfLicencesInput').value;

  // Output number of selected licences
  document.getElementById("NumberOfLicencesOutput").innerHTML = SelectedLicences;

  // if selected number of licences is less than 50 then the licence cost is 50 and the total cost is calculated
  if (SelectedLicences < 50) {
    LicenceCost = 50;
    TotalCost = LicenceCost * SelectedLicences;
    document.getElementById("TotalCost").innerHTML = TotalCost
  }
  // if selected number of licences is more than 49 then the licence cost should starts at 49.90 but should decrease by 0.10 for each additional licence I.E 50 = 49.90, 51 = 49.80 etc...
  else if (SelectedLicences > 49 && SelectedLicences < 250) {
    LicenceCost = 49.90;
    TotalCost = LicenceCost * SelectedLicences;
    document.getElementById("TotalCost").innerHTML = TotalCost
  }
  // if 250 or above display a message to call
  else {
    document.getElementById("TotalCost").innerHTML = "Please Call";
  }

});

<input type="number" id="NumberOfLicencesInput"></input>

    Number of Licences:

    Total Cost:

A:

Use LicenceCost = 50.00 - (SelectedLicences-49)*.10; to calculate licence cost when the no. of licences is greater than 49.
Like in the below snippet.

$('#NumberOfLicencesInput').bind('input', function() {
  // Get number of selected licences
  var SelectedLicences = document.getElementById('NumberOfLicencesInput').value;

  // Output number of selected licences
  document.getElementById("NumberOfLicencesOutput").innerHTML = SelectedLicences;

  // if selected number of licences is less than 50 then the licence cost is 50 and the total cost is calculated
  if (SelectedLicences < 50) {
    LicenceCost = 50;
    TotalCost = LicenceCost * SelectedLicences;
    document.getElementById("TotalCost").innerHTML = TotalCost
  }
  // if selected number of licences is more than 49 then the licence cost should starts at 49.90 but should decrease by 0.10 for each additional licence I.E 50 = 49.90, 51 = 49.80 etc...
  else if (SelectedLicences > 49 && SelectedLicences < 250) {
    // this does the trick
    LicenceCost = 50.00 - (SelectedLicences-49)*.10;
    console.log(LicenceCost); // just to log value to console
    TotalCost = LicenceCost * SelectedLicences;
    document.getElementById("TotalCost").innerHTML = TotalCost
  }
  // if 250 or above display a message to call
  else {
    document.getElementById("TotalCost").innerHTML = "Please Call";
  }

});

<input type="number" id="NumberOfLicencesInput"></input>

    Number of Licences:

    Total Cost:


Q:

C++: Conflicts with a previous declaration?

I'm working on this assignment, and I keep getting an error for an apparently previously declared method. Here is the .h file:
#ifndef DLLIST_H
#define DLLIST_H

#include <iostream>
#include <fstream>
#include <cstddef>
#include "DListNode.h"

typedef int ItemType;

class DLList
{
private:
  friend std::ostream & operator<< (std::ostream & out, DLList & other);
  int size;
  int * head;
  int * tail;

  void _copy(const DLList * toCopy);
  void _dealloc();

public:
  DLList();
  DLList(const DLList & toCopy);

  ~DLList();

  DLList & operator=(const DLList & toCopy);

  int size();
  void append(ItemType item);
  void insert(int index, ItemType item);
  ItemType pop(int index);
  ItemType pop();
  const DListNode & operator[] (int idx);

};

std::ostream & operator<< (std::ostream & out, const DLList & d);

#endif

The error is being triggered at int size();, saying it conflicts with a previous declaration. I know this normally would arise from me including this header file multiple times, but I just don't see where it is happening. These are the include statements for all the files in the project:
#include "DLList.h" // DLList.cpp
=======================================
#include "DListNode.h" // DListNode.cpp
=======================================
#include <iostream> // DListNode.h
#include <fstream>
#include <cstddef>
=======================================
#include "DLList.h" // This is the main test file
#include "DListNode.h"
#include <iostream>

I can see that DListNode.h is technically being included twice, but nowhere is DLList.h included more than once. Am I just making a stupid mistake and not seeing it? (Probably the case). Thanks for any help!

A:

It is because you have a member variable also named size. You can fix this issue by renaming one of them.
int size;
...
int size();


Q:

Calendar roll affects other calendar

I have a piece of code I dont quite understand. Its causing a bug.
There's a Calendar object and a method which writes this calendar object to a string, but increments the year first. however, even though there are 2 Calendar objects, they are both being rolled.
See the method that does the roll below
public static synchronized Calendar rollDatePlus1Year(Calendar currentDate){
    Calendar rtn = currentDate;
    rtn.roll(Calendar.YEAR, 1);
    rtn.roll(Calendar.MINUTE, -1);
    return rtn;
}

from this both "currentDate" and "rtn" are incremented by a year. This method should not change any values, but return a new represenation.
Any ideas?

A:

Line Calendar rtn = currentDate; assigns reference to object to other variable. From this point rtn and currntDate refer to the same object. If you want, the same place in memory. Therefore all changes done using one of these references are visible using the second one because are done on the same object.


Q:

Listening to an unlimited number of sockets in python

I was wondering, if I want to listen to each socket that wants to join,
what do I need to write inside the
sock.listen(?)
What number goes there and tells python "I want to listen to everyone" and not to a limited number of sockets.
I thought about just putting a large number, but I feel it's not the right answer.
Thanks for the helpers!!

A:

See this answer where John la Rooy says:

The doc say this

socket.listen(backlog) Listen for connections made to the socket. The
    backlog argument specifies the maximum number of queued connections
    and should be at least 1; the maximum value is system-dependent
    (usually 5).

Obviously the system value is more than 5 on your system. I don't see
  why setting it to a larger number would be a problem. Perhaps some
  memory is reserved for each queued connection.
My linux man page has this to say

If the backlog argument is greater than the value in
    /proc/sys/net/core/somaxconn, then it is silently truncated to that
    value; the default value in this file is 128. In kernels before
    2.4.25, this limit was a hard coded value, SOMAXCONN, with the value 128.


Q:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 269

I am writing a program that counts the number of words in a text file, but only words that have more than 2 characters in them. It was working fine before, but all of a sudden I am getting an error

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 269?

Can someone please help?
import java.io.*;

class count_words {

    public static int countWords(String str)
    {
        int count = 1, num_of_letters = 0, final_count=1;

        for (int i=0;i<=str.length()-1;i++)
        {
            if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
            {
                if(num_of_letters <= 2)
                {
                    count --;
                }

                System.out.println("count is " + num_of_letters);
                num_of_letters = 0;
                count++;
            }
            else if(str.charAt(i) == ',')
            {
                num_of_letters --;
            }
            else
            {
                num_of_letters++;
            }
        }

        return count;
    }

    public static void main(String[] args){

        //name of file to open
        String fileName = "/Users/Chris/Desktop/comp 1 McPhee.txt";
        //reference one line at a time
        String line = null;
        int num;

        try
        {
            //Filereader reads text file in the default encoding.
            FileReader filereader = new FileReader(fileName);
            BufferedReader bufferedreader = new BufferedReader(filereader);

            while ((line = bufferedreader.readLine()) != null)
            {
                num = countWords(line);
                System.out.println(num);
            }
        }

        //Always close file
        catch(FileNotFoundException ex)
        {
            System.out.println("Unable to open file '" + fileName + "'");
        }

        catch(IOException ex)
        {
            System.out.println("Error reading file '" + fileName + "'");
        }
    }
}

A:

The source of your problem is up here.
public static int countWords(String str)
{
  int count = 1, num_of_letters = 0, final_count=1;

  for (int i=0;i<=str.length()-1;i++)
  {
    //This line
    if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')

Because you let i go all the way to str.length()-1, str.charAt(i+1) will exceed the last index position.
For the word "taken"
str.length() = 5;
Index positions 0-4.
When i is 4, src.charAt(i+1) will go for 5.
I think this will solve it.
    if (str.charAt(i) == ' ' && ((i+1) < str.length()) && str.charAt(i+1)!=' ')


Q:

Rails Devise confirmable for some users but not others

I have a Rails app that is using Devise.  Is it possible to have some users confirmable and others not?
The users table has a boolean field called admin.
We add the admin users programmatically using Mule and rest (so we know the email addresses are correct).
The other types of users are self registering and admin is false.
We want the self registering people to get a confirmation email but not the admin users.
UPDATE1
I create the user in the employee.rb file.  I changed the code to this:
  before_create :create_user

protected
def create_user
  self.user = User.create({ :email => self.email, :password => '123456', :admin => true  })
  user.skip_confirmation!
  return user.save

end

This worked.

A:

While adding your admins you can call skip_confirmation! on the user object - before it's being saved. This will prohibit the confirmation process.


Q:

Why form in a form doesn't work in internet explorer

I add a form from code behind to asp:PlaceHolder control.
When I add form to placeholder <form> tags are missing.
Asp.net removes it from some reason.
But I have found workaround for this. I have added (empty form):
<form></form>
<form... my form code that comes from code behind...

And this works fine in all browsers except IE!
Any idea how to workaround this in IE.
(Maybe this is important) This form is actually a PayPal button code and I get it from data source.
I need to add 10 buttons on page:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" ...

A:

One of the dissadvanced of the asp.net webforms is that only one asp.net form is allowed in a normal asp.net page. One form that have the runat="server" and inside that form only the asp.net controls correctly work and cooporate with the code behind.
However you can break that - but not continue to have the same asp.net functionallyty. What you can do is to use a LiteralControl and direct render on the page the PayPal button code and only before just close the global form by using the </form>. Only the close just before add the new ones.
Now the moment you do that, you must forget the post back on the same page and actually have it only for post to PP. The only way to have some asp.net page functionallyty is to keep it before the first form close, and set on web.config the option to keep the validation on top.
So you start with
<form  name="aspnetForm" method="post" action="/ui/login.aspx?ReturnUrl=General.aspx" >
  ... some controls that post back to aspx page
</form>

and you end up with
<form  name="aspnetForm" method="post" action="/ui/login.aspx?ReturnUrl=General.aspx" >
  ... some controls that post back to aspx page
  ... up to here maybe the buttons will work for the page, after that not any more
 </form> //<---- added by you
  // follow the PayPal buttons
  <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
  <input type="hidden" name="cmd" ... >
  </form>

  // second button, etc
  <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
  <input type="hidden" name="cmd" ... >
  </form>
// now this close form is orphan....
</form>

Alternative you can make post redirect, but require a lot more code and  a middle page that create the PayPal post data on code behind. Here is an example http://www.codeproject.com/Articles/37539/Redirect-and-POST-in-ASP-NET
The same trick you can do it with javascript, create a form using javascript on the fly and post that to the paypal button, all on the same page with javascript.
I have use all that techniques, all of them works.


Q:

Setting Content via Response Object in Components

Can someone explain to me why the following code isn't outputting anything in a component? Does the response object in a component behave differently from that in an action (since the code works as part of an action)?
I am using Symfony 1.4.
$this->getResponse()->setContent("OK");

Code block:
class merchantComponents extends sfComponents
{
  .....
  public function executeAjaxrcmc(sfWebRequest $request)
  {
    $company_user_id = $this->getRequestParameter('ids');

    if(($company_user_id>0) && $request->isMethod('post'))
    {
        $this->getResponse()->setContent("OK");
        return sfView::NONE;
    }
    else
    {
        $this->getResponse()->setContent("FAIL");
        return sfView::NONE;
    }
  }
....
}

Thanks in advance!

A:

I think you probably need to send the content after setting it:
$this->getResponse()->sendContent();

Or, output it in a template file.
<?php echo $sf_response->getContent(); ?>


Q:

'rbenv install 2.0.0-p247' fails

i already discussed this issue with the maintainer of ruby-build and followed his advice by googling for similar errors. i found similar ones but they do not seem to match my specific problem:
i'm trying to install ruby with rbenv install 2.0.0-p247 (using the ruby-build plugin) on archlinux – but the command fails.
here the last 10 log lines:
rbconfig.rb updated
generating enc.mk
compiling dln.c
compiling encoding.c
generating prelude.c
compiling prelude.c
linking static-library libruby-static.a
verifying static-library libruby-static.a
collect2: error: ld returned 1 exit status
make: *** [libruby-static.a] Error 1

i would appreciate any hints on this problem – thanks!

A:

To find out what's wrong here, the best bet is to run the Ruby installation yourself to see exactly what's amiss. ruby-build typically downloads and extracts Ruby in /tmp (it should be the same path where it also saves the log file of the failed install).
Go to that directory and run:
$ ./configure
$ make

To see if you get the same error. If you do, then try to re-run the command that failed again. In your case this is probably:
$ ranlib libruby-static.a

To see why it fails.


Q:

get long from bytearray of 4 bytes in android

I am working on android and trying to read tcp socket , my tcp server is sending array of bytes which is created from array of long .
In my android code i am able to read array of bytes but unable to got long values from this array .
My code is as below .

while (true)
                        {
                            if(isClosed){break;}
                            message = "";
                            //byte[] buffer=new byte[4];
                            if (socket != null)
                            {
                                try
                                {
                                    int bytesRead;
                                    InputStream inputStream = socket.getInputStream();
                                    byte[] data = new byte[44];
                                    while ((bytesRead=inputStream.read()) != -1)
                                    {
                                        int count = inputStream.read(data);
                                        bytearraytolong(data);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Log.i("ThreadTask","readFromStream: "+ e.getMessage());
                                }
                            }
                            else
                            {
                                Log.i("ThreadTask", "SocketConnection : Cannot Read, Socket is closed");
                            }
                        }

private void bytearraytolong(byte[] bf)
{
    // how to get long here
}

here my tcp server sending data of 44 bytes so it have 11 long type values ,
i want to back orignal value in my android application "bytearraytolong" method

A:

I suggest looking at ByteBuffer (http://developer.android.com/reference/java/nio/ByteBuffer.html).
You might also want to check to make sure the server is serializing the type consistently with how you are deserializing; the byte order can vary in some cases.
Also, if your server is only sending 44 bytes, then you probably are dealing with ints, not longs.  Longs are 8 bytes.
The snippet of code you are looking for would be
private Long readLongFromBytes(byte[] bytes) {
  ByteBuffer bb = ByteBuffer.wrap(bytes);
  return bb.getLong();
}


Q:

Custom vs. non-custom attributes?

Something which implements the ICustomAttributeProvider interface will allow you to get custom attributes that have been applied to it via the GetCustomAttributes method.  As I understand it, a custom attribute is basically a special class (ending in "Attribute" and extending the Attribute class) that is created to be applied to something like a method or class using the appropriate syntax ([FooAttribute] just before the method/class/etc. in C#, for example).  But if that is a custom attribute, what is a non-custom attribute?  I used to think that attributes that were bundled with .NET were non-custom, but GetCustomAttributes even returns me attributes like System.ThreadStaticAttribute, which are very core to the .NET framework.
Is there such a thing as a non-custom attribute, or is "custom attribute" just a tautology?

A:

Everything that derives from Attribute is a custom attribute.
"Attribute" is a generic term. Objects in the real world have innumerable attributes. Classes, members and parameters all have attributes that we can describe -- names, types, accessors, number of members, inheritance information, etc.
Custom attributes are things that we tack on -- aspects that we want to associate and use to describe, but which are not intrinsic.

A:

I don't know if the following has any relevance, but if you say
var a = typeof(string).Attributes;

you get a value of a flags enum type called TypeAttributes. Maybe these flags are the "non-custom" attributes of the type?


Q:

Transitions Stopped Working after Xcode Update

Today I updated Xcode and then all my transitions in all my apps from the last few years stopped working. I tested running them on the new simulators and also by installing to iOS13.2 devices. However, transitions work fine when I download any of my apps from the App Store. I will try new builds on test flight in a moment. Maybe I've been doing something wrong al along these years?
Transition Code
let details = self.storyboard?.instantiateViewController(withIdentifier: "ViewSettings")
details?.transitioningDelegate = self.slideAnimatorLeft
self.present(details!, animated: true, completion: nil)

Transition Class
class SlideAnimatorLeft: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {

    let duration = 0.9

    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return duration
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) else {
            return
        }

        guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else {
            return
        }

        let container = transitionContext.containerView

        let screenOffUp = CGAffineTransform(translationX: container.frame.width, y: 0)
        let screenOffDown = CGAffineTransform(translationX: -container.frame.width, y: 0)

        container.addSubview(fromView)
        container.addSubview(toView)

        toView.transform = screenOffUp

        UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: [], animations: {

            fromView.transform = screenOffDown
            fromView.alpha = 1
            toView.transform = CGAffineTransform.identity
            toView.alpha = 1

        }) { (success) in
            transitionContext.completeTransition(success )
        }
    }
}

A:

add this line your code.
 details?.modalPresentationStyle = .fullScreen

// complete code
 let details = self.storyboard?.instantiateViewController(withIdentifier: "CollectionViewController")
 details?.transitioningDelegate = self.slideAnimatorLeft
 details?.modalPresentationStyle = .fullScreen
 self.present(details!, animated: true, completion: nil)


Q:

Pass value from another page to MainPage.xaml in Silverlight when using Navigation?

I have a Page in Silverlight which is Navigated from the MainPage.xaml, called OpenPage.xaml, I then want to pass a value back to the MainPage.xaml - this OpenPage.xaml is called using this:
NavigationService.Navigate(new Uri("/OpenPage.xaml", UriKind.Relative));

From the mainpage - this is not a child of the MainPage as the RootVisual is replaced - I can call this:
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

To return to the MainPage - however I need to pass a value from OpenPage.xaml to the MainPage.xaml - how to I access the MainPage instance - I have a Property called Document however when I do this:
        MainPage m = (MainPage)Application.Current.RootVisual;
        m.Document = "Hello World";

Or this:
((MainPage)root).Document = "Hello World";

I get an invalid cast exception because I think it is trying to cast the OpenPage.xaml to MainPage.xaml - how to I get the NavigatedTo Page, I want to set the property on MainPage.xaml from OpenPage.xaml.
I also want to pass values from the MainPage.xaml to another page SavePage.xaml - but this has the same issue - how do I resolve this?

A:

Use a query string value:-
NavigationService.Navigate(new Uri("/MainPage.xaml?value=Hello%20World", UriKind.Relative);

MainPage can then acquire this value using:-
string value =  this.NavigationContext.QueryString["value"];

Edit:
In response to comment re passing other types.
Once you have the above inplace you can use other service patterns to pass other types.  For example consider a MessageService that implements:-
interface IMessageService
{
    Guid Store(object value)
    object Retrieve(Guid key)
}

You would then implement this interface and expose the implementation as singleton say:-
public class MessageService : IMessageService
{
    public static IMessageService Default { // singleton stuff here }
}

Your OpenPage calls MessageService.Default.Store and places the resulting Guid in the query string.
The MainPage then tests for the presence of such a query string value, if present uses its value to call MessageService.Default.Retrieve which removes the item from the service.


Q:

tokenize/untokenize python string code so that it is compatible with interactive-mode

I have python code like that has this kind of structure
def main:

    ''' comment '''
    if True:
        print "do"
    print "done

This code is not compatible with the interactive-mode (for example if I copy/paste it in an interactive session). For this it would need to be :
def main:
    ''' comment '''
    if True:
        print "do"

    print "done"

otherwise the interactive mode breaks on Indentation problems.
Do you know a simple way to transform the code with the generate_token / untokenize chain ? I am a bit lost in the NL / NEWLINE / INDENT / DEDENT semantics.
I found this Script to remove Python comments/docstrings that removes comments/docstrings. It looks like a perfect fit for my problem but it cannot sort it out to have a clean output on complex code.

A:

the best I could come up with (resolved my issue)
def _python_interactive_indent(self, code):
    prev_toktype = tokenize.INDENT
    first_line = None
    last_lineno = -1
    last_col = 0

    output = ''

    tokgen = tokenize.generate_tokens(StringIO.StringIO(code).readline)
    indent = 0
    hasNL = False
    prefixed = False
    for toktype, ttext, (slineno, scol), (elineno, ecol), ltext in tokgen:
        done = False
        if toktype == tokenize.INDENT:
            indent = indent + 1
        if toktype == tokenize.DEDENT:
            indent = indent - 1
        if slineno > last_lineno:
            last_col = 0
        if not done and toktype == tokenize.NL:
            hasNL = True
            done = True
        if not done and toktype == tokenize.COMMENT:
            done = True
        if not done and toktype == tokenize.STRING and prev_toktype == tokenize.INDENT:
            done = True
        if not done and hasNL and toktype != tokenize.DEDENT and toktype != tokenize.INDENT:
            hasNL = False
            output = output + ("    " * indent) + '\n'
            output += "    " * indent
            prefixed = True
        if not done:
            if not prefixed and scol > last_col:
                output += (" " * (scol - last_col))
            output += (ttext)
        prefixed = False
        prev_toktype = toktype
        last_col = ecol
        last_lineno = elineno
    return output


Q:

Return Outlook MAPIFolder type using Excel VBA

I create a folder if it does not exist in my set of Outlook directories with the below code.
Private Sub addOutlookFolderIfNotExists()
     Set apOutlook = CreateObject("Outlook.Application")
     apOutlook.Session.Logon
     Dim myNameSpace As Outlook.Namespace
     Dim myFolder As Outlook.Folder
     Dim myNewFolder As Outlook.Folder

     Set myNameSpace = apOutlook.GetNamespace("MAPI")
     Set myFolder =
    myNameSpace.GetDefaultFolder(olFolderInbox).Parent.Folders("Estimates")
     For i = 1 To myFolder.Folders.Count
        If myFolder.Folders.Item(i).Name = "Testing" Then
           Exit Sub
        End If
     Next

     addOutlookFolderIfNotExists = myFolder.Folders.Add("Testing")
End Sub

I would like to use the properties of the folder afterwards. I would like to return the MAPIFolder object just created.  I changed the sub to a function to look like the below.
Private Function addOutlookFolderIfNotExists() As MAPIFolder
    Set apOutlook = CreateObject("Outlook.Application")
    apOutlook.Session.Logon
    Dim myNameSpace As Outlook.Namespace
    Dim myFolder As Outlook.Folder
    Dim myNewFolder As Outlook.Folder

    Set myNameSpace = apOutlook.GetNamespace("MAPI")
    Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Parent.Folders("Estimates")
    For i = 1 To myFolder.Folders.Count
        If myFolder.Folders.Item(i).Name = "Testing" Then
            'Debug.Print TypeName(myFolder.Folders.Item(i))
            addOutlookFolderIfNotExists = myFolder.Folders.Item(i)
            Exit Function
        End If
    Next

    addOutlookFolderIfNotExists = myFolder.Folders.Add("Testing")
End Function

This returns an error

vba object variable or with block variable not set

but I don't know what it's referring to.

A:

You are doing it incorrectly. Even the For loop is incorrect. The correct way to set or assign an object is to use the command SET
Is this what you are trying?
Private Function addOutlookFolderIfNotExists() As MAPIFolder
    Dim myNameSpace As Outlook.NameSpace
    Dim myFolder As Outlook.Folder
    Dim myNewFolder As Outlook.Folder
    Dim i As Long

    Set apOutlook = CreateObject("Outlook.Application")

    apOutlook.Session.Logon

    Set myNameSpace = apOutlook.GetNamespace("MAPI")
    Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Parent.Folders("Estimates")

    For i = 1 To myFolder.Folders.Count
        If myFolder.Folders.Item(i).Name = "Testing" Then
            '~~> Set the folder
            Set addOutlookFolderIfNotExists = myFolder.Folders.Item("Testing")
            Exit Function
        End If
    Next

    '~~> Create the folder
    myFolder.Folders.Add ("Testing")

    '~~> Set the folder
    Set addOutlookFolderIfNotExists = myFolder.Folders.Item("Testing")
End Function

You can also do the above without the For Loop. We will use On Error Resume Next in lieu of that.
Private Function addOutlookFolderIfNotExists() As MAPIFolder
    Dim myNameSpace As Outlook.NameSpace
    Dim myFolder As Outlook.Folder
    Dim myNewFolder As Outlook.Folder
    Dim i As Long

    Set apOutlook = CreateObject("Outlook.Application")

    apOutlook.Session.Logon

    Set myNameSpace = apOutlook.GetNamespace("MAPI")
    Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Parent.Folders("Estimates")

    '~~> Create the folder if it doesn't exists
    '~~> If it exists then suppress the error message and continue
    On Error Resume Next
    myFolder.Folders.Add ("Testing")
    On Error GoTo 0

    '~~> Set the folder
    Set addOutlookFolderIfNotExists = myFolder.Folders.Item("Testing")
End Function


Q:

RestructuredText - Hyperlinks without leading and trailing spaces

Is it possible to create hyperlinks without leading and trailing spaces?  The following doesn't work:
re`Structured`_Text

.. _`Structured`: http://docutils.sourceforge.net/docs/user/rst/quickstart.html

The reason I'm asking is I'm working with Chinese text. Spaces are not used as word delimiters in Chinese. With the added spaces the text doesn't look well formatted, for example:

没有空格就对了。

versus

多了 空格 不好看。

Any ideas?

A:

Eventually this is how I get away with this problem. Awkward, but works:
没有\ 空格_\就对了。
我觉得\ `中文和 RST`_\不够兼容。

.. _空格: http://a-link-with-pure-zh-te.xt
.. _`中文和 RST`: http://a-link-with-mixed-zh-and.en

Update: Since docutils 0.13 we can enable character level inline markup. This way we can write like below and save a few backslashes.
没有\ 空格_就对了。
我觉得`中文和 RST`_不够兼容。

This option is enabled via the command line switch:
python rst2html.py --character-level-inline-markup 1.rst > 1.html


Q:

Postback of one dropdown fires selectedindexchanged event of all all remaining dropdown

Example:
  <asp:DropDownList runat="server" AutoPostBack="true" ID="ddlSample">
                                    <asp:ListItem Text="text1" />
                                    <asp:ListItem Text="text2" />
                                </asp:DropDownList>

Now if change the item in the above dropdown it will cause all the other dropdowns postback events to fire.
Like
   <asp:DropDownList EnableViewState="true" ID="ddlNewSelec" runat="server"
     AutoPostBack="true" OnSelectedIndexChanged="ddlNewSelec_SelectedIndexChanged">
             <asp:ListItem Text="--Select Test Type--" Value="" />
   </asp:DropDownList>

Details:
The Page has ViewState disabled. I try enabling viewstate for the individual dropdowns but it does not matter.
Any idea why this is happeing.
Let me know if you need any more details
EDIT:
The dropdown fires the selectedindexchanged event of all other dropdowns on the form. The dropdown named as ddlSample is doing nothing just causing postback but why the selectedindexchanged evenet of other dropdowns fired up.
Additional Info:
All the inputs are in updatePanel and removing them does not make any effect.
In Page Load i am not doing anything on postback
   protected void Page_Load(object sender, EventArgs e)
   {
     if (!IsPostBack)
        {
            BindSomeDDLs();
         }
    }

A:

The answer seems to be very weird but this is true.
This is happening just because of EnableViewState property set to false.


Q:

Customizing CKEditor

I'm building a site with Perch Cms (really neat, check it out!), and now I'm trying to customize the ckeditor I just installed.
What I'm trying to to is basicly just to restrict the formatting options and so on in the editor.
I've managed to find the config.js file in CKE's root folder.
The changes so far, which at least make some difference:
CKEDITOR.editorConfig = function( config )
{
    config.toolbar_Full = [
        ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'],
        ['Undo', 'Redo'],
        ['Bold', 'Italic', 'Underline', 'Strike', 'Format']
    ];
};

But how can I specify which heading tags that are allowed?

A:

You can add config.format_tags = 'p;h1;h2;h3'; in this case only p,h1,h2,h3 will be shown in format dropdown.


Q:

How to retrieve all keys from hashtable containing "Keys" and "Values" text?

In PowerShell you can get all keys from a Hashtable using the Keys property:
$ht=@{
    "1"="10";
    "2"="20";
}
$ht.Keys

This returns:
2
1

BUT this:
$ht=@{
    "Keys"="Keys text";
    "text1"="text1111"
}
$ht.Keys

will return Keys text (the value of the Keys item)
Is there any way to force .Keys to return the Keys property instead the Keys item's value?

A:

This seems like a bug since the syntax to retrieve the Keys entry is superseding the HashTable's Keys property, though I could see one expecting it to behave either way.  According to the Adding a key of 'keys' to a Hashtable breaks access to the .Keys property issue on GitHub, this is a bug but would require a breaking change to correct, so the workaround below was added to the documentation.
According to about_Hash_Tables:

If the key name collides with one of the property names of the HashTable type, you can use PSBase to access those properties. For example, if the key name is keys and you want to return the collection of Keys, use this syntax:
$hashtable.PSBase.Keys

You could also retrieve the property value through reflection...
PS> $ht.GetType().GetProperty('Keys').GetValue($ht)
text1
Keys


Q:

Messenger API Handover Pass Thread Control returning error 10 (2018171)

We've set up a bot, which features a persistent menu with the option for a user to switch the discussion to a human, by using the Handover Protocol.
This button sends a payload to DialogFlow, which then calls our web hook to post to the Messenger API the following function:
request({
    url: 'https://graph.facebook.com/v2.6/me/pass_thread_control',
    qs: { access_token: config.page_token },
    method: 'POST',
    json:{
      "recipient": {"id": userID},
      "target_app_id": 263902037430900
    }
  }, (error, res, body) => {
    if (error) {
      console.error('Error sending messages: ', error)
    } else if (res.body.error) {
      console.error('Error: ', res.body.error)
    }
  })

But the call returns the following error:
{
  message:'(#10) Only available to Primary and Secondary Receivers',
  type:'OAuthException',
  code:10,
  error_subcode:2018171,
  fbtrace_id:'HUrgr45FGGC'
}

We can't figure out this error (which is undocumented).
Under the Page Settings, the bot is correctly set as the primary receiver, and the Inbox as secondary.
Has anyone else run into this?

A:

For those getting here via a Google Search : turns out if was a bug on Facebook API, which is now fixed.
➡ https://developers.facebook.com/bugs/820116014857560


Q:

javafx, TableView: detect a doubleclick on a cell

Given a TableView, i need to detect the doubleclick on a cell.
tableView.setOnMouseClicked(new EventHandler<MouseEvent>()
{
    @Override
    public void handle(MouseEvent event)
    {
        if(event.getClickCount()>1)
        {
            System.out.println("double clicked!");
        }
    }
});

How to determine the cell on which the mouse has been clicked?

A:

Code example.
Run the "Example 12-11: Alternative Solution Of Cell Editing" of official tableview tutorial.
Replace the followings:
table.setEditable(false);
Callback<TableColumn, TableCell> cellFactory =
        new Callback<TableColumn, TableCell>() {
            public TableCell call(TableColumn p) {
                TableCell cell = new TableCell<Person, String>() {
                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        setText(empty ? null : getString());
                        setGraphic(null);
                    }

                    private String getString() {
                        return getItem() == null ? "" : getItem().toString();
                    }
                };

                cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getClickCount() > 1) {
                            System.out.println("double clicked!");
                            TableCell c = (TableCell) event.getSource();
                            System.out.println("Cell text: " + c.getText());
                        }
                    }
                });
                return cell;
            }
        };

No need to EditingCell since your cells are uneditable. Cell factory is used for cell rendering. So one can put any node/control other than default Labeled using cell's setGraphics() method. IMO you cannot access the default cell directly so you should define your own cell factory to be able to put event filter on cell.

A:

JavaFX allows you to set up multiple listeners per cell (I'm not saying that this is good or bad, just that you can). Each listener will execute your code if you have code set to execute a response to the specific listener for the specific column/row. To capture cell mouse clicks, I use the following:
table.setEditable(true);
table.getSelectionModel().setCellSelectionEnabled(true);  // selects cell only, not the whole row
table.setOnMouseClicked(new EventHandler<MouseEvent>() {
 @Override
 public void handle(MouseEvent click) {
  if (click.getClickCount() == 2) {
   @SuppressWarnings("rawtypes")
   TablePosition pos = table.getSelectionModel().getSelectedCells().get(0);
   int row = pos.getRow();
   int col = pos.getColumn();
   @SuppressWarnings("rawtypes")
   TableColumn column = pos.getTableColumn();
   String val = column.getCellData(row).toString(); System.out.println("Selected Value, " + val + ", Column: " + col + ", Row: " + row);
   if ( col == 2 ) { ... do something ... }
   if ( col == 5 ) { ... do something ... }
   if ( col == 6 ) { ... do something ... }
   if ( col == 8 ) { ... do something ... }
  }
 }
});

You can see from the above code, on the columns I want to do something based on a mouse click, I have code:
if ( col == <int> ) { ... do something ... }
I also have those columns set to not allow editing:
thisCol.setEditable(false);
The rows that I want to edit I have .setEditable(true) but don't have a response included with a mouse click.
Cell editing defaults to 2 mouse clicks. You can change the above code to capture different mouse events on a cell, so you can still edit the cell with 2 mouse clicks, or open a URL, dialog box, etc., with any other mouse event determined by you. TableView allows you to determine your own functionality based on your imagination and programming skills. You're not stuck with "I can either edit it, or fire a mouse event with it." You can do both :)

A:

Add the following in the body of your listener, with T the type of your table record :
  @SuppressWarnings("rawtypes")
  ObservableList<TablePosition> cells = tableView.getSelectionModel().getSelectedCells();
  for( TablePosition< T, ? > cell : cells )
  {
     System.out.println( cell.getColumn());
  }// for


Q:

Getting rid of Carriage return and new line in a string

I have a string of the form
b'helloworld\r\n'

I would like to strip it of the \r\n and the the starting b. I tried using .rstrip("\n") but it crashes the system.

A:

According to the Python docs, the b prefix means that your string is a byte string. Specifically:

A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the
  literal should become a bytes literal in Python 3 (e.g. when code is
  automatically converted with 2to3). A 'u' or 'b' prefix may be
  followed by an 'r' prefix.

To convert this to a string without trailing newline and return, and to remove the byte prefix, you would use:
str(b'helloworld\r\n').rstrip('\r\n')


Q:

Oracle Forms and Reports : REP-51002

I try to call a report from a form in Oracle Forms and Reports, but I get the following error :
"REP-51002: Echec de liaison avec le serveur Reports Server repsrvr"
Anyone has an idea what could be the reason of this ? I need your help.
Thank you in advance.

A:

I have found the solution (finally !) .. for those who may encounter the same problem :
1) Search the file rwnetwork.conf
2) Change the lines :
<multicast channel="228.5.6.7" port="14021" timeout="1000" retry="5"/>
<!--namingService name="Cos" host="127.0.0.1" port="14021"/-->

Into
<!--multicast channel="228.5.6.7" port="14021" timeout="1000" retry="5"/-->
<namingService name="Cos" host="127.0.0.1" port="14021"/>

3) Start the namingservice : namingservice 14021
Credits to Denis Segard-Oracle from community.oracle.com


Q:

Cleaning up nested if statements

How could I rewrite this? I'd like to see as many ideas as you can come up with so I can pick one I like. I prefer simple and smart solutions.
if (txtName.Text == "")
 {
  txtName.Focus();
 }
 else if (txtSNo.Text == "")
  {
   txtSNo.Focus();
  }
 else if (txtFNo.Text == "")
  {
   txtFNo.Focus();
  }
 else if (txtMNo.Text == "")
  {
   txtMNo.Focus();
  }
 else if (txtEID.Text == "")
  {
   txtEID.Focus();
  }

A:

How about using some form of collection, then iterating over it to call the .Text property, and if it's empty, setting focus and breaking the loop?
The algorithm would be like this: (pseudo code)
foreach (var textfield in textfieldList){
    if(textfield.Text == ""){
        textfield.Focus();
        break;
    }
}

I'd use a List as the collection to iterate over.


Q:

PPTP VPN error: LCP terminated by peer

I cannot connect to my PPTP VPN server, even though the CHAP authentication succeeds.
This is from /var/log/syslog:
Jun 11 07:27:22 aspire pppd[32221]: CHAP authentication succeeded
Jun 11 07:27:22 aspire pppd[32221]: LCP terminated by peer (MPPE required but cannot negotiate MPPE key length)
Jun 11 07:27:22 aspire pptp[32232]: nm-pptp-service-32219 log[pptp_read_some:pptp_ctrl.c:544]: read returned zero, peer has closed

A:

I found the answer, I had to enable Point-to-Point encryption(MPPE) in the Advanced Settings dialog. Now it works.


Q:

printf, logcat and \n

I have C code that uses prints with something clever like
printf("hello ");
// do something
printf(" world!\n");

which outputs

hello world!

I want to reuse that code with Android and iOS, but Log.d() and NSLog() effectively add a newline at the end of every string I pass them, so that the output of this code:
NSLog(@"hello ");
// do something
NSLog(@"world!\n");

comes out  (more or less) as:

hello
world!

I'm willing to replace printf with some macro to make Log.d and NSLog emulate printf's handling of '\n'; any suggestions?

A:

For progeny, this is what I did: store logged strings in a buffer, and print the part before the newline whenever there is a newline in the buffer.


Q:

How to click on links which has similar text?

I have a page containing 100 links having the same text "Results". How can I click on these links one by one? Please suggest me a selenium webdriver script.

A:

If you're working in Java:
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public void clickLinks(final String url,final String linkText) throws Exception
{
    WebDriver webDriver = new FirefoxDriver();
    webDriver.get(url);
    List<WebElement> links = webDriver.findElements(By.linkText(linkText));
    for (WebElement link : links)
        link.click();
    webDriver.quit();
}

If you're working in Python:
from selenium import webdriver

def clickLinks(url,linkText):
    profile = webdriver.FirefoxProfile()
    browser = webdriver.Firefox(firefox_profile=profile)
    browser.get(url)
    links = browser.find_elements_by_link_text(linkText)
    for link in links:
        link.click()
    browser.quit()

UPDATE:
I doubt that you are unable to click the links before scrolling the page down (as you mention in your comment). Perhaps you are unable to find the links... In any case, if you want to scroll the page all the way down, then here is how you can do it:
Java: webDriver.executeScript("window.scrollTo(0,document.body.scrollHeight);").
Python: browser.execute_script("window.scrollTo(0,document.body.scrollHeight);").
You can replace document.body.scrollHeight with some numeric value in order to scroll it partially.


Q:

@require-ing jQuery overwrites the page's $ variable

I'm @require-ing jQuery for my Greasemonkey script with this line in my script file:
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

and it works quite well; I can use $('#id') to access the DOM.
However, the $ variable of the 'real' page is modified (where $ is jQuery 1.2.xx):
I get an error that $.include is not defined.
I thought the sandbox model of Greasemonkey would prevent that the variables of the target-page are overwritten?
How can I ensure that the inclusion of javascript libraries does not affect the 'real' website, but only my Greasemonkey script?

A:

Greasemonkey 1.0, radically changed the way the sandbox works, busting thousands of scripts.  See also, jQuery in Greasemonkey 1.0 conflicts with websites using jQuery.
This is a huge problem, and I hope you will join me in voicing your opinion/experiences on the principle bug report for this issue.
Meanwhile, restore the sandbox to your script, and resolve the $ conflict, by editing your Metadata Block to end with the following lines:
// @grant       GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design change introduced in GM 1.0,
    It restores the sandbox.
*/

Specifying a @grant value (other than none) reactivates the sandbox.

You might also consider switching to Scriptish, which has offered superior features and performance in the past, and does not suffer from this new sandbox behavior.

A:

See jQuery.noConflict();; it explains a lot.
EDIT:
Found "Greasemonkey 1.0 + jQuery: Broken, with Workaround" on searching.
Possible solution:
 this.$ = this.jQuery = jQuery.noConflict(true);

Doing that, probably will implicitly specify that $, jQuery will be available in your script's namespace.


Q:

How ProcessStartInfo.Argument consider arguments

I am using following code to start another process with argument, here i pass a string path as argument, path returned as c:\documents and settings\\local settings: :
string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)).FullName(); //path = c:\documents and settings\<username>\local settings

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = path;
Process.Start(startInfo);

I would like to pass the path as one argument, a whole string. But I found out the path has been separated by multiple arguments, it actually separated by every space. In this case, it pass c:\documents as first argument, and as second argument and  settings\\local as third argument...
I want to pass them as one argument rather than 4 arguments. How can do that with StartInfo.Argument?

A:

I am not sure, if it works, but try to use " around your path:
startInfo.Arguments = "\"" + path + "\"";

This will wrap your string in " and so, whitespaces will be ignored.

A:

The Process object treats arguments in exactly the same way as the Console. Wrap any arguments containing spaces with double quotes: "\"c:\documents and settings\local settings\"".
A good tip is to try to run the process from the console with whatever arguments you've supplied. This makes it easier to understand error feedback than running from a Process object.

A:

Wrap your argument in quotation marks:
startInfo.Arguments = "\"" + path + "\"";