text:
Q: Regularized Logistic Regression in Python The code is about a Regularized Logistic Regression and it is fine until the part that I use fmin_bfgs, that is, until the last line of the code. It was originally wrote in Octave, so I tested some values for each function before use fmin_bfgs and all the outputs were correct. The problem is when I try to minimize the cost_function_reg I receive the following message:
 line 53, in cost_function_reg
    thetaR = theta[1:, 0]
IndexError: too many indices for array

Code:
import numpy as np
from scipy.optimize import fmin_bfgs
from math import e

#import data
data = np.loadtxt('D:\ml\ex2data2.txt', delimiter=',')

X = data[:, 0:2]
y = data[:, 2:3]

#   map_feature(x1, x2) maps the two input features
#   to quadratic features used in the regularization exercise.
#
#   Returns a new feature array with more features, comprising of
#   x1, x2, x1.^2, x2.^2, x1*X2, x1*x2.^2, etc..
# Note that mapFeature also adds a column of ones for us, so the intercept
# term is handled
def map_feature(x1, x2):

    x1.shape = (x1.size, 1)
    x2.shape = (x2.size, 1)
    degree = 6
    out = np.ones(shape=(x1[:, 0].size, 1))

    for i in range(1, degree + 1 ):
        for j in range(i + 1):
            r = (x1 ** (i - j)) * (x2 ** j)
            out = np.append(out, r, axis=1)

    return out

# Compute sigmoid function
def sigmoid(X):

    sigmoid = 1.0 / (1.0 + e ** (-1.0 * X))

    return sigmoid

#   Compute cost and gradient for logistic regression with regularization
def cost_function_reg(theta, X, y, l):

    h = sigmoid(X.dot(theta))
    m, n = X.shape
    thetaR = theta[1:, 0]

    epsilon = 1e-5

    J = (1/m) * ((-y.T @ np.log(h+epsilon)) - (1-y).T @ np.log(1-h+epsilon)) + (l / (2 * m)) * (thetaR.T @ thetaR)

    delta = h - y
    grad1 = (1./m)*(delta.T.dot((X[:, 0:1])))

    XR = X[:, 1:]
    sumdelta = delta.T.dot(XR)
    grad2 = (1.0 / m) * (sumdelta + l * thetaR)
    grad2 = grad2.T

    grad = np.zeros(shape=(grad2.shape[0]+1, grad2.shape[1]))

    grad[0]=grad1
    grad[1:]=grad2

    return J.flatten(), grad.flatten()

mf = map_feature(X[:, 0], X[:, 1])

#Initialize theta parameters
initial_theta = np.zeros(shape=(mf.shape[1], 1))

#Set regularization parameter lambda to 1
l = 1

# Compute and display initial cost and gradient for regularized logistic
# regression
cost, grad = cost_function_reg(initial_theta, mf, y, l)
print('Cost at inicial theta: ', cost)
print('\nGrad at inicial theta: ', grad)

def decorated_cost(theta):
    return cost_function_reg(theta, mf, y, l)

fmin_bfgs(decorated_cost, initial_theta, maxiter=400)

Data that I used:
0.051267,0.69956,1
-0.092742,0.68494,1
-0.21371,0.69225,1
-0.375,0.50219,1
-0.51325,0.46564,1
-0.52477,0.2098,1
-0.39804,0.034357,1
-0.30588,-0.19225,1
0.016705,-0.40424,1
0.13191,-0.51389,1
0.38537,-0.56506,1
0.52938,-0.5212,1
0.63882,-0.24342,1
0.73675,-0.18494,1
0.54666,0.48757,1
0.322,0.5826,1
0.16647,0.53874,1
-0.046659,0.81652,1
-0.17339,0.69956,1
-0.47869,0.63377,1
-0.60541,0.59722,1
-0.62846,0.33406,1
-0.59389,0.005117,1
-0.42108,-0.27266,1
-0.11578,-0.39693,1
0.20104,-0.60161,1
0.46601,-0.53582,1
0.67339,-0.53582,1
-0.13882,0.54605,1
-0.29435,0.77997,1
-0.26555,0.96272,1
-0.16187,0.8019,1
-0.17339,0.64839,1
-0.28283,0.47295,1
-0.36348,0.31213,1
-0.30012,0.027047,1
-0.23675,-0.21418,1
-0.06394,-0.18494,1
0.062788,-0.16301,1
0.22984,-0.41155,1
0.2932,-0.2288,1
0.48329,-0.18494,1
0.64459,-0.14108,1
0.46025,0.012427,1
0.6273,0.15863,1
0.57546,0.26827,1
0.72523,0.44371,1
0.22408,0.52412,1
0.44297,0.67032,1
0.322,0.69225,1
0.13767,0.57529,1
-0.0063364,0.39985,1
-0.092742,0.55336,1
-0.20795,0.35599,1
-0.20795,0.17325,1
-0.43836,0.21711,1
-0.21947,-0.016813,1
-0.13882,-0.27266,1
0.18376,0.93348,0
0.22408,0.77997,0
0.29896,0.61915,0
0.50634,0.75804,0
0.61578,0.7288,0
0.60426,0.59722,0
0.76555,0.50219,0
0.92684,0.3633,0
0.82316,0.27558,0
0.96141,0.085526,0
0.93836,0.012427,0
0.86348,-0.082602,0
0.89804,-0.20687,0
0.85196,-0.36769,0
0.82892,-0.5212,0
0.79435,-0.55775,0
0.59274,-0.7405,0
0.51786,-0.5943,0
0.46601,-0.41886,0
0.35081,-0.57968,0
0.28744,-0.76974,0
0.085829,-0.75512,0
0.14919,-0.57968,0
-0.13306,-0.4481,0
-0.40956,-0.41155,0
-0.39228,-0.25804,0
-0.74366,-0.25804,0
-0.69758,0.041667,0
-0.75518,0.2902,0
-0.69758,0.68494,0
-0.4038,0.70687,0
-0.38076,0.91886,0
-0.50749,0.90424,0
-0.54781,0.70687,0
0.10311,0.77997,0
0.057028,0.91886,0
-0.10426,0.99196,0
-0.081221,1.1089,0
0.28744,1.087,0
0.39689,0.82383,0
0.63882,0.88962,0
0.82316,0.66301,0
0.67339,0.64108,0
1.0709,0.10015,0
-0.046659,-0.57968,0
-0.23675,-0.63816,0
-0.15035,-0.36769,0
-0.49021,-0.3019,0
-0.46717,-0.13377,0
-0.28859,-0.060673,0
-0.61118,-0.067982,0
-0.66302,-0.21418,0
-0.59965,-0.41886,0
-0.72638,-0.082602,0
-0.83007,0.31213,0
-0.72062,0.53874,0
-0.59389,0.49488,0
-0.48445,0.99927,0
-0.0063364,0.99927,0
0.63265,-0.030612,0

I am still beggining to learn python so any suggestions are acceptable. Thanks for your attention and I'm sorry for any problem, it's the first time I ask here.

A: Your logic scores better than 80% accuracy! Not shabby. Nicely done. I just had to make a few pythonic edits is all.
I would break it up in Python(computing cost and gradient). It's ok in Matlab/Octave to return the pair...
I took the Coursera Stanford Machine Learning Andrew Ng and did a similar assignment this way:
import scipy.optimize as op
import numpy as np
from pylab import scatter, show, legend, xlabel, ylabel
from numpy import where
from sklearn.preprocessing import PolynomialFeatures

def sigmoid(z):
    return 1/(1 + np.exp(-z))

def compute_gradient(theta, X, y, l):
    m, n = X.shape
    theta = theta.reshape((n, 1))
    theta_r = theta[1:n, :]
    y = y.reshape((m, 1))
    h = sigmoid(X.dot(theta))
    non_regularized_gradient = ((np.sum(((h-y)*X), axis=0))/m).reshape(n, 1)
    reg = np.insert((l/m)*theta_r, 0, 0, axis=0)
    grad = non_regularized_gradient + reg
    return grad.flatten()

def compute_cost(theta, X, y, l):
    h = sigmoid(X.dot(theta))
    m, n = X.shape
    theta = theta.reshape((n, 1))
    theta_r = theta[1:n, :]
    cost = np.sum((np.multiply(-y,np.log(h))-np.multiply((1-y),np.log(1-h))))/m
    reg=(l/(2*m)) * np.sum(np.square(theta_r))
    J = cost + reg
    return J

def make_predictions(theta,X):
    m, n = X.shape
    return np.round(sigmoid(X.dot(theta.reshape(n, 1))))

data = np.loadtxt(open("ex2data2.txt", "rb"), delimiter=",", skiprows=1)
nr, nc = data.shape
X = data[:, 0:nc - 1]
y = data[:, [nc - 1]]
pos = where(y == 1)
neg = where(y == 0)
scatter(X[pos, 0], X[pos, 1], marker='o', c='b')
scatter(X[neg, 0], X[neg, 1], marker='x', c='r')
xlabel('Equipment Test 1')
ylabel('Eguipment Test 2')
legend(['Nominal', 'Adverse'])
show()
storeX = X
poly = PolynomialFeatures(6)
X = poly.fit_transform(X)
m, n = X.shape
initial_theta = np.zeros((n, 1))
l = 1

print("Optimizing...")
Result = op.minimize(fun=compute_cost, x0=initial_theta, args=(X, y, l), method='TNC', jac=compute_gradient)
optimal_theta = Result.x
print(Result.x.shape)
print("optimal theta value")
print(optimal_theta)
p = make_predictions(optimal_theta, X)
score = np.mean(np.double(p == y))
print("Score:")
print(score)

Here's the output in PyCharm Community, Python version 3.7.3:

A: You should check out this answer.
You should try to print theta array to see which values it actually holds and what are its dimensions. The type of error you get suggests that it does not have that many dimensions.


text:
Q: show django messages inside form_invalid of FormView How can i show a message when using FormView class when form is invalid? I could show the message in form_valid function but no idea on form_invalid as i am using self.get_context_data.
This is what i have done to show message when the form is valid
def form_valid(self, form):
    messages.success(self.request, '{0} added successfully'.format(name))
    return HttpResponseRedirect('/')

How can i use message here?
def form_invalid(self, form):
    return self.render_to_response(self.get_context_data(form=form))

A: Maybe like this one;
def form_invalid(self, form):
    name = 'john'
    messages.warning(self.request, '{0} error'.format(name))

    return self.render_to_response(
        self.get_context_data(request=self.request, form=form))

Explanation:
messages.warning(self.request, '{0} error'.format(name)) put before self.render_to_response(**kwargs), why? this for updating your self.request with your message.
and self.render_to_response(**kwargs) is using **kwargs parameters.
one of it for the form and request fields. see this docs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get all button types of a window? Is possible to retrieve all button types of a window?
I'm trying to written a function like this:
...

for (const auto* but : list)
{
    qDebug() << "   " << but->objectName();

    if (QToolButton* tbn = qobject_cast<QToolButton*>(but))
    {
        connect(but, SIGNAL(pressed()), this, SLOT(toolButton_pressed()));
        connect(but, SIGNAL(released()), this, SLOT(toolButton_released()));
    }
    else if (QPushButton* pbn = qobject_cast<QPushButton*>(but))
    {
        connect(but, SIGNAL(pressed()), this, SLOT(pushButton_pressed()));
        connect(but, SIGNAL(released()), this, SLOT(pushButton_released()));
    }
}

