text:
Q: Easy way to add change Id's to older git commits? I have seven commits I need to add change IDs to. I see a lot of people say to use interactive git rebase. I'm not familiar with rebasing, and I'm having trouble with the files and functions that I changed the name of reverting back when I try and reword them to add change IDs.
Is there any other way to add change IDs? Or how do I stop my files/functions reverting back when I try and rebase. Once I abort the rebase, they go back to how I had them.
Thanks!

A: Try the following, and note you will need to
push and [Submit] one commit at a time:

*

*Set the Gerrit Hook to add the Change-ID as you commit (or amend)

*Create a new branch for your changes

*For each of the changes, starting with the OLDEST, do:

*

*git cherry-pick ...

*git commit --amend  (this should add a Change-ID - different one each time)

*(push the change to Gerrit - however you do that)

*In Gerrit - approve and [Submit] this change

*In your branch, again, do git pull --rebase


text:
Q: jQuery: Disable button 10min after click I want to disable button 10 minutes after it was clicked. I am using this code and it is working if there is no delay() added. But with delay it is not working.
<script>
$(".selected-button").delay(600000).attr({
    disabled: true,
    title: "You have already chosen the best answer and now you can not change it!"
});
</script>

A: You can try to do something like this using setTimeout instead:
$(".selected-button").click(function() {
    var $this = $(this);
    $this.attr("disabled", true);
    setTimeout(function() {
        $this.removeAttr("disabled");
    }, 600000);
});

A: To disable button 10 minutes after click:
$(".selected-button").click(function() {
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        done: function (data) {
            if (data.status === 'OK') {
                var that = $(this);
                setTimeout(function() {
                    that.prop("disabled", true);
                }, 10*60*1000);
            }
        }
    });
});

See fiddle example for 5s.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeScript 2.1.4 breaking changes in webpack ts-loader Upgrading from Typescript 2.0.10 to 2.1.4 appears to break something in webpack, webpack-stream, ts-loader, or gulp as it's no longer respecting my entry point or gulp source glob. It appears to be including all .ts files in my project (including the ones in the /server source folder) rather than just the ts files in /client and app.ts as per the gulp.src and web pack entry point. Is there a different/newer/better way I should be doing this?
in gulp file:
const serverPath = 'server';
const clientPath = 'client';
const buildPath = 'build';
const paths = {
    server: {
        scripts: [
            `${serverPath}/**/*.ts`
        ]
    },
    client: {
        files: [
            `${clientPath}/**/*`
        ],
        scripts: [
            `${clientPath}/**/*.ts`
        ],
        entry: `${clientPath}/app.ts`
    }
};

gulp.task('build:client', cb => {
    gulp.src(paths.client.entry)
        .pipe(webpackStream(webpackConfig, webpack))
        .pipe(gulp.dest(`${buildPath}/${clientPath}`));
    cb();
});

in web pack config:
entry: {
    app: './client/app.ts'
}

ts: {
    configFileName: './tsconfig.json'
}

resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
}

module: {
    loaders: [
        { test: /\.ts$/, loader: 'ng-annotate-loader!ts-loader' }
    ]
}

in tsconfig.json:
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "removeComments": false,
        "noImplicitAny": true,
        "sourceMap": true,
        "inlineSources": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    }
}

Output using 2.0.10:
ts-loader: Using typescript@2.0.10 and /Users/chris/code/class-app/tsconfig.json
[20:47:36] Version: webpack 1.14.0
Asset       Size  Chunks             Chunk Names
app.js.map  950 bytes       0  [emitted]  app
app.js  550 bytes       0  [emitted]  app

Output using 2.1.4:
ts-loader: Using typescript@2.1.4 and /Users/chris/code/class-app/tsconfig.json
server/api/thing/thing.controller.ts(17,16): error TS2322: <ts error in server portion, not relevant>
[20:53:03] TypeScript: 1 semantic error
[20:53:03] TypeScript: emit succeeded (with errors)
Unhandled rejection Error in plugin 'webpack-stream'
Message:
/Users/chris/code/class-app/server/api/thing/thing.controller.ts <same as above>

