text:
Q: How fix Python import error in VS Code editor when using a Dev Container? I've opened a project with the following structure in VS Code (1.71.0 on macOS, Intel) and activated a Dev Container (I've tried the default Python 3.9 and 3.10 containers from Microsoft, with and without using python3 -m venv ...):
project/
  .devcontainer/
    devcontainer.json
    Dockerfile
  foo/
    foo/
      tests/
        test_bar.py  <-- IDE reports import error in this file
      resources/
      __init__.py
      bar.py
    setup.py

In VS Code's terminal window, I can successfully run test_bar.py from directory project/foo with:
python3 -m unittest discover foo/tests -p 'test_*.py'

So the project is valid and runs OK from the command line.
But when I open file project/foo/foo/tests/test_bar.py in VS Code, I see the error Unable to import 'foo' pylint(import-error) underlined in red for the following line:
from foo import bar

I see similar supposed errors for external packages I've installed with pip3 install.
I've tried to inform VS Code by adding various relative and absolute paths (e.g. /workspaces/project/foo) to various places in project/.devcontainer.json, such as at:

*

*customizations.vscode.settings

*

*python.analysis.extraPaths

*python.autoComplete.extraPaths

*python.testing.unittestargs
But I've had no luck so far (after many IDE restarts and container image rebuilds).
So I'm left wondering; how should one fix such IDE-flagged import errors in VS Code when using a Dev Container?
Additional Info
As a file was requested in the comments, here are the key test project files I used (I've not fixed any paths; my last test project was named vscode-python-dev-container, not project, which I used as shorthand above).
devcontainer.json (with the containerEnv section added for the suggested PYTHONPATH change):
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/python-3
{
    "name": "Python 3",
    "build": {
        "dockerfile": "Dockerfile",
        "context": "..",
        "args": {
            // Update 'VARIANT' to pick a Python version: 3, 3.10, 3.9, 3.8, 3.7, 3.6
            // Append -bullseye or -buster to pin to an OS version.
            // Use -bullseye variants on local on arm64/Apple Silicon.
            "VARIANT": "3.10-bullseye",
            // Options
            "NODE_VERSION": "lts/*"
        }
    },

    "containerEnv": {
        "PYTHONPATH": "/workspaces/vscode-python-dev-container/foo"
    },

    // Configure tool-specific properties.
    "customizations": {
        // Configure properties specific to VS Code.
        "vscode": {
            // Set *default* container specific settings.json values on container create.
            "settings": {
                "python.defaultInterpreterPath": "/usr/local/bin/python",
                "python.linting.enabled": true,
                "python.linting.pylintEnabled": true,
                "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
                "python.formatting.blackPath": "/usr/local/py-utils/bin/black",
                "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
                "python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
                "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
                "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
                "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
                "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
                "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint"
            },

            // Add the IDs of extensions you want installed when the container is created.
            "extensions": [
                "ms-python.python",
                "ms-python.vscode-pylance"
            ]
        }
    },

    // Use 'forwardPorts' to make a list of ports inside the container available locally.
    // "forwardPorts": [],

    // Use 'postCreateCommand' to run commands after the container is created.
    // "postCreateCommand": "pip3 install --user -r requirements.txt",

    // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
    "remoteUser": "vscode"
}

Dockerfile:
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/python-3/.devcontainer/base.Dockerfile

# [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster
ARG VARIANT="3.10-bullseye"
FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT}

# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10
ARG NODE_VERSION="none"
RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi

# [Optional] If your pip requirements rarely change, uncomment this section to add them to the image.
# COPY requirements.txt /tmp/pip-tmp/
# RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
#    && rm -rf /tmp/pip-tmp

# [Optional] Uncomment this section to install additional OS packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
#     && apt-get -y install --no-install-recommends <your-package-list-here>

# [Optional] Uncomment this line to install global node packages.
# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1

bar.py:
"""An example module."""
JSON_STR = '{"a": 1}'

test_bar.py:
"""An example test."""
import json
import unittest
import requests  # test external lib access
from foo import bar

class TestFooBar(unittest.TestCase):
    """An example test class."""
    a = requests.__name__  # to eliminate warning above that package isn't used
    def test_foo_bar_json(self):
        """An example test."""
        data = json.loads(bar.JSON_STR)
        self.assertEqual(data['a'], 1)

A: I often have this same issue with Python+Devcontainer. What works for me is:

*

*setting this env variable: export PYTHONPATH=/workspace, you can also try with /workspaces or /yourProjectName depending on your setup.

*restart the Python Language Server with Ctrl+Shift+P > Python: Restart Language Server.
Note that you do not need to rebuild the container. When you find the correct value for PYTHONPATH, you can add it to your Devcontainer configuration.

A: Is this issue completely resolved?
I believe it has to do something with your directory structure.
Please have a look at recommended directory structure here
.devcontainer/
  devcontainer.json
.devcontainer/
  Dockerfile
README.rst
LICENSE
setup.py
requirements.txt
foo/
  __init__.py
foo/
  bar.py
tests/
  test_bar.py
docs/
  conf.py    // optional
docs/
  index.rst  // optional

If you don't want to disturb your directory structure, you may consider below two entries:

*

*In the devcontainer.json file, give context:"."

*In the Dockerfile, adding appropriate entry for WORKDIR


text:
Q: After migration from 1.8.x to 1.9.3 admin image browse button not working I have migrated my magento from 1.8.x to 1.9.3 but after that magento product image browse file button is not working, if I click browse button it doesn't do anything.
in console I can see error like

Uncaught ReferenceError: Uploader is not defined(…)

I can see already existing images and working fine in both admin and front end.

A: Try this,
Please check this file available or not

/skin/adminhtml/default/default/media/uploader.swf
  /skin/adminhtml/default/default/media/uploaderSingle.swf
  /skin/adminhtml/default/default/media/editor.swf
  /skin/adminhtml/default/default/media/flex.swf
  /app/design/adminhtml/default/default/template/media/uploader.phtml
  /app/design/adminhtml/default/default/template/media/editor.phtml