I know only how to get a specific button type:
QList<QToolButton*> list = this->findChildren<QToolButton*>();


text:
Q: Passing array of strings as character pointers I have been trying to pass an array of string to a function. Although i know of other processes of doing it, i specifically want to know exactly why this particular code isn't working
I have tried in the following manner
#include<stdio.h>

void check_number(char* str[])
{
    int sum=0;
    int i=0;
    while(str[0][i]!='/0')
    {
        char a='a';
        sum=sum+str[0][i]-(int)(a);
    }
    printf("number = %d ",sum);
}

int main()
{
    char* str[2];
    printf("Enter a string ");
    scanf("%s",str[0]);

    printf("Enter a string ");
    scanf("%s",str[1]);

    check_number(str);
    return 0;
}

A: This is one of the issue in the posted code, here
char* str[2];

str is array of two character pointer i.e str[0] and str[1] are character pointers i.e they need to initialize with valid address but you haven't allocated memory for them.
scanf("%s",str[0]); /* No memory allocated for str[0] */
scanf("%s",str[1]); /* No memory allocated for str[1] */

You need to allocate memory for str[0] & str[1] before scanning data into it. for e.g
int main(void)
{
    char* str[2];
    for(int i = 0; i < 2 ; i++) {
        printf("Enter a string ");
        str[i] = malloc(MAX_BUF_SIZE); /*define this macro for no of bytes */
        scanf("%s",str[i]);
    }
    /* do some stuff */
    /* free dynamically allocated memory for each str[index] */
    return 0;
}

Another problem is here
while(str[0][i]!='\0') { /* '/0' --> '\0' */
    char a='a';
    sum=sum+str[0][i]-(int)(a); /* what you want to achieve here, please explain */
}

when this loop is going to terminate ? There should be a loop terminating condition else it will loop infinitely.

A: This line:
char* str[2];

declares an array of 2 pointers to char, but the pointers do not point to valid memory. You need to reserve/allocate some space somewhere.
One possible solution is to simply have two independent buffers in the stack:
const size_t bufferSize = 100;
char str1[bufferSize];
char str2[bufferSize];


text:
Q: Рекурсия, запускаемая в цикле Вот ссылка http://jsfiddle.net/92F94/
Вот код:

function lol(iter, depth){
    alert("Из итерации "+iter+", Глубина "+depth)
    if(depth<5){
        for(i=0;i<3;i++){
            lol(i,depth+1);
        }
    }
}
lol(0,0);

Я ожидаю, что в первом вызове функции она три раза вызовется в цикле, потом в каждый из этих вывозов ещё три раза, и ещё и ещё, итого у меня получится 3^5 вызовов. На деле же получилось, что она отрабатывает только 7 раз (Считаю без первого вызова). Почему так? Это я что-то делаю не так, или это баг/фича языка?
A: Разобрался сам.
Товарищи, не повторяйте моих ошибок, не забывайте var!
for(var i=0;i<3;i++){


text:
Q: How should I make these commands work where we take a variable on the python program to execute a command in MySQL? This is a bank management system. where acc_id the account I want to delete from a MySQL Table BANK I have already connected python to mysql but this code dosen't work. Is there any alternative to .format ?
if choice == 2:
    acc_id = int(input("ENTER ACCOUNT NUMBER TO DELETE:"))
    cursor = mydb.cursor()
    cmd2 = "DELETE FROM BANK WHERE ACC_NO = {}".format(acc_id)
    cursor.execute(cmd2)

A: user_input = raw_input("Required Data")

cursor.execute("DELETE FROM BANK WHERE ACC_NO = %s", (user_input))

Hopefully, this will help you to solve your problem.


text:
Q: Generating Google Analytics from a C# Application I would like to be able to generate Google analytics data that will show me number of startups of my application but also the time it tool for each starup and the average time for all startups.  Something like:
Startups      1296

Startup Times
40ms
27ms
128ms
700ms
42ms
82ms
...
...
127ms (Average)

I know it is possible to get the Startups but not sure if it is possible to also get Startup Times.  Is it possible to do this and how from a C# desktop application?

A: I am developing a lib called gappalytics, it allows you to log analytics events for desktop apps. Link to package nuget.org/Gappalytics.
Usage sample: github.org/gapalytics

A: As long as you can sent http request in realtime (or a narrowly defined offset window) you can use the measurement protocol. I don't think there is a C# client library, but this is basically just a http request with the parameters and and such its language agnostic.
There are a few required parameters - the protocol version (always v1 for now), Google Account ID, a unique Client ID per user or device and a hit type (pageview, screen, event, transaction etc.). Also depending on the hit type you need additional parameters (document location/page title, event category/action/label etc.).
There is a parameter reference with all possible fields, and you can construct hits for testing via the hit builder.
Google Analytics has a "user timings" hit type (basically you pass a description and a duration in microseconds), so the report from your example should be very easily doable.
I don't know C#, but I'm reasonably certain is has a way to format a string as an url with parameters and send an http request, and in the end that's really all you need for data collection with GA.


text:
Q: Angular Material 2 Spinner with Angular 4 With the help of existing angular material tutorial on coursetro, I was able to try http and subscribe scenarios with Angular 4 & Angular Material controls. As i was fetching all the photos at first place I see a lag in UI. Hence I've thought of implementing Spinner which gives impression of loading of data md-progress-spinner, but for some reason spinner doesn't show up & moreover I don't see any console logs too, Could you please advise?
spinner.service.ts:
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class SpinnerService {
    public status: Subject<boolean> = new Subject();
    private _active: boolean = false;

    public get active(): boolean {
        return this._active;
    }

    public set active(v: boolean) {
        this._active = v;
        this.status.next(v);
    }

    public start(): void {
        this.active = true;
    }

    public stop(): void {
        this.active = false;
    }
}

app.module.ts:
@NgModule({
    declarations: [
        AppComponent,
        SpinnerComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        BrowserAnimationsModule,
        MdButtonModule,
        MdMenuModule,
        MdCardModule,
        MdToolbarModule,
        MdIconModule,
        MdProgressSpinnerModule
    ],
    providers: [SpinnerService],
    bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    myData: Array<any>;

    constructor(private http:Http,private spinner: SpinnerService) {
        this.spinner.start();
        this.http.get('https://jsonplaceholder.typicode.com/photos')
                 .map(response => response.json())
                 .subscribe(res => this.myData = res,
                            error => console.error(error),
                            () => this.spinner.stop()
                           );
     }
}

app.component.html:
<app-spinner>Spinning...</app-spinner>

<md-toolbar color="primary">

    MyCompany

    <button md-button [mdMenuTriggerFor]="appMenu"><md-icon>menu</md-icon> Menu</button>

</md-toolbar>

<md-menu #appMenu="mdMenu">
    <button md-menu-item> Settings </button>
    <button md-menu-item> Help </button>
</md-menu>

<md-card class="example-card" *ngFor="let data of myData; let i = index">

    <md-card-header>
        <md-card-title>{{ data.title }}</md-card-title>
    </md-card-header>

    <md-card-actions>
        <button md-button>LIKE</button>
        <button md-button>SHARE</button>
    </md-card-actions>
</md-card>

spinner.component.ts:
 @Component({
     selector: 'app-spinner',
     templateUrl: './spinner.component.html',
     styleUrls: ['./spinner.component.css']
 })
 export class SpinnerComponent implements OnInit, OnDestroy {

     public active: boolean;

     public constructor(private spinner: SpinnerService) {
         spinner.status.subscribe((status: boolean) => {
             this.active = status;
         });
     }

     ngOnInit(){
         this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
     }

     ngOnDestroy(){
         this.spinner.start();
     }

 }

spinner.component.html:

     <md-progress-spinner mode="indeterminate"></md-progress-spinner>

Please check if I've made any errors in loading the spinner and my vision is to have this spinner used across multiple components within multiple subscribing calls by having the app-spinner selector mentioned in only app.component.html, could you please advise if above approach holds good & any changes required?

A: You can do something like this  :
Create a service with an event Emmitter
   import { Injectable , EventEmitter } from '@angular/core';

   @Injectable()
   export class SpinnerService {
   public spinnerActive: EventEmitter<Boolean>;
   constructor() {
   this.spinnerActive = new EventEmitter();

   }

   activate(){
   this.spinnerActive.emit(true)
   }

   deactivate(){
   this.spinnerActive.emit(false)
   }

}

In your app.component.ts
    constructor(private http: Http , private spinnerService : SpinnerService){
     this.spinnerService.spinnerActive.subscribe(active =>
     this.toggleSpinner(active));
     }
    toggleSpinner(active){
      console.log("inside Toggle Spinner")
      this.activeSpinner = active
    }

And your activeSpinner could be used like this in your template :
<md-spinner *ngIf="activeSpinner"></md-spinner>
Activate and deactivate your spinner via activate and deactivate service methods.
For this to work from anywhere , make sure your spinner is elavated (z-index) and position fixed so that the spinner comes on top of everything that has been rendered above it (if ever).

A: Instead of different methods, have a variable which is directly set from the component where you want to implement the spinner . So for example
Your spinner.ts
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-loader',
  templateUrl: './loader.component.html',
  styleUrls: ['./loader.component.css']
})
export class LoaderComponent{
  @Input() show:boolean;
}

HTML :

      <md-spinner></md-spinner>

Component where you would like to use your spinner.
<app-loader [show]="showLoader">

  </app-loader>

And in your TS just set the value of showLoader to true/false.

A: I got the spinner elements in the DOM, but I couldn't see it, this is the way I solved:
In html component:
<mat-progress-spinner mode="indeterminate" [diameter]="28"></mat-progress-spinner>