A: Apparently the problem is TypeScript in WebPack has been running on the server code this whole time (although it shouldn't have been) and although I had planned to fix the server TS issue that upgrading TypeScript introduced, what it really exposed was WebPack was compiling files it shouldn't have all along. Tested this by intentionally introducing a problem to the server ts on the previous ("working") version of TypeScript, getting the same error.
I still need to figure out why it's trying to compile all my TS files, and not just the ones in /client, but I'll ask a new question for that.


text:
Q: jQuery document.ready not prepending I have noticed that document.ready not prepending
 tag.

- In console, There are no errors.
This is truly frustrating now and any help will be really appreciated.
~ Dipak G.

A: try this:-
 var shadow = jQuery('

');
 jQuery(document).ready(function() {
    jQuery('body').prepend(shadow);
 });

for more information check This link

A: I suppose that problem is in document.ready().
Try this instead:
$(function() {
$('body').prepend('
Test
');
});

A: I would look into a conflict with prototype.js and jQuery. You may need to try  jQuery.noConflict();
I would suggest using one library instead of both. Of course you will need to use a jquery lightbox instead, from what I see on your link.


text:
Q: double free or corruption (out) and Aborted (core dumped) error Help, I'm new in programming and I'm also new in this site, pardon for my unorganized question.
Also, I cannot understand the explanation for the same error from the other existing questions. I did not used malloc and did not have the same situation as the others. Lastly, this is one of our final requirements and I hope questions like this is valid to our prof.
#ifndef __VECTOR_H__
#define __VECTOR_H__

#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
using namespace std;

typedef unsigned int uint;

// Modified vector class to handle basic linear algebra operations.
template<typename T>
class Vector
{
    public:
        vector<T> elements;
        uint size;

        // Constructors
        Vector();
        Vector(uint);
        Vector(vector<T>);
        Vector(string);

        // Print vector elements.
        void print() const;

        // Save vector to a text file with string filename as parameter.
        void savetxt(string) const;

        // Append element after the last entry.
        void push_back(T value);

        // Check if vector has same size to other vector.
        bool has_equal_size(Vector<T>&) const;

        // Retuns dot product.
        double dot(Vector<T>&) const;

        // Returns Euclidean norm.
        double norm() const;

        // Indexing operator.
        T operator[] (uint);

        // Comparison operator.
        bool operator== (Vector<T>&);

        // Destructor.
        ~Vector();
};

// Default constructor
template<typename T>
Vector<T>::Vector() {};

// Constructor for zero vector with size equal to the parameter num_elements.
template<typename T>
Vector<T>::Vector(uint num_elements){
    for(uint i = 0; i <= num_elements; i++){
        elements.push_back(0);
    }
    size = num_elements;
}

// Constructor with vector data as parameter.
template<typename T>
Vector<T>::Vector(vector<T> data){
    for(uint i = 0; i <= data.size(); i++){
        elements.push_back(data[i]);
    }
    size = data.size();
}

// Constructor with txt filename as parameter.
/*
template<typename T>
Vector<T>::Vector(string filename){
    ifstream infile("filename.txt");
    if(infile.is_open()){
        while(infile >> value)
            V.push_back(value);
    }
    else{
        cout << "File does not exists!" << endl;
        exit(0);
    }
    infile.close();
}
*/
// Print vector elements.
template<typename T>
void Vector<T>::print() const{
    for(uint i = 0; i < size; i++){
            cout << elements[i] << " ";
    }
    cout << endl;
}
// Save vector elements to a txt file.
template<typename T>
void Vector<T>::savetxt(string filename) const{
    ofstream outfile("output.txt");
    if (outfile.is_open())
    {
        for (int i=0; i < size; i++){
            outfile << elements[i] << " ";
        }
    }
    else{
        cout << "File does not exists!" << endl;
        exit(0);
    }
    outfile.close();
}

// Check if vector has the same size as other parameter vector.
template<typename T>
bool Vector<T>::has_equal_size(Vector<T>& V) const{
    if(size == V.size)
        return true;

    else
        return false;
}

// Dot product.
template<typename T>
double Vector<T>::dot(Vector<T>& V) const{
    T dotproduct = 0;
    T temp;
    if (has_equal_size(V) == 0){
        cout << "Vectors must have equal size! ";
        return 0;
    }
    else{
        for(uint i=0; i < size; i++){
            temp = elements[i] * V.elements[i];
            dotproduct += temp;
        }
    }
    return dotproduct;
}

// Euclidean norm of vector.
template<typename T>
double Vector<T>::norm() const{
    double temp2;
    double sum;
    for(int i=0; i < size; i++){
        temp2 = elements[i]*elements[i];
        sum += temp2;
    }
    return sqrt(sum);
}

// Indexing operator.
template<typename T>
T Vector<T>::operator[] (uint index){
    return elements[index];
}

/*
Vector componentwise sum.
*/
template<typename T>
Vector<T> operator+ (Vector<T>& V, Vector<T>& W){
    Vector<T> S(0);
    double sum;
    if (V.has_equal_size(W) == 0){
        cout << "Vectors must have equal size! ";
    }
    else{
        for(uint i=0; i < V.size; i++){
            sum = V.elements[i] + W.elements[i];
            S.push_back(sum);
        }
    }
    return S;
}

template<typename T>
Vector<T> operator+ (Vector<T>& V, T scalar){
    Vector<T> S(0);
    double sum;
    for(uint i=0; i < V.size; i++){
            sum = V.elements[i] + scalar;
            S.push_back(sum);
        }
    return S;
}

template<typename T>
Vector<T> operator+ (T scalar, Vector<T>& V){
    Vector<T> S(0);
    double sum;
    for(uint i=0; i < V.size; i++){
            sum = scalar + V.elements[i];
            S.push_back(sum);
        }
    return S;
}

/*
Vector componentwise difference.
*/
template<typename T>
Vector<T> operator- (Vector<T>& V, Vector<T>& W){
    Vector<T> D(0);
    double diff;
    if (V.has_equal_size(W) == 0){
        cout << "Vectors must have equal size! ";
    }
    else{
        for(uint i=0; i < V.size; i++){
            diff = V.elements[i] - W.elements[i];
            D.push_back(diff);
        }
    }
    return D;
}

template<typename T>
Vector<T> operator- (Vector<T>& V, T scalar){
    Vector<T> D(0);
    double diff;
    for(uint i=0; i < V.size; i++){
            diff = V.elements[i] - scalar;
            D.push_back(diff);
        }
    return D;
}

template<typename T>
Vector<T> operator- (T scalar, Vector<T>& V){
    Vector<T> D(0);
    double diff;
    for(uint i=0; i < V.size; i++){
            diff = scalar - V.elements[i];
            D.push_back(diff);
        }
    return D;
}

/*
Vector componentwise multiplication.
*/
template<typename T>
Vector<T> operator* (Vector<T>& V, Vector<T>& W){
    Vector<T> P(0);
    double prod;
    if (V.has_equal_size(W) == 0){
        cout << "Vectors must have equal size! ";
    }
    else{
        for(uint i=0; i < V.size; i++){
            prod = V.elements[i] * W.elements[i];
            P.push_back(prod);
        }
    }
    return P;
}

template<typename T>
Vector<T> operator* (Vector<T>& V, T scalar){
    Vector<T> P(0);
    double prod;
    for(uint i=0; i < V.size; i++){
            prod = V.elements[i] * scalar;
            P.push_back(prod);
        }
    return P;
}

template<typename T>
Vector<T> operator* (T scalar, Vector<T>& V){
    Vector<T> P(0);
    double prod;
    for(uint i=0; i < V.size; i++){
            prod = scalar * V.elements[i];
            P.push_back(prod);
        }
    return P;
}

/*
Vector componentwise division.
*/
template<typename T>
Vector<T> operator/ (Vector<T>& V, Vector<T>& W){
    Vector<T> Q(0);
    double quot;
    if (V.has_equal_size(W) == 0){
        cout << "Vectors must have equal size! ";
    }
    else{
        for(uint i=0; i < V.size; i++){
            if(W.elements[i] = 0){
                cout << "Vector division not applicable! There should be no component(s) with zero value in the second vector." << endl;
            }
            else{
                quot = V.elements[i] / W.elements[i];
                Q.push_back(quot);
            }
        }
    }
    return Q;
}

template<typename T>
Vector<T> operator/ (Vector<T>& V, T scalar){
    Vector<T> Q(0);
    double quot;
    for(uint i=0; i < V.size; i++){
        if(scalar = 0){
            cout << "Vector division not applicable! Scalar value must not be equal to zero." << endl;
        }
        else{
            quot = V.elements[i] / scalar;
            Q.push_back(quot);
        }
    }
    return Q;
}

template<typename T>
void operator/ (T scalar, Vector<T>& V){
    cout << "\nError: Operation not supported!" << endl;
}

// Vector push_back version.
template<typename T>
void Vector<T>::push_back(T value){
    elements[size] = value;
    size++;
}

// Comparison ovalue.;
template<typename T>
bool Vector<T>::operator== (Vector<T>& V){
    uint truth;
    if (has_equal_size(V) == 0){
        return false;
    }
    else{
        for(uint i=0; i < V.size; i++){
            if(elements[i] == V.elements){
                truth = 1;
            }
            else{
                return false;
                break;
            }
        }
        if(truth == 1)
            return true;
        else
            return false;
    }
}

// Default Destructor.
template<typename T>
Vector<T>::~Vector() {};

#endif

A: You have out of bounds issues at two places.
One is here,
// Constructor with vector data as parameter.
template<typename T>
Vector<T>::Vector(vector<T> data) {
    for(uint i = 0; i <= data.size(); i++){
      elements.push_back(data[i]);
    }
    size = data.size();
}

Loop terminal condition i <= data.size() is wrong. It should be i < data.size()

Second one:
Your push_back method is wrong. You are not checking bounds there too.

Vector S(0); Creating vector of size 0 and accessing elements by index will trigger
  a segmentation fault (Crash).

Due to the reason that you are only allocating a Vector of size 0 and accessing the elements by index without checking size bounds.
// Constructor for zero vector with size equal to the parameter num_elements.
template<typename T>
Vector<T>::Vector(uint num_elements){
    for(uint i = 0; i <= num_elements; i++){
        elements.push_back(0);
    }
    size = num_elements;
}

The above code is fine. But the below one is not.
// Vector push_back version.
template<typename T>
void Vector<T>::push_back(T value){
   elements[size] = value;
   size++;
}

How it should have been:
// Vector push_back version.
template<typename T>
void Vector<T>::push_back(T value){
   elements.push_back(value); // std::vector::push_back will automatically reallocate the size.
   size++;
}

Or
// Vector push_back version.
template<typename T>
void Vector<T>::push_back(T value){
   if (elements.capacity() < size) {
      elements.resize(some value here);
   }

   elements[size] = value;
   size++;
}

Overall, your approach is flawed a bit, and just need to be improved.


text:
Q: Magento2 pub/static permissions I'm getting 403 errors in my console for calendar.css, mixins.js, require.js. Is it permission or ownership issue?

A: I usually use the following file/folder permissions and haven't run into issues so far.
cd <MAGENTO_INSTALL_DIR>
find . -type f -exec chmod 664 {} \;
find . -type d -exec chmod 775 {} \;
find var pub/static pub/media app/etc -type f -exec chmod g+w {} \;
find var pub/static pub/media app/etc -type d -exec chmod g+ws {} \;
chmod u+x bin/magento


text:
Q: Why 'import mmap' throws ImportError in jython I'm new to python and jython. I had a script in python which imports mmap, it works fine without any issues. I need to invoke a function in that script from a java class, which throws the following exception upon execution.
Exception in thread "main"
Traceback (most recent call last):
    File "<string>", line 1, in <module>
ImportError: No module named mmap

I executed the same script in jython which gives me the below error.
C:\jython2.5.3>jython.bat d:\Python\AddConfToFile.py
Traceback (most recent call last):
  File "d:\Python\AddConfToFile.py", line 9, in <module>
    import mmap
ImportError: No module named mmap

I'm not able to find any suggestions through Google. Am I missing some thing here, kindly Help me fix this.
Thanks in Advance
Adithyan

A: The mmap module is not available under Jython. You will need to find an alternative.

A: It's just because the Jython doesn't  support mmap still..As explained in the FAQ in the official site, in the paragraph below:

Modules that we don't support, and perhaps won't, include bsddb3, curses, dbm, gdbm,
  ioctl, mmap, pty, Tkinter, and win32reg. Some of these might be readily doable, like
  mapping the curses module against CHARVA, but given limited resources, are not likely to
  be worked on. (Contributions welcome!)


text:
Q: Windows Error: Error 5, when decompiling minecraft server I want to start create mods and so on to minecraft. I am a javaprogrammer myself, so the coding shouldn't be a problem. but to start the programming I need to decompile the server file from minecraft. Everything to do so is given and explained in a txt document, but nontheless I still get an annoying error.
I have checked my pth for JDK and JRE, have the latest version of both and all.
I really hope someone can help me. Here's the traceback:
File "runtime\decompile.py", line 143, in <module> main()
File "runtime\decompile.py", line 143, in <module> main()
File "runtime(options.config, options.force_jad) commands = Commands(donffile)
File "C:\Program Files\Java\MCP\runtime\commands.py", line 158, in __init__ self.checkfolders()
File "C.\Program Files\Java\MCP\runtime\commands.py", line 530, in checkfolders os.makedirs(self.dirtemp)
File "os.pyc", line 157, in makedirs
WindowsError: [Error 5] Access is denied: 'temp'

If I run as administrator I get following msg:
The system cannot find the path specified.

You'd safe my day if you could help me with this problem.

A: Which decompiler do you use? I'd start checking this commands.py line 530 for any clues what value does this dirtemp has. I'd recommend using the JD decompiler.
Also, I'd be surprised if Notch hadn't used any obfuscators to prevent decompiling. That means you'll get a bunch of unreadable gibberish Java sources.


text:
Q: React Native - NativeEventEmitter - JSModule not listen to events Im want to create a RN package (will publish on npm soon) that has a native side. Because of that i thought could be a good idea to put it in my node_modules dir, so i can test while develop, only android for now.

*

*I create the module following the docs, with create-react-native-library, it create with typescript

*Wrote the Java Module and Package

*Wrote the JS side of my module

Only thing thats not working is to get events from native side in my module js side. But if i put the event NativeEventEmitter directly on my App.js (RN component) it works like a charm.
I need to do some abstractions on top of events, so i can expose a friendly api.
Every change i made in my module, i run yarn run bob build (comes from create-react-native-library), and then yarn run android on my testing project
Here is my package directory structure
.
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── android
│   ├── build
│   │   ├── generated
│   │   ├── intermediates
│   │   ├── outputs
│   │   └── tmp
│   ├── build.gradle
│   ├── gradle
│   │   └── wrapper
│   ├── gradlew
│   ├── gradlew.bat
│   ├── local.properties
│   └── src
│       └── main
├── babel.config.js
├── ios
│   ├── GpsState.h
│   ├── GpsState.m
│   └── GpsState.xcodeproj
│       ├── project.pbxproj
│       └── project.xcworkspace
├── lib // that is the build destination dir
│   ├── commonjs
│   │   ├── index.js
│   │   ├── index.js.map
│   │   ├── types.js
│   │   └── types.js.map
│   ├── module
│   │   ├── index.js
│   │   ├── index.js.map
│   │   ├── types.js
│   │   └── types.js.map
│   └── typescript
│       ├── __tests__
│       ├── index.d.ts
│       └── types.d.ts
├── package-lock.json
├── package.json
├── react-native-gps-state.podspec
├── scripts
│   └── bootstrap.js
├── src
│   ├── __tests__
│   │   └── index.test.tsx
│   ├── index.tsx
│   └── types.ts
├── tsconfig.build.json
├── tsconfig.json
└── yarn.lock

My Module package.json only relevants parts
{
  "main": "lib/commonjs/index",
  "module": "lib/module/index",
  "types": "lib/typescript/index.d.ts",
  "react-native": "src/index",
  "source": "src/index",
  ....
  "scripts": {
    "test": "jest",
    "typescript": "tsc --noEmit",
    "lint": "eslint \"**/*.{js,ts,tsx}\"",
    "prepare": "bob build",
    "release": "release-it",
    "example": "yarn --cwd example",
    "pods": "cd example && pod-install --quiet",
    "bootstrap": "yarn example && yarn && yarn pods"
  },
}

My index.tsx (js part of my package)
import { NativeModules, NativeEventEmitter } from 'react-native';

const emitter = new NativeEventEmitter(NativeModules.GpsState);
emitter.addListener('OnStatusChange', (response: any) => {
    // never reach here, seems theres no listeners attached
    console.log('jsmodule -> OnStatusChange -> received....', response);
});

const GPSState = {
 foo: ()=>NativeModules.GPSState.bar() //those call to native side are working well by the way
 debugEmitter: ()=>NativeModules.GPSState.debugEmitter()
}

export default GPSState

And finally, iam use MessageQueue too to guarantee events are being dispatched, and they are
 LOG  GPSState debugEmitter js -> native
 LOG  {"args": [], "method": "debugEmitter", "module": "GPSState", "type": 1}
 LOG  ----------------------------------------------------------------------------------------------------------------------------------------------
 LOG  RCTDeviceEventEmitter emit native -> js
 LOG  {"args": ["OnStatusChange", {"status": 99}], "method": "emit", "module": "RCTDeviceEventEmitter", "type": 0}
 LOG  ----------------------------------------------------------------------------------------------------------------------------------------------

One last note, the MessageQueue.spy not work on my js package too, only in my App.js (RN component)
For who want a closer look this is the repo
Yep, thats all folks

A: The react-native used is not the same path and cannot receive events.
It is because custom_ library uses react-native of custom_library/node_modules/react-native instead of your_app of your_app/node_modules/react-native.
Modify import xxx from 'react-native'to
import xxx from 'your_app/node_modules/react-native' in custom_ library to receive events normally.
Using the released custom_ library will not cause this problem. Expected: it will not install devDependencies defined in react-native.
I also want to know why react-native with different paths can not receive events.


text:
Q: Randomize MAC Address Using Platypus I am running the following script in Platypus but the MAC address does not change:
#!/bin/zsh

IF=en7

mac=`ifconfig $IF | awk '/ether/{print $2}'`
echo "$IF mac before change=$mac"
randmac=`openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'`
sudo ifconfig $IF ether $randmac
mac=`ifconfig $IF | awk '/ether/{print $2}'`
echo "$IF mac after change=$mac"

Not receiving errors anymore.  However, the MAC address is not changed by the script.  Commands work individually pasted into Terminal, but not executed as an application by Platypus.
Platypus screenshot:

A: Platypus
Use Platypus to create an application from your bash script. This approach avoids needing to use AppleScript.

Platypus is a developer tool that creates native Mac applications from command line scripts such as shell scripts or Perl, Ruby and Python programs. This is done by wrapping the script in a macOS application bundle along with an executable binary that runs the script.

Other Approaches
Mathias Bynens has an article on How to create simple Mac apps from shell scripts.
Also worth reading is the related question How to make a Mac OS X .app with a shell script?


text:
Q: Theano GPU Installation Issue I have installed Anaconda, theano , GPU Toolkit ver 8. I am getting this error.
    ERROR: refusing to load cuda driver library because the version is blacklisted.  Versions 373.06 and below are known to be ok.
If you want to bypass this check and force the driver load define GPUARRAY_FORCE_CUDA_DRIVER_LOAD in your environement.
ERROR (theano.gpuarray): Could not initialize pygpu, support disabled

A: See discussion here.
I reinstalled libgpuarray and it worked for me.

A: Your cuda driver is faulty. Install another one, preferably 373.06. Using your current driver will result in wrong computations. DO NOT force the driver load


text:
Q: Superclass meant only to be extended, not directly instanciated i am coding an OOP application in PHP. I want to have a Superclass from which other classes will inherit from.
Is there a way i can make sure the class itself can't be instantiated directly?
like:
class Mother {}
class Child extends Mother{}
$child = new Child();//no problemo
$mother = new Mother();//throws exception or dies

A: You can use abstract classes which only define methods but not their implementation.
abstract class Mother
{
    public function doSomething();
}

class Child implements Mother
{
    public function doSomething()
    {
        echo 'Hello world';
    }
}

$mother = new Mother(); // won't work
$child = new Child(); // works
$child->doSomething(); // echoes hello world

Alternatively, if you need to implement the method implementation (functions do something but they can be overloaded) then you can use protected constructor.
class Mother
{
    protected function __construct()
    {
        echo "Hello World!";
    }
}

class Child extends Mother
{
    public function __construct()
    {
        parent::__construct();
    }
}

$mother = new Mother(); // won't work, you're trying to access protected method
$child = new Child(); // it'll work echoing "Hello World!"

A: There is abstract keyword.
abstract class Mother { }


text:
Q: How do I download an entire webpage (with images) on the iPhone? Is there a way to download an entire webpage for offline viewing with the iPhone SDK? I can use NSString with the contents of the URL, but that would just give me the HTML and no images. Is there any way to do it?

A: The popular open source library ASIHTTPRequest has a class that will do just this for you: download all HTML, images, and other resources associated with the page you're requesting.
It's called ASIWebPageRequest, and you can read the documentation and download it from here: http://allseeing-i.com/ASIHTTPRequest/ASIWebPageRequest


text:
Q: Using vectorization to get a specific matrix output from two vectors I wanted to know if there is a efficient way using MATLAB vectorization to generate a specific matrix from two vectors.
Suppose the vectors are
x = [u v]

y = [a1 a2 a3 b1 b2 b3]

where u, v, a1, a2, a3, b1, b2, b3 are some real numbers.
The 2-column matrix that I wish to generate using these vectors is
M = [u  a1;
     u  a2;
     u  a3;
     v  a1;
     v  a2;
     v  a3;
     u  b1;
     u  b2;
     u  b3;
     v  b1;
     v  b2;
     v  b3]

In general, the length of x can be anything and the length of y is multiple of 3. Here is the code that I have now, but I think there should some better way (that possibly avoids the use of for-loop):
M = [];
Y = reshape(y, 3, []);

for j = 1:size(Y, 2)
    [a, b] = meshgrid(x, Y(:, j));
    L = [a(:) b(:)];
    M = [M; L];
end

A: A solution using repmat and repelem :
M = [repmat(repelem(x(:),3),numel(y)/3,1) , ...
reshape(repmat(reshape(y,3,[]),numel(x),1),[],1)];

A: you have a pretty strange order in M. Is that order important? if not, or if you are happy to fix the order later yourself I have two solutions:
1) code
[a,b] = meshgrid(x,y);
M = [a(:) b(:)]

will give you:
M = [
 u  a1
 u  a2
 u  a3
 u  b1
 u  b2
 u  b3
 v  a1
 v  a2
 v  a3
 v  b1
 v  b2
 v  b3]

and
2) code M = combvec(x, y)' gives you:
M = [
 u  a1
 v  a1
 u  a2
 v  a2
 u  a3
 v  a3
 u  b1
 v  b1
 u  b2
 v  b2
 u  b3
 v  b3]


text:
Q: The flaw in my derivation of relativistic momentum/mass? I am trying to derive relativistic momentum in a manner similar to that of Max Planck in "The Principle of Relativity and the Fundamental Equations of Mechanics". I begin with a frame of reference $S$ with coordinates $x$, $y$, $z$, and $t$. In that frame of reference a charged particle of charge $\epsilon$ travels along the $x$-axis with a velocity $v$. There is another frame $S'$ with coordinates $x'$, $y'$, $z'$ and $t'$, which is moving at a constant velocity $v$ along the axis, that is, it initially moves together with the charged particle. A purely electric field is present in S' ($\vec{E}=[E_x, E_y ,E_z]$), exerting a force on the charge. Since in the frame $S'$ the charge is not moving, the equations of motion reduce to Newton's classical equations of motion:
$$m\dfrac{d^2x'}{dt'^2}=\epsilon E_x'$$
$$m\dfrac{d^2y'}{dt'^2}=\epsilon E_y'$$
$$m\dfrac{d^2z'}{dt'^2}=\epsilon E_z'$$
Transforming these equations of motion into $S$ coordinates, using the transformation of the electromagnetic field (in Gaussian Units) and the Lorentz transformations:
$$m\gamma^3 \dfrac{d^2x}{dt^2}=\epsilon E_x$$
$$m\gamma^2 \dfrac{d^2y}{dt^2}=\epsilon \gamma\left(E_y-\frac{v}{c}B_z\right)$$
$$m\gamma^2 \dfrac{d^2z}{dt^2}=\epsilon \gamma\left(E_z+\frac{v}{c}B_y\right)$$
Where
$$\gamma=\frac{1}{\sqrt{1-\frac{v^2}{c^2}}}$$
And a magnetic field is present in S such that $\vec{B}=[B_x, B_y, B_z]$. If we make it so that the force present of the $S$ frame will be the Lorentz force due to the Electromagnetic Field is equivalent to the electric force in the $S'$ frame, but not necessarily equal. The components of the Lorentz Force are:
$$F_x=\epsilon E_x+\frac{\epsilon}{c}(v_yB_z-v_zB_y)$$
$$F_y=\epsilon E_y+\frac{\epsilon}{c}(v_zB_x-v_xB_z)$$
$$F_z=\epsilon E_z+\frac{\epsilon}{c}(v_xB_y-v_yB_x)$$
Since the field in $S'$ is purely electric, electromagnetic field in $S$ is given by
$$E_x=E_x'$$
$$E_y=\gamma E_y'$$
$$E_z=\gamma E_z'$$
$$B_x=0$$
$$B_y=-\gamma \frac{v}{c}E_z'$$
$$B_z=\gamma \frac{v}{c}E_y'$$
With these and the fact that in the $S$ frame the charge has no $y$ or $z$ conponents of velocity, we get that the Lorentz Force equations in $S$ are:
$$F_x=\epsilon E_x$$
$$F_y=\epsilon \left(E_y-\frac{v}{c}B_z\right)$$
$$F_z=\epsilon \left(E_z+\frac{v}{c}B_y\right)$$
With these, the original equations of motion can be transformerd into
$$m\gamma^3 \dfrac{d^2x}{dt^2}=F_x$$
$$m\gamma \dfrac{d^2y}{dt^2}=F_y$$
$$m\gamma \dfrac{d^2z}{dt^2}=F_z$$
From the $y$ and $z$ components I get the usual 'Relativistic Mass' formula
$$m=\frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}$$
But I get a different 'mass' in the $x$-direction, one of
$$m=\frac{m_0}{\left(\sqrt{1-\frac{v^2}{c^2}}\right)^3}$$
similar to what Einstein got in his original 1905 paper on Special Relativity using a different definition of force. Where is it that I went wrong?