A: This might be due to the Uploader module not being recognized. Try flushing your configuration cache (System > Cache Management or rm -rf var/cache/*).
Make sure following files are in place and readable by the webserver – try retrieving their URLs directly to see if this is the case:
js/lib/uploader/flow.min.js
js/lib/uploader/fusty-flow-factory.js
js/lib/uploader/fusty-flow.js
js/mage/adminhtml/uploader/instance.js

Ensure file app/design/adminhtml/default/default/layout/main.xml contains
<action method="addJs"><name>lib/uploader/flow.min.js</name></action>
<action method="addJs"><name>lib/uploader/fusty-flow.js</name></action>
<action method="addJs"><name>lib/uploader/fusty-flow-factory.js</name></action>
<action method="addJs"><name>mage/adminhtml/uploader/instance.js</name></action>

If this is the case, flush your layout cache and especially delete your merged JS & CSS file cache (lower left at System > Cache Management).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Documentation of Default Target of "git merge --squash" Sometimes I squash a bunch of commits together. Usually my commands follow this pattern:
git reset --hard HEAD~4
git merge --squash HEAD@{1}
git commit

Today, though, at step 2, I got distracted by something (squirrel? Slack? Facebook?) and I forgot to end the git merge --squash command with HEAD@{1}. Yet it magically did what I wanted.
I can't find any documentation that omitting the target of the merge will default to HEAD@{1}, but it was nice that it worked out.
Is there documentation on this somewhere?
I see the following from git help merge, but it doesn't seem to answer the question:
--squash, --no-squash
           Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit, move the HEAD, or record $GIT_DIR/MERGE_HEAD (to cause the next git commit command to create a merge commit). This
           allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).

           With --no-squash perform the merge and commit the result. This option can be used to override --squash.

           With --squash, --commit is not allowed, and will fail.

A: Running:
git merge

(with no options and no arguments) "means":
git merge @{upstream}

Adding options, such as --squash, does not change this, so:
git merge --squash

is a synonym for:
git merge --squash @{upstream}

The @{upstream} syntax means locate the commit pointed-to by the upstream of the current branch.  The upstream of master is pretty typically origin/master.  The upstream of dev is pretty typically origin/dev.  This pattern repeats.  The actual upstream can be found with git rev-parse:
git rev-parse --symbolic-full-name @{upstream}

which for instance in my Git clone of the Git repository for Git produces:
$ git rev-parse --symbolic-full-name @{u}
refs/remotes/origin/master

i.e., I'm on master and its upstream is origin/master.  (This particular clone is primarily a reference clone for me, so I just keep its master in sync with the other various duplicates of the Git repository for Git.  @{u} is a shorter way to write @{upstream}: less mnemonic, but easier to type in.)  Whatever commit @{u} meant, that's the one that Git squash-merged with.
As jthill noted in a comment, you should consider git reset --soft for your particular goal.  The soft reset moves the current branch, without touching the index and working tree, which avoids doing the work that git merge --squash would have to perform.  The resulting index-and-work-tree will be the same either way, and since --squash does not create .git/MERGE_HEAD (and does imply --no-commit) the final git commit will behave the same way as well.


text:
Q: Error calling class method from extended Electron class First of all, I'm a newbie on javascript and Electron.
This is a code snippet to replicate a concept coming from a basic Javascrip/Electron tutorial on YouTube, that for some reason is not working for me.

*

*Define a base class "base"

*Define a class called "derived" that extends "base"

*In derived constructor, call super() and then call the derived class method this.showSomething()

Everything works as expected. Now, define a derived class by extending Tray (Electron class) and do the same things:

*

*Define a class called "derivedFromTray" that extends "Tray"

*In derived constructor, call super() and then call the derived class method this.showSomething()
This leads to an error: this.ShowSomething is not a function
Am I missing something in the script? Why this happens?
NOTE 1: I'm not interested in alternative coding solutions to call the extended class methods, unless there is a clear indication that, by design, deriving Electron classes breaks the coding solution used in this snippet.
You can find the tutorial here: How To Code - Electron JS Tutorial #46
Node version: 15.8.0 - Electron version: 11.2.3
Code to replicate the issue:

const electron = require('electron')
const path = require('path');
const {app, Tray} = electron;

class base{
    constructor(path){
        this.internalPath = path
    }

}

class derived extends base {
    constructor(path) {
        super(path)
        this.showSomething();
    }
    showSomething()
    {
        console.log(`internal Path: ${this.internalPath}`);
    }
}

class derivedFromTray extends Tray {
    constructor(iconPath) {
        super(iconPath)
        this.showSomething() // ERROR: this.showSomething is not a function
    }
    showSomething()
    {
        console.log('Log from derivedFromTray.showSomething');
    }
}

app.on('ready', ()=>{
    // WARNING: specify a valid image path or the example
    // will not work!
    const paramPath = path.join(__dirname, "app_tray_icon.png")
    const workingDerived = new derived(paramPath)
    const notWorkingDerived = new derivedFromTray(paramPath)
})

A:
unless there is a clear indication that, by design, deriving Electron classes breaks the coding solution used in this snippet.

https://github.com/electron/electron/issues/25721

we do not support extending built in classes in Electron

Built in classes in Electron are not plain javscript object and do not support all js behaviors like extending class.


text:
Q: cannot use again my magento site I cannot use my frontend site on a pc browser.
I will get only a grey site and cannot click any Link.
Hope somebody can help me there.
kindly regards for any answer.

A: The problem was a defect css file.
kindly regards


text:
Q: Connecting react native and node js how do call an api running on localhost from react native.I am using expo cli and running the app on real device using expo app.I tried fetch("https://localhost:3000") but that doesn't work pls help!!
Network Error
at node_modules\axios\lib\core\createError.js:16:14 in createError
at node_modules\axios\lib\adapters\xhr.js:84:24 in handleError
at node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:600:10 in setReadyState
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:395:6 in __didCompleteResponse
at node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 in emit
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
at [native code]:null in callFunctionReturnFlushedQueue

A: try to change https to http make sure your server is running on port 3000.
fetch("http://localhost:3000").then((data)=>{
  console.log(data);
});


text:
Q: Adding to local storage I am using local storage to add json data as favorites. for some reason when i add more that one favorite it removes the one already in local storage.
 $('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));
        var favArray = [];
        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));

A: It is the expected behavior.
The local storage is a key-value storage, when you write a data in an already existing key, it is overridden.
In order to add a value, you need to parse the existing value, add an item and write it again.
var storedFavs = JSON.parse(localStorage.get('favourites') || '[]');
storedFavs.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
localStorage.setItem('favourites', JSON.stringify(storedFavs));

A: put the line var favArray = []; out of click event
var favArray = []; //here
 $('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));

        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));

A: You are writting an array of one element, first you need to read in your favourites, add your new element to it then save it back. Try something like this, though your porbably want to add some checks to handle the case where there is no favourties already and use an empty array then etc.
    var storedbar = JSON.parse(localStorage.getItem('storedBar'));
    var favArray = JSON.parse(localStorage.getItem('favourites'));
    favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
    localStorage.setItem('favourites', JSON.stringify(favArray));
    console.log(localStorage.getItem('favourites'));


text:
Q: Can IfxConnection and threading get along? We have an application using the IBM Informix driver. Whenever we try to open connections in parallel, we start getting some really weird errors.
This is the smallest reproduction code I could come up with:
const int Count = 10;
const string ConnectionString = "Host=the_host;Service=the_service;Server=the_server;Database=the_database;User ID=the_user_id;Password=the_password";

static void Main()
{
    var threads = new Thread[Count];
    for (var i = 0; i < threads.Length; i++)
    {
        threads[i] = new Thread(
            number =>
            {
                using (var conn = new IfxConnection(ConnectionString))
                {
                    Console.WriteLine("Opening connection {0}... ", number);
                    try
                    {
                        conn.Open();
                        Console.WriteLine("Opened connection {0}", number);
                        var setLockCommand = conn.CreateCommand();
                        setLockCommand.CommandText = "set lock mode to wait 10;";
                        setLockCommand.ExecuteNonQuery();
                        Console.WriteLine("Releasing connection {0}", number);
                    }
                    catch (IfxException ex)
                    {
                        Console.WriteLine("Failed opening connection {0}: {1}", number, ex);
                    }
                }
            });
        threads[i].Start(i);
    }
    foreach (var thread in threads)
        thread.Join();
}

Depending on which machine we run it on, we had to play a little with the Count value to make it fail, but 10 seems to reproduce the error consistently.
Of course this is not production code, nor how we handle threading, but it highlights the issue without introducting any other variables.
This is the exception stack trace:
IBM.Data.Informix.IfxException: ERROR [HY000] [Informix .NET provider]General error.
   at IBM.Data.Informix.IfxConnection.GetConnectAttr(SQL_ATTR attribute, HANDLER handler)
   at IBM.Data.Informix.IfxConnection.ConnectionIsAlive()
   at IBM.Data.Informix.IfxConnectionPool.BindNodeToConnection(IfxConnPoolNode poolNode, IfxConnection connection, ConnectionPoolType ConnPoolType)
   at IBM.Data.Informix.IfxConnectionPool.Open(IfxConnection connection)
   at IBM.Data.Informix.IfxConnPoolManager.Open(IfxConnection connection)
   at IBM.Data.Informix.IfxConnection.Open()

IBM.Data.Informix.dll version is 3.00.06000.2.
This was tested on Windows 7 (32 and 64 bits) and 2008 (64 bits).

A: I asked about this internally, and got the following feedback about the IBM Informix ClientSDK .NET provider:

*

*The issue is not reproducible on our Windows XP 32-bit development machine.

*The user/customer is trying to run the application on Windows 7. CSDK 3.00 is NOT certified on Windows 7 (and never will be).

*The customer should upgrade to the latest version, CSDK 3.50.TC6 (32-bit) or 3.50.FC6 (64-bit).  That is supported.  Note that CSDK 3.50.xC5 and earlier fix packs do not support Windows 7.

  The Informix.NET provider is also referred to as CSDK .NET provider. It is still the preferred .NET provider used by the majority of IDS customers. The 'latest' IBM Common.NET provider (which works with DB2 as well as IDS using the DRDA protocol, instead of the SQLI protocol used by the CSDK .NET provider) is definitely the future strategy, but few customers are actually using Common.NET for IDS application development.

Since I didn't develop the answer, I've made it Community Wiki.

A: I solved this issue adding a "Pooling=false" on the connection string.
const string ConnectionString = "Host=the_host;Service=the_service;Server=the_server;Database=the_database;User ID=the_user_id;Password=the_password;Pooling=false";


text:
Q: How to filter data in Angular view based on user input? I would like to display data in Angular 7/8 based on user search parameters. Initially the view should be blank,but when the user inputs the search parameters and clicks the Submit button the view should be updated with the new/filtered information.
Desired approach: Empty ArrayB should be populated with the filtered data of ArrayA
Implementation:
ArrayA = [{id:1, Name:"Steve"},{id:2, Name:"Maureen"},{id:3, Name:"Damian"},{id:4, Name:"Dee"}];
ArrayB = [];

HTML code:

        <form class="form" [formGroup]="filterForm" >
            ID
            <input type="text" name="person_id" formControlName="person_id" id="person_id">
            <button type="submit" (click)="submit($event)">Submit</button>
        </form>

{{filteredArr.name}}

When i click submit, the ArrayA should be filtered based on the ID provided by the user and pushed into ArrayB and the view updated with the new information.
    submit(event){
//Filter ArrayA and push to ArrayB
    }

If there is a better and much simpler way of achieving the same i will greatly appreciate

A: You can use .filter() method:
let filteredUserID = this.form.get('person_id').value
this.ArrayB = this.ArrayA.filter(item => item.id == filteredUserID))

A: You can use .filter() function to filter arrayA then you can store the generated result in arrayB and then bind this arrayB to your html template.
In  below example id can be considered as input coming from user and when he click on submit button you can fire this filter function to get arrayB.
Your html code can be like this:
   <button (click)="clickHandler()">submit</button>
Where clickHandler() will be the function where you'll write your filter logic.

ArrayA = [{id:1, Name:"Steve"},{id:2, Name:"Maureen"},{id:3, Name:"Damian"},{id:4, Name:"Dee"}];

let id = 1;

arrayB = ArrayA.filter((item)=>{
    if(item.id == id)
      return item;
    else
      return null;
})

console.log(arrayB);

A: Try this,
this.ArrayB = this.ArrayA.filter(item => item.id == this.filterForm.value.person_id))

A: You should have to filter your array arrayA based on values of formControlName person_id

this.ArrayB = this.ArrayA.filter(item => item.id == this.filterForm('person_id').value));


text:
Q: AttributeError: 'DataFrame' object has no attribute 'Class' Here is a sample of my data set:
   Pat_ID  Flare_Up  Demo1     Demo2     Demo3     Demo4  Demo5     Demo6  DisHis1  DisHis1Times  DisHis2    ...     Dis6Treat  Dis7  RespQues1  ResQues1a  ResQues1b  ResQues1c  ResQues2a  SmokHis1  SmokHis2  SmokHis3  SmokHis4
0       1         0      1  0.246004  0.391931  0.237792      0  0.443526        0      0.000000        0    ...             1     0    0.12623     0.1032     0.2439     0.0597        0.0  0.411765  0.263620  0.482759    0.1875
1       2         1      1  0.225851  0.268012  0.268481      0  0.286501        0      0.000000        1    ...             1     0    0.60707     0.3808     0.8637     0.4949        0.1  0.117647  0.098418  0.624138    0.0000
2       3         0      0  0.342599  0.476945  0.296468      1  0.159780        1      0.166667        1    ...             0     0    0.77541     0.6318     1.0000     0.6570        0.3  0.035294  0.020211  0.510345    0.0000

[3 rows x 62 columns]

My code to traverse through that data set and print ROC is:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, roc_auc_score
import itertools

def plot_confusion_matrix(cm, classes, normalize=True, title='Confusion matrix', cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
#    else:
#        print('Confusion matrix, without normalization')

#    print(cm)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()

def show_data(cm, print_res = 0):
    tp = cm[1,1]
    fn = cm[1,0]
    fp = cm[0,1]
    tn = cm[0,0]
    if print_res == 1:
        print('Precision =     {:.3f}'.format(tp/(tp+fp)))
        print('Recall (TPR) =  {:.3f}'.format(tp/(tp+fn)))
        print('Fallout (FPR) = {:.3e}'.format(fp/(fp+tn)))
    return tp/(tp+fp), tp/(tp+fn), fp/(fp+tn)

df = pd.read_csv("datasource/DevelopmentData.csv")
print(df.head(3))
y = np.array(df.Class.tolist())     #classes: 1..fraud, 0..no fraud
df = df.drop('Class', 1)
df = df.drop('Time', 1)     # optional
df['Amount'] = StandardScaler().fit_transform(df['Amount'].values.reshape(-1,1))    #optionally rescale non-normalized column
X = np.array(df.as_matrix())   # features

A class of 0 means that the transaction was in order, and a class of 1 means that the transaction was fraudulent.
When I run my code, I get this error:
Traceback (most recent call last):
  File "finalindex.py", line 54, in <module>
    y = np.array(df.Class.tolist())     #classes: 1..fraud, 0..no fraud
  File "C:\Users\kulkaa\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\generic.py", line 4376, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'Class'

How can I fix that error? Do I need to change column names according to data set?

A:
[...] The author of this
  link (kaggle.com/dstuerzer/optimized-logistic-regression) has used it
  and it is working fine with his code.

In the link you mentioned, example, the author's database has a column named "Class" but the database that you have shown does not.  As a result, the Class attribute does not exist in your database and therefore cannot be accessed.
Dominik Stuerzer:

   Time        V1        V2        V3        V4        V5        V6        V7  \
0   0.0 -1.359807 -0.072781  2.536347  1.378155 -0.338321  0.462388  0.239599
1   0.0  1.191857  0.266151  0.166480  0.448154  0.060018 -0.082361 -0.078803
2   1.0 -1.358354 -1.340163  1.773209  0.379780 -0.503198  1.800499  0.791461

         V8        V9  ...         V21       V22       V23       V24  \
0  0.098698  0.363787  ...   -0.018307  0.277838 -0.110474  0.066928
1  0.085102 -0.255425  ...   -0.225775 -0.638672  0.101288 -0.339846
2  0.247676 -1.514654  ...    0.247998  0.771679  0.909412 -0.689281

        V25       V26       V27       V28  Amount  Class
0  0.128539 -0.189115  0.133558 -0.021053  149.62      0
1  0.167170  0.125895 -0.008983  0.014724    2.69      0
2 -0.327642 -0.139097 -0.055353 -0.059752  378.66      0

[3 rows x 31 columns]

A class of 0 means that the transaction was in order, and a class of 1
  means that the transaction was fraudulent. From personal experience we
  expect frauds to make up only a tiny fraction of all transactions.
  Indeed, in this dataset, for every fraud there are almost 600
  non-fraudulent transactions: [...]

A: Try this,
df = df.drop(['Class'],axis=1)
df = df.drop(['Time'],axis=1) # optional

A: try
y = np.array(df['Class'].tolist())


text:
Q: Azure Web App, PHP 7.4, OCI8 (Oracle Instant Client 12.2.0.1.0) We're trying to lift an existing PHP 7.4 app from an internal server running on Windows Server 2012 to an Azure Web App. The PHP app uses OCI8 to connect to an Oracle database. Everything (except the database connection) works fine without the OCI8 extension enabled.
We've followed the guide at https://learn.microsoft.com/en-us/archive/blogs/azureossds/access-oracle-databases-from-azure-web-apps-using-oci8-drivers-with-php as recommended in other Stack Overflow Questions, but whenever the OCI8 extension is enabled we get logless HTTP 500 errors.
The steps we take are:

*

*Starting with OCI8 disabled, the app loads fine but can't run any database calls.  Database call errors are recorded in the logs.

*Edit the D:\home\site\ini\extensions.ini file to enable OCI8 (we've tried multiple variations - full path, 32 bit, 64 bit, extension name only e.g. extension=php_oci8 - all have the same results).

*Restart the app

*Refresh the page - result is status code 500, with a plain white screen reading The page cannot be displayed because an internal server error has occurred.

*Check everything under D:\home\LogFiles, including php_errors.log, eventlog.xml, and /http/RawLogs.  eventlog.xml shows the server reboot, nothing else is recorded after that.

We have also tried using the "App Service Logs" in the Azure App Service, and enabling Application Insights, but there was similarly nothing of interest (we could see the HTTP 500 response in the logs, but not any details about what caused it).
The suspicion is that PHP isn't starting, but we aren't sure how to trace that when nothing seems to be logged.
Ultimately, that leads to this being two questions:

*

*Is there perhaps a different way to enable logs in the Azure App Service, or a log location I might be missing?

*Is there an updated guide available for running a PHP app with OCI8 on Azure App Service?  The guide above is 5+ years old, and at a minimum the versions of everything listed in it appear to be outdated. I suspect the Azure App Service has updated in a way that might be blocking us too.

Thanks!

UPDATE 2021-08-10
Turns out this issue was due to an incompatibility between the App Service "Composer" extension and OCI8.  I'll continue to update this post with progress as we get that enabled, since I assume others will run into this at some point as well.

UPDATE 2021-08-16
Just as a final update, we wound up with an old version of Composer installed (1.6.4). We didn't test all the other versions, but if you run into the same issue 1.6.4 can at least act as a solid baseline.
The Azure Extension's repo doesn't appear to specify a version, so it should grab the latest, but it seems only 1.8.5 gets installed so there might be a bad cache somewhere.  TL;DR: If you encounter issues, try manually installing Composer instead of using the Extension.

A: I did some searching, this one seems like a pretty solid and more recent answer: Does Azure PHP 7 web app have Oracle drivers?.
I think you're probably right that PHP isn't starting correctly. A few questions:

*

*Did you configure and toggle on PHP error logging for the site like described here: https://azureossd.github.io/2016/09/28/how-to-identifyreview-errors-on-php-applications-in-azure-web-apps-using-log-stream-service/

*If you create a phpinfo.php file in /wwwroot/ containing <?php phpinfo(); , and try to access it while the issue is happening, does oci8 driver load?

*If you create and try to access a static file like index.html while the issue is happening, can it be accessed directly? It would confirm the PHP issue.

*Can you check the post with the proper screenshots, maybe it will help be more clear what is missing, the link referenced above drops the screenshots: https://azureossd.github.io/2016/02/23/access-oracle-databases-from-azure-web-apps-using-oci8-drivers-with-php/ (I followed the steps here to a T and it worked for me)

I built a lab, it took me a little work, but I actually got it running so it seems. I could build an Oracle server and fetch some data to prove it works:
Driver output
I'd probably follow those steps above and I am sure it can be figured out. It's probably missing one of these steps:

*

*Needs App Setting PHP_INI_SCAN_DIR

*Need the /site/ini/extensions.ini file with the proper setting, I used this:
extension="D:\Program Files (x86)\PHP\v7.4\ext\php_oci8_12c.dll"

*Needs the ApplicationHost.xdt with the proper setting

*Need to download and upload the Oracle Instant Client folder
I uploaded instantclient_19_11 but you could probably just as well upload instantclient_12_X

*Restart after you get these all in place and confirm the OCI8 driver loaded. I was seeing a similar white error page up until I had all of these proper.


text:
Q: Balance Of Power I have a question about the noun "balance" here:

2014 Senate Balance of Power

Does "balance" here mean a specified state of equilibrium?

A: http://www.rasmussenreports.com/public_content/election_2014/2014_senate_balance_of_power
The Balance of Power refers to some measure of difference between the majority and minority political parties.  In the US Senate, the difference is 6.  If the Republicans gain 6 seats, the Balance of Power swings to them.  If the Democrats maintain a majority, the Balance of Power stays "dipped" on their side.

A: Yes, though equilibrium and balance, in this context, do not necessarily imply equal or static power distribution. At the time of publishing, the document aims to show how the Democratic and Republican parties measure up to one another, as if putting both on an old fashioned set of swing scales.


text:
Q: How to use NSMutableDictionary to store and retrieve data I have created Window Based application and tab bar controller as root controller. My objective is to store Text Field data values in one tab bar VC and will be accessible and editable by other VC and also retrievable when application start.
I am looking to use NSMutableDictionary class in AppDelegate so that I can access stored Data Values with keys.
//TestAppDelegate.h

extern NSString *kNamekey ;
extern NSString *kUserIDkey ;
extern NSString *kPasswordkey ;

@interface TestAppDelegate :NSObject<UIApplicationDelegate>{
 UIWindow *window;
 IBOutlet UITabBarController *rootController;
 NSMutableDictionary *outlineData ;

}
@property(nonatomic,retain)IBOutlet UIWindow *window;
@property(nonatomic,retain)IBOutlet UITabBarController *rootController;
@property(nonatomic,retain) NSMutableDictionary *outlineData ;
@end

//TestAppDelegate.m
 #import "TestAppDelegate.h"

NSString *kNamekey =@"Namekey";
NSString *kUserIDkey =@"UserIDkey";
NSString *kPasswordkey =@"Passwordkey";

@implemetation TestAppDelegate

@synthesize outlineData ;

-(void)applicationDidFinishLaunching:(UIApplication)application
{

  NSMutableDictionary *tempMutableCopy = [[[NSUserDefaults standardUserDefaults] objectForKey:kRestoreLocationKey] mutableCopy];
 self.outlineData = tempMutableCopy;
 [tempMutableCopy release];
 if(outlineData == nil){
 NSString *NameDefault   = NULL;
 NSString *UserIDdefault= NULL;
 NSString *Passworddefault= NULL;

 NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithObjectsAndKeys:
      NameDefault, kNamekey ,
      UserIDdefault, kUserIDkey ,
      Passworddefault, kPasswordkey ,
      nil];
 self.outlineData = appDefaults;
  [appDefaults release];
  }

 [window addSubview:rootController.view];
 [window makeKeyAndVisible];

 NSMutableDictionary *savedLocationDict = [NSMutableDictionary dictionaryWithObject:outlineData forKey:kRestoreLocationKey];
 [[NSUserDefaults standardUserDefaults] registerDefaults:savedLocationDict];
 [[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)applicationWillTerminate:(UIApplication *)application
{

 [[NSUserDefaults standardUserDefaults] setObject:outlineData forKey:kRestoreLocationKey];
}
@end
Here ViewController is ViewController of Navigation Controller which is attached with one tab bar.. I have attached xib file with ViewController

//ViewController.h
@interface
   IBOutlet UITextField *Name;
   IBOutlet UITextField *UserId;
   IBOutlet UITextField *Password;
}
@property(retain,nonatomic) IBOutlet UITextField *Name
@property(retain,nonatomic) IBOutlet UITextField *UserId;
@property(retain,nonatomic) IBOutlet UITextField *Password;
-(IBAction)Save:(id)sender;
@end

Here in ViewController.m, I am storing object values with keys.
/ViewController.m
-(IBAction)Save:(id)sender{

  TestAppDelegate *appDelegate = (TestAppDelegate*)[[UIApplication sharedApplication] delegate];
   [appDelegate.outlineData setObject:Name.text forKey:kNamekey ];
   [appDelegate.outlineData setObject:UserId.text forKey:kUserIDkey ];
   [appDelegate.outlineData setObject:Password.text forKey:kPasswordkey];
   [[NSUserDefaults standardUserDefaults] synchronize];
}

I am accessing stored object using following method.
-(void)loadData
{

 TabBarAppDelegate *appDelegate = (TabBarAppDelegate *)[[UIApplication sharedApplication] delegate];
 Name = [appDelegate.outlineData  objectForKey:kNamekey ];
 UserId = [appDelegate.outlineData  objectForKey:kUserIDkey ];
 Password = [appDelegate.outlineData  objectForKey:kPasswordkey];

 [Name release];
 [UserId release];
 [Password release];

}

I am getting EXEC_BAD_ACCESS in application. Where I am making mistake ?
Thanks,

A: You are creating objects as autoreleased, and then calling release on them (eg in loadData).  You need to read the Memory Management Guide.  You should only be calling release on objects that you have created using alloc or copy.


text:
Q: Where is log.info written? I am working on a grails 2.2.4 application and i have found code like
log.info("info to be logged")
but i don't know where i can fond the file that is being written or if the location for the log file can be configured somewhere.
I thought that it may be written in stackstrace.log but that does not seem correct.
I thought that it may be written in the database but i cannot find the log anywhere.
I have searched the project directory for the log and i cannot find it.
Amy help would be appreciated since i haven't found where that log is written.

A: In grails 2, logging is accomplished via log4j and can be configured per the information in the documentation here: https://grails.github.io/grails2-doc/2.2.4/guide/conf.html#logging
If you cannot access the full documentation, or want a quick reference, you basically need to add a log4j section to your Config.groovy file with a block like
log4j = {
    appenders {
        appender new RollingFileAppender(
            name: "myAppender",
            maxFileSize: 1024,
            file: "/tmp/logs/myApp.log")
    }
}

Log4j is extremely customizable, so I wouldn't recommend just copying that verbatim and calling it complete, but instead use this as a starting point.


text:
Q: Rails 4: update form field displayed value based on value selected in previous field In my Rails 4 app, I have the following form

  <%= f.label :target_age_lower_limit, "AGE (LOWER LIMIT)" %>
  <%= f.select :target_age_lower_limit, (0..99) %>

  <%= f.label :target_age_upper_limit, "AGE (UPPER LIMIT)" %>
  <%= f.select :target_age_upper_limit, (0..99) %>

Which renders the following HTML code:

      AGE (LOWER LIMIT)
      <select name="calendar[target_age_lower_limit]" id="calendar_target_age_lower_limit"><option value="0">0</option>
      <option value="1">1</option>
      [...]
      <option value="99">99</option></select>

      AGE (UPPER LIMIT)
      <select name="calendar[target_age_upper_limit]" id="calendar_target_age_upper_limit"><option value="0">0</option>
      <option value="1">1</option>
      [...]
      <option value="99">99</option></select>

Currently, a user can select an age lower limit of 34 and an age upper limit of 25 if he wants to, which makes no sense in terms of business logic.
I would like to implement a JS function that will:

*

*Freeze the upper limit options that are smaller than the value selected in the lower limit field (if the lower limit field was filled first)

*Freeze the lower limit options that are bigger than the value selected in the upper limit field (if the upper limit field was filled first)

How can I achieve this?


text:
Q: Initiating a ViewModel with Input parameters in Jetpack Compose -> Composable function I have a ViewModel that takes a string as an argument
class ComplimentIdeasViewModel(ideaCategory : String) : ViewModel()  {
    //some code here
}

What is the best way to initiate this ViewModel inside a composable fun without using a ViewModel factory and Hilt? A simple statement seems to achieve this inside a composable fun
@Composable
fun SampleComposableFun() {
    val compIdeasViewModel = remember { ComplimentIdeasViewModel("someCategory") }
}

There is no warning in Android studio when I try to do this, but this seems too easy to be true, I am able to do this without Dependency Injection and with a ViewModelFactory class. Am I missing something here?

A: I've tried how you have written yours out and I had issues with screen rotation resetting the view model. I suspect you may too.
I was able to fix it by utilizing the the factory parameter on viewModel() for this, which worked well for me. See this answer on a similar question with example on how to use it: jetpack compose pass parameter to viewModel

A: This will not provide you the correct instance if viewmodel. See if you store some state in the viewmodel, then using the factory to initialise it is necessary to ensure that you get the same and latest copy of the viewmodel currently present. There is no error since the syntactic implementation is correct. I do not know of any way to do this because most of the times, you don't need to. Why don't you initialise it in the top-level container, like the activity? Then pass it down wherever necessary.

A: Create a CompositionLocal for your ViewModel.
val YourViewModel = compositionLocalOf { YourViewModel(...) }

Then initialise it (You'd likely use the ViewModelProvider.Factory here). And then provide that to your app.
CompositionLocalProvider(
  YourViewModel provides yourInitialisedViewModel,
) {
  YourApp()
}

Then reference it in the composable.
@Composable
fun SampleComposableFun(
  compIdeasViewModel = YourViewModel.current
) {
  ...
}

Note, the docs say that ViewModels are not a good fit for CompositionLocals because they will make your composable harder to test, make your composables tied to this app and make it harder to use @Preview.
Some get pretty angry about this. However, if you manage to mock out the ViewModel, so you can test the app and use @Preview and your composables are tied to the app and not generic, then I see no problem.
You can mock a ViewModel fairly simply, providing its dependencies are included as parameters (which is good practice anyway).
open class MockedViewModel : MyViewModel(
  app = Application(),
  someOtherDependeny = MockedDependecy(),
)

The more dependencies your ViewModel has the more mocking you'll need to do. But I've not found it prohibitive and including the ViewModel as a default parameter has massively sped up development.


text:
Q: How can I get the error/warning messages out of the parsed HTML using JTidy? I am able to parse the HTML but I want to extract the warning messages from the parsed HTML and show them to the user.
Here is my code:
Tidy tidy = new Tidy();
StringBuffer StringBuffer1 = new StringBuffer("<b>Hello<u><b>I am tsting another one.....<i>another.....");
InputStream in = new ByteArrayInputStream(StringBuffer1.toString().getBytes("UTF-8"));
Writer stringWriter = new StringWriter();
    tidy.setPrintBodyOnly(true);
    tidy.setQuiet(true);
    tidy.setShowWarnings(true);
    tidy.setTidyMark(false);
    tidy.setXHTML(true);
    tidy.setXmlTags(false);
    Node parsedNode = tidy.parse(in, stringWriter);
    System.out.print(stringWriter.toString());

A: I noticed it in the jTidy documentation that starting from release r8 jTidy privdes TidyMessageListener interface you can implement to be notified for warning and errors in your html code.
Here is the doc

A: You can setup an error output stream like this:
errorOutputStream = new java.io.ByteArrayOutputStream();
errorPrintWriter = new java.io.PrintWriter(errorOutputStream, true); //second param enables autoflush so you don't have to manually flush the printWriter
tidy.setErrout(errorPrintWriter);

Then when you need to see the errors errorOutputStream.toString();


text:
Q: Add a border to each number in a div I'm not sure if this is possible but I would like to add a border to each number in a div.
I know how to add a border to a div but I would like that each number in a div to have a border.
Example:

12345

The output should look like this:
(1) (2) (3) (4) (5)

Where "()" is the border.
PS: I don't want to use a separate div for each number because this number will be a php code, like this:

<?php $number; ?>

Is it possible?

A: Not possible without adding extra markup:

Live example: http://codepen.io/anon/pen/gDHlA

Markup

  1
  2
  3
  4
  5

Css
span:before, span:after {
  display: inline-block;
}

span:before {
  content: "(";
}

span:after {
  content: ")";
}

I've inserted parens, of course feel free to change them with a pipe (|) or use borders applied to span elements (in this case, give them also a display, a width and a height)

About your latest requirement, your code can easily adapted like so:
$number = 12345;
$span_number = "";

foreach (str_split($number) as $key => $digit) {
  $span_number .= "$digit";
}

echo $span_number;
//output: 12...5

A: I think it is impossible. You can wrap each number in a  and make border for spans

A: You can use span elements like this, but you have to build all tags according to the numbers, using php string functions to split each number. There is no way to do that without tags.

  1
  2
  3
  4
  5

Your CSS:
#borders span {
    display:inline-block;
    border:1px solid red;
    padding:2px;
    margin:2px;/*if you want space between numbers*/
}