In app.module.ts:
import { MatProgressSpinnerModule } from '@angular/material';
@NgModule({
  imports: [
    MatProgressSpinnerModule],
  exports: [
    MatProgressSpinnerModule
  ]

and in style.css:
@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';


text:
Q: Why is my OpenVPN Client not connecting to the server? Amazon EC2 Windows I have been trying to set up OpenVPN on an Amazon EC2 instance running Windows 2008 SQL Server. After following several tutorials, I have been able to get the server running. Here is my server conf file:
## server.ovpn ##

port 1194

proto udp

dev tun

ca xxxx.crt

cert xxxx.crt

key xxxx.key

dh dh2048.pem

server 10.8.0.0 255.255.255.0

ifconfig-pool-persist ipp.txt

keepalive 10 120

comp-lzo

max-clients 100

persist-key

persist-tun

status openvpn-status.log

verb 3

But when setting up the client side, the connection times out giving the following error:
TLS key negotiation failed to occur within 60 seconds (check your network connectivity)
I have tried a TCP connection instead to no avail, and I opened the 1194 port on the EC2 firewall. Both internally and on the security settings of the EC2 instance.
The OpenVPN HOWTO says to make sure I am are using a correct port forward rule on the server's gateway firewall. But I am not sure what that means exactly.
Thanks in advance. I will post my client conf file as well just in case.
client

dev tun

proto udp

remote "Amazon instance Elastic IP" 1194

resolv-retry infinite

nobind

persist-key

persist-tun

ca xxxx.crt

cert xxxx.crt

key xxxx.key

ns-cert-type server

comp-lzo

verb 3

A: You can ignore the thing about port forwarding.  That's in a situation where you have the OpenVPN server behind some sort of router.  In that case, you'll have to forward 1194/udp traffic to the server.
Can you make sure the clocks on both machines are in sync?
The other thing would be to double check the EC2 Security Groups to make sure you're allowing incoming 1194/udp traffic.


text:
Q: Script only loading directly after clearing the cache, but cant get found after second reload I am using the extension Aheadworks_Wbtab. I don't know whats going on. If I flush the cache and reload then the slider shows and works fine. But if I reload again, then the slider dissapears and I get this error logged in my browser console:

mixins.js:245 GET
  https://www.example.com/pub/static/version1584092638/frontend/company/base/de_DE/Aheadworks_Wbtab/js/aw-wbtab-ajax.js
  net::ERR_ABORTED 404 req.load @ require.js:1895 ... Show 268 more
  frames
main.js:37 Error: Script error for: Aheadworks_Wbtab/js/aw-wbtab-ajax
  http://requirejs.org/docs/errors.html#scripterror
      at makeError (require.js:166)
      at HTMLScriptElement.onScriptError (require.js:1681)

So I checked if the file was created in pub/static and it is there (as a symlink):

pub/static/frontend/company/base/de_DE/Aheadworks_Wbtab/js/aw-wbtab-ajax.js
  -> /home/company/example.com/vendor/aheadworks/module-wbtab/view/frontend/web/js/aw-wbtab-ajax.js

I also opened the file and it has content.
How can I fix it and what causes the bug?
Only this extension from Aheadworks causes this bug, all other extensions from Amasty work fine.

A: I executed "grunt clean" and flushed the cache again. Now it seems to work suddenly.


text:
Q: Exclude hash value and match ID Sorry not sure how to ask this question but I'm trying to match a ID with a image file, however the file names are formatted as:
6993b22905d7a4dae0f6e5ff1212a47c-5.jpeg

5 been the ID, so how would I exclude the hash value, the - symbol and display the image using the unique ID instead?
<img src="images/uploads/6993b22905d7a4dae0f6e5ff1212a47c-5.jpeg"

I would like to have something like:
<img src="images/uploads/."IGNOREHASH-".$ID.jpeg"

A: Just split the string on period and then on hyphen and get the last instance:
str.split('.')[0].split('-').pop();

FIDDLE
or in PHP, get the content between the hyphen and the period:
preg_match('/\-(.*?)\./',$str, $match);

A: Asuming that every image name follows the same format:
function getImageId($imageHashedName) {
     return substr($imageHashedName, strrpos($imageHashedName, '-') + 1)
}

(Sorry if the syntax is wrong, my PHP is a little bit rusty.)
You would use it in the following way:
"<img src='images/uploads/".getImageId($imageName).".jpeg"


text:
Q: SQL Server 2005 Express: upgrading to SP3 in mixed-mode installations I'm having trouble upgrading SQL Server 2005 Express SP1 to SP3.
The SP1 install uses mixed mode authentication (so there is an sa password).
This is the message I get:
TITLE: Microsoft SQL Server Setup
------------------------------
None of the selected features can be installed or upgraded. Setup cannot proceed since no effective change is being made to the machine. To continue, click Back and then select features to install. To exit SQL Server Setup, click Cancel.

For help, click: http://go.microsoft.com/fwlink?LinkID=20476&ProdName=Microsoft+SQL+Server&ProdVer=9.00.4035.00&EvtSrc=setup.rll&EvtID=SQLSetup90&EvtType=28108
------------------------------
BUTTONS: OK
------------------------------

The link then tells me To continue you must provide a strong sa password.
I tried some searching, and found something about BPAClient.dll, but this batch-file does not fix it:
mkdir "%ProgramFiles%\Microsoft SQL Server\90\Setup Bootstrap\BPA\BPAClient"
copy "%ProgramFiles%\Microsoft SQL Server\90\Setup Bootstrap\BPA\bin\BPAClient.dll" "%ProgramFiles%\Microsoft SQL Server\90\Setup Bootstrap\BPA\BPAClient\"

I also tried this, but that didn't help either (probably because the services had been started at least once before trying the update).
So I think the clue is the strong in the link above.
Am I on the right track?
Where do I find more information on the strongness of an sa password?
Duh - that was in the above link. Just didn't read well enough.
So I changed the sa password to something strong (Upper and lower case letters, special signs, at least 6 characters).
Rebooted, restarted SP3 install: still fails.

A: Resolved; the last link about SBS installation guide I mentioned above also had this somewhere in the middle:

Didn't think about it until I downlaoded the SP3 and ran it that it is the FULL install with SP3. DUH!

So this is how I upgraded from SQL Server Express 2005 SP1 to SP3:

*

*Uninstall SQL Server Express 2005 SP1

*Install the SQL Server Express 2005 SP3 (which now acts as a new install)

Simple but effective :-)
--jeroen


text:
Q: Google Map API v3 multiple marker with labels/text I found a solution on placing label/text on the google map marker. Which is found in this link http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.8/docs/reference.html
My problem is the markers are placed in one place. But the label/text on each marker is placed on the correct points. Can anyone help me?
The code below is inside a $.each() jQuery function for looping.
geocoder.geocode( { 'address': address }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var contentString = "sample text";

        var infowindow = new google.maps.InfoWindow({
            content: contentString;
        });

        var marker = new MarkerWithLabel({
            position: results[0].geometry.location,
            map: map,
            animation: google.maps.Animation.DROP,
            title: address,
            labelContent: lblAddress,
            labelAnchor: new google.maps.Point(7, 30),
            labelClass: "map-labels", // the CSS class for the marker
        });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, this);
        });
}

The image above shows the markers of two different points is shown in one place. I'm sure about it because when I click the label "18107 Gold Mesa" a infowindow will open, but the infowindow will show on the "3611 Alonzo Fields". There are two markers on that point.
But when I don't used the 3rd party library. The markers are placed on the correct points. using the google map method on placing markers. new google.maps.Marker
Thanks,
Justin

A: use infowindow.open(map, marker);
instead of
infowindow.open(map, this);
I guess this will show your popup near the label only and your may find some substantial reason for markers not showing up


text:
Q: How to implement Restful Webservice using C++ Are there any helpful c++ libraries which can support me, implementing a simple REST webservice?
I am not searching for a bloated webservice framework like c++ REST SDK, or something like that. I already have a HTTP server running which can handle HTTP calls. (especially the HTTP server from the poco libraries).
I guess it should be not too hard to implement a Restful webservice interface around that.
But my question is, do i have to implement it on my own (how would you implement it?) or can I still make use of some libraries? So I am searchin for a library that can actually help me processing rest requests.
kind regards


text:
Q: How to get check particular checkboxes by default based on some values in angular 7 I have a checkboxes and selectbox whose values are coming from loop,but here I need to get some checkboxes checked by default based on an array of object.Here checkbox and selectbox value is coming from usersg and usersr variable.But the checked and selected by default should be from variable usersg_checked and usersr_selected inside ngOnInit(). Here is the code below
home.component.html

<input type="checkbox" checked="checked.id" value="{{group.id}}" />{{group.name}}

<select><option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option></select>

home.component.html
import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

    submitted = false;
    usersg_checked:any;
    usersr_selected:any;

 constructor(private formBuilder: FormBuilder) {

     }
public usersg = [{"id":1,"name":"test1"},{"id":2,"name":"test2"},{"id":3,"name":"test3"},{"id":4,"name":"test4"}];

public usersr = [{"id":1,"name":"test1"},{"id":2,"name":"test2"}];

  ngOnInit() {
this.usersg_checked = [{"id":1,"name":"test1"},{"id":2,"name":"test2"}];

this.usersr_selected = [{"id":1,"name":"test1"}];

  }

}

A: Add isChecked() method in component to check if a checkbox must be selected.
Component:
isChecked(id) {
  return this.usersg_checked.some(item => item.id === id);
}

Template:

  <input type="checkbox" [checked]="isChecked(group.id)" value="{{group.id}}" />{{group.name}}

For <select> elements better to use [(ngModel)].
Template:

<select [(ngModel)]="usersr_selected.id">
   <option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option>
</select>

Component:
And change usersr_selected to an object.
ngOnInit() {
  this.usersr_selected = {"id":1,"name":"test1"};
}

If usersr_selected is an array, use the first element of the array as NgModel.
ngOnInit() {
  this.usersr_selected = this.usersr_selected[0];
}


text:
Q: Android - gradle/maven dependency management scope As in topic what are the working differences and issues connected with following scopes while working in eclipse/android studio in java/android platform with those dependency types:

Regards


text:
Q: Will I Lose Completed Mission Progress When Mass Retreating? If I mass-retreat after completing a secondary mission, do I lose any progress from that mission? The popup isn't clear...

A: No, you will not lose mission progress once you complete the mission.
(I did this after one of the story missions, though I'm sure this would work for secondary missions too)


text:
Q: JNDI connection pool I am currently working on java project which is based on struts and tomcat 7.Now due to memory reasons I am planning to convert the project from using normal JDBC/ODBC connections to JNDI connection pooling.Am kind of stuck here.What are the basic changes that I should make in the code as part of this conversion.Should I change the configuration of tomcat?Is there any jars that needed to be added?

A: Apache Tomcat 7 has a robust connection pool implementation and provides a really good documentation. It will guide you through the configuration changes you need to make in Tomcat and/or in your application. There are also code examples.


text:
Q: How to solve for delimter conflicts I have a large .TXT file which is delimited by ";". Unfortunately some of my values contain ";" aswell, which in that case is not a delimiter but recognized as delimiter by pandas. Becasue of this I have difficulties reading the .txt. files into pandas because some lines have more columns than the others. Background: I am trying to combine several .txt files into 1 dataframe and get the following error: ParserError: Error tokenizing data. C error: Expected 21 fields in line 443, saw 22.
So when checking line 443 I saw indeed that that line had 1 more instance of ";" because it was part of one of the values.
Reproduction:
Text file 1:
1;2;3;4
23123213;23123213;23123213;23123213
123;123;123;123
123;123;123;123
1;1;1;1
123;123;123;123
12;12;12;12
3;3;3;3

Text file 2:
1;2;3;4
23123213;23123213;23123213;23123213
123;123;123;123
123;123;12;3;123
1;1;1;1
123;123;123;123
12;12;12;12
3;3;3;3

Code:
import pandas as pd
import glob
import os

path = r'C:\Users\file'
all_files = glob.glob(path + "/*.txt")
li = []
for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0, delimiter=';')
    li.append(df)
frame = pd.concat(li, axis=0, ignore_index=True)


text:
Q: browser network tab resource limit I do not speak English well. Understand me.
I have a question. For resources on the Network tab,.
During the test, if the transferred and resources shown in the picture exceed 50GB, the network err is displayed. No more response can be received.
Please let me know if there is any documentation on this. I can't find
Thanks in advance.

A: Try below. Network.setDataSizeLimitsForTest argument could work for your needs.
Resource