A: As the link I provided in the comments explains, the force on an object has different proportionalities to mass and acceleration in the longitudinal and transverse directions. Specifically,
$$\mathbf{F} = \gamma^3 m_0\mathbf{a_{||}}+\gamma m_0\mathbf{a_{\perp}}$$
which is derived from $\mathbf{F} = \frac{d\mathbf{p}}{dt}$ by letting $\mathbf{p}=\gamma m_0\mathbf{v}$ and taking the product rule when differentiating $\gamma\mathbf{v}$.
As is plain to see, you obtained the correct relations, so there is no problem.


text:
Q: How can I write the following statement as a constraint? I have the following condition:

*

*If $x = 0$ and $c=0$ then $z=1$.

*If $x>0$ and $c=1$ then $z = 1$.

*If $x>0$ and $c=0$ then $z = 0$.

I find the constraint $x(1-c) \geqslant 1-z$, but it misses the last point.
EDIT
The variables $z$ and $c$ are binary variables.

A: $$z=-sgn(x)+sgn(c)+1$$ does the job.


text:
Q: Silently Uninstall ALL previous MS Office Software I am trying to silently uninstall ALL previous Microsoft software in order to run a vbscript to install Office 365(which works).
This is what works currently.
Using the scripts from here:
https://marckean.wordpress.com/2013/06/18/fully-automate-removal-of-any-version-office-in-preparation-for-office-365/
From this link I use
OffScrub7.vbs & OffScrub10.vbs which uninstalls ALL Office 2010 products and  all Office 2007 products in theory, but it doesn't!
After running uninstall scripts above, they still leave Lync 2010 and MS Access Database 2007 (32-bit).
Whats the best way to make sure all previous office products are uninstalled including the above software that was not uninstalled by OffScrub7.vbs & OffScrub10.vbs  ? My guess is to find silent vbscripts to uninstall Lync 2010 and MS Access Database 2007 (32-bit)?

