text:
Q: Assigning values to two dimensional array in c I have written a piece of code for finding the continuous sum equal to one of the argument provided.
#include <stdio.h>
#include <string.h>

int main()
{
    //number of test case
    int n;
    int monfri[2];

    scanf("%d",&n);

    char res[n][3] ;
    char yestok[3] = {"YES"};

    int sum = 0;
    int h = 0;

    for(int i = 0 ; i < n; i++)
    {
        h=0;
        //read no of friends and money
        while (h < 2 && scanf("%d", &monfri[h]) == 1)
            h++;

        int fri[monfri[0]];

        for(int j = 0; j < monfri[0]; j++)
            scanf("%d",&fri[j]);

        for(int k = 0; k < monfri[0] ; k++)
        {
            sum = 0;

            for(int l=k+1; l<monfri[0]; l++)
            {
                sum = sum + fri[l - 1];

                if(sum == monfri[1])
                {
                    strcpy (res[i],yestok);
                    continue;
                }

                if(sum > monfri[i])
                    continue;
            }
        }

        if(strcmp(res[i],yestok) != 0)
        {
            strcpy (res[i],"NO");
        }

    }

    for(int d = 0; d < n ; d++)
    {
        puts(res[d]);
    }

    return 0;
}

providing the input for the same
2
5 12
2
3
4
5
6
3 15
2
2
2

Here first input represents the no of test case in our case its 2
the next input represents actual no of data and sum value. here its
5 12
3 15

The expected output should be
YES
NO

But I am getting
YESNO
NO

What wrong I did. If no of test case is 1 then it works fine. but failed in 2 or more test cases.

A: The string "YES" needs space of 4 chars. Thus, you must change the declaration of yestok to
char yestok[4] = {"YES"};

or even better, let the compiler determine the length:
char yestok[] = {"YES"};

Otherwise, the terminating NUL character gets lost and your program invokes undefined behaviour. For example the strcmp call may fail.


text:
Q: How does a balloon expanding at relativistic speed look like? Suppose that we could observe from outside a system expanding radially at relativistic speed ($\frac{dr}{dt}$ about $c$, constant and/or accelerated).
It can be an ideal balloon, or a spherical distribution of particles.
What would it look like? A shrinking sphere? Or a sphere expanding slower than expected? Nothing of the above?

A: If you were at the centre of the balloon, it would appear to be a sphere. The speed at which the balloon was expanding away from you would appear to be reduced owing to the Doppler red-shift effect.
If you were outside the sphere, the Doppler effect would distort the appearance of the balloon, so that instead of appearing spherical, the parts of the balloon nearer to you would appear to be expanding more rapidly than the parts further from you, so that it would seem egg-shaped, with the flatter end of the egg being away from you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to round when you have a mix of numeric and character in R? After some statistics, I have a final data frame Measure containing 2 columns Mean and Sd.
We can easily merge Mean and Sd into a single column Mean_Sd:
Measure = Measure %>%
  unite(Mean_Sd, Mean, Sd, sep = " ± ", remove = FALSE)

Size    Mean    Sd                                   Mean_Sd
1       0.025 0.000                               0.0253 ± NA
2       0.049 0.000                               0.0492 ± NA
3       0.009 0.000                               0.0089 ± NA
4       0.027 0.000                               0.0266 ± NA
5       0.046 0.000                               0.0463 ± NA
6       0.196 0.178     0.195966666666667 ± 0.177617576082249
7       0.143 0.000                                0.143 ± NA
8       0.052 0.002               0.0522 ± 0.0015556349186104
9       0.013 0.002               0.0128 ± 0.0019672315572906
10      0.052 0.000                               0.0524 ± NA
...

But now, how can I round (avec 3 digits) each value in the column Mean_Sd ? This column is a mix of character and numeric.
I've tried the following function but in this case, only the Mean and Sd columns (numeric) were effectively changed.
Measure <- data.frame(lapply(Measure, function(y) if(is.numeric(y)) round(y, 3) else y))


text:
Q: Resolving python package dependencies I am trying to lock the Pipfile and running into below error:
$pipenv install
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Building requirements...
Resolving dependencies...
✘ Locking Failed!
[pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You
likely have a mismatch in your sub-dependencies.
First try clearing your dependency cache with $ pipenv lock --clear, then try the original
command again.
Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $
pipenv graph to inspect the situation.
Hint: try $ pipenv lock --pre if it is a pre-release dependency.
ERROR: Could not find a version that matches pep8 (from -r
/var/folders/k_/z7wqjx090x7ccf11mkbpbnw80000gn/T/pipenv7upqst3zrequirements/pipenv-DczZI5-
constraints.txt (line 2))
No versions found
Was https://pypi.org/simple reachable?

Tried running suggested commands but still the same.
pipenv lock --clear
Locking [dev-packages] dependencies…
Building requirements...
Resolving dependencies...
✘ Locking Failed!
[pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You
likely have a mismatch in your sub-dependencies.
First try clearing your dependency cache with $ pipenv lock --clear, then try the original
command again.
Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $
pipenv graph to inspect the situation.
Hint: try $ pipenv lock --pre if it is a pre-release dependency.
ERROR: Could not find a version that matches pep8 (from -r
/var/folders/k_/z7wqjx090x7ccf11mkbpbnw80000gn/T/pipenv0s9lv_igrequirements/pipenv-G4Zdsv-
constraints.txt (line 2))
No versions found
Was https://pypi.org/simple reachable?

A: Nevermind, figured it out using pipenv --support.
Turned out pipenv was using python3. So had to explicitly point it to python2 using command below and that did create Pipfile.lock
pipenv --two install


text:
Q: how to test application deployed in websphere cluster.? I have create a cluster in websphere and deployed a defaultapplication coming with ibm package to cluster.
Now,i want to test this application to check weather it installed correctly on each member of the cluster or not.
How can i check that on which port it is running i have tried with default port but i fail not get that.
i have installed websphere in machine that have Windows OS.
Thanks in advanced.
Edited:-
i want to ope application that deployed in the cluster, how can i open it??
any idea about this..??

A: Check the WC_defaulthost port for each of the cluster members. You can find these ports in the WebSphere Integrated Solutions Console in WAS 6.1 at Servers > Application Servers > [serverName] > Communications > Ports.


text:
Q: QSqlrelationalTableModel.SubmitAll() returns an error I'm working on postgreSQL 9.5, QT4 and Python2.
I've brought data from a PostgreSQL query to a QTableView with this code :
self.nomtable = resultQuery
 if not self.nomtable:
    QtGui.QMessageBox.warning(self, 'Alerte', u'Pas de données pour ce salarié et cette année')
 self.model = QtSql.QSqlRelationalTableModel(self, self.db)
 self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
 self.ui.tbv_suivtemp.setModel(self.model)
 self.ui.tbv_suivtemp.setItemDelegate(QtSql.QSqlRelationalDelegate(self.ui.tbv_suivtemp))
 self.ui.tbv_suivtemp.setSortingEnabled(True)
 self.model.setQuery(query_rempl_suivemp)
 self.model.select()

It works perfectly : data from the query is displayed in the QTableView.
But now, if an user modifies a number in a cell and push a button, I want new data to be entered in the model, to be then inserted in my database.
There's my piece of code to do that :
self.ui.btn_okannul.accepted.connect(self.sauvModifs)

def sauvModifs(self):
    self.model.submitAll()
    erreur = self.model.lastError().text()
    print erreur

Now, the error is :
ERROR:  syntax error on or near « = »
LIGNE 1 : PREPARE qpsqlpstmt_5 AS UPDATE  SET "juillet"=$1 WHERE "sp_i...
                                                       ^
(42601) QPSQL: Impossible to prepare the query

So, these are my questions :

*

*How could I have the whole error message?

*The error seams to occur in the submitAll() method, not in my code. How can I debug that?


text:
Q: Mod_Rewrite not working when i add a query string I'm using the following rewrite rule in my .htaccess file, but whenever i add parameters to the string it makes the rewrite fail
RewriteRule ^c([0-9]+)/[a-zA-z0-9\-]+$ category.php?id=$1 [L]

For example:
If i go to the following, all works fine:
c87/newest-post

But if i go to:
c87/newest-post?param1=this&param2=that
c87/newest-post/?param1=this&param2=that

it redirects incorrectly and fails. I think it has something to do with the QSA tag, but with my poor knowledge of redirects i cant see what I'm doing wrong.

A: The QSA flag is required since you have specified a query string in the replacement URL:

When the replacement URI contains a query string, the default behavior
  of RewriteRule is to discard the existing query string, and replace it
  with the newly generated one. Using the [QSA] flag causes the query
  strings to be combined.

For the trailing slash you need an extra tweak. The suggested RewriteRule is:
RewriteRule ^c([0-9]+)/[a-zA-z0-9\-]+/?$ category.php?id=$1 [QSA,L]
# c87/newest-post?param1=this&param2=that  -> category.php?id=87&param1=this&param2=that
# c87/newest-post/?param1=this&param2=that -> category.php?id=87&param1=this&param2=that


text:
Q: PHP if statement - Resource id issue I have some code below which retrieves data from a table named "tally_point"
What I am trying to is retrieve a value from a column named 'tpt_id'
On another table, there is a table named "tally_point_type", which has has the primary key 'tpt_id' as well.
What I am trying to do is get the 'tpt_name' value to print from the tally_point_type row. At the moment I can get the "Order Details" link to work but the $tpt_name value prints out a Resource id# value.
I knwo Im close but can't quite figure out how to get this to work.
    <?php

    $pointstype = $row['tpt_id'];

    $type = '';

    if($pointstype > '0') {

    $query = "SELECT tpt_name
    FROM tally_point_type
    WHERE'" . $row['tpt_id'] . "'=$pointstype";

    $tpt_name = mysql_query($query);
     $type .='' . $tpt_name . '
';
    }
    else {
     $type .='Order Details
';
    }
    echo $type;
    ?>

Full code here:
        <?php # index.php

        require_once ('./includes/config.inc.php');

        $page_title = 'Title';
        include ('includes/header.html');

        if (!isset($_SESSION['admin_int_id'])) {

           $url = 'http://' . $_SERVER['HTTP_HOST']
            . dirname($_SERVER['PHP_SELF']);
           // Check for a trailing slash.
           if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
                $url = substr ($url, 0, -1); // Chop off the slash.
           }
           $url .= '/login.php';

        ob_end_clean(); // Delete the buffer.
        header("Location: $url");
        exit(); // Quit the script.
        }

        if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
           { // Accessed through view_users.php
            $id = $_GET['id'];

        } elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
           { // Form has been submitted.
            $id = $_POST['id'];
        } else { // No valid ID, kill the script.
            echo '
Page Error

This page has been accessed in error.

';
            include ('./includes/header.html');
            exit();
        }

        require_once ('/database.php'); // Connect to the db.

        $display = 1000;

        if (isset($_GET['np'])) { // Already been determined.
            $num_pages = $_GET['np'];
        } else { // Need to determine.

            $query = "SELECT COUNT(*) FROM tally_point, users WHERE tally_point.users_id = users.users_id ORDER BY tally_points_entry_date DESC";
            $result = @mysql_query ($query);
            $row = @mysql_fetch_array ($result, MYSQL_NUM);
            $num_records = $row[0];

            if ($num_records > $display) { // More than 1 page.
               $num_pages = ceil($num_records/$display);
            } else {
               $num_pages = 1;
            }

        }

        if (isset($_GET['s'])) {
            $start = $_GET['s'];
        } else {
            $start = 0;
        }

        $link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
        $link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
        $link3 = "{$_SERVER['PHP_SELF']}?sort=dra";

        if (isset($_GET['sort'])) {

            switch ($_GET['sort']) {
               case 'lna':
                  $order_by = 'tally_points_in ASC';
                  $link1 = "{$_SERVER['PHP_SELF']}?sort=lnd";
                  break;
               case 'lnd':
                  $order_by = 'tally_points_in DESC';
                  $link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
                  break;
               case 'fna':
                  $order_by = 'total ASC';
                  $link2 = "{$_SERVER['PHP_SELF']}?sort=fnd";
                  break;
               case 'fnd':
                  $order_by = 'total DESC';
                  $link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
                  break;
               case 'dra':
                  $order_by = 'tally_points_entry_date ASC';
                  $link3 = "{$_SERVER['PHP_SELF']}?sort=drd";
                  break;
               case 'drd':
                  $order_by = 'tally_points_entry_date DESC';
                  $link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
                  break;
               default:
                  $order_by = 'tally_points_entry_date DESC';
                  break;
            }

            $sort = $_GET['sort'];

        } else { // Use the default sorting order.
            $order_by = 'tally_points_entry_date DESC';
            $sort = 'dra';
        }

        $query =   "SELECT ta.tally_points_in, ta.order_id, ta.total, ta.tpt_id , DATE_FORMAT(ta.tally_points_entry_date, '%d-%m-%Y') AS dr, ta.users_id
                    FROM tally_point AS ta
                    WHERE ta.users_id=$id
                    ORDER BY
        ".$order_by." LIMIT ".$start.", ".$display;

        $result = @mysql_query ($query); // Run the query.

        echo '

            Date
            Credit
            Debit
            Description

        ';

        $bg = '#ffffff'; // Set the background color.

        while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $pointsitem = $row['order_id'];
            $pointstype = $row['tpt_id'];

            $bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color.
            //$entries = floor($row['ltd_entry_amount']/200);
            echo '
';
            echo '' . $row['dr'] . '	';
            echo  '' . $row['tally_points_in'] . '	 ';
            echo  '' . $row['total'] . '	';

            $type = '';
            if($pointstype > '0') {
            $query = "SELECT tpt_name
            FROM tally_point_type
            WHERE'" . $row['tpt_id'] . "'=$pointstype"; //THIS ALSO SEEMS WRONG column name should have backticks if you're trying to escape it and maybe value should be quoted? Also these values are the same, no?
            $result = mysql_query($query);
            $tpt_name = mysql_fetch_assoc($result);
            $type .='' . $tpt_name['tpt_name'] . '
';
            } else {
            $type .='Order Details
';
            }
            echo $type;

            }

        echo '