text:
Q: Is change of inner product equivalent to change of basis? Suppose I have a Hilbert space equipped with the inner product $(x, y)$. If I introduce a new inner product $[x,y]$, can I say that this is equivalent to a certain change of basis, i.e., there is a $T$ such that $(x,y)=[Tx,Ty]$?
For finite-dimensional cases, we may just choose $\{\bf{e}_i\}$ to be an orthonormal basis with regard to the old inner product, and $\{\bf{f}_i\}$ to the new one. Then we simply define $T\bf{e}_i=\bf{f}_i$ to shuttle between the new and odd inner products.
What about the infinite-dimensional case?


text:
Q: Show that $\sum b_n$ is divergent. Show that $\sum b_n$ is divergent for $b_n = \frac{1}{n}\sum_{r=1}^{\infty}a_r$ and nonnegative $a_r$ and not all $a_r$ are zero. I used comparison test:
$S_n = \sum_{r=1}^n a_r$ is partial sum of $\sum_{n=1}^{\infty} a_n$ and it's an increasing sequence. If $S_n\geq1$ $$ 0 < \frac{1}{n} \leq \frac{S_n}{n}$$ and we know that $\sum_{n=1}^{\infty}\frac{1}{n}$ is divergent. So by comparison test, $\sum \frac{S_n}{n} = \sum b_n$ is divergent. but what if $S_n < 1$?

