text:
Q: this keyword lost its reference to current module I am working on a BackboneJS module. In the view I am applying a plugin to the current element. I am passing an options object setOptions that is setup as a property of the current view. In this object I am also calling a function this.foo. But it gives me the following error: foo of undefined. Below is my code.
var b = Backbone.View.extend({

    setOptions: {
        opt1: 'Option 1',
        opt2: 'Option 2',
        opt3: 'Option 3',
        opt4: 'Option 4',
        callback: this.foo // this returns foo of undefined
    },

    initialize: function () {
        this.setPlugin();
    },

    setPlugin: function () {
        this.$el.pluginName(this.setOptions);
    },

    foo: function () {
        console.log('FOO');
    }

});

To solve this I wrote a function setOptions. and return object literal that sets up options for plugin. This time the function this.foo calls successfully but in foo the reference to this points  to this.$el. I want this keyword to point to current module not that element. I need this because I want to call more functions inside foo but I cannot as reference to this keyword is changed. How can I do this?
below is my code for second attempt
var b = Backbone.View.extend({

    initialize: function () {
        this.setPlugin();
    },

    setPlugin: function () {
        this.$el.pluginName(this.setOptions());
    },

    setOptions: function () {
        return {
            opt1: 'Option 1',
            opt2: 'Option 2',
            opt3: 'Option 3',
            opt4: 'Option 4',
            callback: this.foo
        }
    },

    foo: function () {
        // here "this" reference to this.$el but not current module
        console.log('FOO');
    }

});

A: The problem is that you can't reference properties of the object from the same object until the object is created. Thus in your case when the view object is being constructed and it comes to line callback: this.foo there is no such property created in the object yet. Hence the error.
The simplest workaround is to use getter function:
setOptions: function() {
    return {
        opt1: 'Option 1',
        opt2: 'Option 2',
        opt3: 'Option 3',
        opt4: 'Option 4',
        callback: _.bind(this.foo, this)
    }
},

and use it like this:
setPlugin: function () {
    this.$el.pluginName(this.setOptions());
},

A: Here is what's happening (check out the comments):
// Fake "plugin" function.
function pluginName(options) {
  // Here I'm setting the 'this' value of 'foo' to the document body.
  options.callback.call(document.body);

  // Here the 'this' value would be the 'options' object because I'm calling
  // the method through the 'options' object itself.
  /* options.callback(); */

  // If I did the following instead, the 'this' value of 'foo' would
  // be the global object, which is the 'window' object. That's because
  // any function that's not called by a specific object is automatically
  // executed in the context of the 'window' object.
  // var fn = options.callback;
  /* fn(); */
}

var view = {
  initialize: function () {
    this.setPlugin();
  },

  setPlugin: function () {
    pluginName(this.setOptions());
  },

  setOptions: function () {
    return {
      opt1: 'Option 1',
      opt2: 'Option 2',
      opt3: 'Option 3',
      opt4: 'Option 4',

      // 'foo' here is called by the plugin, and its
      // 'this' value depends on how the plugin calls it.
      callback: this.foo
    }
  },

  foo: function () {
    console.log('FOO');

    // The 'this' value here depends on how the plugin calls 'foo'; in this example it is the document body.
    console.log(this);
  }
};

Here is a fix:
// Fake "plugin" function.
function pluginName(options) {
  options.callback.call(document.body);
}

var view = {
  initialize: function () {
    this.setPlugin();
  },

  setPlugin: function () {
    pluginName(this.setOptions());
  },

  setOptions: function () {
    return {
      opt1: 'Option 1',
      opt2: 'Option 2',
      opt3: 'Option 3',
      opt4: 'Option 4',

      // The 'bind' method creates an other callback for you, by making
      // the 'this' value equal to whatever you pass it as the first argument.
      callback: this.foo.bind(this) // or use Underscore's '_.bind()' method as mentioned below.
    }
  },

  foo: function () {
    console.log('FOO');
    console.log(this); // 'this' here is the 'view' object.
  }
};

Here is another fix:
// Fake "plugin" function.
function pluginName(options) {
  options.callback.call(document.body);
}

var view = {
  initialize: function () {
    this.setPlugin();
  },

  setPlugin: function () {
    pluginName(this.setOptions());
  },

  setOptions: function () {
    var self = this;

    return {
      opt1: 'Option 1',
      opt2: 'Option 2',
      opt3: 'Option 3',
      opt4: 'Option 4',

      // Similar to the 'bind' method but manually.
      callback: function() {
        self.foo();
      }
    }
  },

  foo: function () {
    console.log('FOO');
    console.log(this); // 'this' here is the 'view' object.
  }
};


text:
Q: How do I allow numbers in htaccess rewrite rule? I have a htaccess setup like so:
RewriteRule ^([A-Za-z_]+)$ profile.php?name=$1 [NC,B,QSA]

it works fine however it doesn't work when the parameter has a number in it.
also is it possible to allow periods and commas?
What can I change?

A: Change the regex:
RewriteRule ^([0-9A-Za-z_]+)$ profile.php?name=$1 [L,QSA]

OR even better
RewriteRule ^(\w+)/?$ profile.php?name=$1 [QSA,L]

Since \w is same as [0-9A-Za-z_]
OP's comment:

is there a way to let it use periods and commas as well?

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([\w,.]+)/?$ profile.php?name=$1 [QSA,L]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compare new/changed file sizes from one point in time to another My problem is that I cannot find out where my disk space is being utilized after freeing space; for example I free 20GiB, then three days later it's used up despite me not downloading or transferring any files in that time.
I have attempted to use WizTree (WinDirStat alternative), though it's only really useful for looking at the disk as a whole, where 20GiB can easily go missing.
Is there some way in Windows (or some software) that can allow me to take a snapshot of all the file paths and their filesize on the disk at a particular time, and compare it to an earlier snapshot, then show me the difference in new/changed files, effectively allowing me to determine where my disk space is going?

A: I would suspect some Windows' updates files being sneakly downloaded to your PC. But 20 GiB seems too much even for than.
It looks like you've used Windows' stock "system cleaner", please give us a screenshot of it before you wipe everything out.
Try to use your Windows completely offline and see if space is still wasted. And by offline I mean physically offline (no ethernet cable or WiFi hardware connected).
It also looks like your 20GiB of file are small ones and scattered, but there may be only one or little processes who make all these files. Windows' "Performance Monitor" may give you a clue about processes that heavily writes or use a lot of I/O... or even CPU. I'd look for that first too.
Also, have you enabled file-system level compression or anything that happens at the filesystem level ?

A: As it turns out WizTree can export and import CSV files, and importing works just as well for a differential CSV than an ordinary CSV.
I developed a program to create a differential CSV from a past and future CSV from WizTree, which can then be loaded back in WizTree
Source code and download available here: https://github.com/AlphaDelta/WizTreeCompare


text:
Q: Access real time Heart Rate data on Apple Watch Can we access the heart rate directly from the apple watch? I know this is a duplicate question, but no one has asked this in like 5 years. I know you can access it from the Health App but I'm not sure how "real-time" that will be.

A: If you don't expect 100% real-time.
You can use this one: HKAnchoredObjectQuery. I think it has a 300-500ms delay.

A query that returns changes to the HealthKit store, including a snapshot of new changes and continuous monitoring as a long-running query.


text:
Q: While button is clicked my local C drive is being opened I was doing a form using HTML and i found that when I'm using my submit button it is showing my local C drive
It doesn't submit my form
CODE:

    <form id="form" action="/">

Registration

            Username
            <input id="username" name="username" type="text">

            Email
            <input id="email" name="username" type="text">

            Message
            <input id="Message" name="username" type="text">

            <button type="submit">Sign up</button>
    </form>

A: Here you can use this logic :
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <form onsubmit="sub(event)">
      <input type="text" name="username" />
      <input type="password" name="password" />
      <button type="submit">save</button>
    </form>

A: In your <form> tag you have used an attribute action='/' which is opened when you click submit button. That is in case of a file the index or your drive default address. If you change it to:
<form id="form" action="#">

it will not redirect to default address.


text:
Q: Write permissions on a new encrypted partition The HD of my MacBook Pro (macOS Mojave) is encrypted with FileVault.
Yesterday, I created a new partition from the Macintosh HD (APFS) using the DiskUtility and called the new partition Data (Extended Journaled).
The problem is that now I cannot copy any files to the new partition. It seems that I don't have write permissions to write anything on the new partition.

Why is that and how can I fix it?

A: I assume this happened as you have used the partition on Extended Journaled
Open the finder, find the drive under 'Devices', then right-click and select 'Get Info'.  A dialog box should pop up and display the basic info of the drive. At the bottom, there is a collapsed menu for 'Sharing & Permissions', make sure your username has read and write permission, and check "Ignore ownership on this volume"

If you are unable to do this , then first try to disable Journaling, and do the previous step shared above
Open Disk Utility, Select the partition and then hold down the alt key. Select the file from the top menu and you will then see an option to 'disable Journalling'


text:
Q: npm i command works in one terminal directory and not working in a different directory for a same nestJs Project in a ubuntumachine? I have cloned a nestJs project which has the package.json file as below :
###package.json :
{
  "name": "customer-portal-api-server",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "prepare": "husky install",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "migrate:dev": "dotenv -e .development.env -- npx prisma migrate dev",
    "seed-run:dev": "dotenv -e .development.env -- npx prisma db seed",
    "prisma-studio:dev": "dotenv -e .development.env -- npx prisma studio"
  },
  "dependencies": {
    "@fastify/static": "^6.8.0",
    "@nestjs/common": "^9.0.0",
    "@nestjs/config": "^2.2.0",
    "@nestjs/core": "^9.0.0",
    "@nestjs/jwt": "^9.0.0",
    "@nestjs/passport": "^9.0.0",
    "@nestjs/platform-express": "^9.0.0",
    "@nestjs/platform-fastify": "^9.1.4",
    "@nestjs/swagger": "^6.2.1",
    "@prisma/client": "^4.10.1",
    "bcrypt": "^5.1.0",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.14.0",
    "fastify": "^4.12.0",
    "joi": "^17.7.0",
    "moment": "^2.29.4",
    "passport": "^0.6.0",
    "passport-jwt": "^4.0.1",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.2.0"
  },
  "devDependencies": {
    "@nestjs/cli": "^9.0.0",
    "@nestjs/schematics": "^9.0.0",
    "@nestjs/testing": "^9.0.0",
    "@types/express": "^4.17.13",
    "@types/jest": "27.5.0",
    "@types/node": "^16.0.0",
    "@types/supertest": "^2.0.11",
    "@typescript-eslint/eslint-plugin": "^5.0.0",
    "@typescript-eslint/parser": "^5.0.0",
    "eslint": "^8.0.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "husky": "^8.0.3",
    "jest": "28.0.3",
    "prettier": "^2.3.2",
    "prisma": "^4.10.0",
    "source-map-support": "^0.5.20",
    "supertest": "^6.1.3",
    "ts-jest": "28.0.1",
    "ts-loader": "^9.2.3",
    "ts-node": "^10.0.0",
    "tsconfig-paths": "4.0.0",
    "typescript": "^4.3.5"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  },
  "prisma": {
    "seed": "ts-node prisma/seeders/seed_data.ts"
  }
}