text:
Q: How do Chrome knows when to prompt a user with a direct download prompt? Any link or reference to understand when Chrome shows the direct download prompt to the user?
From what I've tested, some Content-Type headers initiate a direct download.
But there is also the Content-Disposition header, which is used when it is set to attachment;


text:
Q: Why Unicode subscript symbol is not properly displayed in C# Label? I have a C# Label and I set the text to the String "CO\u2082" (CO2 with the Unicode subscript) .
The label is displayed properly on my PC which runs Windows XP service pack 3, but not displayed properly on a PC with Windows XP service pack2.
m_labelDescCO2 = new System.Windows.Forms.Label();
m_labelDescCO2.Text = "CO\u2082";

The Label font is defined to be Microsoft Sans Serif.
Thanks for any advice!

A: It's possible that the font that you've selected doesn't support Unicode subscript characters on XP service pack 2.
Have a look here for some information regarding Unicode support.
I think that you'll have to check for a different font.

A: I also think it's a font problem.
It doesn't work with MS Sans and Verdana, it does work with Arial Unicode MS

A: Hi I found the answer here.  Some fonts do not have superscript or subscript support in other operating systems. The "Character Map" program in Windows is a good point to start figuring out.


text:
Q: Why I get wrong forecast values python-weka wrapper I would like to predict data using the python-weka-wrapper in Jupyter Notebook, however, I just get the error but not the given prediction. This is a sample of my data:
@relation data_new3

@attribute pos_x numeric
@attribute pos_y numeric
@attribute angle numeric
@attribute vel numeric
@attribute vel_x numeric
@attribute vel_y numeric

@data
414049364,21773560,75.06043,16.775027,15.827037,-5.559355
414049656,21773926,43.232657,4.452031,3.258594,-3.033504
414049938,21774287,43.836066,4.347145,4.300749,-0.633426
414050204,21774638,44.704315,4.157368,3.119995,2.747606

When I run this data on Weka using the Forecast tab (selecting pos_x and pos_y as variables to predict) y get a valid prediction (linear regression). However, when I'm trying to build it on python to automatize the process, the results are far from expected.
This is my current code:
import weka.core.jvm as jvm
import weka.core.converters as conv
from weka.classifiers import Evaluation, Classifier
from weka.core.classes import Random
import weka.plot.classifiers as plcls
df = conv.load_any_file("data_new3.arff")
df.class_is_last()

cls = Classifier(classname="weka.classifiers.functions.LinearRegression", options=["-C","-S","1"])
evl = Evaluation(df)
evl.crossvalidate_model(cls, df, 10, Random(1))
plcls.plot_classifier_errors(evl.predictions, absolute=False, wait=True)

I would like to get n number of predictions (forecast).
Below the result of the above code. However, I would like data not error.
evl.predictions content:
[NUM: 2.341519980578598 -0.46169578717854165 1.0,
 NUM: 0.0324593108656498 -1.250148004408402 1.0,
 NUM: 1.0894596695042125 -0.19638227888390247 1.0,
 NUM: 2.2415137801101532 0.21523000008892268 1.0,
 NUM: 0.8403094260947848 1.4159336571192398 1.0,
 NUM: -0.6246802557143522 0.02694804349266633 1.0,
 NUM: -1.1291083174467442 -0.9771784825188661 1.0,
 NUM: 1.9865123314290711 0.0020180962164886296 1.0,
 NUM: -1.4171054579203468 -0.1185322656565404 1.0,
 NUM: 1.701392413210111 -0.31173498990392545 1.0,
 NUM: 0.9142204697441169 -0.46289838829034125 1.0,
 NUM: 2.2371544887471027 0.26863408847202663 1.0,
 NUM: 1.0104945457853498 0.08266907560209802 1.0,
 NUM: -2.1844092184524277 0.2537549599419435 1.0,
 NUM: -1.64486932964462 -0.0757717380165559 1.0,
 NUM: -0.8833185855520697 0.272053514894651 1.0,
 NUM: 2.023258402624002 0.20075652151535905 1.0,
 NUM: -0.09766261800428815 -0.13010619249325828 1.0,
 NUM: 0.008614470166021827 -2.0206928075313044 1.0,
 NUM: -0.3746145438554381 0.2627094869476423 1.0,
 NUM: 0.321292162562831 -0.39300510611246864 1.0,
 NUM: -0.8603272578575111 -0.24401632088301994 1.0,
 NUM: 1.2917808082313293 0.27398191955035145 1.0,
 NUM: 2.5069928462982736 -0.28666784299093706 1.0,
 NUM: 0.5342954034915244 0.023908866474812385 1.0,
 NUM: -0.8199944215138957 -0.35662294870599 1.0,
 NUM: 1.5190967129296846 -0.494692957136067 1.0,
 NUM: 2.1750768892884005 0.17687020938865317 1.0,
 NUM: -1.3129196874730458 -0.4337196896722162 1.0,
 NUM: 0.9085960948511023 -1.0273595147173182 1.0,
 NUM: -1.790840080776049 -0.7976173866791214 1.0,
 NUM: 0.6226362259069361 0.8034413426921674 1.0,
 NUM: -1.6641718286913476 0.1441503225123597 1.0,
 NUM: 0.9671958169480396 0.4460301975123002 1.0,
 NUM: -0.0762479157090975 -0.014214109052772983 1.0,
 NUM: 0.1274295194870555 -0.7136733953120711 1.0,

What I'm doing wrong? I cannot find the right function in https://fracpete.github.io/python-weka-wrapper3/weka.html

A: Forecasting (i.e., predicting the next point in a timeseries) is different from a single point prediction. The former is available through Weka's timeseriesForecasting package and the Forecast tab in the Weka Explorer. The latter is what classifiers normally do and is available through the Classify tab in the Weka Explorer.
The Forecast tab wraps the actual base classifier in a WekaForecaster instance (which is not a classifier but a forecaster!) and also transforms the data using the TSLagMaker filter internally.
Up till now, the python-weka-wrapper3 library had no support for forecasting.
With the new release 0.2.0 a new module got introduced: weka.timeseries. This new module wraps the essential classes of the timeseriesForecasting package.
Some pointers:

*

*API documentation

*code examples (1, 2, 3)


text:
Q: Magento 2 - Store View redirects to main domain I am running magento 2 in a VM on apache2.
I created a new store view for another language of our shop.
Main domain: company.com
Storeview subdomain: de.company.com
Problem:
If I go to "http://de.company.com" then I get redirected to http://company.com.

I deleted all cookies and flushed the magento cache.

A: 1)Go to Admin CMS Configuration->General->Web->Url Options and store settings like followings:

A: 1)app/etc/frontend/events.xml :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch">
        <observer name="force_storecode_redirect" instance="Vendor\Module\Observer\ForceStorecodeRedirectObserver" shared="false" />
    </event>
</config>

2)Observer/ForceStorecodeRedirectObserver.php
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;

class ForceStorecodeRedirectObserver implements ObserverInterface
{
    protected $storeManager;
    protected $url;
    /** @var string $defaultStorecode */
    protected $defaultStorecode = 'es';
    /** @var array $storeCodes - array of existing storecodes*/
    protected $storeCodes = [];

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\UrlInterface $url
    ) {
       $this->storeManager = $storeManager;
       $this->url = $url;
       $this->storeCodes = array_keys($this->storeManager->getStores(false, true));
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
         $urlParts = parse_url($this->url->getCurrentUrl());
         $path = $urlParts['path'];

         // get storecode from URL
         $urlCode = trim(substr($path, 0, 4), '/');

         // If path does not already contain an existing storecode
         if (!in_array($urlCode, $this->storeCodes)) {
             $path = ltrim($path, '/');
             if ($path == 'en') {
                 $path = '';
             }

             // Redirect to URL including storecode
             header("HTTP/1.1 301 Moved Permanently");
             header("Location: " . $this->storeManager->getStore()->getBaseUrl() . $path);
             exit();
       }
    }
}


text:
Q: Android 3d flip animation I am using eclipes the create an android card game.For some reason my application crashes when i call the animation. One change i had to make was in the Flip Class and that was changing the layoutview to imageview because in the animation method "createDisplayNextView" had an error.
////////ANIMATION
    private ImageView FrontView;
    private ImageView BackView;
    private boolean isFirstImage = true;
private void applyRotation(float start, float end) {
    // Find the center of image

    FrontView = (ImageView) findViewById(R.id.imgC1);
    BackView = (ImageView) findViewById(R.drawable.clubs2);
    BackView.setVisibility(View.GONE);

    final float centerX = FrontView.getWidth() / 2.0f;
    final float centerY = FrontView.getHeight() / 2.0f;

    // Create a new 3D rotation with the supplied parameter
    // The animation listener is used to trigger the next animation
    final cardFlip rotation =  new cardFlip(start, end, centerX, centerY);
    rotation.setDuration(500);
    rotation.setFillAfter(true);
    rotation.setInterpolator(new AccelerateInterpolator());
    rotation.setAnimationListener(rotation.createDisplayNextView(isFirstImage, FrontView, BackView));

    if (isFirstImage) {
        FrontView.startAnimation(rotation);
    } else {
        BackView.startAnimation(rotation);
    }
}

///////////////

This is the Flip class:
////////////////FLIP CLASS//////////////

    import android.graphics.Camera;
    import android.graphics.Matrix;
    import android.view.View;
    import android.view.animation.Animation;
    import android.view.animation.DecelerateInterpolator;
    import android.view.animation.Transformation;
    import android.widget.ImageView;
    import android.widget.LinearLayout;

    public class cardFlip  extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private Camera mCamera;

    public cardFlip(float fromDegrees, float toDegrees, float centerX, float centerY) {
mFromDegrees = fromDegrees;
mToDegrees = toDegrees;
mCenterX = centerX;
mCenterY = centerY;
    }
    public DisplayNextView createDisplayNextView (boolean isFirstImage, ImageView         llFrontView, ImageView llBackView)
    {
        return new DisplayNextView(isFirstImage,llFrontView, llBackView);
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();
        camera.save();
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);

    }
        public final class DisplayNextView implements Animation.AnimationListener {
            private boolean mCurrentView;
            ImageView image1;
            ImageView image2;

            public DisplayNextView(boolean currentView, ImageView llFrontView, ImageView llBackView) {
                mCurrentView = currentView;
                this.image1 = llFrontView;
                this.image2 = llBackView;
            }

    public void onAnimationStart(Animation animation) {
    }

    public void onAnimationEnd(Animation animation) {
        image1.post(new SwapViews(mCurrentView, image1, image2));
    }

    public void onAnimationRepeat(Animation animation) {
    }

    public final class SwapViews implements Runnable {
        private boolean mIsFirstView;
        ImageView image1;
        ImageView image2;

    public SwapViews(boolean isFirstView, ImageView image12, ImageView image22) {
         mIsFirstView = isFirstView;
         this.image1 = image12;
         this.image2 = image22;
    }

    public void run() {
         final float centerX = image1.getWidth() / 2.0f;
         final float centerY = image1.getHeight() / 2.0f;
         cardFlip rotation;

         if (mIsFirstView) {
          image1.setVisibility(View.GONE);
          image2.setVisibility(View.VISIBLE);
          image2.requestFocus();

             rotation = new cardFlip(90, 0, centerX, centerY);
         } else {
          image2.setVisibility(View.GONE);
          image1.setVisibility(View.VISIBLE);
          image1.requestFocus();

             rotation = new cardFlip(-90, 0, centerX, centerY);
         }

         rotation.setDuration(500);
         rotation.setFillAfter(true);
         rotation.setInterpolator(new DecelerateInterpolator());

         if (mIsFirstView) {
             image2.startAnimation(rotation);
         } else {
             image1.startAnimation(rotation);
         }
    }
}
    }

    }