';

        mysql_free_result ($result); // Free up the resources.

        mysql_close(); // Close the database connection.

        if ($num_pages > 1) {

            echo '

';
            $current_page = ($start/$display) + 1;

            if ($current_page != 1) {
               echo 'Previous ';
            }

            for ($i = 1; $i <= $num_pages; $i++) {
               if ($i != $current_page) {
                  echo '' . $i . ' ';
               } else {
                  echo $i . ' ';
               }
            }

            if ($current_page != $num_pages) {
               echo 'Next ';
            }

            echo '
';

        }
        include ('./includes/footer.html'); // Include the HTML footer.
        ?>

A: You need to fetch the result:
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$tpt_name = $row['tpt_name'];

A: You need to fetch the result.
<?php
$pointstype = $row['tpt_id'];
$type = '';
if($pointstype > '0') {
    $query = "SELECT tpt_name
            FROM tally_point_type
            WHERE'" . $row['tpt_id'] . "'=$pointstype"; //THIS ALSO SEEMS WRONG column name should have backticks if you're trying to escape it and maybe value should be quoted? Also these values are the same, no?
    $result = mysql_query($query);
    $tpt_name = mysql_fetch_assoc($result);
    $type .='' . $tpt_name['tpt_name'] . '
';
} else {
    $type .='Order Details
';
}
echo $type;
?>

Also see notes in the comment of your query, consider switching drivers to mysqli or PDO, and I'm not sure about where the data you're using is coming from but might be open to a SQL injection. How can I prevent SQL injection in PHP?
Here's the manual link for future reference http://php.net/manual/en/function.mysql-query.php. See example #2.


text:
Q: Stack vs Heap in C/Java Here's my understanding.
In C programming, if I do int a then that a is created on stack and thus the memory is taken from stack. Heap plays no part here.
But if I do something like
int *a;
a=(int*)malloc(sizeof(int));

and dynamically allocate the memory, then the reference variable will be placed on stack, but the memory it points to will be on the heap.
Am I correct with my understanding?
Now, I picked up this book on java that says

Whenever you need an object, you
  simply write the code to create it by using new, and the storage is allocated on the
  heap when that code is executed.

So there's no way of creating objects on Stack in Java?
I guess, the primitive data types can still be placed on stack, but I am concerned about the Objects.

A: There is no way to create objects on the stack in Java. Java also has automatic garbage collection, so you don't have any way of deleting objects. You just let all references to them go out of scope and eventually the garbage collector deals with them.

A: That is correct. Objects are stored on the heap. The stack contains primitive values like int and double (from local variables) and references to objects (again from local variables).

A: The whole premise of your question is false: in Java you don't have any control over where the objects will be allocated. Some are indeed stack-allocated, but you'll never notice the difference.
What is fundamentally different between Java and C is that in Java the value of a variable can never be the object itself, whereas in C the value can be the struct itself, with no indirection. You can pass such structs by value to other functions and there is no equivalent of that in Java.


text:
Q: Faster way to detect a image from a large one Currently I use this to find a bitmap that occurs in another image on the screen i.e. a window but it is tool slow, i want it to take 1 or less seconds, I was thinking of cropping the image into a section i.e. a 80,60 section at point 0,0 of the image and searching there, when it has done that it do the same crop but y+60 and continue until it has covered the full image assuming it is 800 by 600 pixel
the code i currently use is:
        public bool findImage(Bitmap small, Bitmap large, out Point location)
    {
        //Loop through large images width
        for (int largeX = 0; largeX < large.Width; largeX++)
        {
            //And height
            for (int largeY = 0; largeY < large.Height; largeY++)
            {
                //Loop through the small width
                for (int smallX = 0; smallX < small.Width; smallX++)
                {
                    //And height
                    for (int smallY = 0; smallY < small.Height; smallY++)
                    {
                        //Get current pixels for both image
                        Color currentSmall = small.GetPixel(smallX, smallY);
                        Color currentLarge = large.GetPixel(largeX + smallX, largeY + smallY);
                        //If they dont match (i.e. the image is not there)

                        if (!colorsMatch(currentSmall, currentLarge))
                            //Goto the next pixel in the large image

                            goto nextLoop;
                    }
                }
                //If all the pixels match up, then return true and change Point location to the top left co-ordinates where it was found
                location = new Point(largeX, largeY);
                return true;
            //Go to next pixel on large image
            nextLoop:
                continue;
            }
        }
        //Return false if image is not found, and set an empty point
        location = Point.Empty;
        return false;
    }

A: Since you are looking for an exact match you can downsample your large picture, and downsample your small picture (but several times, at different offsets). Then search for an exact match of the downsampled pictures (potentially recursing).
Your large picture does not sound that large, you may be able to get away with doing a Boyer-Moore search for one of the lines.


text:
Q: Big difference in CV accuracy and overall training accuracy #some imports
.......
.......

acctrain=[]
acctest=[]
roctrain=[]
roctest=[]
specifitylist=[]
specifity1list=[]
sensitivitylist=[]
sensitivity1list=[]

danesas=pd.read_csv('danesasowe.csv',delimiter=';',decimal=',')
danesas['datazalozenia'] = pd.to_datetime(danesas['datazalozenia'],format='%d.%m.%Y')
danesas['dataurodzenia'] = pd.to_datetime(danesas['dataurodzenia'],format='%d.%m.%Y')
danesas['datapozyczki'] = pd.to_datetime(danesas['datapozyczki'],format='%d.%m.%Y')
X=danesas.drop(['account_id','datazalozenia','dataurodzenia','datazalozenia','datapozyczki','status','disp_id','typkarty','Czy_problemy','duration','payments','balance'],axis=1)
y=danesas['Czy_problemy']
kolumnyX=["platnosci","wielkosckredytu","ileremittancetoanotherbank","ilewithdraw","ilecollectionfromanotherbank","iletransakcji","staz_pozyczka","ilecreditcardwithdrawal","A14","A7","POM1","A9","A11","A16","A15","A4","czastrwaniakredytu","A12","plec","ilecreditincash","A6","A13","stan_konta_przydzielanie_kredytu","ilecredit","A8","POM2","A5","wiek_pozyczka","A10"]
A=X[["platnosci","wielkosckredytu","ileremittancetoanotherbank","ilewithdraw","ilecollectionfromanotherbank"]]
neg, pos = np.bincount(y)
print("Neg:",neg,"Pos:",pos)

for i in range(100):
    X_train,X_test,y_train,y_test = train_test_split(A,y,test_size=0.2)
    sc=StandardScaler()
    X_train=sc.fit_transform(X_train)
    X_test=sc.transform(X_test)
    sample_weights = np.zeros(len(y_train))
    sample_weights[y_train == 0] = 1
    sample_weights[y_train == 1] = 9.5
    clf=GradientBoostingClassifier(loss='deviance',n_estimators=5,learning_rate=0.3)
    clf.fit(X_train,y_train,sample_weight=sample_weights)
    y_pred=clf.predict(X_train)
    y_pred

    scores = cross_val_score(clf, A, y, cv=5)

    tn, fp, fn, tp = confusion_matrix(y_train, y_pred).ravel()
    specificity = tn / (tn+fp)
    sensitivity=tp/(tp+fn)
    specificity

    y_pred1=clf.predict(X_test)
    y_pred1
    print("CV ACC:",scores)
    print("Accuracy test:",metrics.accuracy_score(y_test, y_pred1))

    tn1, fp1, fn1, tp1 = confusion_matrix(y_test, y_pred1).ravel()
    specificity1 = tn1 / (tn1+fp1) # True negative rate
    sensitivity1=tp1/(tp1+fn1) #True positive rate
    sensitivity1

    #### FUNKCJA ROC ####
    acctrain.append(scores.mean())
    acctest.append(scores1.mean())
    roctest.append(roc_auc_score(y_test,y_pred1))
    roctrain.append(roc_auc_score(y_train,y_pred))

    specifitylist.append(specificity)
    specifity1list.append(specificity1)
    sensitivitylist.append(sensitivity)
    sensitivity1list.append(sensitivity1)