A: All Microsoft apps can be uninstall using easy c++ code and msi api.
Req.: win 7 pro
Works in 32 and 64 bits os.
One mini tool.exe, that may be wrapped in vb script, PowerShell , etc
UPD:
I have a little free time.
I want to supplement my answer.
I talked about a little application, but did not show a single line of code.
Now we will correct the matter.
1) Need Win7 Pro, 64 or 32 bits, it does not matter.
The project we are going to compile a 32-bit compiler, because our application needs to run on 32 bit and 64 bit OS.
2) Need any Ide, I advise Code :: Blocks.
3) Need mingv32-w64 compiler - more information here -- mingw-w64.org
3.1) It is necessary to install two versions of the compiler for 64 bit and 32 bit operating system, even if you have 32 operating as a host. We need a static library from 64-bit compiler installation.
4) Create a console application
5) Build options for project - to add the static library project libmsi.a
But! in 32-bit installation of the compiler has only the header file mhi.n, but the library itself is not!
But it is in the 64 bit version of the installer.
Find this static library in your Lib folder of 64 bit compiler installation.
6) Code - Enum applications (source: http://mariusbancila.ro/blog/2011/05/01/finding-installed-applications-with-vc/)
The utility must be run with administrator privileges.
That is, if we run the utility from powershell script, then powershell should be run with administrator rights.
#include <iostream>
#include <windows.h>
#include <tchar.h>
#include <msi.h>
#include <string>

using namespace std;

string MsiQueryProperty(LPCTSTR szProductCode,
                     LPCTSTR szUserSid,
                     MSIINSTALLCONTEXT dwContext,
                     LPCTSTR szProperty)
{
    string value;
    DWORD cchValue = 0;
    UINT ret2 = ::MsiGetProductInfoEx(
        szProductCode,
        szUserSid,
        dwContext,
        szProperty,
        NULL,
        &cchValue);
    if(ret2 == ERROR_SUCCESS)
    {
        cchValue++;
        value.resize(cchValue);
        ret2 = ::MsiGetProductInfoEx(
            szProductCode,
            szUserSid,
            dwContext,
            szProperty,
            (LPTSTR)&value[0],
            &cchValue);
    }
    return value;
}

void MsiEnum()
{
    UINT ret = 0;
    DWORD dwIndex = 0;
    TCHAR szInstalledProductCode[39] = {0};
    TCHAR szSid[128] = {0};
    DWORD cchSid;
    MSIINSTALLCONTEXT dwInstalledContext;
    do
    {
        memset(szInstalledProductCode, 0, sizeof(szInstalledProductCode));
        cchSid = sizeof(szSid)/sizeof(szSid[0]);
        ret = ::MsiEnumProductsEx(
            NULL,           // all the products in the context
            _T("s-1-1-0"),  // i.e.Everyone, all users in the system
            MSIINSTALLCONTEXT_USERMANAGED | MSIINSTALLCONTEXT_USERUNMANAGED | MSIINSTALLCONTEXT_MACHINE,
            dwIndex,
            szInstalledProductCode,
            &dwInstalledContext,
            szSid,
            &cchSid);
        if(ret == ERROR_SUCCESS)
        {
            string name = MsiQueryProperty(
                szInstalledProductCode,
                cchSid == 0 ? NULL : szSid,
                dwInstalledContext,
                INSTALLPROPERTY_INSTALLEDPRODUCTNAME);
            string publisher = MsiQueryProperty(
                szInstalledProductCode,
                cchSid == 0 ? NULL : szSid,
                dwInstalledContext,
                INSTALLPROPERTY_PUBLISHER);
            string version = MsiQueryProperty(
                szInstalledProductCode,
                cchSid == 0 ? NULL : szSid,
                dwInstalledContext,
                INSTALLPROPERTY_VERSIONSTRING);
            string location = MsiQueryProperty(
                szInstalledProductCode,
                cchSid == 0 ? NULL : szSid,
                dwInstalledContext,
                INSTALLPROPERTY_INSTALLLOCATION);

            cout << name << endl;
            cout << "  - " << publisher << endl;
            cout << "  - " << version << endl;
            cout << "  - " << location << endl;
            cout << endl;
            dwIndex++;
        }
    }
    while(ret == ERROR_SUCCESS);
}

int main()
{
    MsiEnum();
    return 0;
}

After a time will add the code, remove the application on his behalf, which is displayed in the list of installed programs in the Control Panel.
Just not enough time, sad = (
But you can try is to write an application (if you're interested, nothing fancy really, but still very interesting)


text:
Q: jqueryUI: initialising dialog content on first click This should be easy for experienced jqueryUI users. What I'd like to achieve is:

*

*to have one button when the page has just been rendered (and nothing more)

*when this button is clicked, a dialog opens and the dialog content is generated, using AJAX

At the moment I've got most of those, but using two distinct jquery UI buttons. I'm using icanhaz, but it should make no difference, since I got this part working fine. This is the html part:

show users

show dialog

and this is javascript part:
$(document).ready( function() {

    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "../php/client/json.php",
            data: {
                type: "users"
            }
        }).done(function( response ) {
            var element = $('#dialog-message');
            element.append(ich.user(response));
        });
    });

    $("#dialog-btn").click(function() {
        $("#dialog-message").dialog().dialog("open");
    });
});

When I click the first button, "show users", it generates the content for the dialog. When I click "show dialog", the dialog is created and opened. I'd jut like to clean it - to call the ajax (and render icanhaz) when clicked, use the rendered html to create the dialog, open the dialog and display (all in one single click).

A: $(document).ready( function() {

    $("#user-btn").click(function() {
        if ($('#dialog-message').is('.ui-dialog-content')) {
            // data already loaded and dialog already initialized
            $('#dialog-message').dialog('open');
        } else {
            // request data and initialize dialog
            $.ajax({
                type: "GET",
                dataType: "json",
                url: "../php/client/json.php",
                data: {
                    type: "users"
                }
            }).done(function( response ) {
                $('#dialog-message')
                    .append(ich.user(response)) // load data into element
                    .dialog(); // show as dialog (autoOpen is true by default)
            });
        }
    });
});

$('#dialog-message').is('.ui-dialog-content') is just one way to check if a dialog has already been initialized on an element; there may be a better way.


text:
Q: I create an instance of 3 different view models and assign each to a state object. How do I place this into a dispatch queue? I have a Swift program that works as desired.  I have 3 view models that each call a separate model.  Each model calls a function that reads a separate large CSV file, performs some manipulation and returns a data frame.  This takes some time and I would like to speed things up.
Swift offers a DispatchQueue that allows one to place code into an asynchronous global queue with QOS and I believe if I ran the creation of the view models in this fashion, I would display the initial view sooner.
The problem is: I have no idea how to incorporate it.  Any help to point me in the right direction will be appreciated.
Below is my content view, one view model, and one model.  The test dispatch queue code at the end runs successfully in a playground.
struct ContentView: View {
    @StateObject var vooVM: VOOViewModel = VOOViewModel()
    @StateObject var vfiaxVM: VFIAXViewModel = VFIAXViewModel()
    @StateObject var principalVM: PrincipalViewModel = PrincipalViewModel()
    @State private var selectedItemId: Int?
    var body: some View {
        NavigationView {
            VStack (alignment: .leading) {
                List {
                    Spacer()
                        .frame(height: 20)
                    Group {
                        Divider()
                        NavigationLink(destination: Summary(vooVM: vooVM, vfiaxVM: vfiaxVM, prinVM: principalVM), tag: 1, selection: $selectedItemId, label: {
                            HStack {
                                Image(systemName: "house")
                                    .padding(.leading, 10)
                                    .padding(.trailing, 0)
                                    .padding(.bottom, 5)
                                Text("Summary")
                                    .bold()
                                    .padding(.bottom, 2)
                            } // end h stack
                        })
                    } // end group
                    NavigationLinks(listText: "VOO", dataFrame1: vooVM.timeSeriesDailyDF1, dataFrame5: vooVM.timeSeriesDailyDF5)
                    NavigationLinks(listText: "VFIAX", dataFrame1: vfiaxVM.timeSeriesDailyDF1, dataFrame5: vfiaxVM.timeSeriesDailyDF5)
                    NavigationLinks(listText: "Principal", dataFrame1: principalVM.timeSeriesDailyDF1, dataFrame5: principalVM.timeSeriesDailyDF5)
                    Divider()
                    Spacer()
                } // end list
            } // end  v stack
        } // end navigation view
        .onAppear {self.selectedItemId = 1}
        .navigationTitle("Stock Data")
        .frame(width: 1200, height: 900, alignment: .center)
    } // end body view
} // end content view

View Model
class VOOViewModel: ObservableObject {
    @Published private var vooModel: VOOModel = VOOModel()
    var timeSeriesDailyDF1: DataFrame {
        return vooModel.vooDF.0
    }
    var timeSeriesDailyDF5: DataFrame {
        return vooModel.vooDF.1
    }
    var symbol: String {
        return vooModel.symbol
    }
    var currentShares: Double {
        return vooModel.currentShares
    }
    var currentSharePrice: Double {
        let lastRowIndex: Int = vooModel.vooDF.0.shape.rows - 1
        let currentPrice: Double = (vooModel.vooDF.0[row: lastRowIndex])[1] as! Double

        return currentPrice
    }
    var percentGain: Double {
        let pastValue: Double = (vooModel.vooDF.0[row: 0])[1] as! Double
        let numRows: Int = vooModel.vooDF.0.shape.rows - 1
        let curValue: Double = (vooModel.vooDF.0[row: numRows])[1] as! Double
        let oneYearGain: Double = (100 * (curValue - pastValue)) / pastValue
        return oneYearGain
    }
}

Model
struct VOOModel {
    var vooDF = GetDF(fileName: "FormattedVOO")
    let symbol: String = "VOO"
    let currentShares: Double = 1
}

Playground Code
let myQue = DispatchQueue.global()
let myGroup = DispatchGroup()
myQue.async(group: myGroup) {
    sleep(5)
    print("Task 1 complete")
}
myQue.async(group: myGroup) {
    sleep(3)
    print("Task 2 complete")
}
myGroup.wait()
print("All tasks completed")

A: I was able to solve my problem by using only 1 viewmodel instead of 3.  The viewmodel calls all three models which were modified such that their function call to read a CSV file and place it into a dataframe is contained in a function. This function is in turn called within a function in the viewmodel which is called in the viewmodels init.  Below is the updated code.  Note that the ContentView was simplified to make testing easy.
New Content View:
struct ContentView: View {
    @StateObject var viewModel: ViewModel = ViewModel()
    var body: some View {
        let printValue1 = (viewModel.dataFrames.0.0[row: 0])[0]
        let tempValue = (viewModel.dataFrames.0.0[row: 0])[1] as! Double
        let tempValueFormatted: String = String(format: "$%.2f", tempValue)
        Text("\(dateToStringFormatter.string(from: printValue1 as! Date))" + "     " + tempValueFormatted )
            .frame(width: 1200, height: 900, alignment: .center)
    }
}

New ViewModel:
class ViewModel: ObservableObject {
    @Published private var vooModel: VOOModel = VOOModel()
    @Published private var vfiaxModel: VFIAXModel = VFIAXModel()
    @Published private var principalModel: PrincipalModel = PrincipalModel()
    var dataFrames = ((DataFrame(), DataFrame()), (DataFrame(), DataFrame()), (DataFrame(), DataFrame()))
    init() {
        self.dataFrames = GetDataFrames()
    }
    func GetDataFrames() -> ((DataFrame, DataFrame), (DataFrame, DataFrame), (DataFrame, DataFrame)) {
        let myQue: DispatchQueue = DispatchQueue.global()
        let myGroup: DispatchGroup = DispatchGroup()
        var vooDF = (DataFrame(), DataFrame())
        var vfiaxDF = (DataFrame(), DataFrame())
        var principalDF = (DataFrame(), DataFrame())
        myQue.async(group: myGroup) {
            vfiaxDF = self.vfiaxModel.GetData()
        }
        myQue.async(group: myGroup) {
            principalDF = self.principalModel.GetData()
        }
        myQue.async(group: myGroup) {
            vooDF = self.vooModel.GetData()
        }
        myGroup.wait()
        return (vooDF, vfiaxDF, principalDF)
    }
}