A: 1) Say if $\sum a_r$ diverges, then you are done
2) Say if $\sum a_r$ converges. Then it is some non-zero constant. Since $\sum \frac 1 n$ diverges, $\sum \frac c n$ diverges for all constant c that is not zero.


text:
Q: Creating URL for an external route in Zend Framework 2 I'd like to save a route to an external URL, and so, doing
echo $this->url('externalSite');

would return
http://some-other-site.domain/somePage.php?list=modules

A: In case anyone wondered how I resolved this issue, I put the url inside the application config and wrote a view&controller helper to retrieve it
module.config.php:
// ...

'view_helpers' => array(
    'invokables' => array(
        'externalUrl' => 'MyModule\Helper\ExternalUrlHelper',
    ),
),

'controller_plugins' => array(
    'invokables' => array(
        'externalUrl' => 'MyModule\Helper\ExternalUrlHelper',
    )
),

// ...
'external_urls' => array(
    'home' => 'http://some-other-site.domain/somePage.php?list=modules',
),

MyModule/Helper/ExternalUrlHelper.php:
<?php
namespace MyModule\Helper;

use Zend\Stdlib\DispatchableInterface as Dispatchable;
use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Mvc\Controller\Plugin\PluginInterface;
use InvalidArgumentException;

class ExternalUrlHelper extends AbstractHelper implements
    ServiceLocatorAwareInterface, PluginInterface
{
    /** @var \Zend\View\HelperPluginManager  */
    protected $sm;

    /** @var Dispatchable */
    protected $controller;

    /**
     * Set service locator
     * @param ServiceLocatorInterface $serviceLocator
     */
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->sm=$serviceLocator;
    }

    /**
     * Get service locator
     * @return ServiceLocatorInterface
     */
    public function getServiceLocator()
    {
        return $this->sm;
    }

    /**
     * Set the current controller instance
     *
     * @param  Dispatchable $controller
     * @return void
     */
    public function setController(Dispatchable $controller)
    {
        $this->controller=$controller;
    }

    /**
     * Get the current controller instance
     *
     * @return null|Dispatchable
     */
    public function getController()
    {
        return $this->controller;
    }

    /**
     * @param string $name
     * @return string
     */
    public function __invoke($name)
    {
        return $this->getRouteByName($name);
    }

    /**
     * @param string $name
     * @return string
     * @throws \InvalidArgumentException
     */
    protected function getRouteByName($name)
    {
        $config=$this->sm->getServiceLocator()->get('config');
        $routes=$config['external_urls'];

        if (! isset($routes[$name])) {
            throw new InvalidArgumentException(
                sprintf('Route name %s not found', htmlspecialchars($name, ENT_QUOTES))
            );
        }

        return $routes[$name];
    }
}