print("ACCTRAIN/ACCTEST/ROCTRAIN/ROCTEST")
print(np.mean(acctrain),np.mean(acctest),np.mean(roctrain),np.mean(roctest))
print("SPECIFITYTRAIN/SPECIFITYTEST/SENSITIVITYTRAIN/SENSITIVITYTEST")
print(np.mean(specifitylist),np.mean(specifity1list),np.mean(sensitivitylist),np.mean(sensitivity1list))
print()

I know that code doesn't look decent, as it's only for my learning however I encountered a big problem for me. I understand how cross-validation accuracy works - that it splits my data set into 5 portions in this case and tests the model on each of 5 times separately each time, so exactly how I created my model by splitting 20% of data for training, but it is done 5 times.
However, whenever I do that, the score is much higher on CV than on normal accuracy from model. For example:

I don't know whether I am doing something wrong code-wise or if Ijust don't understand how this works.

A: Your cross validation scores (CV ACC) are the scores on the entire dataset since you call
scores = cross_val_score(clf, A, y, cv=5)

But your model was trained on 80% of that data, thus it is only natural that it performs better there than on the test set (Accuracy test), which it has not "seen" at all. I would advise to instead apply cross validation on the training set only:
scores = cross_val_score(clf, X_train, y_train, cv=5)


text:
Q: can't change pycharm sql dialect color I have some string SQL stuff in some variables, how can I change the background color that pycharm is adding to my SQL dialect (annoying yellow)
I check in the settings I wasn't able to find anything related to SQL background
current_rep_query = "select  * from Customers where %s = ?"

something like this will have a yellow background

A: You can change all foreground and background related colors for SQL in Settings -> Editor -> Color Scheme -> SQL.
You can click either on elements in the list, or on elements in the preview. To the right side of the window, you can tick or untick the boxes Foreground and/or Background and choose the colors you want.
This is valid for at least PyCharm Pro 2019.

A: To just change the color and keep language injection: Settings -> Editor -> Color Scheme -> General -> Code -> Injected language fragment. And from there deselect or change the background.
To disable SQL select/delete/insert/update/create language injection altogether: Settings -> Editor -> Language Injections. And from there deselect python: "SQL select/delete/insert/update/create".

A: I've had this issue occasionally re-occur after a JetBrain's update reverted my prior settings.  Your post inspired me to deep-dive into solving this.  Here's what I found:
The Cause:
The yellow background is actually PyCharm highlighting the entire SQL block with an inspection warning.
Disabling PyCharm's Language Injection for python: SQL prevents PyCharm from inspecting the SQL which is why it's a common solution.  However, this prevents PyCharm from applying formatting/color schemes to the SQL.
How to Prevent the Highlighting:
Fixing whatever is triggering the SQL warning will remove the highlighting.
You can do this by one of the following ways:

*

*Fixing the SQL issue (probably the preferred way)

*OR tell PyCharm to ignore the warning via Settings > Editor > Inspections > SQL
How to Change or Disable the Background Color:
If you just want to remove or change the color of the warning block, you can do so by:

*

*Open PyCharm settings

*Go to: Color Scheme > General > Errors and Warnings > Warning

*Disable or change the background color

A: Settings -> Editor -> Color Scheme -> General
Look for Injected language fragment


text:
Q: Write output of process to log4j I start a process with ProcessBuilder and want to write the output to log4j. How can I achieve this?
I know that I can redirect the output of the process to a File and then read that File back, but I hope there is some easier way.
I would like to avoid to write my own OutputStream implementation if there is a simpler solution. I hope that I am not the first who would like to get the output of a ProcessBuilder as a "good java object" like a
 List<String>

or something else which is easy to handle.

A: You can use Process.getInputStream() and/or Process.getErrorStream() to retrieve output and write that to log4j. For example:
private static final Logger LOG = Logger.getLogger(MyClass.class);
....
ProcessBuilder pBuilder = new ProcessBuilder("MyProcess").redirectErrorStream(true);
Process process = pBuilder.start();
LOG.info(new String(IOUtils.toByteArray(process.getInputStream())));

If it's a process that runs a long time and occasionally provides output, then it's better to put the last line in a separate thread.


text:
Q: How to emit an event in Jmeter? In javascript:
socket.emit('ui:home:loaded',{_id: '576a5bde4dd0ec7a...'});

I'm trying using WebSocket Sampler

*

*Request data : 2probe

*Response data : 3probe

But I can't emit an event.
How can do this in the Jmeter?

A: Did you try in the following WebsocketSAmpler setting in Request Data textarea:

'ui:home:loaded',{_id: '576a5bde4dd0ec7a...'}

Also is this the approach you followed ?

A: It's working for me.
使用jmeter对websocket进行压力测试


text:
Q: ts-node "interpreter" does not allow me to run typescript file without opening powershell (node spawn) My question is about the ts-node interpreter.
I am making an application that allows code to execute as soon as I save the file (nodemon type).
The problem is that I cannot execute the command with a simple spawn since I am forced to open the powershell like this
spawn("powershell",["npx ts-node", fileName],
                {
                    stdio: [process.stdin, process.stdout, process.stderr],
                }
            );

I would like to know if it would be possible to use the ts-node command without opening the powershell since it would weigh on performance.
PS:
this doesn't work
spawn("ts-node",[ fileName],
                {
                    stdio: [process.stdin, process.stdout, process.stderr],
                }
            );


text: Q: Getting Composer to use the version of PHP installed with Homebrew on Mac I'm using Composer on a Mac (Big Sur). Running php -v, I get PHP 8.0.12.  This is the version I installed with Homebrew. Composer is using default version of PHP, installed at /usr/bin/php (PHP 7.3.29). I need Composer to use the Homebrew version (/usr/local/Cellar...), but can't figure out a solution.


text:
Q: Enormous JMeter Results file I'm running a very simple JMeter test (screenshot attached) that hits 2 web pages.  It's set to run for 6 hours but for some reason, the report is enormous.  The last run came out at 41GB and as a result, I cannot generate the HTML report.
Any ideas as to why it's so big and what I can do about it?

A: Well, you're running a test with 100 users for 6 hours and each user creates a separate line for each page in the .jtl results file like this:
1657532286921,298,HTTP Request,200,OK,Thread Group 1-1,text,true,,1591,116,1,1,http://example.com/,295,0,163

so it's roughly 100 bytes per user per page
One iteration (100 users hitting 2 pages) would be 19 kilobytes
If response time of each page is 1 second each user will be able to execute 1800 requests per hour and 10800 requests per 6 hours. 100 users will execute 1080000 requests resulting in 108 gigabytes of results file.
There is nothing you can do about the results file size, you could increase JMeter's heap space so the file would fit into memory (if you don't have enough RAM you can use swap for this)
Alternative option is using Backend Listener to send the results to InfluxDB, in this case JMeter will send only aggregate data and the size will be lower, the results can be visualized in Grafana. More information: JMeter + Grafana: How to Use Grafana to Monitor JMeter


text:
Q: Deployment with e(fx)clipse - Build Error I am trying to deploy a stand-alone build of my JavaFx application and have followed the tutorial from Code.Makery.
I am getting this error:

init-fx-tasks:
    [taskdef] Could not load definitions from resource com/sun/javafx/tools/ant/antlib.xml. It could not be found.
  do-deploy:
       [copy] Copying 1 file to C:_source\MasterGuildWarsCode\build\dist\libs
BUILD FAILED C:_source\MasterGuildWarsCode\build\build.xml:91:
  C:_source\MasterGuildWarsCode\resources does not exist.
Total time: 2 seconds

This is the section of my build.xml file that seems to be the problem:
<mkdir dir="dist/resources" />
<copy todir="dist/resources" >
    <fileset dir="../resources" />
</copy>

<mkdir dir="package" />

<!-- Icons only for Windows -->
<mkdir dir="package/windows" />
<copy todir="package/windows">
    <fileset dir="..">
        <include name="AXI.ico" />
        <include name="AXI.bmp" />
    </fileset>
</copy>

<!-- Icons only for MacOS -->
<mkdir dir="package/macosx" />
<copy todir="package/macosx">
    <fileset dir="..">
        <include name="AXI.icns" />
    </fileset>
</copy>

<fx:resources id="appRes">
    <fx:fileset dir="dist" includes="MasterGuildWarsCode.jar"/>
    <fx:fileset dir="dist" includes="libs/*"/>
    <fx:fileset dir="dist" includes="resources/**"/>
</fx:resources>

Any help is greatly appreciated!

A: You may want to try this tutorial instead: Efxclipse/Tutorials/AddingE(fx)clipse to eclipse. I've tested it and works perfectly.
Make sure you follow all the steps. Specially this one: "Configure eclipse to use a JDK not a JRE". This will guarantee that you won't have any trouble when you ant build and run your app.

A: Looking at that tutorial (Step 4), there is a section like this in the build.xml:
<path id="fxant">
  <filelist>
    <file name="${java.home}\..\lib\ant-javafx.jar"/>
    <file name="${java.home}\lib\jfxrt.jar"/>
    <file name="${basedir}"/>
  </filelist>
</path>

Do those jars exist at the specified paths in the JDK that Ant executes with?
A very similar question was asked here: JAVAFx Build Failed, with suggestion to change from
<file name="${java.home}\lib\jfxrt.jar"/>

to
<file name="${java.home}\lib\ext\jfxrt.jar"/>

I don't know whether that is correct or not, but I do suggest checking those paths.


text:
Q: How to get data inside a Nested Array of object const datafromback=[[{name:ravi}],[{}],[{}],[{}]]
I want to access ravi. Can anyone help me how can i see ravi in my console.with dealing with nested arrays
I not getting approach but i can use map to map through datafromback array but don't know how to get inside it

A: You can use 0 index

const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]]

const dataFrom = (arr, nameRavi) => {
    let result
    arr.forEach((ele) => {
        if (ele[0].name === nameRavi) result = ele[0].name
    })
    return result
}

console.log(dataFrom(datafromback, 'ravi'))

A: one possible way is to use flat first to remove nested array
const datafromback=[[{name:ravi}],[{}],[{}],[{}]]
const flatternArray = datafromback.flat() // [{name:ravi},{},{},{}]
flatternArray.map(item => {
    console.log(item.name) //
})

A: you can do this :

const datafromback=[[{name:'ravi'}],[{}],[{}],[{}]]

const [{name}] =  datafromback.find(data=>data.find(item=>item.name === 'ravi')?.name === 'ravi')

    console.log(name)

A: You can create a recursive function if you have non-fixed dimensions array :
const handle = e => {
  if (Array.isArray(e))
    return e.map(handle)
  else {
    console.log(e.name)
  }
}

handle(array)

Or if you know the dimensions, you can use nested for loops like so :
// example for 2 dimensions
for (let y = 0; y < array.length; y++)
  for (let x = 0; x < array[y].length; x++)
    console.log(array[y][x].name)