One of the new models.  The other 2 are identical except for the CSV file they read.
struct VOOModel {
    let symbol: String = "VOO"
    let currentShares: Double = 1
    func GetData() -> (DataFrame, DataFrame) {
        let vooDF = GetDF(fileName: "FormattedVOO")
        return vooDF
    }
}


text:
Q: MVC5 Models outside of area EF6 I am trying to call a public virtual into a Asset.cs to link data on the ModelID.
My issue is that the Model.cs is outside of the area of where the asset.cs is.
How do i link the two tables models together when they are separated by areas ?
Assets.cs in a area, using "model" is an issue in the public virtual because it cant find it in the Area.
    namespace Assets.Areas.Company.Models
     {
      public class Asset
      {
        [Key]
        public int AssetID { get; set; }
        public int ModelID { get; set; }
        public virtual Model ModelName { get; set; }

Model.cs outside the area
     namespace Assets.Models
     {
       public class Model
     {

    [Key]
    public int ModelID { get; set; }
    public int AssetAssignmentID { get; set; }
    [Required]
    [StringLength(100, MinimumLength = 2)]
    public string ModelName { get; set; }

I have tried a viewmodel approach but it just adds the fields to the asset table rather than foreign keys when i use public virtual ModelVM ModelName { get; set; }
I have tried using the using Assets.Models; to link to the model.cs when looking at public virtual Model ModelName { get; set; } , but when updating the table an object named 'models' is already in the database.

A: I have found i can you models outside of an area, with:
using Assets.Models;

My EF Migration was causing me the issue with "object named 'models' is already in the database."   This was because the table Models was already there!


text:
Q: Remove Decimal but Keep Values - SQL I have a data request - SQL Server 2014 (fourth column). The application does not handle decimals. So I have to provide the data without the decimals. For example: If an employee worked 8 hours, I am sending 8.00. The upstream application wants the data as 800. Or if its less than 8 hours then 050 (.50) for half hour.
My calculation for two weeks of work is:
CONVERT(decimal(10, 2), dur) / 60 AS HOURS

My question is: how do I strip that decimal yet maintain the correct hours such that 8.00 becomes 800?

A: You could simply convert the hours to a string and then replace the decimal with nothing. If necessary, convert the string without the decimal to an integer.
DECLARE @Hours DECIMAL(10, 2)

SET @Hours = 8.50

SELECT
  @Hours AS [Hours]
, REPLACE(CONVERT(VARCHAR(13), @Hours), '.', '') AS [Hours as String]
, CONVERT(INT, REPLACE(CONVERT(VARCHAR(13), @Hours), '.', '')) AS [Hours as Integer]

A: Since your application is expecting leading zeros on values under an hour, you're going to have to pad that out. However, since there can be values over 10 hours, we need to treat those a little differently to account for the extra characters in the end result.
This seems to give the values you're looking for.
Setup:
create table t
    (tm decimal(18,5));

insert t values (8.05999),(11.00000),(0.34111);

Query:
select
    case
        when t.tm > 10
            then cast(cast(t.tm*100 as integer) as varchar(5)) --<-Handles longer shifts
        else right(concat('000',cast(t.tm*100 as integer)),3)  --<-Handles shorter shifts
    end as appVal
from t;

Results:
+--------+
| appVal |
+--------+
|    805 |
|   1100 |
|    034 |
+--------+

A: Replaced the decimal sign as suggested by @isaac and @eric-brandt. Then only populated the number of values the upstream application needed.
LEFT(REPLACE((CONVERT(decimal(10, 2), dur) / 60),'.',''),3) AS HOURS,


text:
Q: Monitoring text property validity as user types [Winforms Application .NET 4.0 C#]
I have a textbox that receives data from a handheld barcode scanner.
I want my application to check if the text is valid without the user having to do anything.
Example rule:

*

*Text length =18 and starts with '1520'

*Text length =17 and starts with '0520'

Should i checkit with:

*

*TextChanged event?

*Add a timer to check the rules every 200-300ms?

something else?

A: TextChanged event will suffice, I have implemented something similar in the past and you will only be notified once so you will have the full barcode on each scan.


text:
Q: creating nested resource I have a question that bothers me every time I face the same situation.
How to create a nested resource..
I have the following repo
 https://github.com/abhishekdagarit/app-e-commerce.git

You can clone the repo and create the dabtabase to see the project.
I need to add categories to the products..
 product
    belongs_to_and_has_many :categories

 category
    has_many :products

Could anyone please tell me how to achieve this to work properly...
I added comments to individual products but that took me four hours to achieve that...
This is what I normally do...
  1). add the category model using
       rails g model category category_type:string

  2). then add the has_to and the belongs_to_and_has_many in the models

  3). add the controller
       rails g controller categories

  4). add the following lines in the categories controller
       class CategoriesController < ApplicationController
       def new
         @product = Product.find(params[:product_id])
         @category = @product.categories.build
         respond_with(@category)
       end
      def create
         @product = Product.find(params[:product_id])
         @category = @product.categories.create(params[:category])
         redirect_to product_path(@product)
      end
     end

Now the thing is that these steps just don't seem to work...
I need someone to help me with the few lines to code that work in order to create a nested resource...

A: You can find the Nested Resources from rails guides.
did you try the following nested resources?
resources :categories do
    resources :products
end

A: You might also want to checkout:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2


text:
Q: C# Possible Memory Leak? So, I have an app, written in C# (vs2010), performing OCR using the tesseract 3.02 dll and Charles Weld's terreract .net wrapper.
I think I have a memory leak and it seems to be in the area of code where the Pix object is allocated.  I am taking a PDF, converting that to a grayscale PNG, then loading that into a Pix object for OCR.  When it works, it works really well.  Image is large in size (5100 or so pixels in each dim) but not so large in size (only 500k or so).
My code:
Init engine at app startup:
private TesseractEngine engine = new TesseractEngine(@"./tessdata/", "eng+fra", EngineMode.Default);

Method to convert PDF to PNG, then calls:
// Load the image file created earlier into a Pix object.
Pix pixImage = Pix.LoadFromFile(Path.Combine(textBoxSourceFolder.Text, sourceFile));

And then calls the following:
// Perform OCR on the image referenced in the Pix object.
private String PerformImageOCR(Pix pixImage)
{
    int safety = 0;

    do
    {
        try
        {
            // Deskew the image.
            pixImage = pixImage.Deskew();
            //pixImage.Save(@"c:\temp\img_deskewed.png", ImageFormat.Png); // Debugging - verify image deskewed properly to allow good OCR.

            string text = "";

            // Use the tesseract OCR engine to process the image
            using (var page = engine.Process(pixImage))
            {
                // and then extract the text.
                text = page.GetText();
            }

            return text;
        }
        catch (Exception e)
        {
            MessageBox.Show(string.Format("There was an error performing OCR on image, Retrying.\n\nError:\n{0}", e.Message), "Error", MessageBoxButtons.OK);
        }
    } while (++safety < 3);

    return string.Empty;
}

I have observed that memory usage jumps by about 31MB when the Pix object is created, then jumps again while OCR is being performed, then finally settles about 33MB higher than before it started.  ie: if app, after loading, was consuming 50MB, loading the Pix object causes the memory usage to jump to about 81MB.  Performing OCR will see it spike to 114+MB, then, once the process is complete and the results saved, the memory usage settles to about 84MB.  Repeating this over many files in a folder will eventually cause the app to barf at 1.5GB or so consumed.
I think my code is okay, but there's something somewhere that's holding onto resources.
The tesseract and leptonica dlls are written in C and I have recompiled them with VS2010 along with the latest or recommended image lib versions, as appropriate.  What I'm unsure of, is how to diagnose a memory leak in a C dll from a C# app using visual studio.  If I were using Linux, I'd use a tool such as valgrind to help me spot the leak, but my leak sniffing skills on the windows side are sadly lacking.  Looking for advice on how to proceed.

A: I'm not familliar with Tesseract or the wrapper, but for memory profiling issues, if you have Visual Studio 2012/2013, you can use the Performance Wizard.  I know it's available in Ultimate, but not sure on other versions.
http://blogs.msdn.com/b/dotnet/archive/2013/04/04/net-memory-allocation-profiling-with-visual-studio-2012.aspx
It's either something in your code or something in the wrapper is not disposing an unmanaged object properly.  My guess would be it's in the wrapper.  Running the Performance Wizard or another C# memory profiler (like JetBrains DotTrace) may help you track it down.

A: Reading your code here I do not see you disposing your Pix pixImage anywhere? That's what is taking up all the resources when you are processing x images.
Before you return your string result you should call the dispose method on your pixImage. That should reduce the amount of resources used by your program.


text:
Q: Make a  dynamically fill the remainder of parent's height Is it possible to make a div fill the remainder of a parent's height, after space has already been allocated to other elements?
Specifically, with the following layout:

The parent has a known, fixed height. However, the sibling is toggle-able, and may either have 0 height (display: none), or its normal height. The resizable div is the last child of the parent.

Can this be done:

*

*Dynamically, meaning that it updates when a previous sibling is shown or hidden; or inserted, removed; etc

*Without JavaScript?

*Without knowing the height of the other siblings in advance?

*For IE9 (extra credit)

Thanks!

A: It is possible with CSS table and table-row.
http://jsfiddle.net/xs06asy9/

$("button").click(function () {
    $("#resizableDiv").toggle();
});
#parent {
    display: table;
    width: 100%;
    height: 100px;
}
#sibling, #resizableDiv {
    display: table-row;
    background: silver;
}
#resizableDiv {
    background: gray;
}

1

2

<button>Show/Hide</button>

A: I tried using CSS3 flex-box model. I added flex properties to the #parent and it's children
#parent {
    height: 400px;
    border: 2px solid #333;
    display: flex;
    flex-flow: column nowrap;
    align-items: stretch;
}
#sibling {
    border: 2px solid red;
    flex: 0 0 100px;
}
#resizableDiv {
    border: 2px solid green;
    flex: 1 0;
}

Please see working fiddle here.

*