in a view:
<a href="<?php echo $this->externalUrl('home'); ?>">Main portal

in a controller:
$this->redirect()->toUrl($this->externalUrl('home'));


text:
Q: Is Eta interoprable with Java and/or Kotlin yet? I've been learning Haskell, but during my day job I am writing Kotlin/Java.
I've come across Eta (https://eta-lang.org/), a Haskell dialect that compiles to Java byte code and runs on the JVM. On the website it states that it has:
Robust Interoperability

Eta has a strongly-typed Foreign Function Interface (FFI) that allows you to safely interoperate with Java.

But further down the page there is a "Coming Soon" section, where the interop is listed. So my question, before I go to the hassle of setting up an environment to dev in:
Is this officially supported yet?

A: The thing that's "Coming soon" is the "bindings generator". Eta has implemented syntax for Java interop, but you need to explicitly write foreign declarations for each Java entity you want to call. E.g. as in the linked example, a class like
public class Counter {
    private int counter = 0;
    private final int max;
    public Counter(int max) { this.max = max; }
    public int postIncrement() { return max == counter ? counter : counter++; }
}

necessitates a block of foreign imports
data Counter = Counter @example.Counter deriving Class
foreign import java unsafe "@new" newCounter :: Int -> Java a Counter
foreign import java unsafe "postIncrement" postIncrement :: Java Counter Int

As you might guess, it would be preferable for this to be auto-generated. The program to do that generation is what's WIP, not the FFI itself.


text:
Q: Showing month names in English when using UIDatePicker when device region format is arabic How to Show month names in English when using UIDatePicker when device region format is arabic.
Please help.
Thanks.

A: You can do it by using localeWithLocaleIdentifier: by passing current locale to UIDatePicker refer


text:
Q: How to create a file that runs without displaying the code (similar to an .exe) I am writting a code that could be useful for some people. The program will be free but I would like to protect the code. As I am not good at explaining myself I will simply illustrate my question with an example:
Let's say that I make the following code:
CreateDialog[
 Column[{Row[{InputField[Dynamic[a]], InputField[Dynamic[b]]}],
   Button["Calculate SUM", c = a + b], "\n", "Result:", Dynamic[c],
   "\n", Button["Plot c*x+5",
    CreateDialog[Plot[c*x + 5, {x, -1, 1}]]]}]]

It allows you to calculate the sum of a number and to display the "y=c*x+5" function, where "a" is the sum of the previous values.
Anyway, I would like to somehow create a protected file (opening with a text editor would show something unreadable) and that, when doubling clicking on it, it opens Mathematica but evaluating it, without displaying the code. Something similar to an executable file that can be opened with mathematica (or the OS).
So, I should not able to see or modify the code but I want to solely display the Dialog.
I hope that someone can understand my question...
I have been reading stuff about "Encode", protecting functions but I did not understand it.... should I waste more time looking into it or is it not going to help me? any tips?
Why is that difficult to create an executable that only Mathematica could read and evaluate?
Is there a simple solution? if not, I have been thinking in creating millions and millions of not useful functions or/and text, inserting some in between the code and so on, with the hope of making it hard to uncode if someone would like to. My logic is that if one person can differenciate the non-useful code then it means that he/she knows how to program and if so, he/she can create a code. If it takes that person more time to get to the useful code discarding the non-usuful one than to make it from scratch, then I should be safe because they won't waste time on reading it?
Any ideas? perhaps it is simpler that I think?
Thanks in advance,


text:
Q: Can't get anything other than a 404 after creating a new wordpress page Can anyone please help here?
I have the latest apache2 and wordpress installed on Ubuntu 16.04. My problem is that I cannot create a new page in wordpress and then have access to it in my browser i.e. example.net/newpage I just get a 404, I have check my permalink settings and they are set properly. Wordpress says the page is created, and I can edit it no problem within the wordpress interface, I can also view it if it's just saved as a draft, as soon as I publish I get a 404.
My wordpress virtualhost settings:
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ServerName example.net
        ErrorLog ${APACHE_LOG_DIR}/error.log
        LogLevel warn
        CustomLog ${APACHE_LOG_DIR}/access.log combined
                <Directory /var/www/html>
                        Options FollowSymLinks
                        AllowOverride Limit Options FileInfo
                        DirectoryIndex index.php
                        Order allow,deny
                        Allow from all
                </Directory>
                <Directory /var/www/html/wp-content>
                        Options FollowSymLinks
                        Order allow,deny
                        Allow from all
                </Directory>
</VirtualHost>

The logs from "tail -f /var/log/apache2/access.log" when I create the new page then try to access it straight away:
$myip - - [24/Jul/2017:16:57:04 +0200] "POST /wp-admin/post.php HTTP/1.1" 302 520 "http://example.net/wp-admin/post-new.php?post_type=page&wp-post-new-reload=true" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
$myip - - [24/Jul/2017:16:57:04 +0200] "GET /wp-admin/post.php?post=12&action=edit&message=6 HTTP/1.1" 200 26740 "http://example.net/wp-admin/post-new.php?post_type=page&wp-post-new-reload=true" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
$myip - - [24/Jul/2017:16:57:05 +0200] "GET /wp-admin/admin-ajax.php?action=oembed-cache&post=12 HTTP/1.1" 200 382 "http://example.net/wp-admin/post.php?post=12&action=edit" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
$myip - - [24/Jul/2017:16:57:08 +0200] "GET /newpage/ HTTP/1.1" 404 507 "http://example.net/wp-admin/post.php?post=12&action=edit" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"

For folder and file permissions I ran:
find /var/www/html/ -type d -exec chmod 755 {} \; && find /var/www/html/ -type f -exec chmod 644 {} \;

I have tried everything I can think of including setup tutorials and reinstalling wordpress and mysql from the beginning but to no avail.
Thanks in advance!

A: From this article, it could be due to mod_rewrite module not being loaded in Apache.


text:
Q: Show a remote URL as popup in a chrome extension I am developing a Chrome addon and I need to show a remote URL as a popup. I have tried the following in manifest.json.
"browser_action": {
    "default_title" : "Pennyful",
    "default_popup" : "http://www.google.com"
}

This was not working. So I handled the event and set the popup from code.
chrome.browserAction.onClicked.addListener(function() {
    chrome.browserAction.setPopup({popup: "http://www.google.com"});
});

This also didn't work. I have also tried creating a html page packaged with the addon, and when loaded does a JS redirect to the remote website. This didn't work. Then I put a iframe inside the page and set the remote URL as source to the iframe. In this case iframe shows up, but it takes long time to load the page and the width is incorrect.
So it looks like there is no way to set a remote URL as a popup page. I'm wondering is there any way to achieve this?

A: In short, no, you can't just open an external website without using an iframe into your popup.html file.
This Google Developer Codelabs article goes through how to use external service APIs (like Twitter or Flickr) to display information from another site in your popup. That might be the way to go if an iframe doesn't work for what you're trying to do.


text:
Q: Find which process is modifying a file A specific file on our production servers is being modified at apparently random times which do not appear to correlate with any log activity.  We can't figure out what program is doing it, and there are many suspects.  How can I find the culprit?
It is always the same file, at the same path, but on different servers and at different times.  The boxes are managed by puppet, but the puppet logs show no activity at the time the file is modified.
What kernel hook, tool, or technique could help us find what process is modifying this file?