When i try to install node_modules using the npm i command .
Initially It showed the husky not available error . So I installed the husky using the below command :
export PATH="./node_modules/.bin:$PATH"

After the command **husky got installed ** . But bcrypt package shows the below error :
kathishkumaran@kathish-Latitude-3420:~/Documents/projects$ npm i
npm ERR! code 1
npm ERR! path /home/kathishkumaran/Documents/project/node_modules/bcrypt
npm ERR! command failed
npm ERR! command sh -c node-pre-gyp install --fallback-to-build
npm ERR! Failed to execute '/usr/bin/node /
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/kathishkumaran/.npm/_logs/2023-02-15T17_35_42_847Z-debug-0.log

.
.
.

So I try to copy the project and pasted in another directory and did the same as i mentioned above.
But bcrypt package is get installed sucessfully and run as expected as below :
kathishkumaran@kathish-Latitude-3420:~/Desktop/server-api$ npm i

> xxx@0.0.1 prepare
> husky install

husky - Git hooks installed

removed 888 packages, changed 1 package, and audited 871 packages in 4s

97 packages are looking for funding
  run `npm fund` for details

2 moderate severity vulnerabilities

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

NOTE:
In Both directories the versions are same as below :
xxx$ node -v
v18.14.0
xxx$ npm -v
9.3.1
xxx$ nvm -v
0.39.1
xxx$

So someone help me to fix this issue in my linux system.


text:
Q: How to call template file to check mail? I am having problem to call template pankaj.html after sending mail. I have search through google but not found better solution to solve my issue.
path: /app/locale/en_US/template/email/pankaj.html

& i am calling template file in config.xml of module under global tag.
 <template>
            <email>
                <inquiry  module="inquiry">
                    <label>pankaj</label>
                    <file>pankaj.html</file>
                    <type>html</type>
                </inquiry>
            </email>
   </template>

Controller code:
 public function sendemailAction()
        {
            echo "abc";
            $data = $this->getRequest()->getParams();

            //echo "<pre>"; print_r($data);

            $adminUserModel = Mage::getModel('admin/user');
            $admin = $adminUserModel->getCollection()->load();

            $emailTemplate = Mage::getModel('core/email_template')
                    ->loadDefault('inquiry');

            $senderName = $admin->getFirstItem()->getFirstname();
            $senderEmail = $admin->getFirstItem()->getEmail();
        $sender = array('name' => $senderName,
            'email' => $senderEmail);

        $recepientEmail = array();
        $recepientName =array();

        /*$customer_name = $senderName = $customer->getFirstname().' '.$customer->getLastname();*/
        $recepientEmail = $data['email'];

        $store = Mage::app()->getStore()->getId();

        $vars = array('product_name' => $data['productname'],
            'sku' => $data['sku'],
            'qty' => $data['qty'],
            'customprice' => $data['customprice']
            );

        $translate  = Mage::getSingleton('core/translate');

        // Send Transactional Email

        try {

            Mage::getModel('core/email_template')
            ->sendTransactional($emailTemplate, $sender, $recepientEmail, $vars, $store);

            $translate->setTranslateInline(true);

            Mage::getSingleton('core/session')->addSuccess('email send');

        }
        catch(Exception $ex) {

            Mage::getSingleton('core/session')->addError('Unable to send email. Sample of a custom notification error.');

        }
        $this->_redirect('');
    }

To check pankaj.html file, i have print $text in template.php file.
  echo "<pre>"; print_r($text); die;
path: app/code/core/Mage/Core/Model/Email/template.php
How to solve this issue, Thanks in Advance .

A: Use following code to solve issue
$emailTemplate  = Mage::getModel('core/email_template')->loadDefault('inquiry');

I suggest you to following magento default contact us email


text:
Q: Evaluating $\sum_{n = 1}^{\infty} \frac{2}{2^{n}}$
Evaluate $$\sum_{n = 1}^{\infty} \frac{2}{2^{n}}$$

This is a geometric series and since $a = \dfrac{1}{2}$ Then the infinite sum is jsut $S = \dfrac{1}{1-\frac{1}{2}} = 2$ Then I multiply by $2$ to get $4$ right? But the actual answer should just be $2$. Am I missing something?

A: $$\sum\limits_{n = 1}^\infty  {\frac{2}{{{2^n}}}}  = 2\sum\limits_{n = 1}^\infty  {{{\left( {\frac{1}
{2}} \right)}^n}}  = 2.\frac{{1/2}}
{{1 - 1/2}} = 2.1 = 2$$

A: The first term in $\sum_{n=1}^{\infty}\frac{1}{2^n} = \frac{1}{2}+\frac{1}{4}+\dots$ is $\frac{1}{2}$, so the sum of the geometric series is $\frac{\frac{1}{2}}{1-\frac{1}{2}} = 1$.
Another way to do it is to absorb the $2$ into the denominator and then change the index from $n$ to $k = n-1$:
$$\sum_{n=1}^{\infty}\frac{2}{2^n} = \sum_{n=1}^{\infty}\frac{1}{2^{n-1}} = \sum_{k=0}^{\infty}\frac{1}{2^{k}} = 1 + \frac{1}{2}+\frac{1}{4}+\dots= \frac{1}{1-\frac{1}{2}} = 2$$

A: Almost right. Note that the stated formula works only for
$$\sum_{n=1}^\infty \left(\frac{1}{2}\right)^{n-1} = 2$$


text:
Q: Find $P(Y_1≤3/4,Y_2≥1/2)$ of a joint probability density function. Let Y1 and Y2 have the joint probability density function given by:
$ f (y_1, y_2) = 6(1−y_2), \text{for  } 0≤y_1 ≤y_2 ≤1$
Find $P(Y_1≤3/4,Y_2≥1/2).$
Answer:
$$\int_{1/2}^{3/4}\int_{y_1}^{1}6(1− y_2 )dy_2dy_1 + \int_{1/2}^{1}\int_{1/2}^{1}6(1− y_2 )dy_1dy_2 = 7/64 + 24/64   = 31/64 $$
My problem is I don't understand the logic for the second part. We know for a fact that:
$$P(a_1 ≤ Y_1 ≤ a_2, b_1 ≤ Y_2 ≤ b_2) = \int^{b_2}_{b_1}\int^{a_2}_{a_1}6(1− y_2 )dy_1dy_2$$
Thus, I can make the following equations
$$ \int_{1/2}^{3/4}\int_{y_1}^{1}6(1− y_2 )dy_2dy_1 = P(1/2 \leq Y_2 \leq 1, 1/2 \leq Y_1 \leq 3/4 | Y_1 \leq Y_2) $$
This part I understand the logic of why we would add this integral to the expression
$$\int_{1/2}^{1}\int_{1/2}^{1}6(1− y_2 )dy_1dy_2 = P(1/2 \leq Y_2 \leq 1, 1/2 \leq Y_1 \leq 1)$$.
I don't understand the logic of how adding both expressions leads to $P(Y_1≤3/4,Y_2≥1/2).$. In fact, I don't see the logic of choosing $P(1/2 \leq Y_2 \leq 1, 1/2 \leq Y_1 \leq 1)$.

A: No you are right! You should instead choose
$$ P(1/2 \leq Y_2 \leq 1 \, , \, {\bf0 \leq Y_1 \leq 1/2)}. $$
This doesn't affect the answer since
$$ \int_{1/2}^1 \int^{1/2}_{y_1=0} 6(1-y_2) \, dy_1 dy_2 =  \int_{1/2}^1 \int^{1}_{y_1=1/2} 6(1-y_2) \, dy_1 dy_2. $$
Do you see why this makes sense? Hint: Draw the area you want to integrate over.

A: Hint: consider the figure below

By the specification of your joint PDF, you only want to integrate within triangle ABC. Now, within the ABC triangle, the region described by $\{(y_1,y_2):y_1\leq\frac{3}{4},y_2\geq\frac{1}{2}\}$ is the polygon DEGHB which can be decomposed into 2 bits: a rectangle DEIB and a quadrilateral EGHI.


text:
Q: Double Alert Windows I am getting double Alert prompts for a single form: The alert pops up the first time, then when I click OK, the same one pops open again. I think my code should do the alert once when it hits "else  window.alert(sameWarning) and the stop when it reaches "return false()"; but it seems return false() is causing the alert twice. Maybe because I have two forms on one page; yet, they have two separate function names ("signinForm()" and "saveSignUp()")and call two separate forms (forms[0] and forms[1])?  I think my code is correct, but I can't figure it out at this point. Any help would be appreciated. Thanks in advance!

HTML

Login

<form method="post" onsubmit="return signinForm();" action="" >
    <input type="text" placeholder="Username/Email" name="userName">
    <input type="password" placeholder="Password" name="pswd" id="pswd">
    <input type="submit" onclick="signinForm();" value="Sign In">
</form>

Sign Up!

    <form method="post" onsubmit="return saveSignUp()" action="" >
    <input type="text" placeholder="First Name" name="firstName">
    <input type="text" placeholder="Last Name" name="lastName">
    <input type="text" placeholder="Email" name="email">
    <input type="text" placeholder="Phone Number" name="phoneNumber">
    <input type="submit" onclick="saveSignUp();" class="button wide" value="Request an Account">

A: It is because you call signinForm(); twice.
Remove one of these listeners
onclick="signinForm();"
onsubmit="return signinForm()"
When you click on submit button you call signinForm();. And because it is a submit button, it will trigger the onsubmit event, and call return signinForm()

A: When you click submit, first it fires the click event (calling your function), then it fires a submit event (calling your function again).  Just remove the onclick for the submit buttons.


text:
Q: Weird Element Spacing in UniformGrid I have a fairly simple setup so far which looks like this:

As you can see Number 3 looks perfectly fine. The other two however does not. I have the following code:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <StackPanel Grid.Row="0" Orientation="Vertical" Margin="0,0,5,0" Background="#FFEAEAEA">
        <GroupBox x:Name="playStyleBox" Header="1. Play Style" HorizontalAlignment="Left" Margin="10,0,10,0" VerticalAlignment="Top">
            <UniformGrid Columns="4">
                <CheckBox x:Name="CheckBoxSubtle">Subtle</CheckBox>
                <CheckBox x:Name="CheckBoxBalanced">Balanced</CheckBox>
                <CheckBox x:Name="CheckBoxAggressive">Aggressive</CheckBox>
                <CheckBox x:Name="CheckBoxSupportive">Supportive</CheckBox>
            </UniformGrid>
        </GroupBox>
        <GroupBox x:Name="playStyleSubBox" Header="2. Sub Play Style" HorizontalAlignment="Left" Margin="10,0,10,0" VerticalAlignment="Top">
            <UniformGrid Columns="3">
                <CheckBox x:Name="CheckBoxMelee">Melee</CheckBox>
                <CheckBox x:Name="CheckBoxRanged">Ranged</CheckBox>
                <CheckBox x:Name="CheckBoxMagic">Magic</CheckBox>
            </UniformGrid>
        </GroupBox>
        <GroupBox x:Name="alignmentBox" Header="3. Alignment" HorizontalAlignment="Left" Margin="10,0,5,0" VerticalAlignment="Top">
            <UniformGrid Columns="3">
                <CheckBox x:Name="CheckBoxLawfulGood">Lawful Good</CheckBox>
                <CheckBox x:Name="CheckBoxNeutralGood">Neutral Good</CheckBox>
                <CheckBox x:Name="CheckBoxChaoticGood">Chaotic Good</CheckBox>
                <CheckBox x:Name="CheckBoxLawfulNeutral">Lawful Neutral</CheckBox>
                <CheckBox x:Name="CheckBoxNeutral">Neutral</CheckBox>
                <CheckBox x:Name="CheckBoxChaoticNeutral">Chaotic Neutral</CheckBox>
                <CheckBox x:Name="CheckBoxLawfulEvil">Lawful Evil</CheckBox>
                <CheckBox x:Name="CheckBoxNeutralEvil">Neutral Evil</CheckBox>
                <CheckBox x:Name="CheckBoxChaoticEvil">Chaotic Evil</CheckBox>
            </UniformGrid>
        </GroupBox>
    </StackPanel>
    <GridSplitter Grid.Column="0" Width="4" BorderBrush="Red" VerticalAlignment="Stretch">
        <GridSplitter.Template>
            <ControlTemplate TargetType="{x:Type GridSplitter}">
                <Grid>
                    <Button Content="⁞"/>
                    <Rectangle Fill="#FFACACAC"/>
                </Grid>
            </ControlTemplate>
        </GridSplitter.Template>
    </GridSplitter>
</Grid>

Any help would be appreciated. I am pretty lost as to why this happens to the first two UniformGrid's but not the last one.

A: *

*UniformGrid create Columns of equal size. So, largest control governs the size of the Column.

*Set HorizontalAlignment="Stretch", and Margin="10,0,10,0" in all GroupBox .

*Change number of Columns in first UniformGrid to 3.


text:
Q: Understanding read syscall I'm reading man read manual page and discovered that it was possible to read less then the desired number of bytes passed in as a parameter:

It is not an error if this number is smaller than the number of bytes
  requested; this may happen for example because fewer bytes are
  actually available right now (maybe because we were close to
  end-of-file, or because we are reading from a pipe, or from a
  termi‐nal), or because read() was interrupted by a signal.

I have the following situation:

*

*Some process moved a file into a directory I'm listening to IN_MOVED_TO inotify events.

*I receive a IN_MOVED_TO event, open a file and start reading it till the EOF is reached

*No other processes modify the moved at 1. file (After it is moved it is left unchanged all the time)

Is it guaranteed that if read returns the number of bytes read less then I requested then the next call to read will return 0? I mean the situation like 'reading 1 000 000 000 by a single bytes for a gigabyte file' is forbidden by the documentation

A:
Is it guaranteed that if read returns the number of bytes read less then I requested then the next call to read will return 0?

No, not in practice. It should be true if the file system is entirely POSIX compliant, but many of them are not (in corner cases). In particular NFS (see nfs(5)) and FUSE or proc (see proc(5)) are not exactly POSIX compliant.
So in practice I strongly recommend handling the "read returns a smaller number of bytes than wanted case", even if you are right to believe that it should not happen. Handling that "impossible" case should be easy for you.
Notice also that inotify(7) facilities don't work with bizarre filesystems like NFS, proc, FUSE, ... Think also of corner cases like, inside an Ext4 file system, a symlink to an NFS file,; or bind mounts, etc...


text:
Q: No sound from notebook speakers while I can hear the sound in headphones I can hear no sound in the speakers. When I attach headphones the sound is heard correctly. alsmixer shows no clues:

(when I attach headphones speaker gets muted and sound-bar of headphones goes up to 100 - visible in real-time)
Again pavucontrol - Ubuntu volume control - seems OK:

(when I attach headphones port changes to "Headphones (plugged in)" - visible in real-time and I hear the sound via headphones as expected)
There is one thing interesting in gnome-alsamixer though. However I have no idea how to rectify it. When launched from terminal it prints the following errors:
    pdebski@PaDeLT430s:~$ gnome-alsamixer

    ** (gnome-alsamixer:24782): WARNING **: gam_toggle_get_state (). No idea what to do for mixer element "Auto-Mute Mode"!

    ** (gnome-alsamixer:24782): WARNING **:         gam_toggle_get_state (). No idea what to do for mixer element "Loopback Mixing"!

    (gnome-alsamixer:24782): GLib-CRITICAL **: Source ID 71 was not found when attempting to remove it

and shows speaker muted:

However un-muting speaker and sliding it to top does not help. Same for "Internal". Note that when I close and reopen gnome-alsamixer both Speaker and Internal sliders stay at the top position but no sound from internal speakers is heard.
What else can I do to hear the sound in the speakers?


text:
Q: From & To Date Filter on List Using LINQ working on Localhost but on IIS does not works (MVC.NET) Applied Date Filter on a list ofFrom and To Date . It works fine on localhost but on publishing on IIS it does not works.
if (!string.IsNullOrEmpty(fromDate))
{
     candidateList = candidateList.FindAll(x => Convert.ToDateTime(x.CandidateRegistrationDate).Date >= Convert.ToDateTime(fromDate).Date);
}
if (!string.IsNullOrEmpty(toDate))
{
    candidateList = candidateList.FindAll(x => Convert.ToDateTime(x.CandidateRegistrationDate).Date <= Convert.ToDateTime(toDate).Date);
}

A: First what type is candidateList? is it a db object or a collection. Assuming its a db object, you will have to change the date functions and use EF date functions. Also try to extract the convert.Datetime() function from the linq query
if (!string.IsNullOrEmpty(fromDate))
            {
                var Frodate = Convert.ToDateTime(fromDate).Date;
                candidateList = candidateList.FindAll(x => DbFunctions.TruncateTime(x.CandidateRegistrationDate).Date >= date);
            }
            if (!string.IsNullOrEmpty(toDate))
            {
                var tdate = Convert.ToDateTime(fromDate).Date;
                candidateList = candidateList.FindAll(x => DbFunctions.TruncateTime(x.CandidateRegistrationDate) <= tdate);
            }


text:
Q: Matrix Elements Ratio Control I am using the code
import numpy as np
P=np.random.choice([0, 1], (10000, 10, 10, 10))

to generate 10,000 3D binary matrices. But I need to control the ratio of ones to zeros in each of the matrices. What I mean is that for any given matrix, I want 70% of its elements to be 1 and the rest to be 0. Is there a way for doing so? A probabilistic approach would work as well. For example, if, for any given matrix, the probability of each of its elements to be 1 could be equal to 70% that would work too.

A: You should specify probablity parameter in numpy.random.choice
import numpy as np

size = (10000, 10, 10, 10)
prob_0 = 0.3 # 30% of zeros
prob_1 = 1 - prob_0 # 70% of ones

P = np.random.choice([0, 1], size=size, p=[prob_0, prob_1])

However this will allow to control the ratio in the overall 4d array, not in each sub-array.


text:
Q: Switching a current with an NPN transistor and a P-MOSFET Just learning about transistors and I'm trying to clearly understand how to apply them for basic switching, in terms of the two standard cases, i.e., Active HIGH behavior and Active LOW behavior. For the Active LOW case, I am still having some trouble.
Assume a simple circuit where I want to switch an arbitrary 1-Amp current based on the status of a Digital signal, and I want Active LOW behavior (i.e., current should flow when digital signal LOW).
I'd be interested in brief feedback in terms of whether my circuit drawn below would accomplish the above, or if it can be improved/simplified further.
Notes: Q1 is an NPN transistor, and M1 is a P-MOSFET. And I chose a 10K value resistor for R2 because fast switching is not critical, but I'd also welcome opinions on that.
EDIT: Below circuits are 1st revision based on @ThePhoton's suggestions.
Method A:

Method B:

(Below is my original, erroneous method prior to 1st revision:)

A: You can just use the PMOS, and use a pin switched from output low to high impedance (e.g. input) to switch it on/off:

The 10kΩ resistor holds the FET off when the ON-OFF signal is left floating (i.e. your pin is an input/high impedance)
Then when the pin is driven low, the gate is pulled to ground and the FET turns on. You need to make sure the P-ch MOSFET you use has a suitably low Vgs(th) (turn on voltage threshold - some can be quite high) so you want a "logic level" MOSFET.
Simulation:

A: When the input is high, Q1's base-emitter junction will be forward biased. This will make a large collector current flow in Q1, and the collector voltage will be almost ground (about 0.2 V for most transistors -- see data sheet).
When this happens, M1's gate will quickly be pulled low through Q1. The gate of M1 will be near ground, while the source is connected to Vcc. A P-channel MOSFET is on when the gate is lower than the source by a threshold specified in the datasheet. So, M1 is now on, and it's effectively a small resistor (see \$R_{ds_on}\$ in the datasheet).
Now now, the digital input is high, and the output is effectively connected to Vcc. This is the opposite of what you want.
Now, the digital input goes low. Q1's base-emitter junction is no longer forward biased, so no collector current can flow in Q1. Since the collector is connected through R2 to Vcc, the collector voltage will be Vcc. The source of M1 is also Vcc for a different of 0V -- M1 is off, effectively an open switch.
At this point, your output isn't 0 V, it's simply floating. You could connect the output to a pull-down resistor if you needed it to be 0 V. That's not always necessary, however.
What you actually have here is pretty common, and it's called an open drain output. The BJT equivalent is called an open collector output. Normally it's done with N-channel or NPN devices, however. It allows the other end to add the pull-up resistor, and there's no reason it has to be connected to Vcc; it could be connected to some other voltage.
Finally, you asked about R2. There's nothing really wrong with it, but it does mean that M1 won't turn off as fast as it turns on. The reason is that a MOSFET's gate looks like a capacitor to the circuitry driving it. If you look at the schematic symbol, it even looks like a capacitor. It takes some amount of current to change the voltage across a capacitor, and the more current you can make flow, the faster that can happen. Q1 provides a lower impedance path for current to turn M1, while R2 presents a significantly higher impedance path to turn off M1. This isn't a problem unless you need to switch at high speed.