A: You can try this ..
public class SplashActivity extends Activity {
    // protected boolean _active = true;
    protected int _splashTime = 5000;
    private ImageView imag;
    AnimationDrawable frameAnimation ;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.splashactivity);
        imag = (ImageView) findViewById(R.id.splashactivity_imag);

        imag.setBackgroundResource(R.drawable.splash_animation);

             frameAnimation = (AnimationDrawable) imag
                .getBackground();

             Thread splashTread = new Thread() {
                public void run() {
                    try {
                        sleep(_splashTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        Intent intent;
                        intent = new Intent(SplashActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            };
            splashTread.start();
        }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        frameAnimation.start();

    }

}

drawable in create new xml...
splash_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"

    android:oneshot="true" >

    <item
        android:drawable="@drawable/ac"
        android:duration="200"/>
    <item
        android:drawable="@drawable/ab"
        android:duration="200"/>
    <item
        android:drawable="@drawable/aa"
        android:duration="200"/>
    <item
        android:drawable="@drawable/z"
        android:duration="200"/>
   <item
        android:drawable="@drawable/y"
        android:duration="200"/>
   <item
        android:drawable="@drawable/x"
        android:duration="200"/>
<item
        android:drawable="@drawable/w"
        android:duration="200"/>
<item
        android:drawable="@drawable/v"
        android:duration="200"/>
<item
        android:drawable="@drawable/u"
        android:duration="200"/>
<item
        android:drawable="@drawable/t"
        android:duration="200"/>
<item
        android:drawable="@drawable/s"
        android:duration="200"/>
<item
        android:drawable="@drawable/q"
        android:duration="200"/>
<item
        android:drawable="@drawable/p"
        android:duration="200"/>
<item
        android:drawable="@drawable/n"
        android:duration="300"/>
<item
        android:drawable="@drawable/o"
        android:duration="300"/>
<item
        android:drawable="@drawable/m"
        android:duration="200"/>
<item
        android:drawable="@drawable/l"
        android:duration="200"/>
<item
        android:drawable="@drawable/k"
        android:duration="200"/>
<item
        android:drawable="@drawable/j"
        android:duration="200"/>
<item
        android:drawable="@drawable/i"
        android:duration="200"/>
<item
        android:drawable="@drawable/h"
        android:duration="200"/>
<item
        android:drawable="@drawable/g"
        android:duration="200"/>
<item
        android:drawable="@drawable/f"
        android:duration="200"/>
<item
        android:drawable="@drawable/e"
        android:duration="200"/>
<item
        android:drawable="@drawable/d"
        android:duration="200"/>
<item
        android:drawable="@drawable/c"
        android:duration="200"/>
<item
        android:drawable="@drawable/b"
        android:duration="200"/>
<item
        android:drawable="@drawable/a"
        android:duration="200"/>

</animation-list>


text:
Q: I'm using AngularFire, How can I retrieve this "email", "uid" data? JS CODE
 var myFirebaseRef = new Firebase('https://blinding-inferno-7068.firebaseio.com/');
     var createdUserRef = myFirebaseRef.child('users').child('createdUser');
     $scope.users = $firebaseArray(createdUserRef);

HTML CODE

{{user.uid}}

{{user.email}}

{{user}}

What I wanted was user.uid and user.email, but those thing didn't come out.
So I checked the user object, and these things came out.
{"-Js0q1mWTwK-AZDZyVdc":{"email":"roro7828@gmail.com","uid":"simplelogin:11"},"$id":"simplelogin:11","$priority":null}

How can I retrieve the key's value? (I mean email's value and uid's value)
Should I have to retrieve that data by putting code like this?
{{user.-Js0q1mWtwk-AZDZyVdc.email}}
like this ? horrible.
Please help me T_T..

A: Let's have a look at your actual data:
{
  "users": {
    "createdUser": {
      "simplelogin:11": {
        "-Js0q1mWTwK-AZDZyVdc": {
          "email": "roro7828@gmail.com",
          "uid": "simplelogin:11"
        }
      },
      "simplelogin:12": {
        "-Js0qpcW6jI9Yf3kplCs": {
          "email": "ao7828@gmail.com",
          "uid": "simplelogin:12"
        }
      },
      "simplelogin:13": {
        "-Js0qrEbzYnFOOWtnCbg": {
          "email": "do7828@gmail.com",
          "uid": "simplelogin:13"
        }
      }
    },
    ...
  }
}

*

*You can get such a dump of your data by new Firebase('https://blinding-inferno-7068.firebaseio.com/').once('value', function(s) { console.log(JSON.stringify(s.val())); }, function(e) { console.error(e); }) or by looking at the Data tab in the dashboard of your application.*

Your $firebaseArray contains objects such as this:
      "simplelogin:11": {
        "-Js0q1mWTwK-AZDZyVdc": {
          "email": "roro7828@gmail.com",
          "uid": "simplelogin:11"
        }
      },

And there is no child email under simplelogin:11. So that's why you're not seeing that output.
It looks like you accidentally are adding the users with a $add operation, which creates the "-Js0q1mWTwK-AZDZyVdc" in the sample above. You should instead be using $save or just by using the regular Firebase JavaScript SDK:
ref.child('users/createdUser').child(user.uid).set(user);

Note that it is a bit tricky to explain without seeing the code you use to create those users. So if you edit your question to include that code, I'll update my answer.


text:
Q: How can I see how much network traffic each thread is doing in Linux? How can I see how much network traffic each thread is doing in Linux?
Any information would be useful. (bytes transferred, # of accepts, etc)

A: You could try ntop.
After installing it, based on what distribution you're using, you will have to start the ntop service. Most probably it will look something like this (check your distro's documentation for proper ntop service starting):
service ntop start

After you successfully started the ntop service, you will be able to access ntop's web interface through your web browser:
http://localhost:3000/

Keep in mind that 3000 is the default port for ntop. If you changed it, you will have to change it in your browser as well. If you installed ntop on a remote machine, instead of "localhost", you will have to enter the proper IP/hostname.
After that, ntop usage is pretty straightforward. Go through its web interface and find the information you need. The web interface itself looks like this:

Source

Source

A: There are several applications that can show you a "top"-like list of network traffic for a particular process or thread.
These are the two I've found most useful:

*

*nethogs

*iftop


text:
Q: How to convert Php CURL request to command line curl How to translate following php curl request to curl executable command.
 $curlOpts = array(
                    CURLOPT_PORT           => "3000",
                    CURLOPT_URL            => 'www.example.com',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_HTTPHEADER     => array("Cookie: connect.sid=aASD234SDFfds", "content-type:application/json"),
                    CURLOPT_POST           => true,
                    CURLOPT_POSTFIELDS     => {"email": "test.com",
   "password": "123456"},
                );

curl_setopt_array($ch, $curlOpts);
 $output = curl_exec($ch);

Respected Curl command which I want
curl -X GET --header 'Accept: application/json' 'http://www.example.com?sort=clicks&order=des'

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
   "email": "test.com", \
   "password": "123456" \
 }' 'http://example.com/login'

Please help me for the same.

A: Please note that this is a workaround only.
Try to assemble your http request in Postman which is a really rich tool for testing APIs. It is a Chrome plugin, and available from the Chrome webstore for free (link). Alternatively, you can install it as a standalone client too from their website.
It has a nice feature which let you to grab the curl command wrapped in different languages/formats of your preference. In your case, in BASH too.
Put the request together then:

*

*click "Code" (Right under the "Save" button)

*choose "cURL" from the dropdown list

*click "copy to Clipboard"

...and that's it, you have your preformatted cURL command line.
Also, there's a tool called cURL-to-PHP written in JavaScript, which does the exact thing you'd like to do.
If you take some time, you can translate the converter logic to PHP with little effort (eg. you don't need to research every aspects of cURL internals).

A: take a look at https://github.com/biganfa/php2curl. Start a webserver, send your request, and you will get the command line cURL version of the request using the library.


text:
Q: When to use parallel programming in R to apply a function to each row There are many ways to apply a function to each row.
Here some methods that I know:
method 1
for (i in 1:nrow(data) ) { my_function(data[i,]) }

method 2
apply(data,1,my_function)

method 3
library(plyr)
adply(data,.margins=1, .fun=my_function)

method 4
library(doParallel)
nodes <- detectCores()
cl <- makeCluster(nodes)
registerDoParallel(cl)
clusterEvalQ(cl,source("my_fun.R"))
adply(data,.margins=1, .parallel = T, .fun=my_function)
stopCluster(cl)

among the top 3 methods, I think the faster is the third one. But the question is: when method 4 (the parallel one) is faster than method 3? there is a way to understand it before to run all the code?


text:
Q: RAID 0 array REALLY slow after replacing drive I had a 3X SSD RAID 0 array (It's for a render machine so the increased failure risk is acceptable) with 2X sandisk SSDs all was working fine. I set up the RAID, installed windows 10, then did some speed tests. I then added a drive from Kingston and redid the setup - again, all good but the write speeds were lower because the Kingston drive had really low write speeds.
SO, I replaced the kingston for another sandisk SSD and followed the same method. This time instaling windows 10 took a number of hours and just crashed at the end. I assumed this could be a initialising issue (Even thogh the Intel RAID setup utility said they were ok.I reset the raid, gave it an hour or two to set, then installed windows. slow process again but got there in the end. Now it seems to hang a lot. it'll work just fine then just hang for no reason! I just did a disk speed test and it gave me 1482 MBps Seq Q32T1 Read and 1450 MBps Seq Read VS 3.197 MBps  Seq Q32T1 Write and 95.22 Seq Write :/. It also took FOREVER to run the disk check. Am I just being impatient here and it actually needs longer to initialise the RAID 0? also, if this is the case, have I done the right thing putting the OS on or do I need to start from scratch? I've also swapped out the PSU and removed the DVD drive just incase it's a pwoer issue but no luck.
It's an intel i7 with 12GB RAM


text:
Q: appendChild failed appending same element to one of the same class elements? Please see here.
We have this code in javascript:
document.addEventListener("DOMContentLoaded", function(event) {

  let source_elem = document.querySelector('.ProductMeta__Description .Rte .TableWrapper table');

  let size_table = source_elem.cloneNode( true );

  let hooks = document.querySelectorAll('.product-desc-table-clone');
  console.log('size: ' + hooks.length);
  for (i = 0; i < hooks.length; ++i) {
    hooks[i].appendChild( size_table );
    console.log(i);
  }

});

Which appends a size chart table to 2 div elements with class product-desc-table-clone. Oddly only the 2nd element got appended with the table.
Why?

A: Node.appendChild()

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

You can either use innerHTML or Element.insertAdjacentHTML().
Demo:

document.addEventListener("DOMContentLoaded", function(event) {

  let source_elem = document.querySelector('.ProductMeta__Description .Rte .TableWrapper table');
  let size_table = source_elem.cloneNode(true);
  let hooks = document.querySelectorAll('.product-desc-table-clone');
  console.log('size: ' + hooks.length);
  for (i = 0; i < hooks.length; i++) {
    hooks[i].insertAdjacentHTML('beforeend', size_table.outerHTML);
    console.log(i);
  }

});

          Month
          Savings

          January
          $100


text:
Q: How to get value from UITextfield and sent it to email? I've created an app which contains form and that have to filled up in appropiate text fields..now i need to get all data in textfield and it to be sent in email.here is my code for composing email
- (IBAction)compose:(id)sender
{
if (text1.text=@"" && text2.text=@"" && text3.text=@"" && text4.text=@"" && text5.text=@"") {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                    message:@"Please enter all the field details"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles: nil];
}
                                                                             else{

if ([MFMailComposeViewController canSendMail])
{
    MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

    mailer.mailComposeDelegate = self;

    [mailer setSubject:[NSString stringWithFormat:@"Appointment From Mr/Mrs. %@",text1.text]];

    NSArray *toRecipients = [NSArray arrayWithObjects:@"xxx@xxxx.com", nil];
    [mailer setToRecipients:toRecipients];

    NSString *emailBody =[NSString stringWithFormat:@"Name =%@\nDate= %@\nPreferred Time Slot= %@\nE-Mail=%@\nSpecific Requests=",text1.text,text2.text,text3.text,text4.text,text5.text];
    [mailer setMessageBody:emailBody isHTML:NO];

    [self presentModalViewController:mailer animated:YES];

    [mailer release];
}
else
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                    message:@"Your device doesn't support the composer sheet"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles: nil];
    [alert show];
    [alert release];
}
}

}
if all the text field is null it have to popup an alert.But i'm getting error?...guide me pls..