lsof is unsuitible for this, because the file is being opened, modified and closed very quickly.  Any solution that relies upon polling (such as running lsof often) is no good.

*

*OS: Debian testing

*Kernels: Linux, 2.6.32 through 3.9, both 32 and 64-bit.

A: SystemTap can do this, using the inodewatch script .

A: You can use auditd and add a rule for that file to be watched:
auditctl -w /path/to/that/file -p wa

Then watch for entries to be written to /var/log/audit/audit.log.

A: in case the program(s) you are looking for still have the file opened, you can use the following:
 sudo lsof /path/to/file/being/modified

you could also call this in a small loop, suing the following script getfileusers.sh:
 #!/bin/sh

 FILE=$1

 while true; do
    lsof "${FILE}"
 done > /tmp/fileusers.log

and then call it:
 sudo ./getfileusers.sh /path/to/file/being/modified

and eventually inspect /tmp/fileusers.log to see who touched the file...

A: If you can catch it in the act, that is if the file is being accessed at the moment, you can find the process by running lsof:
$ while :; do echo foo >> bar.txt; done &
$ sudo lsof bar.txt
COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
bash    25723 terdon    1u   REG    8,6  5015796 16647496 bar.txt


text:
Q: Ktor - create List from Json file i am getting error - This class does not have constructor at object : TypeToken<List<Todo>>() + object is not abstract and does not implement object member
data class Todo(
    val identifier: Long ,
    val name: String ,
    val description: String
)

class DefaultData {

private lateinit var myService: MyService

@PostConstruct
fun initializeDefault() {
    val fileContent = this::class.java.classLoader.getResource("example.json").readText()

    val todos: List<Todo> = Gson().fromJson(fileContent, object : TypeToken<List<Todo>>() {}.type)

    myService.createTodoFromJsontodos
}

}
how can I fix this?
Objective is : To be able to create an endpoint that can get data from json file via service
Is there is a full fledged example
Also how to create interfaces in Ktor? As I want to use Dependency Inversion to enable retrieving data from different sources

A: Kotlin has built-in util similar to TypeToken, so I suggest using it instead:
Gson().fromJson(fileContent, typeOf<List<Todo>>().javaType)

You will need to add a dependency to kotlin-reflect. typeOf() function is marked as experimental, but I use it for some time already and never had any problems with it.
Also, you said in your comment that this is a starter project. If you don't have any existing code already then I suggest to use kotlinx-serialization instead of Gson. It is a de facto standard in Kotlin.

A: You can easily take advantage of kotlinx-serialization.
Steps:

*

*Add the kotlin serialization plugin in your build.gradle file

kotlin("plugin.serialization") version "1.5.20"
plugins {
    application
    java
    id("org.jetbrains.kotlin.jvm") version "1.5.21"
    kotlin("plugin.serialization") version "1.5.20"
}

*Add the dependecy for serialization library

dependencies {
     ...
     implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2")
}

*Decode your json string to corresponding object using Json decode method

val JSON = Json {isLenient = true}
val mytodos = JSON.decodeFromString(message) as List<Todo>


text: Q: How to predict the clusters for new data using HCPC with FactoMineR in R I clustered some data I have using FactoMineR::HCPC in R and now I am trying to cluster new data using the model I have trained. However I can not find a function that will give me such prediction. So far I've been able to see that I can use predict.PCA with my new data set and the previous PCA I implemented on the trainig data set and use that result on the function HCPC. I know that for kmenas there exist a predict which will take as input the trained model and the new data. Does anybody know if there is an equivalent for HCPC?


text:
Q: RealityKit – Error: 'translation' is inaccessible due to 'internal' protection level I'm new to Swift, I'm programming an AR app with RealityKit for the app interface and a Wrapped SwiftUI struct inside one of those View Controllers, so I can create a custom AR interface. (I don't know if that's the proper way to do it, but as I told you, been learning by myself and managed to do it until now).
Anyway, the objective is to place AR objects according to a latitude and longitude given by the user (still haven't done that part, but I'm testing with manual values), a good approach to accomplish that will be to use ARGeoTrackingConfiguration() (from what I've read) but because my device (iPhone 7) doesn't have an A12 Bionic chip, I can't use it, so I am trying to implement it with ARWorldTrackingConfiguration(), but so far, I got stuck whit the issue of 'translation' is inaccessible due to 'internal' protection level when trying to get the location of the touch on the screen with self.raycast(...).first?.worldTransform.translation
extension ARView {

    @objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {

        guard let touchInView = sender?.location(in: self) else {
            print("Failed on touch")
            return
        }

        let results = self.raycast(from: touchInView,
                               allowing: .estimatedPlane,
                              alignment: .horizontal)
        print(results)

        if let firstResult = results.first {
            let anchor = ARGeoAnchor(name: "pinus_pinaster.usdz",
                           coordinate: firstResult.worldTransform.translation)
            self.session.add(anchor: anchor)
        } else {
            print("Object placement failed - coudn't find surface")
        }
    }
}

Any explanations about how to solve this issue (an example would be nice)?
Also, any general advice for ARKit development, would it be possible to implement an app with these functionalities without ARGeoTrackingConfiguration() ?

A: *

*Try using public access level, instead of internal:
 extension ARView {

     @objc public func handleTap(_ sender: UIGestureRecognizer) { }
 }

*It makes no sense to use ARGeoAnchors without running ARGeoTrackingConfiguration().

A: If you're using the ARKit geo tracking example from Apple, you might notice that transform is accessed via an extension of simd_float4x4 in Utilities.swift:
extension simd_float4x4 {
    var translation: SIMD3<Float> {
        get {
            return SIMD3<Float>(columns.3.x, columns.3.y, columns.3.z)
        }
        set (newValue) {
            columns.3.x = newValue.x
            columns.3.y = newValue.y
            columns.3.z = newValue.z
        }
    }
}

What this code does is extend the data type simd_float4x4, and create a transform property which is accessible from an instance of a simd_float4x4 (such as worldTransform.translation.)


text:
Q: Passing destructured args through macros I'm having some trouble writing macros which use destrucutred arguments. Here is an example:
(defmacro defny
  [n args & forms]
  `(defn ~n ~args ~@forms))

(defmacro defnz
  [n f args & forms]
  `(defn ~n ~args
    (do
      (~f ~@args)
      ~@forms)))

(defny y
  [{:keys [value] :as args}]
  (println "Y ARGS" args)
  (println "Y VALUE" value))

(defnz z y
  [{:keys [value] :as args}]
  (println "Z ARGS" args)
  (println "Z VALUE" value))

Here, I have two macros, defny which simply calls through to defn, and defnz, which does the same, but additionally accepts another function which invokes prior to the function body with defnz's args.
When I invoke z, I expect to see both values and args printed out the same, but instead I get:
(z {:value 1})
Y ARGS {:keys [1], :as {:value 1}}
Y VALUE nil
Z ARGS {:value 1}
Z VALUE 1
=> nil

I can see why this is happening, the destructured args {:keys [1] :as {:value 1}} are getting passed to y, but I'm not sure how to fix the macro defnz so that the destructured args can be passed in properly.

A: you can easily see the mistake with macroexpansion:
(defnz z y
  [{:keys [value] :as args}]
  (println "Z ARGS" args)
  (println "Z VALUE" value))

expands to:
(defn z [{:keys [value], :as args}]
  (do
    (y [{:keys [value], :as args}])
    (println "Z ARGS" args)
    (println "Z VALUE" value)))

you are correct: you pass the whole args form to y, but what you need is make that line to be expanded to (y args) where args is just a plain symbol. To do it within macro (which turns symbols no namespace qualified ones) you should use "quote-unquote" trick:
(defmacro defnz
  [n f args & forms]
  `(defn ~n ~args
    (do
      (~f ~'args)
      ~@forms)))

now the expansion would be correct:
(defn z [{:keys [value], :as args}]
  (do (y args) (println "Z ARGS" args) (println "Z VALUE" value)))

but it is rather bad idea, since you don't know exactly what allargs name would be passed to defnz, like {:keys [value] :as all-of-them} would fail (because defnz expects it to be args. You can fix it by dynamically retrieving allargs name in defnz:
(defmacro defnz
  [n f [a :as args] & forms]
  (let [a (if (:as a) a (assoc a :as 'everything))]
    `(defn ~n ~[a]
       (do
         (~f ~(:as a))
         ~@forms))))

so now it would expand to the following:
(defnz z y
  [{:keys [value] :as args}]
  (println "Z ARGS" args)
  (println "Z VALUE" value))

;;(defn z [{:keys [value], :as args}]
;;  (do (y args) (println "Z ARGS" args) (println "Z VALUE" value)))

(defnz z y
  [{:keys [value] :as all-args}]
  (println "Z ARGS" all-args)
  (println "Z VALUE" value))

;;(defn z [{:keys [value], :as all-args}]
;;  (do
;;    (y all-args)
;;    (println "Z ARGS" all-args)
;;    (println "Z VALUE" value)))

(defnz z y
  [{:keys [value]}]
  (println "Z ARGS" everything)
  (println "Z VALUE" value))

;;(defn z [{:keys [value], :as everything}]
;;  (do
;;    (y everything)
;;    (println "Z ARGS" everything)
;;    (println "Z VALUE" value)))


text:
Q: How to declare and initialize in a 4-dimensional array in C I'm relatively new to programming, and I need to enter in a 4-dimensional array, and I can barely wrap my head around it. So, let's start with a simple 3-d array, 2 elements each like so:
int arr[2][2][2] =
{
    {
        {1, 2}
        {3, 4}    //redline on "{"
    }
    {             //redline on "{"
        {5, 6}
        {7, 8}
    }
};

VS-2012 redlines the "{" before the "3", and says it's expecting a "}" instead. How would I be able to enter the array in a neat format? Having 4 dimensions will make it more complicated, and I need to be able to see the data clearly.
Also, I'm going to have a good number of zeroes in my array, in essense every arr[n][n] will be 0, so I'm wondering if I can make the initialization a little simpler.
my array will be of the type
int arr[7][7][15][2]