A: Hey so what you have above is a 2D object array. if you just want to console you can use a nested forEach to get the key value, like this.
datafromback.forEach(data => {
  //this is the nested array that contains the objects
  data.forEach(obj => {
    //here you can access the actual object
    if (obj?.name) console.log(obj.name);
  });
});

this will return the value of key (name) if present ie ravi in your case.

A: you can do it like this

const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]];
const names = [];

datafromback.map((items) => {
  items.map((item) => {
    if (item?.name) names.push(item?.name);
  });
});
console.log(names);


text:
Q: Is the order of static class initialization in C# deterministic? I've done some searching and I think the following code is guaranteed to produce output:
B.X = 7

B.X = 0

A.X = 1

A = 1, B = 0

static class B
{
    public static int X = 7;
    static B() {
        Console.WriteLine("B.X = " + X);
        X = A.X;
        Console.WriteLine("B.X = " + X);
    }
}

static class A
{
    public static int X = B.X + 1;
    static A() {
        Console.WriteLine("A.X = " + X);
    }
}

static class Program
{
    static void Main() {
        Console.WriteLine("A = {0}, B = {1}", A.X, B.X);
    }
}

I've run this numerous times and always get the output above the code section; I just wanted to verify will it change?  Even if textually, class A and class B are re-arranged?
Is it guaranteed that the first use of a static object will trigger the initialization of its static members, followed by instantiating its static constructor?  For this program, using A.X in main will trigger the initialization of A.X, which in turn initializes B.X, then B() and after finishing the initialization of A.X, will proceed to A().  Finally, Main() will output A.X and B.X`.

A: About four different rules in the C# spec are involved in making this guarantee, and it is specific to C#.  The only guarantee made by the .NET runtime is that type initialization begins before the type is used.

*

*That static fields are zero-initialized until the type initializer runs.

*That static field initializers run immediately before the static constructor.

*That static constructors are called at the first instance constructor call or first static member reference.

*That function arguments are evaluated in left-to-right order.

Relying on this is a very bad idea because it is likely to confuse anyone reading your code, especially if they are familiar with languages with a similar syntax which do not make all four of the above guarantees.
Please note that Porges comment was related to my initial statement (based on the .NET behavior) that the guarantees are too weak to assure the observed behavior.  Porges is right that the guarantees are strong enough, but in fact a far more complex chain is involved than he suggests.

A: You may be interested to know that it's even possible to assign values to a field between its default initialization and variable initialization.
private static int b = Foo();
private static int a = 4;

private static int Foo()
{
    Console.WriteLine("{0} - Default initialization", a);
    a = 3;
    Console.WriteLine("{0} - Assignment", a);
    return 0;
}

public static void Main()
{
    Console.WriteLine("{0} - Variable initialization", a);
}

outputs
0 - Default initialization
3 - Assignment
4 - Variable initialization

A: Straight from ECMA-334:

17.4.5.1: "If a static constructor (§17.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class."

And:

17.11: The execution of a static constructor is triggered by the first
  of the following events to occur within an application domain:

*

*An instance of the class is created.

*Any of the static members of the class are referenced.

  If a class contains the Main method (§10.1) in which execution begins, the static constructor for that class
  executes before the Main method is called. If a class contains any static fields with initializers, those
  initializers are executed in textual order immediately prior to executing the static constructor (§17.4.5).

So the order is:

*

*A.X used, so static A() called.

*A.X needs to be initialized, but it uses B.X, so static B() called.

*B.X needs to be initialized, and it is initialized to 7. B.X = 7

*All static fields of B are initialized, so static B() is called. X is printed ("7"), then it is set to A.X. A has already started being initialized, so we get the value of A.X, which is the default value ("when a class is initialized, all static fields in that class are first initialized to their default value"); B.X = 0, and is printed ("0").

*Done initializing B, and the value of A.X is set to B.X+1. A.X = 1.

*All static fields of A are initialized, so static A() is called. A.X is printed ("1").

*Back in Main, the values of A.X and B.X are printed ("1", "0").

It actually comments upon this in the standard:

17.4.5: It is possible for static fields with variable initializers to be observed in their default value state. However, this is strongly discouraged as a matter of style.

A: Deterministic initialization of static members is indeed guaranteed ... but it's not in "textual order". Furthermore, it may not be performed in a completely lazy fashion (meaning only when the static variable is first referenced). However, in your example using integers it wouldn't make a difference.
In some cases, it's desirable to get lazy initialization (particularly with expensive Singletons) - in which case you sometimes have to jump through some hoops to get it right.


text:
Q: React routeer is causing a blank index page. Next JS I'm creating a website, and I want the users to be directed to a specific page when they open the site. The page they are going to be directed to depends on if they already logged in. My problem is: the router doesn't work (user is not redirected to any page) and all that appears is a blank page. I've tried to get rid of the routes, but even though, I couldn't display anything on the index page. Maybe the problem is not even the router, but something else.
I never get any error messages. Here are the parts of the code, where I think the problem may be.
_app.js:
import React from 'react'
import { BrowserRouter as Router, Route } from "react-router-dom"
import Novidades from './lancamento'
import SignUp from './signup'
import Croosa from './croosa'
import { AuthProvider } from '../utils/auth'
import PrivateRoute from '../utils/PrivateRoute'

const App = () => {
  return(
        <AuthProvider>
          <Router>

              <PrivateRoute exact path='/lancamento' component={Lancamento} />
              <Route exact path='/croosa' component={Croosa}/>
              <Route exact path='/signup' component={SignUp} />

          </Router>
        </AuthProvider>
  )
}

export default App

index.js:
import React from 'react'
import App from './_app'

export default function Home() {
      return(
        <App/>
      )
}

And the PrivateRoute.js, which decides to which page the user is going to be redirected:
import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";
import { AuthContext } from "./auth";

const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
  const {currentUser} = useContext(AuthContext);
  return (
    <Route
      {...rest}
      render={routeProps =>
        !!currentUser ? (
          <RouteComponent {...routeProps} />
        ) : (
          <Redirect to={"/signup"} />
        )
      }
    />
  )
}

export default PrivateRoute

I would appreciate it if someone could point out my mistake(s).

A: Next.js uses a filesystem based routing structure.
You have a misunderstanding of how the _app.js file works. It's the parent component that is responsible for rendering the other components that get exported from other pages.
For example: if my _app.js file looks like this:
export default function App({ Component, pageProps }) {
    return (

This was injected by _app.js

            <Component {...pageProps} />

    );
}

and my pages/index.js file looks like this:
export default function Hello(){
    return
Hello World!

}

With that setup if I visit the localhost:3000/ then the following will get rendered

This was injected by _app.js

Hello World!

What you did instead is in your _app.js you ignored the Component property that was passed and so on every page you visit the same content will be rendered. That is:
<AuthProvider>
  <Router>

      <PrivateRoute exact path="/lancamento" component={Lancamento} />
      <Route exact path="/croosa" component={Croosa} />
      <Route exact path="/signup" component={SignUp} />

  </Router>
</AuthProvider>

The reason your index page is blank is because you didn't set up a route for / and so no component will be rendered by react router on that page. Regardless I suggest you stop using react router and start using the built in routing system with next.js


text:
Q: Gradient 2D plot using contourf I did a test code brigging something I saw on stack on different topic, and try to assemble it to make what I need : a filled curve with gradient.
After validate this test code I will make a subplot (4 plots for 4 weeks) with the same min/max for all plot (it's a power consumption).
My code :
from matplotlib import pyplot as plt
import numpy as np

# random x
x = range(100)

# smooth random y
y = 0
result = []
for _ in x:
    result.append(y)
    y += np.random.normal(loc=0, scale=1)#, size=len(x))
y = result
y = list(map(abs, y))

# creation of z for contour
z1 = min(y)
z3 = max(y)/(len(x)+1)
z2 = max(y)-z3
z = [[z] * len(x) for z in np.arange(z1,z2,z3)]

num_bars = len(x)  # more bars = smoother gradient

# plt.contourf(x, y, z, num_bars, cmap='greys')
plt.contourf(x, y, z, num_bars, cmap='cool', levels=101)

background_color = 'w'
plt.fill_between(
    x,
    y,
    y2=max(y),
    color=background_color
    )

But everytime I make the code run, the result display a different gradient scale, that is not smooth neither even straight right.
AND sometime the code is in error : TypeError: Length of y (100) must match number of rows in z (101)

I'm on it since too many time, turning around, and can't figure where I'm wrong...

A: I finally find something particularly cool, how to :

*

*have both filled gradient curves in a different color (thanks to JohanC in this topic)

*use x axis with datetime (thanks to Ffisegydd in this topic)

Here the code :
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates

np.random.seed(2022)

st_date = '2022-11-01 00:00:00'
st_date = pd.to_datetime(st_date)
en_date = st_date + pd.DateOffset(days=7)
x = pd.date_range(start=st_date,end=en_date,freq='30min')
x = mdates.date2num(x)

y = np.random.normal(0.01, 1, len(x)).cumsum()

fig, ax = plt.subplots(figsize=(18, 5))
ax.plot(x, y, color='grey')

########################
# positives fill
#######################

grad1 = ax.imshow(
    np.linspace(0, 1, 256).reshape(-1, 1),
    cmap='Blues',
    vmin=-0.5,
    aspect='auto',
    extent=[x.min(), x.max(), 0, y.max()],
    # extent=[x[0], x[1], 0, y.max()],
    origin='lower'
    )

poly_pos = ax.fill_between(x, y.min(), y, alpha=0.1)

grad1.set_clip_path(
    poly_pos.get_paths()[0],
    transform=ax.transData
    )

poly_pos.remove()

########################
# negatives fill
#######################

grad2 = ax.imshow(
    np.linspace(0, 1, 256).reshape(-1, 1),
    cmap='Reds',
    vmin=-0.5,
    aspect='auto',
    extent=[x.min(), x.max(), y.min(), 0],
    origin='upper'
    )

poly_neg = ax.fill_between(x, y, y.max(), alpha=0.1)

grad2.set_clip_path(
    poly_neg.get_paths()[0],
    transform=ax.transData
    )

poly_neg.remove()

########################
# decorations and formatting plot
########################

ax.xaxis_date()
date_format = mdates.DateFormatter('%d-%b %H:%M')
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate()
ax.grid(True)


text:
Q: Speed up this query joining to a table multiple times I have this query that (stripped right down) goes something like this :
SELECT
    [Person_PrimaryContact].[LegalName],
    [Person_Manager].[LegalName],
    [Person_Owner].[LegalName],
    [Person_ProspectOwner].[LegalName],
    [Person_ProspectBDM].[LegalName],
    [Person_ProspectFE].[LegalName],
    [Person_Signatory].[LegalName]

FROM [Cache]
   LEFT JOIN [dbo].[Person] AS [Person_Owner] WITH (NOLOCK)
       ON [Person_Owner].[PersonID] = [Cache].[ClientOwnerID]
   LEFT JOIN [dbo].[Person] AS [Person_Manager] WITH (NOLOCK)
       ON [Person_Manager].[PersonID] = [Cache].[ClientManagerID]
   LEFT JOIN [dbo].[Person] AS [Person_Signatory] WITH (NOLOCK)
       ON [Person_Signatory].[PersonID] = [Cache].[ClientSignatoryID]
   LEFT JOIN [dbo].[Person] AS [Person_PrimaryContact] WITH (NOLOCK)
       ON [Person_PrimaryContact].[PersonID] = [Cache].[PrimaryContactID]
   LEFT JOIN [dbo].[Person] AS [Person_ProspectOwner] WITH (NOLOCK)
       ON [Person_ProspectOwner].[PersonID] = [Cache].[ProspectOwnerID]
   LEFT JOIN [dbo].[Person] AS [Person_ProspectBDM] WITH (NOLOCK)
       ON [Person_ProspectBDM].[PersonID] = [Cache].[ProspectBDMID]
   LEFT JOIN [dbo].[Person] AS [Person_ProspectFE] WITH (NOLOCK)
       ON [Person_ProspectFE].[PersonID] = [Cache].[ProspectFEID]

Person is a huge table and each join to it has a pretty significant hit in the execution plan.
Is there anyway I can adjust this query so that I am only linking to it once, or at least get SQL Server to scan through it only once?
EDIT
Here is the plan:
  |--Parallelism(Gather Streams)
       |--Merge Join(Right Outer Join, MERGE:([Person_ProspectFE].[PersonID])=([Cache].[ProspectFEID]), RESIDUAL:([PracticeManagement].[dbo].[Person].[PersonID] as [Person_ProspectFE].[PersonID]=[PracticeManagement].[dbo].[ListCache].[ProspectFEID] as [Cache].[ProspectFEID]))
            |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Person_ProspectFE].[PersonID]), ORDER BY:([Person_ProspectFE].[PersonID] ASC))
            |    |--Clustered Index Scan(OBJECT:([PracticeManagement].[dbo].[Person].[Person_PK] AS [Person_ProspectFE]), ORDERED FORWARD)
            |--Sort(ORDER BY:([Cache].[ProspectFEID] ASC))
                 |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Cache].[ProspectFEID]))
                      |--Merge Join(Right Outer Join, MERGE:([Person_ProspectBDM].[PersonID])=([Cache].[ProspectBDMID]), RESIDUAL:([PracticeManagement].[dbo].[Person].[PersonID] as [Person_ProspectBDM].[PersonID]=[PracticeManagement].[dbo].[ListCache].[ProspectBDMID] as [Cache].[ProspectBDMID]))
                           |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Person_ProspectBDM].[PersonID]), ORDER BY:([Person_ProspectBDM].[PersonID] ASC))
                           |    |--Clustered Index Scan(OBJECT:([PracticeManagement].[dbo].[Person].[Person_PK] AS [Person_ProspectBDM]), ORDERED FORWARD)
                           |--Sort(ORDER BY:([Cache].[ProspectBDMID] ASC))
                                |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Cache].[ProspectBDMID]))
                                     |--Merge Join(Right Outer Join, MERGE:([Person_ProspectOwner].[PersonID])=([Cache].[ProspectOwnerID]), RESIDUAL:([PracticeManagement].[dbo].[Person].[PersonID] as [Person_ProspectOwner].[PersonID]=[PracticeManagement].[dbo].[ListCache].[ProspectOwnerID] as [Cache].[ProspectOwnerID]))
                                          |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Person_ProspectOwner].[PersonID]), ORDER BY:([Person_ProspectOwner].[PersonID] ASC))
                                          |    |--Clustered Index Scan(OBJECT:([PracticeManagement].[dbo].[Person].[Person_PK] AS [Person_ProspectOwner]), ORDERED FORWARD)
                                          |--Sort(ORDER BY:([Cache].[ProspectOwnerID] ASC))
                                               |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Cache].[ProspectOwnerID]))
                                                    |--Merge Join(Right Outer Join, MERGE:([Person_PrimaryContact].[PersonID])=([Cache].[PrimaryContactID]), RESIDUAL:([PracticeManagement].[dbo].[Person].[PersonID] as [Person_PrimaryContact].[PersonID]=[PracticeManagement].[dbo].[ListCache].[PrimaryContactID] as [Cache].[PrimaryContactID]))
                                                         |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Person_PrimaryContact].[PersonID]), ORDER BY:([Person_PrimaryContact].[PersonID] ASC))
                                                         |    |--Clustered Index Scan(OBJECT:([PracticeManagement].[dbo].[Person].[Person_PK] AS [Person_PrimaryContact]), ORDERED FORWARD)
                                                         |--Sort(ORDER BY:([Cache].[PrimaryContactID] ASC))
                                                              |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Cache].[PrimaryContactID]))
                                                                   |--Merge Join(Right Outer Join, MERGE:([Person_Signatory].[PersonID])=([Cache].[ClientSignatoryID]), RESIDUAL:([PracticeManagement].[dbo].[Person].[PersonID] as [Person_Signatory].[PersonID]=[PracticeManagement].[dbo].[ListCache].[ClientSignatoryID] as [Cache].[ClientSignatoryID]))
                                                                        |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Person_Signatory].[PersonID]), ORDER BY:([Person_Signatory].[PersonID] ASC))
                                                                        |    |--Clustered Index Scan(OBJECT:([PracticeManagement].[dbo].[Person].[Person_PK] AS [Person_Signatory]), ORDERED FORWARD)
                                                                        |--Sort(ORDER BY:([Cache].[ClientSignatoryID] ASC))
                                                                             |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Cache].[ClientSignatoryID]))
                                                                                |--Merge Join(Right Outer Join, MERGE:([Person_Manager].[PersonID])=([Cache].[ClientManagerID]), RESIDUAL:([PracticeManagement].[dbo].[Person].[PersonID] as [Person_Manager].[PersonID]=[PracticeManagement].[dbo].[ListCache].[ClientManagerID] as [Cache].[ClientManagerID]))
                                                                                |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Person_Manager].[PersonID]), ORDER BY:([Person_Manager].[PersonID] ASC))
                                                                                |    |--Clustered Index Scan(OBJECT:([PracticeManagement].[dbo].[Person].[Person_PK] AS [Person_Manager]), ORDERED FORWARD)
                                                                                |--Sort(ORDER BY:([Cache].[ClientManagerID] ASC))
                                                                                |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Cache].[ClientManagerID]))
                                                                                |--Merge Join(Right Outer Join, MERGE:([Person_Owner].[PersonID])=([Cache].[ClientOwnerID]), RESIDUAL:([PracticeManagement].[dbo].[Person].[PersonID] as [Person_Owner].[PersonID]=[PracticeManagement].[dbo].[ListCache].[ClientOwnerID] as [Cache].[ClientOwnerID]))
                                                                                |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Person_Owner].[PersonID]), ORDER BY:([Person_Owner].[PersonID] ASC))
                                                                                |    |--Clustered Index Scan(OBJECT:([PracticeManagement].[dbo].[Person].[Person_PK] AS [Person_Owner]), ORDERED FORWARD)
                                                                                |--Sort(ORDER BY:([Cache].[ClientOwnerID] ASC))
                                                                                |--Parallelism(Repartition Streams, Hash Partitioning, PARTITION COLUMNS:([Cache].[ClientOwnerID]))
                                                                                |--Clustered Index Scan(OBJECT:([PracticeManagement].[dbo].[ListCache].[IX_ListCache_Type] AS [Cache]))

A: Assuming PersonId is the primary Key on the Person table, and that you have a Primary Key index on that field, (which should happen automatically when you designated that as PK), then no, that PK index is the best way to get at the seven different values in the Person table that you need to access... And what you are doing is the best way... But it should not be scanning the person table seven times, it should be traversing the Primary Key index on the Person table seven times, which is much faster... Check the query plan and ensure that that is what it is doing...

A: If slower inserts, updates and deletes aren't a problem for you, you can create an indexed (materialized) view for your query and select your records from that view.
http://technet.microsoft.com/en-us/library/cc917715.aspx

A: Make sure you've created indexes on not only the Person.PersonID field but also the fields in Cache that are being used to join the two tables.

A: Have you tried using profiler and the DTA to see if it suggests any indexes?

A: One (rather long-winded) approach would be to select PersonID and LegalName into a separate temporary table for each of the Cache Person roles you're interested in, like so:
select [Person].[PersonID], [Person.LegalName]
into #Person_Owner
from [Cache] join [Person] with (nolock)
on [Person].[PersonID] = [Cache].[ClientOwnerID]

Then run a final query, linking each of the Cache Person roles to the relevant temporary tables. It's messy and longwinded (in code terms), but it should ensure that you only retrieve the Person records you need once for each role.
Alternatively, you could do a cartesian join between [Cache] and [Person], then use case structures to determine which Cache roles match which Legal Names. It would ensure that the [Person] table is only scanned once, but the result set would be gigantic; it's only likely to be faster than your existing query if it's logical reads that are slowing you down, and you have an awful lot of memory to spare on your DB server.


text:
Q: Why there is type: Cannot find path error I would like to understand why I'm receiving below error when I'm trying to create new empty file in VS Code terminal. See below:
type : Cannot find path '[FILE_PATH]\nul' because it does not exist.
At line:1 char:1
+ type nul > '[FILE_NAME]'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ([FILE_PATH]\nul:String) [Get-Content], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

I am using Windows and I used:
type nul > '[FILE_NAME]'

It was pretty long name with spaces so that's why I used ''. Also funny thing is that the file was created but the error appears each time. Do you why this is happening and how to get rid of it? Do you recommend any other methods for creating empty files on Windows?

A: I was looking for an answer to this as well. I found out that you can just type echo > filename.txt and you would no longer get that error. Hopefully this helps you as well.


text:
Q: Setting the width to 100% I have a layout that looks kind of like this:

And the code looks like this:
http://jsfiddle.net/redconservatory/L8tBk/
Basically, there is a div on the left that is floated left so that the text and the button end up on the right of the image (which is also floated left).
However, to get this to work I have to put a width on the inner div or else the div will float below the image.
This is all right until the user does not upload an image, and then what I get looks like this:
http://jsfiddle.net/redconservatory/dr3FG/
With the text just taking up a part of the container, instead of filling out to fill up the entire container.
Is there any way around this? I would like the text to take up most of the container...

A: Yes - I'd recommend understand the "media element" by Nicolle Sullivan http://www.stubbornella.org/content/2010/06/25/the-media-object-saves-hundreds-of-lines-of-code/
Essentially:
img { float: left; }
.description { overflow: hidden; }

Now if there is an image its ok, if there isn't, its ok. Remove widths and floats from your description. Use padding to get desired effects needed, or put a margin on the image.


text:
Q: Unable to find Google Chrome DevTools of Overrides to show Emulator tab I'm using Google Chrome Version 49.0.2623.87 (64-bit) on OSX 10.10.5 (14F1605). Tried to find Overrides tab to show Emulator. I had also tried after cleaning all user data from PC & installed a newly downloaded Chrome dmg package, but no luck. Is there any reason to hide Overrides or Emulator tab. Attached image for reference.

A: This is so the drawer panels are able to be kept minimal to what a developer needs to be there. More can also be added later without necessarily adding more panels in the way for everyone. Just toggle what you need and be happy.


text:
Q: Storing LVM encryption key on network share I want to encrypt all my LVM LV's and have them automatically unlocked on boot using a keyfile available on my network. I can make the files available by SMB, NFS, HTTPS, etc.
I have Ubuntu Server 14.04.2 with LVM setup for the main drive and a seperate VG consisting for 3 hard drives organized into a single LV. I want to encrypt everything except the /boot.
EDIT: I guess a question might be more helpful
I want to know how I would access the keyfile from a network share automatically at boot. Would it be as simple as placing the network path somewhere or would I need to download it, decrypt, and delete it? As I said I can share it with just about any network filesystem


text:
Q: Pyschools remove Common Elements def removeCommonElements(tup1,tup2):
count=0
lis1=list(tup1)
lis2=list(tup2)
while count<=len(lis1):
    for i in lis1:
        if i in lis2:
            lis1.remove(i)
            lis2.remove(i)
    count+=1
    return tuple(lis1+lis2)

print(removeCommonElements((1,2,3,4), (3,4,5,6)))

I need the output as (1, 2, 5, 6) and i'm getting an output as (1, 2, 4, 4, 5, 6).
I couldn't able to find my mistake. Can anyone please help me?
Thank you

A: It's the indenting. Indent as follows:
def removeCommonElements(tup1,tup2):
    count=0
    lis1=list(tup1)
    lis2=list(tup2)
    while count<=len(lis1):
        for i in lis1:
            if i in lis2:
                lis1.remove(i)
                lis2.remove(i)
        count+=1
    return tuple(lis1+lis2)

print(removeCommonElements((1,2,3,4), (3,4,5,6)))

A: for i in lis1:
        if i in lis2:
            lis1.remove(i)
            lis2.remove(i)

This part of your code is looping through a list while modifying it meanwhile. So 4 is left out. You can use set to do this:
>>> def removeCommon(x, y):
...     x = set(x)
...     y = set(y)
...     return tuple(set.union(x, y)-set.intersection(x, y))
...
>>> a = (1,2,3,4)
>>> b = (3,4,5,6)
>>> removeCommon(a, b)
(1, 2, 5, 6)


text:
Q: lazy var NSFetchedResultsController producing error in Swift 3.0 I just migrated my project to Swift 3 and am stuck on an error for my lazy instantiated NSFetchResultController. I use this method here :
https://www.andrewcbancroft.com/2015/03/05/displaying-data-with-nsfetchedresultscontroller-and-swift/
My current code
lazy var fetchedResultsController: NSFetchedResultsController = {

    let primarySortDescriptor = NSSortDescriptor(key: "company", ascending: true)
    let sortDescriptors = [primarySortDescriptor]

    self.fetchRequest.sortDescriptors = sortDescriptors

    let frc = NSFetchedResultsController(
        fetchRequest: self.fetchRequest,
        managedObjectContext: self.managedObjectContext!,
        sectionNameKeyPath: nil,
        cacheName: nil)

    frc.delegate = self

    return frc
}()

It produces 2 errors as shown below

Is this method no longer possible under Swift 3? I tried adding () -> <<error type>> in as suggested by Xcode but failed to produce the correct results.

A: The suggested () -> <<error type>> is misleading.
In Swift 3 NSFetchedResultsController has become a generic type.
You have to initialize it:
lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
...
}()

as well as NSFetchRequest
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "MyEntity")

If you are using a subclass of NSManagedObject – which is recommended – you can use the subclass type for being more specific
lazy var fetchedResultsController: NSFetchedResultsController<MyEntity> = {
....
let fetchRequest = NSFetchRequest<MyEntity>(entityName: "MyEntity")

The huge benefit is you get rid of all type casts using fetch, insert etc.


text:
Q: ReCaptcha (Invisible) execute callback is not firing with multiple widget instances I had reCaptcha running on contact forms that trigger by AJAX (Naturally, to use the ReCaptcha server side verification via PHP curl()) for a while.
I've tried to update the javascript triggers to enable multiple forms on one page.
Now, even with just one form per page, the grecaptcha.execute() does not appear to return the call back function at all.
There's no value assigned to the tag <textarea class="g-recaptcha-response"> either after executing (even by manual run on console!).
Here's what I got:
Step A: Calling in the JS Library (I call this as the LAST javascript file, after my common.js file is loaded).

The HTML Code witih public key, and callback function set to CaptchaExecSubmit();:

Enabler in my common.js is as below.
The library from google is called with onload=CaptchaCallback as the attribute to execute upon deferred async loading of the reCaptcha library.
// Render each recaptcha.
window.CaptchaCallback = function(){
    $('.g-recaptcha').each(function(index, el) {
        var recaptcha_widget_callback = $(el).data('callback');
        console.log()
        var attributes = {
            'sitekey'  : $(el).data('sitekey'),
            'size'     : $(el).data('size'),
            'callback' : recaptcha_widget_callback
        };
        var recaptcha_widget_id = grecaptcha.render(el, attributes);
        $(el).data('recaptcha-widget-id', recaptcha_widget_id);
        // assign unique ID to each instance of it, so that multiple recaptcha instances can be initiated.
        console.log('setting ID for recaptcha sequence: '+recaptcha_widget_id+' with call back '+recaptcha_widget_callback);
    });
}

window.CaptchaExecSubmit = function(captcha_response) {
    console.log('invisible captcha verified, activate form '+window.activeForm);
    console.log('Captcha exsec response: '+captcha_response)
    window.recaptchaverified = 1;
    activate_ajaxemailform($(window.activeForm));
    return true;
}

CaptchaCallback(); seems to be running fine, widget IDs and callback definitions are good. (Console says "setting ID for recaptcha sequence: 0 with call back CaptchaExecSubmit").
Then, attaching the behaviour on each form element (with class .emailform):
$(document).ready(function(){
    $('.emailform').each(function(){
        var thisform = $(this);
        var thisform_id = $(this).attr('id');
        console.log('Activating emailform '+thisform_id);

        $(this).submit(function(e){
            var captcha = $(this).find('.g-recaptcha');
            var callback = captcha.data('callback');
            e.preventDefault();
            var captcha_widget_id = captcha.data('recaptcha-widget-id');// this captcha instance.. usually 0, 1 etc. base don sequence of load.
            console.log('Captcha callback: '+callback+' From widget sequence '+captcha_widget_id);
            // If captcha is invisible then enable the test verification before submitting the form
            if ((typeof captcha !== "undefined") && (captcha.data('size') === 'invisible')) {
                window.activeForm = thisform; // Stores current form so we can submit it later
                console.log("Setting active form to "+thisform_id);
                grecaptcha.execute(captcha_widget_id);
                var g_response = thisform.find('.g-recaptcha-response').val();
                // Captcha check, this will run enable_contact_submit_invisible() as a callback if successful.
                console.log('grecaptcha.execute on ID '+ captcha_widget_id+', g_reponse: '+g_response);
                return false;
            } else {
                return activate_ajaxemailform(thisform);
            }
        });
    });

});

When I manually run grecaptcha.execute(0); it runs, returns some complex looking object, but the textarea.g-recaptcha-response is still empty, and the callback of CaptchaExecSubmit(); still does not run.
Then, tried manually run CaptchaExecSubmit(); on console, the form submission DOES work fine - except that the textarea.g-recaptcha-response value is empty, so it just fails the server-side test.

I'm about 4 hours into this, losing my sanity. Help please.
I realize at this point I have a lot of vars declared then console logged and a tad messy - I want to leave no stone unturned, check every single bit before calling out for help.

A: ... make sure you check the ReCaptcha key version to be V3, not V2.
I'm shocked that the RECAPTCHA library doesn't return an error saying the key is not eligible for the new one.
This site, I had running for a long time. Whole 4 hours, it never occurred to me to check the API Key attached in the recaptcha console. It was the old one.


text:
Q: sorting via order by and row_number via user variable in mariadb I've read that any order by Operation is done at the end of the query and therefore sorting cannot be forced in a result before.
So what I'm trying to achive is to get only one record from a result with duplicates by using variables which assign row numbers and by using a having-clause I only select the first row.
Sorry for my bad explanation, I hope you know what I mean by taking a look at this:
select *
from address left join
(select address.add_nr as add_nr, acc.typ as typ, acc.seq as seq,
@num := if(@add_nr = address.add_nr, @num + 1, 1) as row_number,
@add_nr := address.add_nr as dummy
from
address left join

(

select con_add_nr as add_nr, 'XY' as typ, 1 as seq
from conctract,conctractdet
where con_pol_kz IN('L')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
group by 1,2,3

union
select ris_add_nr as add_nr, 'XX' as typ, 4 as seq
from conctract,conctractdet,risaddress
where con_pol_kz IN('P','PU','A')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
and con_nr=ris_con_nr
and ris_art='VP'
group by 1,2,3

union
select ris_add_nr as add_nr, 'YY' as typ, 3 as seq
from conctract,conctractdet,risaddress
where con_pol_kz IN('P','PU','A')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
and vrs_nr=ris_vrs_nr
and ris_art='VP'
group by 1,2,3

union
select ris_add_nr as add_nr, 'YX' as typ, 5 as seq
from conctract,conctractdet,risaddress
where con_pol_kz IN('P','PU','A')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
and con_nr=ris_con_nr
and ris_art='2. VN'
group by 1,2,3

union
select ris_add_nr as add_nr, 'X' as typ, 2 as seq
from conctract,conctractdet,risaddress
where con_pol_kz IN('P','PU','A')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
and vrs_nr=ris_vrs_nr
and ris_art='2. VN'
group by 1,2,3

order by add_nr,seq asc) as acc on acc.add_nr=address.add_nr
having row_number=1) as acc on address.add_nr=acc.add_nr;

So the problem is that the order by Operation is done at the end when the row_number has already been assumed. What I need is to sort the result  by the sequence number "seq" first, achieving that the first entry gets row_number=1. At the moment the first entry in the "unsorted" Result gets the row_number=1 and this is not what I need.

A: Don't use HAVING with columns that you're generating on the fly with a user variable. MySQL performs some optimizations that mess this up. Instead, use a WHERE clause in the outer query.
select *
from address left join
(select address.add_nr as add_nr, acc.typ as typ, acc.seq as seq,
@num := if(@add_nr = address.add_nr, @num + 1, 1) as row_number,
@add_nr := address.add_nr as dummy
from
address
cross join (select @add_nr := 0, @num := 0) AS init
left join

(

select con_add_nr as add_nr, 'XY' as typ, 1 as seq
from conctract,conctractdet
where con_pol_kz IN('L')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
group by 1,2,3

union
select ris_add_nr as add_nr, 'XX' as typ, 4 as seq
from conctract,conctractdet,risaddress
where con_pol_kz IN('P','PU','A')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
and con_nr=ris_con_nr
and ris_art='VP'
group by 1,2,3

union
select ris_add_nr as add_nr, 'YY' as typ, 3 as seq
from conctract,conctractdet,risaddress
where con_pol_kz IN('P','PU','A')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
and vrs_nr=ris_vrs_nr
and ris_art='VP'
group by 1,2,3

union
select ris_add_nr as add_nr, 'YX' as typ, 5 as seq
from conctract,conctractdet,risaddress
where con_pol_kz IN('P','PU','A')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
and con_nr=ris_con_nr
and ris_art='2. VN'
group by 1,2,3

union
select ris_add_nr as add_nr, 'X' as typ, 2 as seq
from conctract,conctractdet,risaddress
where con_pol_kz IN('P','PU','A')
and con_nr=vrs_con_nr
and cond_spa_nr IN (102,160,173)
and vrs_nr=ris_vrs_nr
and ris_art='2. VN'
group by 1,2,3

order by add_nr,seq asc) as acc on acc.add_nr=address.add_nr) as acc on address.add_nr=acc.add_nr
WHERE row_number = 1;

This optimization is briefly alluded to in the documentation

HAVING is merged with WHERE if you do not use GROUP BY or aggregate functions (COUNT(), MIN(), and so on).

What this means is if it can treat the HAVING clause like WHERE, it will do so, so it will remove rows from the results while generating the result set, instead of waiting until all the result rows are produced.


text:
Q: Call method with assembly loaded from GAC I am trying to call the Save method from a System.Drawing.Image object, after loading the assembly from the GAC:
_drawingAssembly = Assembly.Load
                    ("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");

_drawingAssembly.GetType("Image").GetMethod("Save").Invoke(myImageObject, new object[] { path });

But it's not working. I can't even get the type for some reason; this returns null:
var t = _drawingAssembly.GetType("Image"); // null

A: You need to specify the full type name System.Drawing.Image as indicated by the documentation:
https://msdn.microsoft.com/en-us/library/y0cd10tb(v=vs.110).aspx


text:
Q: Convert IDispatch* to a string? I am converting an old VB COM object (which I didn't write) to C++ using ATL.  One of the methods, according to the IDL, takes an IDispatch* as a parameter and the documentation and samples for this method claim that you can pass either a string (which is the progid of an object that will be created and used by the control) or an IDispatch* to an object that has already been created.  How on earth do I implement this in ATL?
For example, the IDL:
[id(1)] HRESULT Test(IDispatch* obj);

The samples (which are all JScript):
obj.Test("foo.bar");

or
var someObject = new ActiveXObject("foo.bar");
obj.Test(someObject);

To make matters even more bizarre the actual VB code that implements this method actually declares the 'obj' parameter as a string!  However, it all seems to work.
Can you even pass a string to a COM method that takes an IDispatch*?  If so, can I determine that the IDispatch* is actually a string in my C++ ATL code?  Even better, if it's an IDispatch that implements a specific interface I will want to call methods on it, or instantiate an object if it's a string.
Any ideas welcome!

A: Declare the method so that it takes a VARIANT argument and check the actual type at runtime.

A: If you have instance obj of VB6 class Class1 and try to assign it to a primitive type like this
    Dim str As String
    str = obj

... then Class1's default property gets evaluated. Same rule applies for method calls
Function MyFunc(str As String)
   ...
End Function

   MyFunc obj

Last method call will succeed only if Class1 has a default property defined and obj's default property value can be cast to String.


text:
Q: Reload choices dynamically when using MultipleChoiceFilter I am trying to construct a MultipleChoiceFilter where the choices are the set of possible dates that exist on a related model (DatedResource).
Here is what I am working with so far...
resource_date = filters.MultipleChoiceFilter(
    field_name='dated_resource__date',
    choices=[
        (d, d.strftime('%Y-%m-%d')) for d in
        sorted(resource_models.DatedResource.objects.all().values_list('date', flat=True).distinct())
    ],
    label="Resource Date"
)

When this is displayed in a html view...

This works fine at first, however if I create new DatedResource objects with new distinct date values I need to re-launch my webserver in order for them to get picked up as a valid choice in this filter. I believe this is because the choices list is evaluated once when the webserver starts up, not every time my page loads.
Is there any way to get around this? Maybe through some creative use of a ModelMultipleChoiceFilter?
Thanks!
Edit:
I tried some simple ModelMultipleChoice usage, but hitting some issues.
resource_date = filters.ModelMultipleChoiceFilter(
    field_name='dated_resource__date',
    queryset=resource_models.DatedResource.objects.all().values_list('date', flat=True).order_by('date').distinct(),
    label="Resource Date"
)

The HTML form is showing up just fine, however the choices are not accepted values to the filter. I get "2019-04-03" is not a valid value. validation errors, I am assuming because this filter is expecting datetime.date objects. I thought about using the coerce parameter, however those are not accepted in ModelMultipleChoice filters.
Per dirkgroten's comment, I tried to use what was suggested in the linked question. This ends up being something like
resource_date = filters.ModelMultipleChoiceFilter(
    field_name='dated_resource__date',
    to_field_name='date',
    queryset=resource_models.DatedResource.objects.all(),
    label="Resource Date"
)

This also isnt what I want, as the HTML now form is now a) displaying the str representation of each DatedResource, instead of the DatedResource.date field and b) they are not unique (ex if I have two DatedResource objects with the same date, both of their str representations appear in the list. This also isnt sustainable because I have 200k+ DatedResources, and the page hangs when attempting to load them all (as compared to the values_list filter, which is able to pull all distinct dates out in seconds.

A: One of the easy solutions will be overriding the __init__() method of the filterset class.
from django_filters import filters, filterset

class FooFilter(filterset.FilterSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        try:
            self.filters['user'].extra['choices'] = [(d, d.strftime('%Y-%m-%d')) for d in sorted(
                resource_models.DatedResource.objects.all().values_list('date', flat=True).distinct())]
        except (KeyError, AttributeError):
            pass

    resource_date = filters.MultipleChoiceFilter(field_name='dated_resource__date', choices=[], label="Resource Date")
NOTE: provide choices=[] in your field definition of filterset class

Results
I tested and verified this solution with following dependencies
1. Python 3.6
2. Django 2.1
3. DRF 3.8.2
4. django-filter 2.0.0
I used following code to reproduce the behaviour
# models.py
from django.db import models

class Musician(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return f'{self.name}'

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()

    def __str__(self):
        return f'{self.name} : {self.artist}'

# serializers.py
from rest_framework import serializers

class AlbumSerializer(serializers.ModelSerializer):
    artist = serializers.StringRelatedField()

    class Meta:
        fields = '__all__'
        model = Album

# filters.py
from django_filters import rest_framework as filters

class AlbumFilter(filters.FilterSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.filters['release_date'].extra['choices'] = self.get_album_filter_choices()

    def get_album_filter_choices(self):
        release_date_list = Album.objects.values_list('release_date', flat=True).distinct()
        return [(date, date) for date in release_date_list]

    release_date = filters.MultipleChoiceFilter(choices=[])

    class Meta:
        model = Album
        fields = ('release_date',)

# views.py
from rest_framework.viewsets import ModelViewSet
from django_filters import rest_framework as filters

class AlbumViewset(ModelViewSet):
    serializer_class = AlbumSerializer
    queryset = Album.objects.all()
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = AlbumFilter

Here I've used the django-filter with DRF.
Now, I populated some data through Django Admin console. After that, the album api become as below,

and I got the release_date as

Then, I added new entry through Django admin -- (Screenshot) and I refresh the DRF API endpoint and the possible choices became as below,

A: I have looked into your problem and I have following suggestions
The Problem
You have got the problem right. Choices for your MultipleChoiceFilter are calculated statically whenever you run server.Thats why they don't get updated dynamically whenever you insert new instance in DatedResource.
To get it working correctly, you have to provide choices dynamically to MultipleChoiceFilter. I searched in documentation but did not find anything regarding this. So here is my solution.
The solution
You have to extend MultipleChoiceFilter and create your own filter class. I have created this and here it is.
from typing import Callable
from django_filters.conf import settings
import django_filters

class LazyMultipleChoiceFilter(django_filters.MultipleChoiceFilter):
    def get_field_choices(self):
        choices = self.extra.get('choices', [])
        if isinstance(choices, Callable):
            choices = choices()
        return choices

    @property
    def field(self):
        if not hasattr(self, '_field'):
            field_kwargs = self.extra.copy()

            if settings.DISABLE_HELP_TEXT:
                field_kwargs.pop('help_text', None)

            field_kwargs.update(choices=self.get_field_choices())

            self._field = self.field_class(label=self.label, **field_kwargs)
        return self._field

Now you can use this class as replacement and pass choices as lambda function like this.
resource_date = LazyMultipleChoiceFilter(
    field_name='dated_resource__date',
    choices=lambda: [
        (d, d.strftime('%Y-%m-%d')) for d in
        sorted(resource_models.DatedResource.objects.all().values_list('date', flat=True).distinct())
    ],
    label="Resource Date"
)

Whenever instance of filter will be created choices will be updated dynamically. You can also pass choices statically (without lambda function) to this field if want default behavior.


text:
Q: Read XML with C# and fill List I have an XML document that contains data about two table.
The structure is like this
<doc>

    <row>
      <field name="id">0431524493258932</field>
      <field name="anno">2018</field>
      <field name="att">0000</field>
      <field name="cen">01</field>
      ...
    </row>
    <row>
      <field name="id">1041524493596749</field>
      <field name="anno">2018</field>
      <field name="att">0000</field>
      <field name="cen">01</field>
      ...
    </row>
...

    <row>
      <field name="id">0431524493258932</field>
      <field name="anno">2018</field>
      <field name="att">0000</field>
      <field name="cen">4U</field>
....

<doc>

I am trying this way with first table in XML with a lot of confusion
var doc = XDocument.Load(filename);

var ordcli = doc.Descendants("table")
             .Where(i => (string)i.Attribute("name") == "ordini")
             .Descendants("row")
             .Select(e => e.Elements());

foreach (var item in ordcli)
{
    foreach (var i in item)
    {
        Console.WriteLine(i);
    }
}

How can I read every row element and get field name to instantiate my Order class and OrderDetails class?
When I have my List<Order> and List<OrderDetails> filled I can populate relative tables.
I hope I've explained my requirement well.
I've never used XlmReader or Linq2Xml. It's first time.

A: try following code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            new XML_DataSet(FILENAME);
        }
    }
    public class XML_DataSet
    {
        static DataSet ds = new DataSet();

        public XML_DataSet(string filename)
        {
            XDocument doc = XDocument.Load(filename);

            foreach(XElement table in doc.Descendants("table"))
            {
                ds.Tables.Add(ReadTable(table));
            }

        }

        private DataTable ReadTable(XElement table)
        {
            DataTable dt = new DataTable();
            Boolean first = true;

            foreach (XElement xRow in table.Elements("row"))
            {
                if (first)
                {
                    foreach (XElement field in xRow.Elements("field"))
                    {
                        dt.Columns.Add((string)field.Attribute("name"), typeof(string));
                    }
                    first = false;
                }
                DataRow newRow = dt.Rows.Add();
                foreach (XElement field in xRow.Elements("field"))
                {
                    newRow[(string)field.Attribute("name")] = (string)field;
                }
            }

            return dt;
        }
    }

}


text:
Q: Specific suggestions on how to prepare for AngularJS 2.0? I have an AngularJS 1.3 application that will I suppose eventually move to AngularJS 2.0. I've watched the videos from ng-europe and I understand there are many changes. As I expect development to continue with our AngularJS 1.3 code for the next 12 I would like to hear if anyone has any specific suggestions on preparing for 2.0.
My application is simple in that it creates no directives. In particular I would like to hear any tips on how I should go about creating controllers to get ready for them being very different in 2.0. Should I eliminate all references to scope in my controllers. Should I move everything to services?
I hope for some useful suggestions but of course specific ones so this question does not get closed.
Thanks

A: I think that so little has specifically been announced yet, and there's so much potential for it to change that it's a hard question to answer, e.g. check out this issue for an example of something quite fundamental that's likely to change since the ng-europe announcement.
Within my team we're trying to take the following approach:

*

*Try not to use $scope (controller-as syntax).

*Keep your controllers as light as possible by using directives to encapsulate UI functionality and services to deal with data models / API calls.

*Use the new syntax for one-way binding where you don't need two-way binding.  One-way binding will be the default for Angular 2.0.

*Write some unit tests!  It'll be much easier to do some significant refactoring if you have some confidence that your code will still work :).

Not only should that help with the move to 2.0 if / when that happens, but it should help your 1.3 apps too!


text:
Q: Domain User logged in with Temp Profile in Windows Server 2008 R2 64 Bit OS I am new to the forum. I am having a trouble with Windows server 2008 R2 Domain. I am having IBM 3650 Server installed with Windows Server 2008 R2 64 Bit domain. I am using Thin Clients as Nodes. Model No of thin client is : NComputing L300. Now I have created Domain users. All the thin Client are successfully connected to the server over the LAN and ask to provide the user log in details i.e. credentials. Now if I login using one of the user and then Go to "c"\Users\" folder what I can see is a "Temp.domainname" folder is created as profile folder instead of the "username" profile. Due to this every time the user logs off, the "temp.domainname" profile is deleted automatically. This is happening with all the users.
More over I tried log in using the uers credentials locally in server it self in order to assure that is related to thin client or some thing is wrong with the server. But even if I login locally in the server using the user credential, it loads with "Temp.domainname" profile instead of the "username" profile.
Can you please let me know how can I get out of this?

A: This happens a lot when you have Mandatory Profiles configured for Server 2003 and then move to 2008+ without planning. Profiles are different between these versions of Windows, so a mandatory 2003/XP profile won't load on Vista+/2008+, which will cause a temporary profile to load.
My hunch is that you just have misconfigured profiles.
If you don't, it could also be caused by disk corruption or some other oddity. Check the event logs for more descriptive details and update your question if this doesn't resolve it.

A: A Fix I have found for this is logging into the server as an admin, deleted the registry keys in regedit for the users that are logging in with a temp account.
The registry key can be found in the program called regedit
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
When you have done this also create a back up of the users files, rename the users fold to username.old.
Log in as the user, this should then mean they are logging in with a clean profile i.e. no documents or settings.
By which point log off as the user, copy all the files from the username.old into the newly created user folder, check there is a new registry key for that user, then log back in.
I am yet to find out why this is happening but by recreating the profile I have not had this problem again.
Regards,
Alex Hawkins

A: I fixed this by making a back up copy of the profile to another disk.  Then restarting the machine into Safe Mode.  I got into System properties and removed all profiles.  Then restarted and logged in with my domain account.
Then it worked.


text:
Q: numbers only push to one index in jquery I'm am trying to push numbers in an array from a variable.
each time a checkbox is clicked its bring back a number which I then want to be pushed into an array. but every time, all numbers are concatenated in the first cell of the array, where I need to hold these numbers separately.
can anyone help?
$('#tbldata tr:has(td)').find('.checkboxes').click(function() {
    var stuff = [] ;
    var Checked = $(this).prop("checked");
    var sep = 0;
    //var val =   $('#tbldata tr:has(td)').find('.checkboxes').find('td:eq(2)').closest("#reqnum").val();
    if(checked = 'checked')
        alert("clicked");
    sep+ 1;

    var selectedRows = JSON.parse("["+ ($('table._tm' ).find('tbody')// select table body and
    .has( 'input[type=checkbox]:checked' )
    .find( 'td' )
    .find( '.reqnum' )).text() + "]");// checked checkbox element

    stuff.push(selectedRows);
    console.log(stuff);

    $('#buttonDone').click(function() {
        $.ajax({
            type: "POST",
            url: "isdone.php",
            data: {reqnum : reqnum},
            success: function(data)
            {
                alert(data);
                alert("success!");
                //alert("con7: " + con7 + "rowid" + rowid);
            }
        });
        console.log("hello");
    });
});

A: jquery's text() method concatenates the text content of every elements. Here is a solution
Same goes for var stuff = [];.
$('#tbldata tr:has(td)').find('.checkboxes').click(function() {
  var stuff = $('table._tm' )
    .find('tbody')
    .has('input[type=checkbox]:checked')
    .find('td')
    .find('.reqnum'))
    // Uses map to apply text on each element separately.
    .map(function(){
      return $(this).text();
    })
    // Transform the jquery object to a JS array.
    .toArray();
  console.log(stuff);
});

I kept your selector as is even though it looks like it could be simpler.
See snippet below for a working example.

$('#container input[type="checkbox"]').click(function(){
  var checkedLabels = $('#container li')
    .has('input[type=checkbox]:checked')
    .find('label')
    .map(function(){
      return $(this).text();
    }).toArray();
  console.log(checkedLabels);
});
#container {
  list-style: none;
  padding: 0;
}

<input type="checkbox" id="c1"/> check 1

<input type="checkbox" id="c2"/> check 2

<input type="checkbox" id="c3"/> check 3

<input type="checkbox" id="c4"/> check 4


text:
Q: bigtable bulk update based on dynamic filter I'm looking for a way to scan huge Google BigTable with filter dynamically composed based on the events and make bulk update/delete on huge numbers of rows.
At the moment, I'm trying to combine BigTable with java-based Dataflow (for intensive serverless compute power).  I reached to the point where I can compose "Scan" object with dynamic filter based on the events but I still can't find a way to stream results from CloudBigtableIO.read() to subsequent dataflow pipeline.
Appreciate any advice.

A: Extend your DoFn from AbstractCloudBigtableTableDoFn.  That will give you access to a getConnection() method.  You'll do something like this:
try(Connection c = getConnection();
    Table t = c.getTable(YOUR_TABLE_NAME);
    ResultScanner resultScanner = t.getScanner(YOUR_SCAN)) {
  for(Result r : resultScanner) {
     Mutation m = ... // construct a Put or Delete
     context.output(m)
  }
}

I'm assuming that your pipeline starts with CloudBigtableIO.read(), has the AbstractCloudBigtableTableDoFn next, and then has a CloudBigtableIO.write().


text:
Q: Making a PropertyEditor out of a Jtable I have a JTree and the Nodes are a abstract class (Item) that extends DefaultMutableTreeNode. I want to be able to select the node in the JTree, then have all the variables of the subclass of Item in a JTable, like in netbeans the properties editor and Navigator. I'm doing this in a swing environment, and not Netbeans module so the PropertyEditor looks nice but won't work.

A: If I understand you correctly you want to be able to display object property using generic way. The common answer to this question is to use reflection. You can discover your object and show as many properties as you want.
But in this case you will probably show properties that should not be shown to the user and are used by your program only.
I'd suggest to solve this problem using annotation. You can define your own annotation, e.g. @DisplayableProperty and mark all fields you wish to display on property editor using this annotation. Now you just have to check whether property is marked or not.
This method is very flexible. Probably in future you will add parameters to this annotation like view (TextField, CheckBox, Radio etc), format etc.


text:
Q: can't seen in kubernetes cluster I create a yaml file to create rabbitmq kubernetes cluster. I can see pods. But when I write kubectl get deployment. I cant see there. I can't access to rabbitmq ui page.
apiVersion: v1
kind: Service
metadata:
  labels:
    app: rabbit
  name: rabbit
spec:
  ports:
  - port: 5672
    protocol: TCP
    name: mqtt
  - port: 15672
    protocol: TCP
    name: ui
  type: NodePort
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: rabbit
spec:
  serviceName: rabbit
  replicas: 3
  selector:
    matchLabels:
      app: rabbit
  template:
    metadata:
      labels:
        app: rabbit
    spec:
      containers:
        - name: rabbitmq
          image: rabbitmq
      nodeSelector:
        rabbitmq: "clustered"

A: @arghya-sadhu's answer is correct.
NB I'm unfamiliar with RabbitMQ but you may need to use a different image (see 'Management Plugin`) to include the UI.
See below for more details.
You should be able to hack your way to the UI on one (!) of the Pods via:
PORT=8888
kubectl port-forward pod/rabbit-0 --namespace=${NAMESPACE} ${PORT}:15672