*No IE9 credits though :(


text:
Q: Why might you want to have more than one table in a database? I have a fair understanding but I want to hear it from people with more experience. Thank you.

A: I give you one simple example
suppose you have employee table like below
EmpId        Name      Adress
1            A1        Olaf Vei
2            A2        Rosenhoff
3            A3        Olaf vei
Now emp 1 and 3 have same address. Suppose if you feel address is wrong and want to update the address then you have to use update statement to change addree for those emp. Instead if you have foriegn key for Address then you can just that record and will be done automatically for both employees.
having relational database makes life easier. I hope you are satisfied

A: Read here about the concept of a relational database model.
Or in a nutshell...
A relational database allows the definition of data structures, storage and retrieval operations and integrity constraints. In such a database the data and relations between them are organized into tables. A table is a collection of records and each record in a table contains the same fields.1   The contents of a table can be permanently saved for future use.

A: Having relational database is really helpful. If you have just one table then it will be very difficult to insert the records. Although search will be quite faster if you just have 1 table because then you avoid joins. It depends how complex your database structure will be.

A: To store data in scaleable, maintainable, structured way.
See this: Normalization in plain English
And, i believe if you know why RDBMS is preferred over flat files. The same answer applied to your question also.
database vs. flat files


text:
Q: facebook friend finder i am create application in which i want to add facebook friend's email..
is it possible. if possible then how?
please help me.
still now i am not using facebook in any application.

A: I'm afraid it is not possible to access to friend's emails.

Likewise, to protect the privacy of
  users who have not explicitly
  authorized your application, your
  application will only be able to
  access the basic profile information
  about a user's friends, like their
  names and profile pictures. If your
  application needs to access other data
  about a user's friends to enable
  social functionality, you will need to
  request some of the special friends
  permissions listed below.

If you look at this table, it says "not available" for email field under "Friends permission".
Also check out this question.


text:
Q: Does HasNext exists in ASP? How do I test in ASP if there is next element in a list?
I'm trying to do something like this:
a=Split("foo, boo, luu, bar", ",")
for each x in a
    response.write("'" & x & "'")
    if a.HasNext then
        response.write(",")
    end if
next

How does it works?
Thank you!

A: there's no HasNext but you can test against the size of the array
a=Split("foo, boo, luu, bar", ",")
i = 0
for each x in a
    response.write("'" & x & "'")
    if i < Ubound(a) then
        response.write(",")
    end if
    i = i + 1
next


text:
Q: How to make a publicly available contact form in rails served via CDN I want to place a contact form (email, name, message) in public facing pages in my rails app. I want to serve them via a CDN (say Cloudflare). The pages then will be cached by the CDN, including the authenticity_token in the form and the csrf-token in the meta tag.
What is the best way to handle this in Rails?

A: Caching an authenticity token and csrf-token basically make them useless.
If you intent to go forward, you need an open form that doesn't pretend to secure itself.  You'll need lots of defenses against spam and should not trust anything submitted via the action.
I'm not sure why you would do this as you're unlikely to get that much contact form traffic to require caching it like that.  Just let rails render a normal form is my recommendation.


text:
Q: Select an element that has an sibling with specific child using purely CSS
Possible Duplicate:
Is there a CSS parent selector?

Say you have:
----------
    X
----------
    Y -> Z
----------

Given Z is children of Y, i want to select all X which have a sibling that has a child Z

A: You cannot select a parent element in CSS based upon the child and sibling elements...so there's no way you can get this done...
So there's no CSS parent selector yet..
CSS 2 Selector's Specification Reference
CSS 3 Selector's Specification Reference
In CSS4 Specification I remember there was something like $ kind of thing but it was rejected later

A: There is currently no way to select the parent of an element in CSS That is why it is impossible to select sibling that has a child Z.


text:
Q: Failed to instantiate c3p0.ComboPooledDataSource on local machine I'm trying to run locally a maven-built, spring app connecting to a PostgreSQL db. When deploying on a remote server (using our server build profile) everything is fine. My local database is set up according to provided instructions as well. We are using tomcat 8.5. Trying to deploy the war on my local machine ends up in a following errors (these are already coming from tomcat):
SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [myartifactname.application.listener.KillBackgroundThreadsListener]

 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [hibernate/hibernate.xml]:

  Cannot resolve reference to bean 'proxyDataSource' while setting bean property 'dataSource';

    nested exception is org.springframework.beans.factory.BeanCreationException:

    Error creating bean with name 'proxyDataSource' defined in class path resource [hibernate/hibernate.xml]:

    Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource';

        nested exception is org.springframework.beans.factory.BeanCreationException:

        Error creating bean with name 'dataSource' defined in class path resource [hibernate/hibernate.xml]:

        Cannot resolve reference to bean 'mainDataSource' while setting bean property 'targetDataSource';

            nested exception is org.springframework.beans.factory.BeanCreationException:

            Error creating bean with name 'mainDataSource' defined in class path resource [hibernate/hibernate.xml]:

            Instantiation of bean failed;

                nested exception is org.springframework.beans.BeanInstantiationException:

                Failed to instantiate [com.mchange.v2.c3p0.ComboPooledDataSource]:

                Constructor threw exception;

                    nested exception is java.lang.ExceptionInInitializerError

c3p0's version in local maven repository is 0.9.5.2, whereas in root pom it's 0.9.1.2, and that's also the highest available version in our company's repo. Changing the version in pom to 0.9.5.2 results in the project not compiling at all. The project is multi-module and one of the modules seems to download other version than stated in root pom. Root pom is the only place where this artifact version is defined.
How should I resolve this? Could you point me to some maven documentation hints?


text:
Q: Animated GIF not animating in browser I have an animated GIF which was working fine in development, but not after build. I have tried it in chrome and edge. I have a static placeholder which is displayed fine and on mouseEnter it gets replaced by the animated file. It does do this as the src has the correct file, but it does not animate. I can see that the correct image is loaded as it is slightly different to its static placeholder. The files are static files, in the public folder.
Is there something I need to add in the config?
I am not sure where to start trouble shooting on this as I am quite new to this.
This is the component :
import React, { useState } from 'react'
import Image from 'next/image'
import styles from '../../styles/Interest.module.scss'

type props = {
    gifRef: React.LegacyRef<HTMLDivElement>
    interest: {
        title: string
        gif: string
        gif_static: string
        text: string
        bg: string
        id: number
    }
}

export const Interest = ({ interest, gifRef }: props) => {
    const {title, gif, gif_static, text, bg} = interest
    const [img, setImg] = useState<string>(gif_static)

  return (

 setImg(gif) }
            onMouseLeave={ () => setImg(gif_static)}
            ref={interest.id === 1 ? gifRef : null}
    >

{ title }

        { gif ? <Image src={ img } width={500} height={500} alt={ interest.title }/> : null }

{ text }

  )
}

Rest of code is here: https://github.com/Bponthemove/my-new-portfolio

A: Next/image will try to optimize any image you throw at it by default, and does not support GIFs.
A workaround would be to set the unoptimized attribute to true on <Image />
See docs: https://nextjs.org/docs/api-reference/next/image#unoptimized
Example:
<Image
  src={'https://domain.tld/image.gif'}
  layout={'responsive'}
  height={175}
  width={175}
  alt={`A cute animal!`}
  unoptimized={true}
/>


text:
Q: How to disable Windows 10 System and Compress Memory feature? As the title says, how do we disable it?
It maybe promising for low memory devices but not on a 32 Gig Ram, it consumes about 50% of disk access and it slows down other access on local disks.
There were few answers discussed in How to disable Windows 10 memory compression? but it does not work now on Windows 10 Build 1511


text:
Q: Angular Modal Window Called From Controller Not Formatting Content Prior to submitting a request, I am required to validate the data associated to the request for specific requirements.  I click a submit button to perform the validation.  If any errors are found, I store the error into an field with  tags between each error.  I then open my modal window and it displays as follows.

I added $modal to my controller
I called the modal window 2 different way to get the best results but both display content similarly
my code is listed below
$scope.modal =
        {
         title: "Title",
         content: "Error Message(s)  new message "
        };
    $scope.open = function()
    {
     var modalInstance = $modal(
     {
      title: "Title 1",
      content: $scope.modal.content
     });
    };

    var myModal = $modal({
     title: "Title 2",
     content: "Error Message(s) <br /> new message 2",
     show: false
    });

    $scope.showModal = function()
    {
     myModal.$promise.then(myModal.show);
    };

    $scope.hideModal = function()
    {
     myModal.$promise.then(myModal.hide);
    };

Neither will wrap the lines properly.
I will need to display the modal window on several different submission based on options selected and data displayed.
TIA

A: I discovered my answer.  Using the first option:
scope.modal = { title: "Title", content: "Error Message(s)
new message " };
$scope.open = function()
{
 var modalInstance = $modal(
 {
  title: "Title 1",
  content: $scope.modal.content
 });
};

I added  the following:
template: '.../.../modal.tpl.html'
This allowed the process to use the modal template html and the output was formatted correctly.
Thanks for the responses


text:
Q: viewDidLoad not called when using loadView Can anyone explain why viewDidLoad does not get called when loadView is used? It's my understanding that viewDidLoad should still get called.
- (void)loadView
{
    CGRect currentFrame = [[UIScreen mainScreen] applicationFrame];

    UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(currentFrame.origin.x, currentFrame.origin.y, currentFrame.size.width, currentFrame.size.height)];
    myView.backgroundColor = [UIColor redColor];

    self.view = myView;
    [myView release];

    [super loadView];
}

- (void)viewDidLoad {

    //this never happens
    NSLog(@"VIEW DID LOAD!");
    [super viewDidLoad];
}

A: I've just found out that viewDidLoad won't be called if you call loadView manually in your application.
If you call loadView manually you have to call viewDidLoad manually as well.
More over according to apple docs you shouldn't call [super loadView] as it will overwrite your view with a default UIView.

A: You must have a warning here:
NSLog("VIEW DID LOAD!");

Instead, you should write like this (the @ sign is necessary):
NSLog(@"VIEW DID LOAD!");

A: viewDidLoad will not get called when you create instance of ViewController. When you are pushing it to navigation controller or present it as model viewcontroller, then only the viewDidLoad get called. Until and unless you are presenting viewController, these delegate will not get called. And one more thing, if your viewcontroller presentation over, and still it remains in the stack or memory, then viewDidLoad method will not get called again because its already load the view. Then viewWillAppear and viewDidAppear delegates only get called when you present the same viewController.


text:
Q: Use SNMP to transfer file from agent to manager? I want invoke my .NET assembly from snmp agent and return an XML document to the agent in order to transmit that XML file to the server (manager).
Can I use SNMP to transmit big files to the manager?

A: The max size of an SNMP PDU is 64k (i.e. the max size of a UDP datagram). Some implementations may have smaller limits. Some networks will not pass large datagrams cleanly (they may get fragmented and not reliably reassembled).
You don't want to transfer a file through SNMP. Use a more suitable protocol: TFTP, FTP, HTTP, SCP all come to mind, depending on the needs of your application.


text: Q: Add numbering in Interactive Report of Pentaho User Console I have a query that show a list of item. I use that query to create a report using Interactive Report in Pentaho User Console. My problem is I don't know how to add numbering column in that report using Interactive Report application. Can anyone tell me is there any way to do that?


text:
Q: jQuery keep checkbox checked while any others are checked I have more than fifteen checkbox inputs all with the same class, looking something like below:
I want to have only the first input be checked and stay checked when any other input with the same class is checked. If only the first input is checked you should be able to check and uncheck it freely. Only the first one has the ID, #SR01201. The rest only have the class check-12.
Right now, I can freely uncheck and check the first input, and it will get checked if any other inputs with the class check-12 are checked. But once any other input (besides the first one) is checked, it can't be unchecked.