Or am I better off using struct instead?
Thanks in advance!

A: You're missing a , .
For a three dimensional array
 int arr[2][3][4] = {
                       {
                          {1, 2, 1, 2}, {1, 2, 1, 4}, {1, 2, 4, 4}
                       },
                       {
                          {1, 1, 2, 4}, {1, 2, 1, 4}, {1, 2, 1, 4}
                       }
                    };

or int arr[2][3][4] = {1,2,1,2,1,2,1,4,1,2,4,4,1,1,2,4,1,2,1,4,1,2,1,4};

For a four dimensional array
int arr[2][3][4][2] = {
                        {
                          {
                            {1,2},{1,2},{1,2},{4,2}
                          },
                          {
                            {2, 4},{1, 4},{1, 4},{1,2}
                          },
                          {
                            {2, 4},{1, 4},{1, 4},{1,8}
                          }
                       },
                       {
                         {
                           {1,2},{1,2},{1,2},{4,2}
                         },
                         {
                           {2, 4},{1, 4},{1, 4},{1,2}
                         },
                         {
                           {2, 4},{1, 4},{1, 4},{1,2}
                         }
                      }
                    };

A: Each bracketed element can be viewed as one of the ints inside { 1, 2 } for example. Initializing with a list dictates that separate elements are enumerated with commas. The correct syntax thus will be with commas after each bracketed array ({ { 1, 2 }, { 3, 4 } }):
int arr[2][2][2] =
{
    {
        {1, 2},
        {3, 4}
    },
    {
        {5, 6},
        {7, 8}
    }
};

For a four-dimensional array you'd have to write a lot of 'hardcoding' code; you're probably better off writing a function that will fill it out with values for you.

A: Inside the outer braces, the inner braces { } denote matrix rows. But which commas are required? And which commas are optional?
In C 1999 two-dimensional array declaration initializations:

*

*Inner braces denote matrix rows.

*A comma must appear between each two adjacent matrix element initialization values (even if separated by a newline).

*A comma should appear between adjacent pairs of inner braces; however, this comma might be optional in some standard compilers (?).

*A trailing comma after the last element in each row is optional (if using inner braces).

*A trailing comma after the last inner brace is optional.

*A trailing semicolon after the last outer brace is required.
(Could experts in standard C 1999 please edit the above list to correct any false statements?)

A: Remember C always uses Row major order for memory allocation for statically declared arrays.
For Example:

*

*In the case of 2-D array, say int A[3][2] the memory allocation starts from the first element i.e A[0][0] then A[0][1] after that jumps to the next row but the memory allocation would be contiguous, hence next element in the order of memory layout would be A[1][0] then A[1][1] -> A[2][0] -> A[2][1].

*Hence the simpler way in your case of your initialization would be visualize it linearly in the 1-D form and write it down.

int arr[2][3][4] = {1,2,1,2,1,2,1,4,1,2,4,4,1,1,2,4,1,2,1,4,1,2,1,4};

A: A representation of a four dimensional array
int arr[2][2][2][2] =
{
    { { {1, 2}, {3, 4} }, { {5, 6}, {7, 8} } },
    { { {9,10}, {11, 12} }, { {13, 14}, {15, 16} } }
};


text:
Q: Como evitar que NavigationPage bloquee CarouselPage? [Leer descripción porfavor] Puede ser una pregunta algo tonta, pero me gustaría preguntarlo, les explico, primero puse el CarouselPage para cuando llegara a una ventana, tenga que presionar un botón y avanzar a la siguiente, esto por medio de NavigationPage, pero al hacer esto NavigationPage me sale primero (me bloquea CarouselPage ya que es la página que no tiene el botón) les adjunto la imagen del código donde tengo estos dos pages, no se como acomodarlo para ser honesto
Edicion -> agregado por el comentario
InitializeComponent();
CarouselPage carouselPage = new CarouselPage();
carouselPage.Children. Add(new MainPage());
carouselPage.Children. Add(new Config1());
MainPage =carousel Page;
MainPage=new Navigation Page(new MainPage())


text:
Q: A problem related to Schwarz reflection principle Let $\Omega$ be a bounded domain in $\mathbb{C}$. Suppose there is a function $f$ which is analytic in $\Omega$ except a simple pole at $a\in\Omega$, such that $(z-a)f(z)$ is continuous on $\bar{\Omega}$ with $f(z)=\bar{z}$ on $\partial\Omega$. Prove that the function $g(z)=(z-a)f(z)-(z-a)\bar{a}$ is constant. What is $\Omega$?
It should be consistent with the problem if we assume $\Omega$ to be the unit disc $\mathbb{D}$, then we may use the reflection principle with respect to $\mathbb{D}$ to extend $g$ to an entire function and then conclude using the Liouville theorem that $g$ is a constant. But how can we see that this is the most general case that can happen?

A: The function $g$ is holomorphic on $\Omega$ and continuous on $\overline{\Omega}$. Its boundary values are real and positive:
$$f(z)(z-a) - \overline{a}(z-a) = \overline{z}(z-a) - \overline{a}(z-a) = \overline{z-a}(z-a) =\lvert z-a\rvert^2.$$
If $g$ weren't constant, $g(\Omega)$ would be an open subset of $\mathbb{C}$, hence $v := \operatorname{Im} g$ would attain nonzero values in $\Omega$. Since $v$ is continuous on the compact set $\overline{\Omega}$, it would attain a strictly positive maximum or a strictly negative minimum, necessarily at a point $z_0 \in \Omega$. But $v$ is a real-valued harmonic function, by assumption non-constant, hence $v$ has no local maxima or minima, contradicting the assumption.
Thus $g$ is constant, $g(z) \equiv r^2$. Thus $\Omega$ is a bounded domain whose boundary is contained in $C_r(a) = \{ z\in \mathbb{C} : \lvert z-a\rvert = r\}$, and that means $\Omega = D_r(a) = \{ z \in \mathbb{C} : \lvert z\rvert < r\}$.


text:
Q: Dynamic settings placement in iOS application I'm building an application that will be reused by multiple clients.  One difference in the application is the EventID.  I dont want to change code everytime I create a new one of these applications, but instead use a configuration file of some sort and set the ID there and keep the code the same accessing this file.  What is the best place to do this (plist)?  and how do I access this key in code and globally if possible?

A: If you put your setting in your app's Info.plist file, you can access it as follows:
NSString *eventID = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"EventID"];

You can also store your value in a separate property list file (Settings.plist, for example), include it in your app's "Copy Bundle Resources" build phase, and access it like so:
NSString *settingsPath = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"plist"];
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:settingsPath];
NSString *eventID = [settings objectForKey:@"EventID"];

One way to make it easier to read your settings would be to provide access via a class:
@interface CNSSettings : NSObject

+ (NSString *)eventID;

@end

@implementation CNSSettings

+ (NSDictionary *)settingsDictionary
{
    static NSDictionary *_settingsDictionary = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *settingsPath = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"plist"];
        _settingsDictionary = [NSDictionary dictionaryWithContentsOfFile:settingsPath];
    });

    return _settingsDictionary;
}

+ (NSString *)eventID
{
    return [[self settingsDictionary] objectForKey:@"EventID"];
}

@end

Using the class above, you would just have to do the following:
NSString *eventID = [CNSSettings eventID];