And then browse localhost:${PORT} (if 8888 is unavailable, try another).
I suspect (!) this won't work unless you use the image with the management plugin.
Plus

*

*The Service needs to select the StatefulSet's Pods

Within the Service spec you should add perhaps:
selector:
  app: rabbit

*

*Presumably (!?) you are using a private repo (because you have imagePullSecrets).

If you don't and wish to use DockerHub, you may remove the imagePullSecrets section.

*

*It's useful to document (!) container ports albeit not mandatory:

In the StatefulSet
ports:
- containerPort: 5672
- containerPort: 15672

Debug
NAMESPACE="default" # Or ...

Ensure the StatefulSet is created:
kubectl get statesfulset/rabbit --namespace=${NAMESPACE}

Check the Pods:
kubectl get pods --selector=app=rabbit --namespace=${NAMESPACE}

You can check the the Pods are bound to a (!) Service:
kubectl describe endpoints/rabbit --namespace=${NAMESPACE}

NB You should see 3 addresses (one per Pod)
Get the NodePort either:
kubectl get service/rabbit --namespace=${NAMESPACE} --output=json
kubectl describe service/rabbit --namespace=${NAMESPACE}

You will need to use the NodePort to access both the MQTT endpoint and the UI.

A: statefulsets and deployments are different kubernetes resources. You have created statefulsets. That's why you don't see deployments. If you do
kubectl get statefulset you should see it and also both statefulset and deployment creates pod finally so you should be able to see rabbitmq pods if you do kubectl get pods
Since you have created a Nodeport service. You should be able to access it via http://nodeip:nodeport where nodeip is ip of any worker node in your kubernetes cluster.
You can get to know what is the Nodeport(a number between 30000-32767) by
kubectl describe services rabbit

Here is the doc on accessing a Nodeport service from outside the cluster.