text:
Q: Force replication of Netlogon I have added a batchfile to the the NETLOGON directory for some start-up scripts. The script is tiny in size.
I have waited hours  for the files to be replicated to the other Domain Controllers but the files have yet to be replicated.
I have also run Repadmin /syncall. I have stopped and re-started the DFS service on the Domain Controller where I added the files. I have used replmon as well to force replication.
What else can I try to speed up the process?
I have Windows Server 2003 on a domain.

A: I just had to be patient. It did eventually replicate. Thank for the assistance anyway.


text:
Q: Type hinting with enumerations? I've read here about enumarations and their "implementation"
PHP and Enumerations
point is, why use enums, when not for type hinting?
but this implementation does not allow use for type hinting. Because the enum entries are all strings.
is there a way I can say
function($a) {

}

$a must be 'foo', 'bar' or 'baz'
in PHP?
I use phpstorm/intellij so if there is another way to do that, that would be fine too. E.g. say in the doc but with autocompletion magic from phpstorm, or maybe compile errors.

A: Starting in PHP 8.1, you'll be able to use actual enumerations.
enum A {
    case FOO = 'foo';
    case BAR = 'bar';
    case BAZ = 'baz';
}

Then in your function a(), you'd type-hint for the enumeration A.
function a(A $a) {
    echo $a->value;
}

Now a($a) would only accept:
a(A::FOO);
a(A::BAR);
a(A::BAZ);

or even:
a(A::from('bar'));

but any input that's not a valid case would fail with a ValueError exception.

A: There is no built-in way in PHP to require that a passed string has a certain value; not even in PHP7. You can type-hint objects and arrays that I know of. Enumerations would solve that problem, but PHP doesn't support enumerations.
If you really, really need that, maybe you should consider a strongly-typed programming language.
If you are stuck with PHP
An easy way you can make sure your string follows some rules is to make it a class that blows up if it's not one of those values.
Try this
<?php

class WeekDay {
    private $value;

    public function __construct($value) {
        if (!in_array($value, ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']))
            throw new Exception("Not a week day.");
        else
            $this->value = $value;
    }

    public function __toString() {
        return $this->value;
    }
}

function echoWeekDay(WeekDay $weekDay) {
    echo $weekDay . "\n";
}

echoWeekDay(new WeekDay("Tuesday"));
echoWeekDay(new WeekDay("Saturday"));

Run with
~/Code/stack-overflow $ php enums.php
Tuesday
PHP Fatal error:  Uncaught exception 'Exception' with message 'Not a week day.' in /Users/marianol/Code/stack-overflow/enums.php:8
Stack trace:
#0 /Users/marianol/Code/stack-overflow/enums.php(23): WeekDay->__construct('Saturday')
#1 {main}
  thrown in /Users/marianol/Code/stack-overflow/enums.php on line 8

Fatal error: Uncaught exception 'Exception' with message 'Not a week day.' in /Users/marianol/Code/stack-overflow/enums.php:8
Stack trace:
#0 /Users/marianol/Code/stack-overflow/enums.php(23): WeekDay->__construct('Saturday')
#1 {main}
  thrown in /Users/marianol/Code/stack-overflow/enums.php on line 8

By the way, enumerations are not primarily used for type-hinting on function arguments. For example, databases use enum fields to optimise storage efficiency (since enums need much less storage space than strings), and if your programming language doesn't offer an enum data type, you have to be very careful when you retrieve, modify and persist to an enum data type back to your database.


text:
Q: Rails Generate Nested JSON I have two objects, an @article and a @profile. Article is a model and @profile is a Struct. I'd like to end up with some JSON that looks like this:
{
    "article": {
        "title": "this is a title",
        "author": "Author McAuthor",
        "profile": {
            "first_name": "Bobby",
            "last_name": "Fisher"
        }
    }
}

As of now, I can just manually create this by doing something like:
@json = { article: { title: @article.title, author: @article.author, profile: { first_name: @profile.first_name, last_name: @profile.last_name } }}

I feel like building the json object this way is sorta crude, also, every time I change the author model, I might have to change this code. It would be great if I could find an easier way to build these json objects without having to do so manually... Any help? Thanks!

A: Rails serializes objects in two steps, first by calling as_json to create the object to be serialized, then by calling to_json to actually create the JSON string.
Generally, if you want to customize how your models are represented in JSON, it's best to override as_json. Assuming your profile struct is a virtual attribute (i.e. defined with attr_accessor, not saved in the db), you could do this in your Article model:
def as_json(options = {})
  super((options || {}).merge({
    :methods => :profile
  }))
end

Hope that helps. See also:

*

*as_json documentation

*Add virtual attribute to json output

A: In addition to shioyama's correct answer, you can use rabl to craft your JSON objects, similar to how ERB works for views.
For example, you would create a 'view', say, index.rabl.  It would look like:
collection @articles
attributes :author, :title
child(:profile) { attributes :first_name, :last_name }


text:
Q: .Net Core MongoDB Identity CurrentUser Null I have been working on implementing .Net 5 Identity for MongoDB. When an user logins into the system, I can not catch the user from _httpContextAccessor.HttpContext.User.Identity.Name. Name is always null.
When I call this code _httpContextAccessor.HttpContext.User.Identity.Name, it returns null.
Here is my Authentication implementations.
    /// <summary>
    /// Adds authentication service
    /// </summary>
    /// <param name="services">Collection of service descriptors</param>
    public static void AddSystemAuthentication(this IServiceCollection services, IConfiguration configuration)
    {
        var appSettings = Singleton<AppConfig>.Instance;
        var mongoDbSettings = appSettings.MongoDbConfig;
        var jwtConfigs = appSettings.JwtConfig;

        services.AddIdentity<AppUser, AppRole>(options =>
        {
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 4;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = false;
            options.User.RequireUniqueEmail = true;
            options.SignIn.RequireConfirmedEmail = false;
        })
        .AddMongoDbStores<AppUser, AppRole, string>
        (
            mongoDbSettings.ConnectionString, mongoDbSettings.Database
        )
        .AddUserManager<UserManager<AppUser>>()
            .AddRoleManager<RoleManager<AppRole>>()
                .AddDefaultTokenProviders();

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

        JwtTokenDefinitions.LoadFromConfiguration(jwtConfigs);
        services.ConfigureJwtAuthentication();
        services.ConfigureJwtAuthorization();
    }

Here is my launchSettings.json.
          {
          "iisSettings": {
            "windowsAuthentication": true,
            "anonymousAuthentication": false,
            "iisExpress": {
              "applicationUrl": "http://localhost:57064",
              "sslPort": 44393
            }
          },
          "profiles": {
            "IIS Express": {
              "commandName": "IISExpress",
              "launchBrowser": true,
              "launchUrl": "swagger",
              "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
              }
            },
            "ChatCase.Api": {
              "commandName": "Project",
              "launchBrowser": true,
              "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
              },
              "applicationUrl": "https://localhost:5001;http://localhost:5000"
            }
          }
       }

Here is ConfigureJwtAuthentication.
public static void ConfigureJwtAuthentication(this IServiceCollection services)
                {
                    services.AddAuthentication(options =>
                    {
                        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    })
                        .AddJwtBearer(options =>
                        {
                            options.RequireHttpsMetadata = false;
                            options.SaveToken = true;
                            options.TokenValidationParameters = new TokenValidationParameters()
                            {
                                ValidateIssuer = true,
                                ValidateAudience = true,
                                RequireExpirationTime = true,
                                IssuerSigningKey = JwtTokenDefinitions.IssuerSigningKey,
                                ValidAudience = JwtTokenDefinitions.Audience,
                                ValidIssuer = JwtTokenDefinitions.Issuer,
                                ValidateIssuerSigningKey = JwtTokenDefinitions.ValidateIssuerSigningKey,
                                ValidateLifetime = JwtTokenDefinitions.ValidateLifetime,
                                ClockSkew = JwtTokenDefinitions.ClockSkew
                            };
                        });
                }

Here is ConfigureJwtAuthorization.
 public static void ConfigureJwtAuthorization(this IServiceCollection services)
    {
        services.AddAuthorizationCore(auth =>
        {
            services.AddAuthorizationCore(auth =>
            {
                auth.AddPolicy("BearerNegotiateNTLM ", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser().Build());
            });
        });
    }

Here is JwtTokenService.
/// <summary>
    /// Generates JWT token
    /// </summary>
    /// <param name="appUserDto"></param>
    /// <returns></returns>
    public TokenUserResponse GenerateToken(AppUserDto appUserDto)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, appUserDto.UserName),
            new Claim(ClaimTypes.NameIdentifier, appUserDto.UserId.ToString()),
        };

        string accessToken = GenerateAccessToken(claims);
        string refreshToken = GenerateRefreshToken();
        var token = new TokenUserResponse
        {
            UserId = appUserDto.UserId,
            UserName = appUserDto.UserName,
            RegisteredDate = appUserDto.RegisteredDate,
            AccessToken = accessToken,
            RefreshToken = refreshToken,
            Expires = JwtTokenDefinitions.TokenExpirationTime.Ticks
        };

        return token;
    }

    /// <summary>
    /// Generates access token
    /// </summary>
    /// <param name="claims"></param>
    /// <returns></returns>
    public string GenerateAccessToken(IEnumerable<Claim> claims)
    {
        var claimsIdentity = new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme);

        var handler = new JwtSecurityTokenHandler();
        var securityTokenHanlder = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = JwtTokenDefinitions.Issuer,
            Audience = JwtTokenDefinitions.Audience,
            SigningCredentials = JwtTokenDefinitions.SigningCredentials,
            Subject = claimsIdentity,
            Expires = DateTime.Now.Add(JwtTokenDefinitions.TokenExpirationTime),
            NotBefore = DateTime.Now
        });
        string accessToken = handler.WriteToken(securityTokenHanlder);

        return accessToken;
    }

    /// <summary>
    /// Generates refresh token
    /// </summary>
    /// <returns></returns>
    public string GenerateRefreshToken()
    {
        var randomNumber = new byte[32];
        using (var rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(randomNumber);
            return Convert.ToBase64String(randomNumber);
        }
    }

Here is Login process.
    /// <summary>
    /// User login async
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [HttpPost("login")]
    [AllowAnonymous]
    public virtual async Task<IActionResult> LoginAsync([FromBody] LoginRequest model)
    {
        var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false);

        if (result.Succeeded)
        {
            var appUser = await _userService.GetByUserNameAsync(model.UserName);

            var token = _tokenService.GenerateToken(new AppUserDto
            {
                UserId = appUser.Id,
                UserName = appUser.UserName,
                Email = appUser.Email
            });

            await _userActivityService.InsertAsync(nameof(AppUser), "UserLoggedIn");

            return OkResponse(token);
        }
        else
        {
            await _userActivityService.InsertAsync(nameof(AppUser), "UserLoginError");

            LoggerFactory.DatabaseLogManager().Error($"AccountController- LoginAsync error: {JsonConvert.SerializeObject(result)}");
            Result.Status = false;
            Result.Message = "Username or password are wrong !";
            return BadResponse(Result);
        }
    }