A: If you are wondering how to get the text from textfield, and send it, you will need to use textfield.text
NSString *emailBody = textField.text;
[mailer setMessageBody:emailBody isHTML:NO];

A: There can be two way -

*

*You can create proprty for your text field, and then access like - myTextField.text where you want.

*You can create a NSString property and set value in to this when text field has some text.

A:  //this is one single line which return your textFiledData

 your_text_field.text

A: Create a variable for ur textfield like IBOutlet UITextField * textFieldVar; and connect it to ur Text field in the nib , then using the following code u can get the text from the text field
 NSString *emailBody = textFieldVar.text;

A: You can create the body of email as you want by appending the string with particular format
Like
User ID: 223984775(value from the textfieldUserID)
Name: XYZ(value from the textfieldName)
......
You can do this by appending the string as the user moves to the next text field to enter.
Use Nsstring "stringWithFormat" method to append the data in the body. Use \n and \t to give a Tabular structure to the body of email. Use formatting too


text:
Q: While deploying index.ts, firebase function call in global scope requires only string literal This two calls are failed:
const client = algoliasearch(functions.config().algolia.app_id, functions.config().algolia.admin_id);
const client = algoliasearch(process.env.app_id, process.env.admin_id);

Error: Error occurred while parsing your function triggers.
AlgoliaSearchError: Please provide an application ID. Usage:
  algoliasearch(applicationID, apiKey, opts)*

But this one, which requires hard coded api keys is ok:
const client = algoliasearch('APP_ID', 'ALGOLIA_ADMIN_KEY');

How can I avoid hardcoded way of initializing algolia client?

A: Deploy mechanics checks if functions.config().algolia.app_id and admin_key are filled while deploying. It is good feature!!! But messages (Error occurred while parsing your function triggers.) don't allow to understand that in deploying (aka compile) time.


text:
Q: Range of successive linear transformations $T^n$ I've been reading Kato's A Short Introduction to Perturbation Theory for Linear Operators, and I'm stuck on a question in Linear Algebra (specifically on the range of a linear transformation).

Let $T:X\rightarrow X$, $dim(X)$ finite, and $T^n(x)=T(T^{n-1}(x))$. Set $R_n=Range(T^n)$ and $K_n=Ker(T^n)$, $n=1,2,...$ (...) There is a nonnegative integer $m \le dim(X)$ such that:
  $$R_n \ne R_{n-1}, n<m$$
  $$R_n = R_{n-1}, n\ge m$$

The same exercise showed that $R_n \subseteq R_{n-1}$ and $K_n \supseteq K_{n-1}$, but I'm struggling with the remainder of the question.

A: Clearly, here (at least in this section, not necessarily in the entire book) vectors spaces are assumed to be finite-dimensional — because otherwise this claim is not true. But for finite-dimensional spaces it's pretty easy. Here's one possible proof.
The numbers $\dim R_n$ are integers that all lie within $0\le\dim R_n\le\dim X$. Being a finite set of integers, it has the smallest element, say $t$. Let $R_m$ be the first (in this chain) subspace with $\dim R_m=t$. Then since $R_{m+1}\subseteq R_m$, we know that $\dim R_{m+1}\le\dim R_m=t$. But $t$ is the least of all these dimensions, so $\dim R_{m+1}=t$. By induction, we have the claim. Similarly for kernels, but using the largest of the dimensions.
But why were all dimensions different before? Assume $R_n=R_{n-1}$ for some $n$. We know that $R_{n+1}\subseteq R_n$. Now pick any $y\in R_n$, then for some $x\in X$ we have $y=T^n(x)=T(T^{n-1}(x))$. Note that $z=T^{n-1}(x)$ lies in $R_{n-1}=R_n$, and therefore $z=T^n(x')$ for some $x'\in X$. Now,
$$y=T^n(x)=T(T^{n-1}(x))=T(z)=T(T^n(x'))=T^{n+1}(x')\in R_{n+1}.$$
Thus $R_n\subseteq R_{n+1}$, which together with the opposite inclusion implies that $R_n=R_{n+1}$. This means that if we have an equality once, them from that point on the sequence of these subspaces has completely stabilized.
This argument, together with the observation that a non-increasing sequence of non-negative integers $\dim R_n$ can't be decreasing forever and thus there has to be at least one place where $R_n=R_{n-1}$, makes my first argument (with the least dimension) unnecessary. But I didn't feel like deleting it... :-)
UPDATE. To address the remaining part: why is $m\le\dim X$? Informally speaking here's the reason. We have the chain of subspaces $X\supseteq R_1\supseteq R_2\supseteq\cdots$ and the corresponding dimensions $\dim X\ge\dim R_1\ge\dim R_2\ge\cdots$. For as long as the dimensions go down, they go down at least by one. But they can't become negative, so going down can only continue for $\dim X$ steps at most.
A more rigorous proof can be done in two cases.
Case 1: $R_1=X$. In this case, $T$ is onto, and for finite-dimensional vector spaces it's equivalent to being bijective, so all $R_n=X$ and $m=1\le\dim X$.
Case 2: $R_1\subsetneqq X$. In this case, the dimensions of all $R_n$ lie within $0$ and $\dim(X)-1$, so we have $\dim X$ possible values. By the pigeonhole principle, the dimensions of the $\dim(X)+1$ subspaces $R_1$, $R_2$, …, $R_{\dim(X)+1}$ can't all be different, so there exists $m$, $1\le m\le\dim X$, such that $\dim R_m=\dim R_{m+1}$ and thus $R_m=R_{m+1}$.

A: If we assume $X$ to be finite-dimensional, the fact that $R_n\supseteq R_{n+1}$ for all $n\in\Bbb N$ implies there must by some integer $n$ where $R_n=R_{n+1}$ (the dimension cannot indefinitely keep decreasing strictly), and one can fix $n_0$ to be the smallest such integer. (In your question you would have $m=n_0+1$; it is unclear to me why one would define $m$ to be one beyond the index where the inclusions cease to be strict.) The point is to prove that also $R_n=R_{n_0}$ for all $n\geq n_0$ (which implies $R_n=R_{n+1}$ for such$~n$).
This is immediate by induction on $n-n_0$ (the starting case $n=n_0$ is obvious). Note that by definition $R_{n+1}=T(R_n)$ (the image under $T$ of the subspace $R_n$) for all $n\in\Bbb N$. Now assuming by induction that $R_n=R_{n_0}$, we get $R_{n+1}=T(R_n)=T(R_{n_0})=R_{n_0+1}=R_{n_0}$, completing the induction step.


text:
Q: Full path name of bash? and base process of Linux? I recently had the following questions:

*

*What is the full path name of bash?

*What is the base process of Linux?

I couldn't answer these.

A: The base process in linux is named init and has the PID 1
If you are on Linux, you can install the command pstree to have a tree view of the process, or using the command ps -eF. See also Wikipedia: init
bash is probably (depending on your distribution) in /bin/bash or /usr/bin/bash
To identify the path of a command an easy thing to use is the command:
type bash
#you can also usee (but not recommanded)
whereis bash
command -v bash

It will read your path (or try to guess) and gives you several path where you can find the file bash


text:
Q: SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3 I keep receiving this error when I do some Ajax calls...
It may even be something to do with Geocoding but I really have no idea how to capture the error to display something useful to users... or even how to solve the problem as it seems to just be referencing some kind of pointer or something :S 0x2ef3

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3.

An image might be more helpful than the error message:

Any ideas at all?
My code fires off 10 ajax calls in 1 second to be processed by geocoding server side.
The error comes up intermittently. Sometimes I get geocoded results and sometimes I get that error. I would say I get it 10% of the time. It completely stops the ajax call from firing my error handler in jQuery.

A: This is the fix that worked for me. There is invalid mime or bad characterset being sent with your json data causing that errror. Add the charset like this to help it from getting confused:
$.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(){
  ...
  }
});

Reference:
Jquery - How to make $.post() use contentType=application/json?
Could not complete the operation due to error c00ce56e

A: We also encountered similar problems. However, setting the charset as noted in the previous comment did not help. Our application was making an AJAX request every 60 seconds and our webserver, nginx, was sending Keep-Alive timeout at 60 seconds.
We fixed the problem by setting the keep-alive timeout value to 75 seconds.
This is what we believe was happening:

*

*IE makes an AJAX request every 60 seconds, setting Keep-Alive in the request.

*At the same time, nginx knows that the Keep-Alive timeout value is ignored by IE, so it starts the TCP connection close process (in the case of FF/Chrome this is started by the client)

*IE receives the close connection request for the previously sent request.  Since this is not expected by IE, it throws an error and aborts.

*nginx still seems to be responding to the request even though the connection is closed.

A Wireshark TCP dump would provide more clarity, our problem is fixed and we do not wish to spend more time on it.

A: I had this problem, a an AJAX Post request that returned some JSON would fail, eventually returning abort, with the:

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3

error in the console. On other browsers (Chrome, Firefox, Safari) the exact same AJAX request was fine.
Tracked my issue down - investigation revealed that the response was missing the status code. In this case it should have been 500 internal error. This was being generated as part of a C# web application using service stack that requires an error code to be explicitly set.
IE seemed to leave the connection open to the server, eventually it timed out and it 'aborted' the request; despite receiving the content and other headers.
Perhaps there is an issue with how IE is handling the headers in posts.
Updating the web application to correctly return the status code fixed the issue.
Hope this helps someone!