text:
Q: Problema al contar registros con rowCount() necesito contar una cantidad de registros de una tabla que cumplan dos condiciones, el problema es que solo me esta contando un solo registro. Esta es mi funcion:
public function NewClients(){

        $fecha_inicio = date('Y-m-01');
        $fecha_fin = date('Y-m-t');

        $sql = $this->pdo->prepare("SELECT COUNT(id_nivel),date_register FROM usuarios
                                    WHERE id_nivel = 2 AND date_register
                                    BETWEEN '$fecha_inicio' AND '$fecha_fin'");
        $sql->execute();
        echo $sql->rowCount();
    }

Me esta imprimiendo que hay un solo registro, pero en mi tabla hay dos registros que cumplen esa condicion.

A: Retorna un objeto.
public function NewClients($fecha_inicio, $fecha_fin){

    $fecha_inicio = date('Y-m-01');
    $fecha_fin = date('Y-m-t');

    $sql = ("SELECT COUNT(id_nivel),date_register FROM usuarios
                                WHERE id_nivel = 2 AND date_register
                                BETWEEN '$fecha_inicio' AND '$fecha_fin'");

    $sentencia = $this->pdo->prepare($sql);
    //$sentencia->bindParam(':fecha_inicio', $fecha_inicio);
    //$sentencia->bindParam(':fecha_fin', $fecha_fin);

    $respuesta = $sentencia->execute();
    print $sentencia->fetch("0")[0];
}


text:
Q: Prevent a command in a shellscript from being executed inside another shellscript I am invoking a shellscript inside another shellscript, and the invoked one has a command to delete a folder, which I don't want to be executed, like this
$ rm ../temp -rf

Is there a way to prevent this command from being executed without changing the invoked script contents?

A: You can define an alias like this in your script:
alias rm='echo SAFE'

By default aliases work only in interactive shells, so you must change this behaviour with:
shopt -s expand_aliases

in your script and source the other script (the one you cannot change):
source the_other_script.sh

or
. the_other_script.sh

This will work unless the other script runs rm in a sub-shell.
Another, safer method is to create your own rm command which does nothing (or just prints out its argument so you know what's going on), put it into a directory and put this directory as the first one in the PATH environment variable like this (Korn shell syntax):
$ export PATH=/path/to/your/dummy/rm/replacement:$PATH


text:
Q: problem in running website from IIS I have pasted my website's folder in wwwroot folder of IIS.
now when I try to access default page of my website from Mozilla Firefox I get the following exception.
Server Error in '/' Application.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.
Source Error:
Line 58:             ASP.NET to identify an incoming user.
Line 59:         -->
Line 60:
Line 61:
Line 62:

Source File: c:\inetpub\wwwroot\akmailnew1\web.config    Line: 60
please help.

A: This is a very common problem for new .NET web developers.  This is how I do it on XP Pro but should be similar for other OSs too.  Hope this helps.

*

*Settings>control panel>administrative tools>Internet Information Services

*Find your default web site (or where ever you want the vDir)

*Right-click>New>New Virtual Directory

From here, you will need to create an alias (usually the same as the root folder for the new site) then put in the path for the site.
Then you should be able to access the site http://[your server]/[alias]/[mainpage].aspx

A: Create a virtual directory. You can do this by going into the project properties window in VS and selecting the Web tab. This works for Web application projects, so I'm guessing that it will work for the Web site as well.


text:
Q: Alert style iOS notifications (like messages) causes real time Game Center match to stop receiving messages For some reason, when iOS alert style notifications pop up during a real time match (message, alarm etc..), the match ceases to receive data from opponents. The app itself functions, but there is no data transmission between players.
The delegate does not receive call backs from match:(GKMatch *)match player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state or authenticationChanged, so it appears that the players are both still connected to the match.
This issue occurs whether the user dismisses the alert style notification, or opens it.
Any thoughts on why/how this is happening and how I can prevent/recover from it?

A: After hours of debugging, research and frustration, I came across my issue.
Since disconnects and resigning active are likely events with mobile devices & Game Center, I am using a data queue to send messages. It works by stacking the current message on the queue (and sending the message if it's the only message) and runs through the following data transmittal steps: 1) Send oldest message in queue, 2) wait for opponent receipt confirmation, 3) remove oldest message from queue, 4) if queue count is still > 0, send oldest message in queue...
For certain data types, however, we want to bypass the queue and not ask for receipt confirmation. One such instance is when we send messages to the opponent regarding application notifications UIApplicationWillResignActiveNotification and UIApplicationDidBecomeActiveNotification. However, even though the message didn't ask for receipt confirmation, I forgot to bypass the queue. Since the opponent never sent back a receipt confirmation, the UIApplicationWillResignActiveNotification message was blocking the queue indefinitely.
I bypassed the queue appropriately and the game now resumes without issue. If anyone wants to see the actual code involved, I will be happy to share.


text:
Q: Members of local System account I'm currently in the process of migrating some shares.  Using my AD account, I was able to navigate to a share and its subfolders.  Looking at the NTFS permissions, I don't belong to any groups that grant "Full" rights.  The only two groups that have "Full" rights are the local administrators (I am not a member) and the System.
Any way to determine exactly how I am able to get "Full" rights without being an explicit member of a group listed in the ACL?

A: "Full Control" allows you to do anything imaginable to the folder or its files, like delete them or fiddle with the ACLs. You don't need Full Control to navigate a folder or even to write to it. "List folder / read data" allows you to look around in the folder or read the contents of a file. (Which one it is depends on whether the object in question is a folder or a file.) "Create files / write data" and "Create folders / append data" allow you to do exactly what they say, but you can have that access without having Full Control.
Note that applications running with administrative privileges can use SeBackupPrivilege and SeRestorePrivilege to read or write anywhere (respectively), no matter what ACLs say. Read more about privileges at TechNet.


text:
Q: What is the MVVM way to call WPF command from another viewmodel? I'm trying to learn more about MVVM implementation in WPF and currently need some guidance on navigation using ViewModels. I'm following WPF navigation example from Rachel's blog and need a way to call Command of ApplicationViewModel from other ViewModel.
As per the blog, switching views from MainWindow is pretty clear, but I want to know more about inter-view navigation i.e. say I've Home, Product and Contact button on MainWindow along with View and ViewModel classes, now I want to open Contact page from some button inside Home view instead of MainWindow. I have written some code in Home ViewModel to achieve the same but I doubt whether this is the best practice of MVVM. And is there any way to achieve the same from HomeView.XAML?
Code Snippet from blog - ApplicationViewModel.cs
private ICommand _changePageCommand;

private IPageViewModel _currentPageViewModel;
private List<IPageViewModel> _pageViewModels;

public ApplicationViewModel()
{
    // Add available pages in c'tor
    PageViewModels.Add(new HomeViewModel(this));
    PageViewModels.Add(new ProductsViewModel());
    PageViewModels.Add(new ContactViewModel());
}

public ICommand ChangePageCommand
{
    get
    {
        if (_changePageCommand == null)
            _changePageCommand = new RelayCommand(
              p => ChangeViewModel((IPageViewModel)p), p => p is IPageViewModel);

        return _changePageCommand;
    }
}

private void ChangeViewModel(IPageViewModel viewModel)
{
    if (!PageViewModels.Contains(viewModel))
        PageViewModels.Add(viewModel);

    CurrentPageViewModel = PageViewModels.FirstOrDefault(vm => vm == viewModel);
}

Code Snippet from blog - ApplicationView.xaml
<Window.Resources>
    <DataTemplate DataType="{x:Type local:HomeViewModel}">
        <local:HomeView />
    </DataTemplate>

    <!-- Data template for other views -->
</Window.Resources>

<DockPanel>
    <Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
        <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding Name}"
                            Command="{Binding DataContext.ChangePageCommand,
                            RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                            CommandParameter="{Binding }"/>

 <!--All closing tags-->

My code inside HomeViewModel.cs
// This is the command to get bind with my button inside Home view to invoke Contact view

private ICommand _loadContactCommand;
public ICommand LoadContactCommand
{
    get
    {
        if (_loadContactCommand == null)
            _loadContactCommand = new RelayCommand(p => LoadOtherView());

        return _loadContactCommand;
    }
}

private void LoadOtherView()
{
    // _appVM is the instance of 'ApplicationViewModel' which is being set from c'tor
    // Even I'm thinking to pass Contact view member of ApplicationViewModel class here,
    // as I need exactly the same instance of the Contact which has been created earlier

    _appVM.ChangePageCommand.Execute(new ContactViewModel());
}

A: There's a couple of ways I'd do this.
The first, if the action is a service type of interaction, which I think this is a reasonably good example of, I would describe the action in an interface and inject it as a dependency into the ViewModels that need it.
This is effectively what you are doing, but it's worth abstracting it out into an interface. This provides less tight coupling between the two ViewModels.
Here is an example of wrapping up the functionality in an IPageDisplay interface:
public interface IPageDisplay
{
    IPageViewModel GetCurrentPage();
    void ChangeViewModel(IPageViewModel newPage);
}

Your ApplicationViewModel implements it and has the exact same methods it did before:
public class ApplicationViewModel: IPageDisplay
{
    // implement like you are doing

You're HomeViewModel then takes as an interface, not the 'whole' ViewModel:
class HomeViewModel
{
    HomeViewModel(IPageDisplay pageDisplay) {//constructor stuff}

private void LoadOtherView()
{
    // Instead of interacting with a whole ViewModel, we just use the interface
    _pageDisplay.ChangePageCommand.Execute(new ContactViewModel());
}

This is 'safer' as it's more abstract. You can test HomeViewModel without creating a AppViewModel by just mocking the IPageDisplay. You can change how pages are displayed or the implementation of AppViewModel, you can also display your pages in any other kind of location, by having some other implementation of IPageDisplay.
It's worth noting that any page that needs to perform navigation actions will require an IPageDisplay. It can be troublesome matching up all these dependencies if you have many of them - that's where something like a Dependency Injection framework can really help out.
The second would be a mediator pattern as suggested in the comments. You could have a common mediator PageManager that defines the ChangeViewModel(IPageViewModel newPage); method and fires a ChangeViewModelRequest event or callback. The ApplicationViewModel, and any other ViewModels that want to change the current page accept the PageManager instance as a dependency. ApplicationViewModel listens to the event, the other's call ChangeViewModelRequest to trigger it.
Again, a Dependency Injection will need to be managed effectively if this is in a complex application.
This naturally leads onto the third. Which is a extension of the mediator pattern, an Event Aggregator.
An event aggregator is a generic service that allows all different ViewModels to raise, or subscribe to application wide events. It's definitely worth looking at.
Here, your ApplicationViewModel subscribes to the event:
public class ApplicationViewModel
{
    private EventAgregator _eventAggregator;

    ApplicationViewModel(EventAgregator eventAggregator)
    {
        this._eventAggregator = eventAggregator;
        _eventAggregator.Subscribe('ChangeViewModelRequest', (EventArgs eventArgs) => ChangeViewModel(eventArgs.Parameter))
    }

    private void ChangeViewModel(IPageViewModel viewModel)
    {
        if (!PageViewModels.Contains(viewModel))
            PageViewModels.Add(viewModel);

        CurrentPageViewModel = PageViewModels.FirstOrDefault(vm => vm == viewModel);
    }
}

And the HomeViewModel publishes to the event:
private void LoadOtherView()
{
    _eventAggregator.Publish("ChangeViewModelRequest", new EventArgs(new ContactViewModel()));
}

There are plenty of Event Aggregators you can use, some built into MVVM frameworks like Prism.
While, like all the others, this is a dependency - it's a very generic one. Chances are, most of your ViewModels will need access to the aggregator instance and have it as a dependency, as it could be used for almost all inter-view-model communication. Simply having all VMs pass it to any created VMs in the constructor could work for a simple application. But I'd still say something that supports dependency injection (say, factory pattern?) would be worth implementing.
Edit:
Here's what you need for your HomeViewModel:
public class HomeViewModel : IPageViewModel // doesn't implement IPageDisplay
{
    private IPageDisplay _pageDisplay;
    public HomeViewModel(IPageDisplay pageDisplay)
    {
        // HomeViewModel doesn't implement IPageDisplay, it *consumes* one
        // as a dependency (instead of the previous ApplicationViewModel).
        // Note, that the instance you're passing still is the ApplicationViewModel,
        // so not much has actually changed - but it means you can have another
        // implementation of IPageDisplay. You're only linking the classes together
        // by the functionality of displaying a page.
        _pageDisplay= pageDisplay;
    }

    public string Name
    {
        get
        {
            return "Home Page";
        }
    }

    private ICommand _loadDashboardCommand;
    public ICommand LoadDashboardCommand
    {
        get
        {
            if (_loadDashboardCommand == null)
            {
                _loadDashboardCommand = new RelayCommand(
                    p => LoadOtherView());
            }
            return _loadDashboardCommand;
        }
    }

    private void LoadOtherView()
    {
        // Here you have the context of ApplicatiomViewModel like you required
        // but it can be replaced by any other implementation of IPageDisplay
        // as you're only linking the little bit of interface, not the whole class

        _pageDisplay.ChangeViewModel(new DashboardViewModel());
    }
}

}