How can I handle it?


text:
Q: Using a Classifier with a split_iterator There is something about the boost string algorithms that I seem to be missing.  I am trying to use a split_iterator with a using Clasifier as the split point.  So, for example I would like to be able to do something like this:
make_split_iterator(str, is_space);

however make_split_iterator expects a Range and a Finder.  So what I need is to find some sequence to create a Finder from a Classifier.  Does anyone know how to do this, or if it is even possible?

A: You can use token_finder, as in make_split_iterator(str, token_finder(is_space())) or make_split_iterator(str, token_finder(is_any_of(" "))) etc.
Full example, assuming your goal is tokenize (hence token_compress_on)
#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
int main()
{
        std::string str = "This is a      test string";

        for( boost::algorithm::split_iterator<std::string::iterator> i
            = make_split_iterator(str, token_finder(
                                        boost::algorithm::is_space(),
                                        boost::algorithm::token_compress_on));
             i != boost::algorithm::split_iterator<std::string::iterator>();
             ++i)
        {
                std::cout << *i << '\n';
        }
}

test run: https://ideone.com/vQ2ZM


text:
Q: Pandas get sorted index order for multiple columns I have something like the following multi-index Pandas series where the values are indexed by Team, Year, and Gender.
>>> import pandas as pd
>>> import numpy as np
>>> multi_index=pd.MultiIndex.from_product([['Team A','Team B', 'Team C', 'Team D'],[2015,2016],['Male','Female']], names = ['Team','Year','Gender'])
>>> np.random.seed(0)
>>> df=pd.Series(index=multi_index, data=np.random.randint(1, 10, 16))
>>> df
>>>
Team    Year  Gender
Team A  2015  Male      6
              Female    1
        2016  Male      4
              Female    4
Team B  2015  Male      8
              Female    4
        2016  Male      6
              Female    3
Team C  2015  Male      5
              Female    8
        2016  Male      7
              Female    9
Team D  2015  Male      9
              Female    2
        2016  Male      7
              Female    8

My goal is to get a dataframe of the team ranked order for each of the 4 Year / Gender combinations (Male 2015, Male 2016, Female 2015, and Female 2016).
My approach has been to first unstack the dataframe so that it is indexed by team...
>>> unstacked_df = df.unstack(['Year','Gender'])
>>> print unstacked_df
>>>
>>>
Year   2015        2016
Gender Male Female Male Female
Team
Team A    6      1    4      4
Team B    8      4    6      3
Team C    5      8    7      9
Team D    9      2    7      8

And then create a dataframe from the index orders by looping through and sorting each of those 4 columns...
>>> team_orders = np.array([unstacked_df.sort_values(x).index.tolist() for x in unstacked_df.columns]).T
>>> result = pd.DataFrame(team_orders, columns=unstacked_df.columns)
>>> print result
Year      2015            2016
Gender    Male  Female    Male  Female
0       Team C  Team A  Team A  Team B
1       Team A  Team D  Team B  Team A
2       Team B  Team B  Team C  Team D
3       Team D  Team C  Team D  Team C

Is there an easier / better approach that I'm missing?

A: Starting from your unstacked version, you can use .argsort() with .apply() to rank order each column and then just use that as a lookup against the index:
df.unstack([1,2]).apply(lambda x: x.index[x.argsort()]).reset_index(drop=True)

Year      2015            2016
Gender    Male  Female    Male  Female
0       Team C  Team A  Team A  Team B
1       Team A  Team D  Team B  Team A
2       Team B  Team B  Team C  Team D
3       Team D  Team C  Team D  Team C

EDIT: Here's a little more info on why this works. With just the .argsort(), you get:
print df.unstack([1,2]).apply(lambda x: x.argsort())

Year   2015        2016
Gender Male Female Male Female
Team
Team A    2      0    0      1
Team B    0      3    1      0
Team C    1      1    2      3
Team D    3      2    3      2

The lookup bit is essentially just doing the following for each column:
df.unstack([1,2]).index[[2,0,1,3]]

Index([u'Team C', u'Team A', u'Team B', u'Team D'], dtype='object', name=u'Team')

and the .reset_index() gets rid of the now-meaningless index labels.


text:
Q: Angular directive and http, model not working When $scope.instrumentNames is setting inside the controller like on the code provided it works
When $scope.instrumentNames is setting in the HTTP success function it doesn't work
The data returned by the http function IS an Array.
Console.log(data)//["Guitar", "Bass", "Violin"]
Console.log($scope.instrumentNames) //["Guitar", "Bass", "Violin"]

Controller
app.controller("PrivateProfileController",
    ["$scope", "$http", "$routeParams",  function( $scope, $http, $routeParams ) {

        $scope.instrumentNames = ["Guitar", "Bass", "Violin"];//WORKING !

        function loadInstrumentNames(){
            $http({
                url: '/Instrument/getInstrumentsName',
                method: "GET"
            }).success(function(data){
                //data = ["Guitar", "Bass", "Violin"]
                $scope.instrumentNames = data;//NOT WORKING
            });
        }

        loadInstrumentNames()
    }]
);

Directive
app.directive('autoComplete', [function($timeout) {
    return    {
        restrict: "A",
        link : function(scope, element, attrs) {
            element.autocomplete({
                source: scope[attrs.uiItems],
                select: function() {
                    $timeout(function() {
                      element.trigger('input');
                    }, 200);
                }
            });
        }
    };
}]);

Template
<input auto-complete ui-items="instrumentNames">

It's like the directive is called before the http success is finished. Im stuck with this problem and any help or suggestion would be very appreciated!
Thanks

A:
It's like the directive is called before the http success is finished.

I'm sure this is exactly what is happening. After the request to /Instrument/getInstrumentsName has been made, and before the response, the directive code will run. When the link function runs, scope[attrs.uiItems] will be undefined. You need to wait until the data comes back before doing the autocomplete call.
This can be done with a $watch. Something like this:
app.directive('autoComplete', [function($timeout) {
    return    {
        restrict: "A",
        link : function(scope, element, attrs) {
            scope.$watch(attrs.uiItems, function(uiItems) {
                if (uiItems) {
                    element.autocomplete({
                        source: scope[attrs.uiItems],
                        select: function() {
                            $timeout(function() {
                              element.trigger('input');
                            }, 200);
                        }
                    });
                }
            });
        }
    };
}]);

You probably only want that to run once, so you can set a var equal to that $watch call, which returns a deregistering function. Call that function at the end, and it won't run the $watch anymore.
var unwatch = scope.$watch(attrs.uiItems, function(uiItems) {
   if (uiItems) {
       //everything you want to do with the data
       unwatch();
   }
});