A: This issue happened in my project because of an ajax GET call with a long xml string as a parameter value. Solved by the following approach:
Making it as ajax post call to Java Spring MVC controller class method like this.
$.ajax({
    url: "controller_Method_Name.html?variable_name="+variable_value,
    type: "POST",
    data:{
            "xmlMetaData": xmlMetaData // This variable contains a long xml string
    },
    success: function(response)
    {
        console.log(response);
    }
  });

Inside Spring MVC Controller class method:
@RequestMapping(value="/controller_Method_Name")
  public void controller_Method_Name(@RequestParam("xmlMetaData") String metaDataXML, HttpServletRequest request)
{
   System.out.println(metaDataXML);
}

A: I received the same error (SCRIPT7002: XMLHttpRequest: Network Error 0x80004004, Operation aborted), in our case it was because of JavaScript's same origin policy.
Our web app was making a JQuery AJAX call to our server on Port 8080. The call was getting intercepted and re-routed over SSL (due to server rules mandating that incoming traffic use SSL).
Once we made our web app load through the SSL port the issue was fixed.

A: I had this error for some time and found a fix. This fix is for Asp.net application, Strange it failed only in IE non compatibility mode, but works in Firefox and Crome. Giving access to the webservice service folder for all/specific users solved the issue.
Add the following code in web.config file:
 <location path="YourWebserviceFolder">
  <system.web>
   <authorization>
    <allow users="*"/>
   </authorization>
  </system.web>
 </location>

A: I have stumbled across this questions and answers after receiving the aforementioned error in IE11 when trying to upload files using XMLHttpRequest:
var reqObj = new XMLHttpRequest();

//event Handler
reqObj.upload.addEventListener("progress", uploadProgress, false);
reqObj.addEventListener("load", uploadComplete, false);
reqObj.addEventListener("error", uploadFailed, false);
reqObj.addEventListener("abort", uploadCanceled, false);

//open the object and set method of call (post), url to call, isAsynchronous(true)
reqObj.open("POST", $rootUrlService.rootUrl + "Controller/UploadFiles", true);

//set Content-Type at request header.for file upload it's value must be multipart/form-data
reqObj.setRequestHeader("Content-Type", "multipart/form-data");

//Set header properties : file name and project milestone id
reqObj.setRequestHeader('X-File-Name', name);

// send the file
// this is the line where the error occurs
reqObj.send(fileToUpload);

Removing the line reqObj.setRequestHeader("Content-Type", "multipart/form-data"); fixed the problem.
Note: this error is shown very differently in other browsers. I.e. Chrome shows something similar to a connection reset which is similar to what Fiddler reports (an empty response due to sudden connection close).
Also, this error appeared only when upload was done from a machine different from WebServer (no problems on localhost).

A: I just want to add what solved this problem for me, as it is different to all of the above answers.
The ajax calls that were causing the problem were trying to pass an empty data object. It seems IE does not like this, but other browsers don't mind.
To fix it I simply removed data: {}, from the ajax call.

A: With the Apache 2 change KeepAliveTimeout   set it to 60 or above

A: Upping the directive in the virtualhost for KeepAliveTimeout to 60 solved this for me.

A: Have encountered the same issue in my asp.net project, in the end i found the issue is with the target function not static, the issue fixed after I put the keyword static.
[WebMethod]
public static List<string> getRawData()

A: [SOLVED]
I only observed this error today, for me the Error code was different though.

SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete
  the operation due to error 00002efd.

It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.

A: Incase none of these solutions were "clear" enough, essentially IE/Edge is failing to parse your "data" field of your AJAX call properly. More than likely you're sending an "encoded" JSON object.
What Failed:
"data": "{\"Key\":\"Value\"}",
What Works:
"data":'{"Key":"Value"}'


text:
Q: Migrating Django project from production to local SQL server I have Django project which is working fine in production(using Mysql as Database). I am running Mysql server locally in my PC(using XAMPP) , i have a done appropriate changes in setting.py as shown below.
BUT when i try to run "python manage.py migrate MYAPP" i am getting an error as shown below.
Also tried different command (same error)
--> python manage.py syncdb
--> python manage.py makemigrations MYAPP
--> python manage.py runserver
..etc.,

It is not creating any table in SQL backend , any suggestion ?
Settings.py

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'MYAPP',
'USER': 'root',
'HOST': '127.0.0.1',
'PORT': '3306',
 }
 }

ERROR
 _mysql.connection.query(self, query)
django.db.utils.ProgrammingError: (1146, "Table 'MYAPP_DB.TABLErole' doesn't exist")

A: Suggesting your working on a current django release: python manage.py syncdb is deprecated. Instead use python manage.py migrate to apply django's core migrations.
Than make and apply your own migrations:
python manage.py makemigrations MYAPP
python manage.py migrate

To get a list of all available and applied migrations use:
python manage.py showmigrations


text:
Q: Char with accent to char without accent in C Hey guys. simple question: how to remove accents from a char? Like ã -> a, and é -> e. I asked in another question how to convert utf-8 to ascii but this is unnecessary, since I only need to treat those situations.
I tried:
char comando;
if( comando == 'ç' || comando == 'Ç') {
        comando = 'c';
        return comando;
    }

But it gives me this error: "comparison is always false due to limited range of data type".
I can't be certain about the version of GCC that my teacher is going to compile my program, but she will run it on Linux (Ubuntu probably). And I can't use the standard lib. :(
Thanks!

A: In supplement to the other answers, try this for size:
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>

int main(int argc, char** argv)
{
    wchar_t* x = calloc(100, sizeof(wchar_t));
    char*    y = calloc(100, sizeof(char));

    printf("Input something: ");
    fread(y, 1, 99, stdin);

    mbstowcs(x, y, 100);

    if ( x[0] = L'è' )
    {
        printf("Ohhh, french character!\n");
    }

    free(y); free(x);

    return 0;
}

This code shows you two things: firstly, how to convert a multi-byte string you have read in into a wide character string. From there, you can handle nearly every character that exists (theoretically at least).
Having done this, you simply need a map of characters and their transform which will allow you to parse each character and map it to something else. See the other answers for this
Some notes: I've deliberately used fread() on stdin - ctrl+D when done typing input. This is to prevent a buffer overflow attack you would be vulnerable to using scanf if you passed the result to a function (see NOP sled).
Secondly, I have blindly assumed y's input will be mostly single byte. The fact is, if in the multi-byte string two bytes are being used per character, 100 char characters = 50 wchar_t characters. I could check lengths etc too, but that's beyond the scope of this example.

A: The C standard says that the character constants such as 'ç' are integer constants:

§6.4.4.4/9
An integer character constant has type int. The value of an integer character constant
containing a single character that maps to a single-byte execution character is the
numerical value of the representation of the mapped character interpreted as an integer.

If the char type is signed on your machine (it is on Linux), then when comando contains 'ç' and is promoted to integer, it becomes a negative integer, whereas 'ç' is a positive integer.  Hence the warning from the compiler.

For an 8-bit character set, by far the fastest way to do such an operation is to create a table of 256 bytes, where each position contains the unaccented version of the character.
int unaccented(int c)
{
     static const char map[256] =
     {
          '\x00', '\x01', ...
          ...
          '0',    '1',    '2', ...
          ...
          'A',    'B',    'C', ...
          ...
          'a',    'b',    'c', ...
          ...
          'A',    'A',    'A', ... // 0xC0 onwards...
          ...
          'a',    'a',    'a', ... // 0xE0 onwards...
          ...
     };
     if (c < 0 || c > 255)
         return EOF;
     else
         return map[c];
}

Of course, you'd write a program - probably a script - to generate the table of data, rather than doing it manually.  In the range 0..127, the character at position x is the character with code x (so map['A'] == 'A').
If you are allowed to exploit C99, you can improve the table by using designated initializers:
static const char map[] =
{
    ['\x00'] = '\x00', ...
    ['A']    = 'A', ...
    ['a']    = 'a', ...
    ['å']    = 'a', ...
    ['Å']    = 'A', ...
    ['ÿ']    = 'y', ...
};

It isn't entirely clear what you should do with diphthongs letters such as 'æ' or 'ß' that have no ASCII equivalent; however, the simple rule of 'when in doubt, do not change it' can be applied sensibly.  They aren't accented characters, but neither are they ASCII characters.
This does not work so well for UTF-8.  For that, you need more specialized tables driven from data in the Unicode standard.
Also note that you should coerce any 'char' value to 'unsigned char' before calling this.  That said, the code could also attempt to deal with abusers.  However, it is hard to distinguish 'ÿ' (0xFF) from EOF when people are not careful in calling the function.  The C standard character test macros are required to support all valid character values (when converted to unsigned char) and EOF as inputs - this follows that design.

§7.4/1
In all cases the argument is an int, the value of which shall be
representable as an unsigned char or shall equal the value of the macro EOF. If the
argument has any other value, the behavior is undefined.

A: You mentioned in another similar question that this was easy enough to do in other languages that you know.  If I were you and couldn't find a good way to do this with available code in C and needed to do so in C I would write a program in another language to generate a C function that would do the conversion for you.  As long as you can cycle through all characters this shouldn't be too difficult, though it may be large code.  I'd probably do this for utf-16, and just have a simple wrapper function that took utf-8, converted them to utf-16, and called the conversion function.
The conversion function would just be made of a very large switch/case statement, and the default case would be for characters that didn't convert.


text:
Q: PHP - Use of undefined constant I am getting following errors. I have tried many things but it is not working. It is a login with Paypal payment system it is working when I tested on Paypal however on code script failing.

Here is the code causing error.

A: if client_id, sanbox etc are variables, put $ with it. like $client_id..etc. if not, it should be like echo 'client_id'; If they are constants, it should be defined. like, define('client_id', 'some value');


text:
Q: If the codomain of the following function is R , is the function surjective? The function given to me was $f(x)= ln|ln(x-[x])|$
This is how I attempted it :-
The given function is also the same as $ln|ln\{x\}|$
Now , as $\{x\}<1$, therefore $ln\{x\}$ will take all possible negative values. It's absolute value will this give us the all possible positive numbers. Therefore the domain $ln|ln\{x\}|$ will have all positive numbers and this will give us all the real numbers. So it's surjective.
Is my reasoning correct ? If I am mistaken , kindly point it out. Thanks for your help !


text:
Q: NullPointerException with ProgressBar using ActionBarCompat I'm using ActionBarCompat in support-v7-r18.
When trying to show an indeterminate progress, it works on Galaxy S3 Android 4.1.2 but doesn't on Galaxy Ace Android 2.3.3.
I can't figure why.
The code raising the exception :
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    final ActionBarActivity activity = this;
    content = (WebView) findViewById(R.id.webContent);
    content.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            activity.setSupportProgressBarIndeterminate(true);   <=== Line 88
            activity.setSupportProgressBarIndeterminateVisibility(true);
        }
    }