$('.check-12:not(#SR01201)').on('change', function() {
  var $this = $(this);
  var SRTwelveOne = $("#SR01201");
  if ($this.prop('checked', true)) {
    SRTwelveOne.prop('checked', true)
  } else if ($this.prop('checked', false) && $this.siblings().prop('checked', false)) {
    SRTwelveOne.prop('checked', false);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12">

A: The $this.prop('checked', true) in if ($this.prop('checked', true)) is setting the checkbox to true, not checking if it's true. For that you want to use if ($this.prop('checked')). But I think your issue can be reduced to the following:

$('.check-12:not(#SR01201)').on('change', function() {
  $("#SR01201").prop('checked', $('.check-12:not(#SR01201):checked').length > 0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12">

The first line selects your checkboxes with the class you specified, but not the first one. Upon changing any of them, the checkbox with the ID SR01201 changes its checked property depending on how many of the other checkboxes are checked. 1 or more? check it, otherwise uncheck it. The result of $('.check-12:not(#SR01201):checked').length > 0 will be true or false.

A: The problem is that you're not checking if a checkbox is checked with $this.prop('checked', true) in your if statement. You're actually checking the box. To see if it's a box is checked, use is(":checked")


text:
Q: Вызвать подфункцию в js Есть js функция модального окна внутри, которого есть такие функции как открыть, закрыть модальное окно. Теперь надо при нажатии на <button class="choose">ok</button> закрыть это окно т.е вызвать "подфунцию". Вот собственно код:
var Modal = (function() {
var open = function(m, div) {
функция открытия}
 var close = function(event) {
функция закрытия}
}());

        Modal.init();

A: да както так делать надо, что вы изобретаете велосипеды ?

var Modal = {
init: function(){console.log('init')},
open: function(){console.log('open')},
close: function(){console.log('close')}
};
Modal.init()
Modal.open();
Modal.close();

A: Вот так работать должно:

var Modal = (function() {
  var init = (name) => { console.log(name) }
  var open = (m, div) => { console.log('open') }
  var close = (event) => { console.log('close') }
  return {open, close, init};
})();

console.log(Modal.init('myName'));


text:
Q: Identify data gaps in data with only timestamps I'm trying to figure out a query to run against Google BigQuery data, that will allow me to identify where the gaps exist, in data that only has timestamps (i.e. there's not a start and end date), data is being ordered by that timestamp, and there are non-consecutive ID numbers on rows.
Sample data:

Row     localised_sample_date_time
1       2019-03-21T00:00:29
2       2019-03-21T00:01:29
3       2019-03-21T00:02:29
4       2019-03-21T00:04:29
3       2019-03-21T00:05:29

Each row of data contains a timestamp, and each row of data is expected to occur at a predictable time interval (e.g. 10 mins). I'm looking for a query that illustrates where there are data gaps i.e. when the expected '10-minutely' row isn't present.
I want the data to look something like this:
data island
-------------------------------------------------------
[start timestamp of island] - [end timestamp of island]

e.g.
data island
-------------------------------------------------------
2019-03-21T00:00:29 - 2019-03-21T00:02:29
2019-03-21T00:04:29 - 2019-03-21T00:05:29

Logically I'm looking for something like:

*

*order by timestamp

*figure out if consecutive records have a 10 minute gap between them

*if they don't, then output the start and end timestamp that represents the data island.

This is a good general resource that explains how to identify data gaps and islands - http://www.kodyaz.com/t-sql/data-islands-and-data-gaps-with-boundaries-using-sql.aspx - it doesn't seem to cover data that is structured in the way mine is though.
I'm thinking there must be something I can use that does something with DATEADD , ORDER BY and GROUP BY, to identify the groups of records that conform to the expected pattern of 10 minute intervals, however I'm not seeing how I need to implement what I'm trying to achieve. What's an elegant, simple solution?

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT CONCAT(
    FORMAT_TIMESTAMP('%F %T', MIN(IF(gap, ts, previous_ts))), ' - ', FORMAT_TIMESTAMP('%F %T', MAX(ts))
  ) data_island
FROM (
  SELECT ts, previous_ts, gap, COUNTIF(gap) OVER(ORDER BY ts) grp
  FROM (
    SELECT ts, LAG(ts) OVER(ORDER BY ts) previous_ts,
      IFNULL(TIMESTAMP_DIFF(ts, LAG(ts, 1) OVER(ORDER BY ts), MINUTE), 2) > 1 gap
    FROM `project.dataset.table`
  )
)
GROUP BY grp

You can test, play with above using sample data from your question as in example below
#standardSQL
WITH `project.dataset.table` AS (
  SELECT TIMESTAMP '2019-03-21T00:00:29' ts UNION ALL
  SELECT '2019-03-21T00:01:29' UNION ALL
  SELECT '2019-03-21T00:02:29' UNION ALL
  SELECT '2019-03-21T00:04:29' UNION ALL
  SELECT '2019-03-21T00:05:29'
)
SELECT CONCAT(
    FORMAT_TIMESTAMP('%F %T', MIN(IF(gap, ts, previous_ts))), ' - ', FORMAT_TIMESTAMP('%F %T', MAX(ts))
  ) data_island
FROM (
  SELECT ts, previous_ts, gap, COUNTIF(gap) OVER(ORDER BY ts) grp
  FROM (
    SELECT ts, LAG(ts) OVER(ORDER BY ts) previous_ts,
      IFNULL(TIMESTAMP_DIFF(ts, LAG(ts, 1) OVER(ORDER BY ts), MINUTE), 2) > 1 gap
    FROM `project.dataset.table`
  )
)
GROUP BY grp
-- ORDER BY grp

with result
Row data_island
1   2019-03-21 00:00:29 - 2019-03-21 00:02:29
2   2019-03-21 00:04:29 - 2019-03-21 00:05:29


text:
Q: Передача нескольких данных в представление View Хочу передать данные с двух таблиц из бд но не могу понять как в View передать сразу два списка.
Вот код:
public IActionResult AllCustomers()
        {
            //Два списка которые нужно передать в view
            db.Custumers.ToList();
            db.Founders.ToList();

            return View();
        }

A: Создайте класс-модель с двумя свойствами:
public class SomeModel
{
    List<Customer> Customers { get; set; }
    List<Founder> Founders { get; set; }
}

Использование:
var someModel = new SomeModel
{
    Customers = db.Customers.ToList(),
    Founders = db.Founders.ToList()
};

return View(someModel);

Самое сложное тут - придумать хорошее название этой модели.


text:
Q: I can not serve a JSON response with Play framework 2.1 I'm trying to export json to an Android device. I have done it using java like Play! doc: http://www.playframework.com/documentation/2.1.1/JavaJsonRequests but it doesn't work. I'm shure it isn't an android problem because I did the same with php return json_encode($some) and it works well. What can I do?
package controllers;

import java.util.List;

import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

import models.Restaurante;
import play.libs.Json;
import play.mvc.*;

public class Servicio extends Controller {

public static Result coordenadas() {

    //System.out.println("XXXxxXX");

    ObjectNode rpta = Json.newObject();
    ArrayNode restaurantes = rpta.arrayNode();

    List <Restaurante> rests = Restaurante.allRests();
    Restaurante rest;

    for(int i=0; i<rests.size(); i++) {
        rest = rests.get(i);
        ObjectNode restJs = Json.newObject();
        restJs.put("nombre", rest.nombre);
        restJs.put("lon", rest.longitud);
        restJs.put("lat", rest.latitud);
        restaurantes.add(restJs);
    }

    ObjectNode response = Json.newObject();
    response.put("restaurantes", restaurantes);

    return ok(response);
}

}
I got it from db and the browser shows me this:
{
   "restaurantes":[
      {
         "nombre":"ODONTOLOGIA",
         "lon":-12.054695,
         "lat":-77.085268
      },
      {
         "nombre":"LETRAS",
         "lon":-12.057444,
         "lat":-77.081856
      },
      {
         "nombre":"FISICA",
         "lon":-12.060279,
         "lat":-77.081594
      },
      {
         "nombre":"COMEDOR",
         "lon":-12.059332,
         "lat":-77.083104
      },
      {
         "nombre":"QUIMICA",
         "lon":-12.06009,
         "lat":-77.083804
      },
      {
         "nombre":"CIBERCAFE",
         "lon":-12.059857,
         "lat":-77.084563
      },
      {
         "nombre":"GEOGRAFICA",
         "lon":-12.05507,
         "lat":-77.086127
      },
      {
         "nombre":"MECANICA",
         "lon":-12.055854,
         "lat":-77.081816
      },
      {
         "nombre":"ELECTRONICA",
         "lon":-12.056347,
         "lat":-77.082055
      },
      {
         "nombre":"ECONOMIA",
         "lon":-12.058123,
         "lat":-77.080639
      },
      {
         "nombre":"MINAS",
         "lon":-12.05199,
         "lat":-77.087165
      },
      {
         "nombre":"ADMINISTRACION",
         "lon":-12.05789,
         "lat":-77.081602
      },
      {
         "nombre":"Nuevo restaurante",
         "lon":-70.23123,
         "lat":-12.31234
      }
   ]
}

A: Try to return only restaurantes as ok attribute:
return ok(restaurantes);


text:
Q: Generating C data structures from IDL I am working to create a framework in "C" language where all data structures (both standard and custom one) used in a program are auto generated from a "IDL" or "XML" file rather than hardcoded by the user.
I want to autogenerate dump functions for these data structures rather than add printf functions for each every variable whenever it is added. This is similar to CORBA functionality and I am no expert in it.
Is there any library or simplified implementation available for reference ?


text:
Q: An Issue with ion-item tag I am working on a Login page where the user chooses the country code then enters his phone number.
The two input fields (code, phone number) are in one line together
The Problem I have is that when I use the ion-item it divide the width between the two input fields equally even if I change the width in the .scss file
I have been in this problem for 2 days and can't get it yet.
Here is my .scss file
ion-item{
    margin-top:170px;
    width: 100%;
}

.countryCode{
    width:20%;
    margin-right: 3px;
    border:none;
    border-bottom: 1px solid grey;
    background-color: rgba(255,255,255,0.0);
}

.phoneNumber{
    width: 50%;
    margin-left: 3px;
    border: none;
    border-bottom: 1px solid grey;
    background-color: rgba(255,255,255,0.0);
}

and here is my HTML file ion item tag
<ion-list>
<ion-item>

  <ion-input class="countryCode" type="text" [(ngModel)]="countryCode" name="code" (tap)="openCountriescodePage()" placeholder="+">{{countryCode}}</ion-input>
  <ion-input class="phoneNumber" type="text" [(ngModel)]="phoneNumber" name="phoneNumber"></ion-input>

</ion-item>

<button margin-top ion-button full color="success" (click)="login()">{{'login' | translate}}</button>

Thanks in advance :)

A: try using min-width and max-width it will fix your problem

A: Try using important,
ion-item{
    margin-top:170px;
    width: 100%;
}

.countryCode{
    width:20%;
    margin-right: 3px !important;
    border:none;
    border-bottom: 1px solid grey;
    background-color: rgba(255,255,255,0.0);
}

.phoneNumber{
    width: 50%;
    margin-left: 3px !important;
    border: none;
    border-bottom: 1px solid grey;
    background-color: rgba(255,255,255,0.0);
}


text:
Q: mysql convert rows to columns I have a table with two columns:client_id and invoice_id. For every client id there can be multiple invoice ids. I am searching for a MySQL query that converts the rows of the aforementioned table into columns. I only need the first two invoices for each client. Something like the pseudo-code below:
SELECT ci.client_id,
  first(ci.invoice_id) AS invoice_column1,
  second(ci.invoice_id) AS invoice_column2
FROM client_invoices ci
GROUP BY ci.client_id

Sample data for client_invoices
client_id | invoice_id
1           45
2           56
1           88

sample output
client_id | invoice_column1 | invoice_column2
1           45                88
2           56                NULL

A: Assuming that you have a single table with multiple entries for each client the expected query should look like this.
SELECT
    ci.client_id,
    GROUP_CONCAT(ci.invoice_id) as InvoiceIds
FROM(
    SELECT
        client_id,
        invoice_id,
        @num := if(@group = client_id, @num + 1, 1) as row_number,
        @group := client_id as dummy
    FROM    client_invoices
    GROUP BY client_id , invoice_id
    HAVING row_number <= 2
) as ci
GROUP BY ci.client_id

Demo

A: Something like this?
DECLARE tmp int(11);
DECLARE tmp2 int(11);
SELECT invoice_id INTO tmp FROM ci LIMIT 1,1;
SELECT invoice_id INTO tmp2 FROM ci LIMIT 2,1;
SELECT ci.client_id,
 tmp AS invoice_column1,
 tmp2 AS invoice_column2
 FROM client_invoices ci
 GROUP BY ci.client_id

A: You can use the following to assign a row number by group and then transforms the data into columns:
select client_id,
  max(case when group_row_number = 1 then invoice_id end) Invoice1,
  max(case when group_row_number = 2 then invoice_id end) Invoice2
from
(
  select client_id, invoice_id,
    @num := if(@client_id = `client_id`, @num + 1, 1) as group_row_number,
    @client_id := `client_id` as dummy, overall_row_num
  from
  (
    select client_id, invoice_id, @rn:=@rn+1 overall_row_num
    from client_invoices, (SELECT @rn:=0) r
  ) x
  order by client_id, overall_row_num
) src
group by client_id

See SQL Fiddle with Demo
Or a simpler way of doing it:
select client_id,
  max(case when rownum = 1 then invoice_id end) Invoice1,
  max(case when rownum = 2 then invoice_id end) Invoice2
from
(
  select client_id,
    invoice_id,
    @row:=if(@prev=client_id,@row,0) + 1 as rownum,
    @prev:=client_id
  from client_invoices
  order by client_id
)src
group by client_id;

See SQL Fiddle with Demo
Both produce the result:
| CLIENT_ID | INVOICE1 | INVOICE2 |
-----------------------------------
|         1 |       45 |       88 |
|         2 |       56 |   (null) |


text: Q: Save file from App Service to on-premise network share I have a requirement to create and save file from web application hosted in Azure App Service (ASE, Linux) to Network share on-premise. Network share already exists and is being written to by applications which I don't have control over. App Service is blocking ports so I can't write to network share directly. Assuming Azure to On premise connection is configured correctly what options do I have?


text:
Q: webClient.DownloadFile() return 404 browser download file with this url ok, but webClient return 404
 string url = "http://zakupki.gov.ru/44fz/filestore/public/1.0/download/priz/file.html?uid=19CC93BEA67C4650B51D69CAA28CB27D";
 using (var webClient = new WebClient())
        {
            webClient.DownloadFile(url , "name");
        }

A: There is the difference between the request done by the Web Browser and the request form the WebClient.
You need to add this to your code:
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

So your code will be changed to this:
string url = "http://zakupki.gov.ru/44fz/filestore/public/1.0/download/priz/file.html?uid=19CC93BEA67C4650B51D69CAA28CB27D";
using (var webClient = new WebClient())
{
  webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
  webClient.DownloadFile(url, "name.docx");
}

I hope it helps you


text:
Q: Fabric8 KubernetesClient sends volumeName as empty string for PersistentVolumeClaim causing Forbidden: spec is immutable after creation I want to apply the following yaml multiple times with the fabric8 kubernetes-client
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  storageClassName: my-storage-class
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi

I apply the yaml using createOrReplace()
Config config = new ConfigBuilder()
        .withMasterUrl("https://my-kubernetes-root:6443")
        .withNamespace("my-namespace")
        .withOauthToken(token)
        .withTrustCerts(true)
        .build();

KubernetesClient client = new DefaultKubernetesClient(config);
ClasspathResource resource = new ClasspathResource("my-pvc.yaml");

client.load(resource.getInputStream()).createOrReplace(); // this works
TimeUnit.MINUTES.sleep(1); // volumeName is dynamically assigned during this period
client.load(resource.getInputStream()).createOrReplace(); // this fails

This works the first time (when the PVC does not exist in the namespace) but fails the second time that createOrReplace() is called for the same yaml with the following error
io.fabric8.kubernetes.client.KubernetesClientException: Failure executing: PUT at: https://my-kubernetes-root:6443/api/v1/namespaces/my-namespace/persistentvolumeclaims/my-pvc. Message: PersistentVolumeClaim "my-pvc" is invalid: spec: Forbidden: spec is immutable after creation except resources.requests for bound claims
  core.PersistentVolumeClaimSpec{
    AccessModes:      []core.PersistentVolumeAccessMode{"ReadWriteMany"},
    Selector:         nil,
    Resources:        core.ResourceRequirements{Requests: core.ResourceList{s"storage": {i: resource.int64Amount{value: 1073741824}, s: "1Gi", Format: "BinarySI"}}},
-   VolumeName:       "",
+   VolumeName:       "pvc-b79ebfcb-d5cb-4450-9f17-d69ec10b8712",
    StorageClassName: &"my-storage-class",
    VolumeMode:       &"Filesystem",
    DataSource:       nil,
  }

Notice how "volumeName" is not present in the yaml (nil) but in the error message "volumeName" is changing from empty string to the dynamically assigned volumeName.
I can reproduce this exact same behavior using kubectl and empty string for volumeName
I can kubectl apply the following yaml as many times as I like
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  storageClassName: my-storage-class
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi

But if I kubectl apply a yaml with volumeName of empty string it works the first time and fails the second time (The error message is the same as above)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  storageClassName: my-storage-class
  volumeName: ""
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi

How can I get KubernetesClient to behave the same as kubectl apply? Is there any way that I can apply the same PersistentVolumeClaim yaml multiple times with KubernetesClient?

A: As a workaround, I have switched to using a StatefulSet to manage my Pod which allows me to specify volumeClaimTemplates
eg the following yaml can be applied multiple times:
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  selector:
    matchLabels:
      app: nginx
  serviceName: "nginx"
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
        volumeMounts:
        - name: www
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: www
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "my-storage-class"
      resources:
        requests:
          storage: 1Gi

A: Kubernetes API doesn't allow you to change some fields for a certain resource type at a certain state. For a PVC, after its state is Bound, the volumeName field in its spec is immutable; you can't change the volume your PVC is referencing.
When you apply a bare PersistentVolumeClaim manifest like the one in your question (a manifest that has no volumeName key or the value of its volumeName is nil), If the cluster has a default StorageClass, it automatically creates a corresponding PersistentVolume object that's the abstraction of your volume in Kubernetes from the underlying storage provider, then assigns its name to your PersistentVolumeClaim with the volumeName key.
After a PersistentVolumeClaim gets bound to a PersistentVolume and its volumeName field gets populated, you can not edit or patch its volumeName field anymore; that's the reason your kubectl apply command fails for the second time.
It's now clear that a Replace verb is not gonna work for a PVC in Bound state. You can Create one and edit or Patch 'some' of its fields (like increasing the size). I'm not familiar with Java SDK, but it should include some APIs for creating, getting, patching, and deleting a PVC.
You can first check for the existence of your PVC using the GetNamespacedPersistentVolumeClaim API; then, if it's not in the cluster, create it using CreateNamespacedPersistentVolumeClaim API. Referencing the axiom: "Explicit is better than Implicit."

A: I raised this issue on the facric8 kubernetes-client codebase and got an interesting response which may do what I want. Please note that I haven't tried yet since I have a workaround using StatefulSet and volumeClaimTemplates (see my other answer)

The problem is the replace operation. It is not a substitute for apply / patch. Instead of createOrReplace you can use the new support for server side apply

And the relevant section from the link

Server Side Apply Basic usage of server side apply is available via
Patchable. At it's simplest you just need to call:

client.services().withName("name").patch(PatchContext.of(PatchType.SERVER_SIDE_APPLY), service);

For any create or update. This can be a good alternative to
using createOrReplace as it is always a single api call and does not
issue a replace/PUT which can be problematic.
If the resources may be created or modified by something other than a
fabric8 patch, you will need to force your modifications:

client.services().withName("name").patch(new PatchContext.Builder().withPatchType(PatchType.SERVER_SIDE_APPLY).withForce(true).build(), service);


text:
Q: Expected Value of Unreimbursed Accident Loss The question goes as follows:
A three person family purchases an auto insurance policy that reimburse accident losses up to a maximum on 4 accidents per year. The joint probability distribution for the number of accidents of this family $(X,Y,Z)$ is given by
$p(x, y, z)=k(x+y+z)$ where $0\leq x,y,z\leq 3$
Suppose that $X$ is not involved in any accident that year, determine the expected number of unreimbursed accident losses during this same year.
I started off this problem by setting up a triple integral with the respective bounds to find $k$.
Given that $x=0$, and the policy has a maximum of 4, unreimbursed losses occur whenever $y+z$ exceeds 4. Then I simply multiplied each possibility of $y+z$ exceeding 4--namely, $(3,2), (2,3)$, and $(3, 3)$-- by its corresponding probability using the pdf given. However I don't seem to be getting this right. What am I missing here?


text:
Q: How does one configure the Windows 10 Anniversary multiple monitor clock? Windows 10 has recently pushed its Anniversary update (version 1607) which now enables clocks on multiple monitors by default. This has solved a major gripe from multi-monitor users who previously had to use third-party software in order to manage their multiple monitor taskbars.
However, a quick Google search doesn't turn up any configuration options for the clock. There is also no apparent option to show the notification area icons on both monitors.
How would one go about configuring the additional options in the updated Windows 10 taskbars?


text:
Q: django orm multiple filter on same many to many field class Book(models.Model):
    title = models.CharField(max_length=50)
    authors = models.ManyToManyField(Author)

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)

Suppose I want to get books having atleast two author's whose first names are Test and Tester.So I will proceed with Book.objects.filter(authors__first_name='Test').filter(authors__first_name='Tester')
What if I have multiple first name(long list) to check,apart from running a for loop and rawsqlquery are there other options?
queryset = Book,objects.all()
for i in ['test','tester']:
   queryset = queryset.filter(authors__first_name=i)

A: You should filter with:
datas = ['test', tester']
qs = Book.objects.all()
for datum in datas:
    qs = qs.filter(authors__first_name=datum)
But this will not scale well, and furthermore you will retrieve the same book.
What works better is to Count the number of Authors with test or tester as first name:
datas = set(['test', 'tester'])

Book.objects.filter(
    authors__first_name__in=datas
).annotate(
    nauthors=Count('authors')
).filter(nauthors=len(data))
or since django-3.2, we can make use of the .alias(…) [Django-doc] to prevent counting twice (once for the filter, and once for the SELECT clause):
datas = set(['test', 'tester'])

Book.objects.filter(
    authors__first_name__in=datas
).alias(
    nauthors=Count('authors')
).filter(nauthors=len(data))
Here we thus will make one JOIN with the table of the Author model, and simply count the number of authors that match.