text:
Q: innerHTML giving NaN output I have got this function that gets data from a websocket into and an array. From that array, I have gone ahead to spilt the values into different variables. Unfortunately I keep getting NaN values when I pass intoinnerHTML`. I am parsing the array wrongly? Please see my code below
socket.on('data_added', function(mess) {

  var x = [];
  x.push(mess);

  var humidity = [];
  var temperature = [];

  for (var i = 0; i < x.length; i++) {
    temperature.push(x[i].temperature);

    humidity.push(x[i].humidity);
  }

  humidity = document.querySelector('#weather > p:nth-child( 2 )');

  temperature = document.querySelector('#weather > p:nth-child( 1 )');

  temperature.innerHTML = 'Temperature: ' + parseFloat(temperature[0]) + '°C';

  // Populate humidity
  humidity.innerHTML = 'Humidity: ' + parseFloat(humidity[0]) + '%';

  console.log(temperature);
  console.log(humidity);
});

I will appreciate your effort.
HTML file

Temperature:  °

Humidity:  %


text:
Q: PHP_NEW_EXTENSION() does nothing I'd like to ask if my guess is correct:
I'm writing an extension (using C++ as the programming language) and when it comes to actually makeeing the configured sources and macros my Makefile contains following settings.
PHP_PECL_EXTENSION = extensionname
EXTENSIONNAME_SHARED_LIBADD =
PHP_MODULES =
PHP_ZEND_EX =

How does it come if I do manually add my
 PHP_NEW_EXTENSION(extensionname, <listofsourcecodefilenames>...)

Maybe I have to provide some additional information? I did try to build some stock extensions that come with PHP source, and everything went fine.

Here's my config.m4
PHP_ARG_WITH(extensionname, enable extensionname,
    [  --with-extensionname        enable extensionname)], no, no)

if test "$PHP_EXTENSIONNAME" != "no"; then
PHP_REQUIRE_CXX()
PHP_EXTENSIONNAME_CFLAGS=""

if test $PHP_EXTENSIONNAME != "yes"; then
    AC_MSG_CHECKING([for required lib in default path])
    for i in $PHP_EXTENSIONNAME /usr/local/ /usr /opt/vendor/liblocation; do
        if test -r $i/include/sqlncli.h; then
            $REQUIREDLIB_DIR=$i
            AC_MSG_RESULT(found in $i)
            break
        fi
    done

    if test -z "$REQUIREDLIB_DIR"; then
        AC_MSG_RESULT([not found])
        AC_MSG_ERROR([please obtain the original required lib for Linux])
    fi

    PHP_CHECK_LIBRARY(requiredlib, RQLCriticalFunction, [
        AC_MSG_RESULT(found)
        PHP_ADD_LIBRARY_WITH_PATH(requiredlib, $REQUIREDLIB_DIR/../lib64, EXTENSIONNAME_SHARED_LIBADD)
        PHP_ADD_INCLUDE($REQUiREDLIB_DIR/include)
    ], [
        AC_MSG_RESULT([not found])
        AC_MSG_ERROR([please install blah-blah])
    ], [
        -L$REQUIREDLIB_DIR/../lib64 -lm
    ])
fi

AC_DEFINE(HAVE_EXTENSIONNAME, 1, [Whether you have extensionname])

PHP_ADD_LIBRARY(stdc++, 1, EXTENSIONNAME_SHARED_LIBADD)

PHP_ADD_INCLUDE('sql.h')
PHP_ADD_INCLUDE('sqlext.h')

PHP_NEW_EXTENSION(extensionname, source1.cpp source2.cpp source3.cpp, $ext_shared)
PHP_SUBST(EXTENSIONNAME_SHARED_LIBADD)
fi

A: I'd been looking at http://www.opensource.apple.com/source/apache_mod_php/apache_mod_php-18.9/php/README.UNIX-BUILD-SYSTEM just a minute ago for a similar issue and noticed that you seem to be missing the $ext_shared at the end:
PHP_NEW_EXTENSION(foo, foo.c bar.c baz.cpp, $ext_shared)


text:
Q: Get list of organizations on GitHub Is there a workaround to get the list of organizations on GitHub?
For example: https://github.com/showcases/open-source-organizations
How can we do that via the GitHub API or GitHub search?

A: On June 17, 2015 GitHub added a new API to get organizations:
curl https://api.github.com/organizations

[
  {
    "login": "github",
    "id": 9919,
    "url": "https://api.github.com/orgs/github",
   "repos_url": "https://api.github.com/orgs/github/repos",
   "events_url": "https://api.github.com/orgs/github/events",
   "members_url": "https://api.github.com/orgs/github/members{/member}",
   "public_members_url": "https://api.github.com/orgs/github/public_members{/member}",
   "avatar_url": "https://avatars.githubusercontent.com/u/9919?v=3",
    "description": "GitHub, the company."
  },
  ...
]

Additional information can be found on the following link:
List all organizations
Lists all organizations, in the order that they were created on GitHub.
Note: Pagination is powered exclusively by the since parameter. Use the Link header to get the URL for the next page of organizations.
Parameters

*

*Name: since

*Type: string

*Description: The integer ID of the last Organization that you've seen.

Response
Status: 200 OK
Link: <https://api.github.com/organizations?since=135>; rel="next"
X-RateLimit-Limit: 5000
X-RateLimit-Remaining: 4999
----------------------------------------------------------------------
[
  {
    "login": "github",
    "id": 1,
    "url": "https://api.github.com/orgs/github",
    "avatar_url": "https://github.com/images/error/octocat_happy.gif",
    "description": "A great organization"
  }
]

A: Note that it's also possible to use Github GraphQL v4 to request organization using :
{
  search(query: "type:org", type: USER, first: 100) {
    userCount
    nodes {
      ... on Organization {
        name
        createdAt
        description
      }
    }
  }
}

Try it in the explorer

A: You can get a list of all accounts:
https://developer.github.com/v3/users/#get-all-users
The type parameter will tell you if it's a user or organization.
An alternative is to use the search API:
https://developer.github.com/v3/search/#search-users
You can specify type:org to get organizations only:
https://api.github.com/search/users?q=type:org

A: I ran into similar problems with you and maybe I get an answer from github API doc now.
Detail Doc in this: https://developer.github.com/v3/search/#search-users
There are several parameters that can be used.

*

*q : (string). The search terms.

*sort : (string). The sort field. Can be followers, repositories, or joined. Default: results are sorted by best match.

*order : (string). The sort order if sort parameter is provided. One of asc or desc. Default: desc
The q search term can also contain any combination of the supported user search qualifiers as described by the in-browser user search documentation and search syntax documentation:

*

*type With this qualifier you can restrict the search to just personal accounts (user) or just organization accounts (org).

*in Qualifies which fields are searched. With this qualifier you can restrict the search to just the username (login), public email (email), full name (fullname), or any combination of these.

*repos Filters users based on the number of repositories they have.

*location Filter users by the location indicated in their profile.

*language Search for users that have repositories that match a certain language.

*created Filter users based on when they joined.

*followers Filter users based on the number of followers they have.

For your problem, you can try this example and change it.
For example:
https://api.github.com/search/users?q=language:objective-c+type:org&page=1
Request GET and return format data (json). Page parameter can be changed to get more pages of results (but no more than 1000, according current API doc).

A: You can check this https://medium.com/@harshitsinghai77/demystifying-github-api-to-fetch-the-top-3-repositories-by-stars-using-node-js-aef8818551cb to have a clear understanding.


text:
Q: Strange problem with session.invalidate() I have strange issue with logging in and out. I've implemented container-based security. I have Login/Logout links on all my pages (through template.xhtml) that are rendered or not based on backing bean boolean property (it's actually method isLoggedIn()). Also in backing bean I have method logout which is the action for Logout link (it's h:commandLink). Logout method returns String that redirects to login page through implicit JSF 2.0 navigation. Now when I deploy application I browse to my page it displays index.xhtml. From there I go to login page. I put my username/password click Login and it logs me in. But now I click Logout which calls backing bean logout method mentioned, which called does this:
public String logout() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
   //HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
   try {
       session.invalidate();
       //request.logout();
   } catch (Exception ex) {
       Logger.getLogger(PostController.class.getName()).log(Level.SEVERE, null, ex);
   }
   return "/ssl/login?faces-redirect=true";
}

Now after clicking Logout it redirects me back to login page when I again put username/password and click Login. But then strange thing happens because it displays me my index.xhtml but I'm not logged in. I have to go again to login page, retype credentials once again to finally be logged in. This happens only when I use session.invalidate() in backing bean logout() method. When I use request.logout() everything works fine. What's the problem?
Edited:
isLoggedIn looks like this but I don't think it's a problem cause I created filter that redirects me (only when I'm logged in) to index.xhtml when I try to browse to login page. And it doesn't happen.
public boolean isLoggedIn() {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    if(request.getUserPrincipal() != null)
        return true;
    else
        return false;
}

Edited:
Here is scenario considering http headers:
I request login.xhtml:
GET /blog-war/ssl/login.xhtml;jsessionid=edccb9f9a1c5fc77dbd7fc86f55b HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://localhost:8080/blog-war/
Cookie: JSESSIONID=edccb9f9a1c5fc77dbd7fc86f55b

Response:
HTTP/1.1 302 Moved Temporarily
X-Powered-By: Servlet/3.0
Server: GlassFish Server Open Source Edition 3.0.1
Location: https://localhost:8181/blog-war/ssl/login.xhtml
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-GB
Content-Length: 197
Date: Sat, 04 Sep 2010 22:27:47 GMT

Moved temporarily so browser makes another request:
GET /blog-war/ssl/login.xhtml HTTP/1.1
Host: localhost:8181
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://localhost:8080/blog-war/
Cookie: JSESSIONID=edccb9f9a1c5fc77dbd7fc86f55b

Response:
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.0, JSF/2.0
Server: GlassFish Server Open Source Edition 3.0.1
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: text/html;charset=UTF-8
Content-Length: 1256
Date: Sat, 04 Sep 2010 22:27:47 GMT

I fill in username/password and click Login:
POST /blog-war/ssl/j_security_check HTTP/1.1
Host: localhost:8181
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: https://localhost:8181/blog-war/ssl/login.xhtml
Cookie: JSESSIONID=edccb9f9a1c5fc77dbd7fc86f55b

Response:
HTTP/1.1 302 Moved Temporarily
X-Powered-By: Servlet/3.0
Server: GlassFish Server Open Source Edition 3.0.1
Location: https://localhost:8181/blog-war/
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-GB
Content-Length: 182
Date: Sat, 04 Sep 2010 22:40:01 GMT

It was redirect to index.xhtml:
GET /blog-war/ HTTP/1.1
Host: localhost:8181
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: https://localhost:8181/blog-war/ssl/login.xhtml
Cookie: JSESSIONID=edccb9f9a1c5fc77dbd7fc86f55b

Response:
HTTP/1.1 302 Moved Temporarily
X-Powered-By: Servlet/3.0
Server: GlassFish Server Open Source Edition 3.0.1
Pragma: No-cache
Cache-Control: no-cache
Expires: Thu, 01 Jan 1970 01:00:00 CET
Location: http://localhost:8080/blog-war/
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-GB
Content-Length: 181
Date: Sat, 04 Sep 2010 22:40:01 GMT

Again redirect because I have filter that switch to https-http and vice versa (I wanted only login.xhtml in https):
GET /blog-war/ HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Cookie: JSESSIONID=edccb9f9a1c5fc77dbd7fc86f55b

Response:
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.0, JSF/2.0
Server: GlassFish Server Open Source Edition 3.0.1
Pragma: no-cache
Cache-Control: no-cache, no-store, must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: text/html;charset=UTF-8
Content-Length: 4002
Date: Sat, 04 Sep 2010 22:40:02 GMT

Now I'm logged in sucessfully, Logout link is rendered means backing bean isLoggedIn returns true. Now I click Logout which invokes session.invalidate() in logout() method in backing bean:
POST /blog-war/index.xhtml HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://localhost:8080/blog-war/
Cookie: JSESSIONID=edccb9f9a1c5fc77dbd7fc86f55b

Response:
HTTP/1.1 302 Moved Temporarily
X-Powered-By: Servlet/3.0, JSF/2.0
Server: GlassFish Server Open Source Edition 3.0.1
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Location: http://localhost:8080/blog-war/ssl/login.xhtml
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-GB
Content-Length: 196
Date: Sat, 04 Sep 2010 22:48:34 GMT

Redirect to login page logout returns String "/ssl/login?faces-redirect=true" so we go there:
GET /blog-war/ssl/login.xhtml HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://localhost:8080/blog-war/
Cookie: JSESSIONID=edccb9f9a1c5fc77dbd7fc86f55b

Response:
HTTP/1.1 302 Moved Temporarily
X-Powered-By: Servlet/3.0
Server: GlassFish Server Open Source Edition 3.0.1
Location: https://localhost:8181/blog-war/ssl/login.xhtml
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-GB
Content-Length: 197
Date: Sat, 04 Sep 2010 22:48:34 GMT

Another redirect, login page should be in https (filter is working :)):
GET /blog-war/ssl/login.xhtml HTTP/1.1
Host: localhost:8181
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://localhost:8080/blog-war/
Cookie: JSESSIONID=edccb9f9a1c5fc77dbd7fc86f55b

Response:
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.0, JSF/2.0
Server: GlassFish Server Open Source Edition 3.0.1
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Set-Cookie: JSESSIONID=eefdcda45337b9c897de2a0e95e3; Path=/blog-war; Secure
Content-Type: text/html;charset=UTF-8
Content-Length: 1256
Date: Sat, 04 Sep 2010 22:48:35 GMT

So this was normal flow of events. Now abnormal:)
I'm already at login page so I retype username/password and click Login:
POST /blog-war/ssl/j_security_check HTTP/1.1
Host: localhost:8181
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: https://localhost:8181/blog-war/ssl/login.xhtml
Cookie: JSESSIONID=eefdcda45337b9c897de2a0e95e3

Response:
HTTP/1.1 302 Moved Temporarily
X-Powered-By: Servlet/3.0
Server: GlassFish Server Open Source Edition 3.0.1
Location: https://localhost:8181/blog-war/
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-GB
Content-Length: 182
Date: Sat, 04 Sep 2010 22:55:46 GMT

Redirect to index:
GET /blog-war/ HTTP/1.1
Host: localhost:8181
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: https://localhost:8181/blog-war/ssl/login.xhtml
Cookie: JSESSIONID=eefdcda45337b9c897de2a0e95e3

Response:
HTTP/1.1 302 Moved Temporarily
X-Powered-By: Servlet/3.0
Server: GlassFish Server Open Source Edition 3.0.1
Pragma: No-cache
Cache-Control: no-cache
Expires: Thu, 01 Jan 1970 01:00:00 CET
Location: http://localhost:8080/blog-war/
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-GB
Content-Length: 181
Date: Sat, 04 Sep 2010 22:55:47 GMT

Again filter redirects to http for index.xhtml:
GET /blog-war/ HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive

Response:
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.0, JSF/2.0
Server: GlassFish Server Open Source Edition 3.0.1
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Set-Cookie: JSESSIONID=ef675cbb9747063c235fdb44137e; Path=/blog-war
Content-Type: text/html;charset=UTF-8
Content-Length: 3410
Date: Sat, 04 Sep 2010 22:55:48 GMT

At this point Logout link is not rendered, means we are not logged in? In response there is set-cookie so does it mean server logged me out? After going again to login page it starts all over from the top. I can also insert server logs which differs a little bit from normal login and abnormal login scenario. Also about Expires in response, why it's January 1970? I'm really confused.

A: Since you shouldn't be able to access restriced pages without being logged in when using container managed security, I strongly suspect that the isLoggedIn() method incorrectly returned false which made it look like that you're not logged in. The method should at least look like this:
public boolean isLoggedIn() {
    return FacesContext.getCurrentInstance()
        .getExternalContext().getUserPrincipal() != null;
}

Update: right, when a cookie is been created in HTTPS context (i.e. has the Secure flag), then the cookie get lost when switching from HTTPS to HTTP. However if the cookie is been created in HTTP context (i.e. has no Secure flag), then the cookie will remain available in both HTTP and HTTPS contexts. This is as per the RFC 2965 cookie spec (check the description for the Secure flag).
Apart from using HttpServletRequest#logout(), another solution would be to create the cookie immediately during the redirect after logout instead of creating it only when the login page is been requested over HTTPS. You can implicitly create a new cookie by just requesting the HttpSession

A: If you're using session.invalidate(), the correct test for isLoggedIn() is userPrincipal() != null && session.isRequestedSessionValid(). Otherwise the page straight after the logout will show you still as logged in.
You shouldn't be redirecting to the login page yourself. CMA should do that for you. Just redirect to a page that requires a login.


text:
Q: Loop through text file and execute If Then statement for each line with bash I have a command that lists the full 8 level deep path of all folders we are backing up.
I also have a command that enumerates all 8 level deep folders on the system.
Both of these are stored as variables in a bash script.
I'm trying to get a loop together that takes file 1 and uses the first line entry as a variable in an if/then/else, and then moves onwards to through the end of the file.
I've tried so many things but its beyond my skillset to provide an example that won't confuse the reader of this post.
TempFile1=/ifs/data/scripts/ConfigMonitor/TempFile1.txt
TempFile2=/ifs/data/scripts/ConfigMonitor/TempFile2.txt
find /ifs/*/*/backup -maxdepth 4 -mindepth 4 -type d > $TempFile1
isi snapshot schedules list -v | grep Path: | awk '{print $2}' > $TempFile2

list line 1 on $TempFile1
Grep for line 1 within $TempFile2
if result yielded then
  echo found
else
  echo fullpath not being backed up
fi

A: This should iterate through Tempfile1.txt and grep for the line in TempFile2.txt.
while read line; do
    if grep $line /path/to/TempFile2.txt > /dev/null
    then
       echo "Found $line"
    else
       echo "Did not find $line"
    fi
done < Tempfile1.txt

Tempfile1.txt:
a
b
c

Tempfile2.txt
b
d
z

Output:
Did not find a
Found b
Did not find c

A: Use Grep's -f Flag
grep(1) says:
   -f FILE, --file=FILE
          Obtain  patterns  from  FILE,  one  per  line.   The  empty file
          contains zero patterns, and therefore matches nothing.   (-f  is
          specified by POSIX.)

Therefore, the following should work:
grep -f patterns_to_match.txt file_to_examine.txt

Faster Reporting
Another way to think about this is that you can ask GNU grep to show you all the matches:
echo 'Lines that match a pattern in your pattern file.'
grep -f patterns_to_match.txt file_to_examine.txt

and then show you all the lines that don't match any of the patterns:
echo 'Lines that do not match any patterns in your pattern file.'
grep -f patterns_to_match.txt -v file_to_examine.txt

This is likely to be faster and more efficient than looping through the file one line at a time in Bash. You may or may not get similar results with a grep other than GNU grep; while the -f and -v flags are specified by POSIX, I only tested it against GNU grep 2.16, so your mileage may vary.


text:
Q: Laravel\Mysql access denied - SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES) (SQL: SHOW TABLES) 1 - The problem:
Laravel is denied access to MYSQL.
2 - Connection test in Laravel:
php artisan tinker
DB::select('SHOW TABLES');
Illuminate\Database\QueryException with message 'SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES) (SQL: SHOW TABLES)'

3 - Checks. The test machine is not a vps the PHP, MySql, Nginx and Laravel are installed locally on this computer.
a. Script used to create the user in Mysql:
CREATE USER 'user'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
GRANT ALL PRIVILEGES ON database.* TO 'user'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;

b. Through the terminal, the listing of tables occurs normally:
mysql -u user -p
use database;
show tables;

c. With a PHP script using PDO access to the DB normally occurs:
<?php
  $user = "user";
  $password = "password";
  $database = "database";
  $table = "test";
  try {
    $db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
    echo "
TODO

";
    foreach($db->query("SELECT value FROM $table") as $row) {
      echo "
" . $row['value'] . "
";
    }
      echo "
";
    } catch (PDOException $e) {
       print "Error!: " . $e->getMessage() . "
";
       die();
 }

4 - Laravel .env:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=*****
APP_DEBUG=true
APP_URL=https://www.app.com
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database
DB_USERNAME=user
DB_PASSWORD=password

5 - Laravel database.php
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
    PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
  ]) : [],
],

6 - Server SETUP
Laravel 8.32.1 | Mysql 8.0.23 | PHP 7.4.3 | Zend Engine 3.4.0 | Nginx 1.18.0 | Ubuntu 20.04.2LTS


text:
Q: Issue in Eclipse: Cannot get a DefaultScreenDevice -> cannot launch any GUI An issue appeared recently when launching Java code from within Eclipse in Windows 10 platform; I googled for help without success.
As of now, I cannot launch any Java application that would rely on Swing or AWT. For instance If I launch such an application from a main method, it exists without an error message.
I debugged into the issue a little bit and I found that the faulty line was in the Window.class of AWT, when initializing the GraphicsEnvironment (line 471-482 in jsk 1.8.121):
private GraphicsConfiguration initGC(GraphicsConfiguration gc) {
    GraphicsEnvironment.checkHeadless();

    if (gc == null) {
        gc = GraphicsEnvironment.getLocalGraphicsEnvironment().
            getDefaultScreenDevice().getDefaultConfiguration();
    }
    setGraphicsConfiguration(gc);

    return gc;
}

A main method used to debug the issue like this:
    public static void main( final String[] args )
{
    System.out.println( "Launching stuff" );
    final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    System.out.println( localGraphicsEnvironment ); // DEBUG
    final GraphicsDevice defaultScreenDevice = localGraphicsEnvironment.getDefaultScreenDevice();
    System.out.println( defaultScreenDevice ); // DEBUG
    final GraphicsConfiguration defaultConfiguration = defaultScreenDevice.getDefaultConfiguration();
    System.out.println( defaultConfiguration ); // DEBUG

    System.out.println( "Launched" );
}

prints:

Launching ImageJ
sun.awt.Win32GraphicsEnvironment@27bc2616

and that's it.

I tried to update the jdk to the latest one (on win-x64 platform) with no success. Updating Eclipse to the latest does not work either (I tried Mars 2 and Neon).
I suspect some issue with the graphic drivers (since I cannot get a default screen service), but I am up to date as well (NVIdia Geforce Experience updater), and the device manager reports no issue.
The issue is recent, it appeared 6 days ago maximum. In this time, I have graphic driver updates, including Vulkan maybe.
I am a lost since it means I cannot develop on this system anymore.
Anyone as leads I could follow to address this issue?
Best
jy

A: I found the possible responsible for this.
I noticed I updated my NVidia drivers (I have a Geforce GTX970) earlier that week and that I had installed their drivers for 3D vision in the process.
Uninstalling the later fixed the problem.


text:
Q: Angular 7 is there libraries to check lazy loading performance tree I am using lazy loading in my angular 7 project, and when I run the following:
npm build --prod --aot
I got the following:
chunk {0} common.0913107449ce910bce3f.js (common) 8.58 kB  [rendered]
chunk {1} 1.c6d0e41cf66977823213.js () 14 kB  [rendered]
chunk {2} 2.e89188e71cd964268db5.js () 407 kB  [rendered]
chunk {3} 3.33139e095dcdc99938cc.js () 62.4 kB  [rendered]
chunk {4} 4.ebda0bbcf86bc49de010.js () 408 kB  [rendered]
chunk {5} 5.2aad2eeebadc8b4b5cd2.js () 479 kB  [rendered]
chunk {6} 6.03f5238fe37cf4a30218.js () 18.3 kB  [rendered]
chunk {7} runtime.f6427d1efd0aebd99cd7.js (runtime) 2.56 kB [entry] [rendered]
chunk {8} 8.c81220186a7896b40e98.js () 201 kB  [rendered]
chunk {9} 9.cf6ecff537fab1ea2da1.js () 120 kB  [rendered]
chunk {10} main.5d49d1e040bce48af816.js (main) 950 kB [initial] [rendered]
chunk {11} polyfills.4e6addda4bdac3fbf7e1.js (polyfills) 58.2 kB [initial] [rendered]
chunk {12} styles.0ace7b519537cad1d56a.css (styles) 218 kB [initial] [rendered]
chunk {13} 13.3b05a7908f130641937a.js () 163 kB  [rendered]
chunk {14} 14.cb38771e3a2dc30be680.js () 7.57 kB  [rendered]
chunk {15} 15.b85622d4429edf650325.js () 4.47 kB  [rendered]
chunk {16} 16.c9f6d17f9cb455e6782a.js () 3.64 kB  [rendered]
chunk {17} 17.7c0893ad5dc1b053e206.js () 3.94 kB  [rendered]
chunk {18} 18.2656773c2af908bb7c14.js () 227 kB  [rendered]
chunk {19} 19.d29460e5effdc355660c.js () 215 kB  [rendered]

We all know, the concept of lazy loading. But are these chunk sizes are normal ? Or should I do something to change the structure using libraries?
Take note that the dist folder builded is all about 13mb.

A: I think it is not so straightforward to define a guideline of what chunk sizes are acceptable or not, since it is very much dependent on the size and required structure of the application.
I think the sizes of the chunks that you've provided are acceptable especially when you consider that delivering those to the client side gzipped would reduce the size of the generated files by a large factor.
A build for one of the applications I am working on generated the following chunks

Notice how the main chunk size totals to 1.74MB... The reason behind that is this particular application under the hood has been based on many third party libraries which are included to the global scope (via angular.json scripts section). This means that the libraries are added as is to the main bundle.
If you want to try and reduce the size of your chunks, try the following

*

*Identify any libraries which you do not need which are added to the global scope

*Make sure that any third party libraries that are not added on the global scope are three shakeable (example libraries providing angular service which uses the provideIn: root notation)

*Make sure that services, components, directives etc needed by a single lazy loaded module are defined in that module.

Internally webpack (which is used by Angular Cli to bundle your application) builds a dependency graph and splits the chunks following some heuristics. This article explains the different ways how chunk splitting can be configured via webpack.

A: Hey There is a package which can be found on npm
https://www.npmjs.com/package/source-map-explorer

while making build use command ng build --prod --source-map=true
source-map explorer path to bundle.js file it will open a tree-like structure in DOM showing the size of each and every part of application


text:
Q: How to distinguish between PowerShell remote ISE and remote console? Is there a way to distinguish between if a PowerShell script is being run via a remote session started in an ISE or a remote session started in a console?
We would like to set some of the RawUI variables and need to distinguish between ISE and console. Locally, Test-Path variable:global:psISE does the trick, but when connecting remotely from an ISE this returns false and our UI adjustments fail.
Test-Path variable:global:psISE
The session is from an ISE it is just from a remote ISE.


text:
Q: Query two SQL entries? I have a SQL database I'm trying to query with PHP. It's for user accounts and I need to test if a certain username and password combination exist in the database.
Currently, I can check if just a username exists by using:
 <?php
session_start();

include "config.php";

if($_POST['nameQuery']) {

$query = "SELECT * FROM ichatlogin WHERE name = '" .$_POST['nameQuery']. "'";
$result = mysql_query($query);
    if (mysql_num_rows($result) > 0) {
        //User exists
        echo '1';
    } else {
        mysql_query($query);
    //User does not exist
    echo '0';
    }
}
?>

Thanks!

A: You can make as many logical comparisons as you need. Combine them with AND or OR as appropriate.
$name = mysql_real_escape_string($_POST['nameQuery']);
$password = mysql_real_escape_string($_POST['password']);

$query = "SELECT * FROM ichatlogin WHERE name = '$name' AND password = '$password' LIMIT 1";

A:  <?php
session_start();

include "config.php";

if($_POST['nameQuery'] && $_POST['passwordQuery']) {

$query = "SELECT * FROM ichatlogin WHERE name = '" .$_POST['nameQuery'] . ' AND WHERE password = ' . $_POST['passwordQuery'];
$result = mysql_query($query);
    if (mysql_num_rows($result) > 0) {
        //User exists
        echo '1';
    } else {
        mysql_query($query);
    //User does not exist
    echo '0';
    }
}
?>


text:
Q: ImportError: cannot import name 'XGBClassifier' from 'xgboost' (unknown location) xgboost imported successfully, but I'm not able to import XGBClassifier.

A: Check whether xgboost is properly installed or not.
To install xgboost in anaconda distribution, you can run the following command in anaconda command-line console.
conda install -c conda-forge xgboost=0.6a2or 'conda install -c anaconda py-xgboost'
It will work fine after the installation.


text:
Q: R and shared memory for parallel::mclapply I am trying to take advantage of a quad-core machine by parallelizing a costly operation that is performed on a list of about 1000 items.
I am using R's parallel::mclapply function currently:
res = rbind.fill(parallel::mclapply(lst, fun, mc.cores=3, mc.preschedule=T))

Which works. Problem is, any additional subprocess that is spawned has to allocate a large chunk of memory:

Ideally, I would like each core to access shared memory from the parent R process, so that as I increase the number of cores used in mclapply, I don't hit RAM limitations before core limitations.
I'm currently at a loss on how to debug this issue. All of the large data structures that each process accesses are globals (currently). Is that somehow the issue?
I did increase my shared memory max setting for the OS to 20 GB (available RAM):
$ cat /etc/sysctl.conf
kern.sysv.shmmax=21474836480
kern.sysv.shmall=5242880
kern.sysv.shmmin=1
kern.sysv.shmmni=32
kern.sysv.shmseg=8
kern.maxprocperuid=512
kern.maxproc=2048

I thought that would fix things, but the issue still occurs.
Any other ideas?

A: Just the tip what might have been going on
R-devel Digest, Vol 149, Issue 22
Radford Neal's answer from Jul 26, 2015:
When mclapply forks to start a new process, the memory is initially
shared with the parent process.  However, a memory page has to be
copied whenever either process writes to it. Unfortunately, R's
garbage collector writes to each object to mark and unmark it whenever
a full garbage collection is done, so it's quite possible that every R
object will be duplicated in each process, even though many of them
are not actually changed (from the point of view of the R programs).

A: Linux and macosx have a copy-on-write mechanism when forking, it means that the pages of memory are not actually copied, but shared until the first write.
mclapply is based on fork(), so probably (unless you write to your big shared data), the memory that you see reported by your process lister is not actual memory.
But, when collecting the results, the master process will have to allocate memory for each returned result of the mclapply.
To help you further, we would need to know more about your fun function.

A: I guess I would have thought this would not have used extra memory because of the copy-on-write functionality.  I take it the elements of the list are large?  Perhaps when R passes the elements to fun() it is actually making a copy of the list item instead of using copy on write.   If so, the following might work better:
fun <- function(itemNumber){
  myitem <- lst[[itemNumber]]
  # now do your computations
}
res = rbind.fill(parallel::mclapply(1:length(lst), fun, mc.cores=3, mc.preschedule=T))

Or use lst[[itemNumber]] directly in your function.  If R/Linux/macos isn't smart enough to use copy-on-write as you wrote the function, it may with this modified approach.
Edit: I assume you are not modifying the items in the list.  If you do, R is going to make copies of the data.


text:
Q: Build And Archive Buttons Don't Do Anything in XCode 3.2.4 for me After I use Build and Archive to produce an Ad Hoc Distribution build, the Organizer appears. When I select the build, and press Share Application, the dialog pops up, but thereafter none of the buttons work. I can't Distribute For Enterprise, Save To Disk or Email. I press the buttons and they just pop right back up.
There are no errors or warnings on the archive build.
Anyone else have this happen and have a fix? Much appreciated.

A: Have you installed multiple copies xcode?  The order of installation matters.
Install the most recent version of xcode last.  The older versions will still work, but the newer install needs it's version of the system files.
(I typically put the latest version in Developer (and earlier versions in Develeoper 3.2 etc..)
How to Troubleshoot this:
Check the OSX Console.app and view your system.log
My system.log shows the error: it was referencing this "other" version of xcode:
- sh: /Developer: is a directory - /Developer 3.2/usr/bin/xcodebuild fails with 32256

A: Are you selecting a valid Distribution Provision profile?  You have to attempt to "share" using a valid profile (from the drop-down above the buttons) to get it push out the .iap.
I don't think Distribute for Enterprise works unless your dev Id is associated with an Enterprise Class DEV license. (could be wrong about that one though)


text:
Q: How to hide some fields in django-admin? class Book(models.Model):
    title = models.CharField(..., null=True)
    type = models.CharField(...)
    author = models.CharField(...)

I have a simple class in models.py. In admin I would like to hide title of the book (in book details form) when type of the saved book is 1.
How do this in a simplest way?

A: I tried to override get_form() function but some mix up errors occur when I switch in different records. I found there is a get_exclude() function we can override.
Use:
class BookAdmin(admin.ModelAdmin):
    def get_exclude(self, request, obj=None):
        if obj and obj.type == "1":
            # When you create new data the obj is None
            return ("title", )
        return super().get_exclude(request, obj)

A: class BookAdmin(admin.ModelAdmin):
    exclude = ("fieldname",)  # hide fields which you want

A: You are to create admin.py in your module (probably book)
class BookAdmin(admin.ModelAdmin):
    list_display = ("pk", "get_title_or_nothing")

In Book class:
class Book:
    ...
    def get_title_or_nothing(self):
        if self.type == WEIRD_TYPE:
            return ""
        return self.title

UPDATED:
class BookAdmin(admin.ModelAdmin):
    list_display = ("pk", "get_title_or_nothing")

    def get_form(self, request, obj=None, **kwargs):
        if obj.type == "1":
            self.exclude = ("title", )
        form = super(BookAdmin, self).get_form(request, obj, **kwargs)
        return form

A: For Django > 1.8 one can directly set the fields to be excluded in admin:
 class PostCodesAdmin(admin.ModelAdmin):
      exclude = ('pcname',)

Hidden fields are directly defined in Django's ORM by setting the Field attribute: editable = False
e.g.
class PostCodes(models.Model):
  gisid  = models.IntegerField(primary_key=True)
  pcname = models.CharField(max_length=32, db_index=True, editable=False)
  ...

However, setting or changing the model's fields directly may not always be possible or advantegous. In principle the following admin.py setup could work, but won't since exclude is an InlineModelAdmin option.
class PostCodesAdmin(admin.ModelAdmin):
     exclude = ('pcname',)
....

A solution working at least in Django 1.4 (and likely later version numbers) is:
class PostCodesAdmin(admin.ModelAdmin):
  def get_form(self, request, obj=None, **kwargs):
      form = super(PostCodesAdmin, self).get_form(request, obj, **kwargs)
      del form.base_fields['enable_comments']
      return form

For the admin list-view of the items, it suffices to simply leave out fields not required:
e.g.
class PostCodesAdmin(admin.ModelAdmin):
  list_display = ('id', 'gisid', 'title', )

A: Apropos @Lorenz @mrts answer
with Django 2.1 I found that exclude does not work if the field is already specified via fields = .
In that case you may use
self.fields.remove('title')

fields will have to be defined as a list [] for this to work

A: If you want to maintain the value in the form (for example set a value, i.e. user, based on the request) and hide the field, you can change the widget to forms.HiddenInput():
from django import forms

...

    def get_form(self, request, obj=None, **kwargs):
        """Set defaults based on request user"""
        # update user field with logged user as default
        form = super().get_form(request, obj, **kwargs)
        form.base_fields["user"].initial = request.user.id
        form.base_fields["user"].widget = forms.HiddenInput()
        return form

A: Here is a working example
class BookAdmin(admin.ModelAdmin):
    def get_fieldsets(self, request, obj):
        if obj is None:
            return [
                (
                    None,
                    {'fields': ('type', 'description',)}
                )
            ]
        elif request.user.is_superuser:
            return [
                (
                    None,
                    {'fields': ('type', 'status', 'author', 'store', 'description',)}
                )
            ]
        else:
            return [
                (
                    None,
                    {'fields': ('type', 'date', 'author', 'store',)}
                )
            ]