The exception :
FATAL EXCEPTION: main
    java.lang.NullPointerException
    at  android.support.v7.app.ActionBarActivityDelegateBase.updateProgressBars(ActionBarActivityDelegateBase.java:508)
    at android.support.v7.app.ActionBarActivityDelegateBase.setSupportProgressBarIndeterminate(ActionBarActivityDelegateBase.java:469)
    at android.support.v7.app.ActionBarActivity.setSupportProgressBarIndeterminate(ActionBarActivity.java:282)
    at MyActivity.onPageStarted(MyActivityActivity.java:88)
    at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:266)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:3687)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
    at dalvik.system.NativeStart.main(Native Method)

A: Add supportRequestWindowFeature(Window.FEATURE_PROGRESS);or         supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); to onCreate() method before calling setContentView().


text:
Q: Allowing customers using our site to pay direct to our Clients Sage Pay account We currently allow our clients to receive payments made via our online booking site, directly into their own Paypal account and then return back to our online booking site to complete and confirm the booking once payment has been successfully completed.
I would like to offer the same service for SagePay (and others e.g. Worldpay).  Can someone please point me in the right direction as I am struggling to connect with SagePay direct at the moment?
Thanks
Nigel


text:
Q: How to copy-by-value (not by reference) a CPLEX IloArray, the easy way I work with CPLEX and C++ via Concert Technology and a recurrent issue I am encountering is that internally the IloArray structures seem to be overloaded vector structures with copy-by-reference operators. Which I must acknowledge is a quite neat and memory efficient way of handling the array structures.
Yet... This implies that making IloIntArray Array_copy = Array, for a previously declared and initialized IloIntArray Array, will make a reference copy of Array into Array_copy. Hence, any change in Array is automatically transferred to Array_copy. The same applies to multi-dimensional IloArray structures via the add() routine.
Let us say, for instance, that I need to populate a 2D IloArray<IloIntArray> Array2D(env), inside a for-loop indexed in i = 1 to iSize, storing in each position of Array2D[i], from i = 1 to iSize, the values of Array which will be different at each iteration of the loop. Making either:

*

*Array2D[i].add(Array) or,

*Array2D[i] = Array, assuming Array2D i-dimension was initially set to be of size iSize.

Fails to make the intended copy-by-value, since each time, a copy-by-reference is made to the elements of the i-dimension and you end up with all identical elements, equal to the last value of Array.
Now, besides, making my own copy-by-value operator constructor (Option I) or a copy routine (Option II) receiving, both, the origin and destination arrays as well as the position of the destination array (e.g. multi-dimensional array) where the origin array is to be copied.
Is there another way to make the copy-by-value? In any case, can you help me decide which one of these options is more neat and/or memory efficient? Intuitively I deem Option I to be the more efficient, but I don't know how to do it...
Thanks in advance for your help
Y

A: So far, I am solving my own issue by implementing a copy() function.
I have typedefed my multi-dimensional arrays as follows:
typedef IloArray<IloIntArray> Ilo2IntArray; and typedef IloArray<IloNumArray> Ilo2NumArray and so on for three or four dimensional integer or numeric arrays.
An example of my Ilo3IntArray copy(Ilo3IntArray origin) overload of the copy function I am using as a patch to make copy-by-value copies, is as follows:
Ilo3IntArray copy(Ilo3IntArray origin) {

IloInt iSize = origin.getSize();
Ilo3IntArray destination(env, iSize);
IloInt jSize = origin[0].getSize();
IloInt zSize = origin[0][0].getSize();

for (IloInt i = 0; i < iSize; i++) {
    destination[i] = Ilo2IntArray(env, jSize);

    for (IloInt j = 0; j < jSize; j++) {
        destination[i][j] = IloIntArray(env, zSize);

        for (IloInt z = 0; z < zSize; z++) {
            destination[i][j][z] = origin[i][j][z];
        }
    }
}

return destination;

// Freeing Local Memory
destination.end();
}

Your comments and/or better answers are welcome!!!


text:
Q: Interrupt the thread  protected void waitAndSweep(String symbol) {
    try {
      long sweepTime = symbolInfo.getSweepTime(symbol);
      long timeSinceLastSweep = System.currentTimeMillis() - sweepTime;
      long waitTime = timeSinceLastSweep >= getInterval() ? 0 : getInterval() - timeSinceLastSweep;
      logTradeEvent("waitAndSweep", symbol, "waittime: " + waitTime);
      if (waitTime > 0){
          Thread.sleep(waitTime);
      }
      callSweep(symbol);
    }catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }catch (Exception e) {
      logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
          "Exception caught...", e);
    }
  }

While it is sleeping (Thread.sleep), How to interrupt this thread so that it comes out of waitandSweep method?
private void replace(){
// interrupt the thread;
// call waitandsweep again here;
waitandsweep(symbol)

A: Using wait() instead of sleep() allows you to wake up the thread via notify(), see e.g. Difference between wait() and sleep()

A: Keep a reference to the thread when you start it, and call Thread#interrupt on that reference. If the thread is sleeping the interruption will cause the sleep method to cut its sleep short and throw InterruptedException; if the thread is not sleeping then the interrupted flag will be set.
I have an example of interrupting a thread in this answer.
Using wait instead of sleep would mean you'd have to introduce a shared lock and a condition variable. The waiting thread would have to acquire that lock, then wait in a loop, checking the condition variable.
The condition variable and loop are required for several reasons:
1) A thread can return from waiting without having received a notification (the "spurious wakeup"), and
2) the notification is made while the thread doesn't have the lock, and there is no telling whether the state will still be the same as the state that caused the notification once the thread manages to re-acquire the lock
In this case it seems like a lot less trouble to use interruption here.

A: You can use an ArrayBlockingQueue and use poll(long, java.util.concurrent.TimeUnit).
All you need then is to wake up the the tread, post something to the queue.
Please do not attempt to use wait/notify as there are many edge cases where that mechanism fails. For example, if a notify happens just after the wait times out, will the next wait immediately finish? Using a BlockingQueue allows you to drain it at appropriate times.


text:
Q: WebGoat - web service SQL injection testing with Webscarab fails Could someone please tell me why do I see the following error message:

when trying to complete WebGoat web service SQL injection by using Webscarab? I'm on Win. Thank you.


text:
Q: Rigorous proof of the duality of Coupon collector's problem and Occupancy problem We have $k$ different types of coupons (with replacement).If we collect at least $l$ different coupons, we win a prize. We can only afford to collect $m$ coupons.
Let's say we take all those $m$ coupons, and we collect exactly $L$ different coupons. Then the probability that we win a prize is $P(L \geq l)$
Let $T$ be the number of trials taken to collect exactly $l$ coupons. Then the probability we win a prize is $P(T \leq m)$
"Clearly" $P(L \geq l) = P(T \leq m)$.
So how on earth does one go about proving it rigorously? I'm not too familiar with the theory of stopping times, and the proof may come from that area, but no treatise that mentions these two problems ever seems to prove this equality. Does anyone know of someone that has taken the time to prove this rigorously, and what formalism that they use?

A: To specify the probability space is rarely a good idea but since you insist on it, a possible choice would be $\Omega=K^\mathbb N$, where $K=\{1,2,\ldots,k\}$ denotes the set of types of coupons, endowed with the sigma-algebra ${\mathcal K}=2^K$ and the discrete measure $p=(p_i)$ on $(K,\mathcal K)$ describing the probability to get a coupon of a given type at each draw. In other words, for every $A\subseteq K$, $A\in\mathcal K$ and $p(A)=\sum\limits_{i\in A}p_i$.
This considers that one collects coupons again and again, even when one is really interested in what happens with the $m$ first coupons collected.
As a product space, $\Omega$ is endowed with the product sigma-algebra $\mathcal F=\mathcal K^{\otimes\mathbb N}$, generated by the cylinders $A\times K^\mathbb N$ with $A\subseteq K^n$ and $n\in\mathbb N$, and with the product probability measure $\mu=p^{\otimes\mathbb N}$. Thus, $\mu$ is the unique probability measure such that, for every positive $n$ and every $\eta=(\eta_t)$ in $K^n$, $\mu(\Omega_\eta)=\prod\limits_{t=1}^np_{\eta_t}$, where $\Omega_\eta=\{\omega=(\omega_n)_{n\in\mathbb N}\in\Omega\mid\forall t\leqslant n,\omega_t=\eta_t\}$.
For every $\omega=(\omega_n)_{n\in\mathbb N}$ in $\Omega$ and every $n\in\mathbb N$, define $N_n(\omega)$ as the size of the set $\{\omega_t\mid t\leqslant n\}$. Then each $N_n$ is a random variable on $(\Omega,\mathcal F)$. Furthermore, for every positive $\ell$, the number $T_\ell$ of draws needed to collect exactly $\ell$ different coupons is such that $[T_\ell\leqslant m]=[N_m\geqslant\ell]$ and, for every positive $m$, the number $L_m$ of different coupons collected during the $m$ first draws is $L_m=N_m$. This proves that $[T_\ell\leqslant m]=[L_m\geqslant\ell]$ for every positive $m$ and $\ell$.


text:
Q: How to create the dynamic columns table in angularjs and how to bind
Im new to angularjs i need to be create dynamically columns which has
  colspan=3

UPS

Time_of_Reading
 Lastreading
Readingby

it shold be in loop based on data this should be generate dynamically
  same only

data is this
[
  {
    "InvDetails": "UPS",
    "LstRecords": [
      {
        "Id": 1,
        "Invertor_Id": 1,
        "Time_of_Reading": "20170214",
        "Lastreading": 0,
        "Readingby": 0
      },
      {
        "Id": 87,
        "Invertor_Id": 1,
        "Time_of_Reading": "20170215",
        "Lastreading": 5,
        "Readingby": 10
      },
      {
        "Id": 110,
        "Invertor_Id": 1,
        "Time_of_Reading": "20170216",
        "Lastreading": 10,
        "Readingby": 92
      },
      {
        "Id": 111,
        "Invertor_Id": 1,
        "Time_of_Reading": "20170216",
        "Lastreading": 92,
        "Readingby": 95
      }
    ]
  },
  {
    "InvDetails": "Power Supply",
    "LstRecords": [
      {
        "Id": 2,
        "Invertor_Id": 2,
        "Time_of_Reading": "20170214",
        "Lastreading": 0,
        "Readingby": 0
      },
      {
        "Id": 88,
        "Invertor_Id": 2,
        "Time_of_Reading": "20170215",
        "Lastreading": 7,
        "Readingby": 13
      },
      {
        "Id": 109,
        "Invertor_Id": 2,
        "Time_of_Reading": "20170216",
        "Lastreading": 13,
        "Readingby": 25
      },
      {
        "Id": 112,
        "Invertor_Id": 2,
        "Time_of_Reading": "20170216",
        "Lastreading": 25,
        "Readingby": 49
      }
    ]
  }
]

please some one help me in this how to create the dynamic colmns and
  how to bind this one to angularjs

A: You could use ng-repeat and start that loop on the tbody and then go deeper down the json array like this

            {{details.InvDetails}}

            {{reads.Time_of_Reading}}
            {{reads.Lastreading}}
            {{reads.Readingby}}

View the results here, Plunker

A:   <!DOCTYPE html>

     {{detail.sno}}
     {{detail.PKN}}
     {{detail.PKV}}
     [[{{item.SCN}}
     :{{item.SCV}}
     :{{item.TCN}}
     {{item.TCV}}]]