text:
Q: Skyping or Skypeing How do you spell the word for phoning by Skype? I would like to use the word in a semi-formal way, in a work related email conversation, where I start emails with "Hi".
Skyping or Skypeing

A: Use "Skyping"; just as you would "Googling" if you want to write what most people do (Based off Google hits per usage). Proper verbs (sic) seem to drop their final 'e' according to populism. That said, both are used.
Imho; Skypeing and Googleing are more correct since proper nouns are usually immutable. We don't capitalize the "i" in "iPhone" and I know of the Kennedys but not of the Kennedies.
That said I always suggest writing what others do when in doubt.
TLDR: Skyping.

A: In your case, it would be "skyping".
The rule for this is very simple. If the word ends in a silent 'e', and the suffix begins with a vowel, then the silent 'e' is dropped. This only applies to silent 'e', and not to any vowels. Examples are:

Hope/Hopeless/Hoping/hoped

Note how in "hopeless" the suffix doesn't begin with a vowel, so the silent 'e' is not dropped; also, "hoped" in which the suffix is "-ed", so its not "hopeed", but the silent 'e' has been dropped.

A: Although there are a few rare worlds ending "eing" ("queueing" is common and valid, although queuing is also used) in general, it's not done.  Therefore I would suggest "skyping" would be the correct word.

A: I would go with skyping because if you were to use "skypeing" you have placed two vowels together which, ignoring the few exceptions (ie dyeing which has previously been noted), is incorrect English literature.


text:
Q: Swift NSURLConnection returns instantly with a 1005 error I working on a new app written in swift, I've seen this error message spammed all over SO saying: Restart the simulator.
Too bad it seems that in my case this is not the answer, an older app written in objective-C which seems to be using exactly the same methods does work fine, but when I make NSUrlConnection calls to an Api (ours) it does not seem to work for the new app.
The response is a proper 200 with some json data, no redirects it works fine on the Android app I'm developing simultaneously.
basicly what I have:
func getRequest() -> NSMutableURLRequest {
        let request = NSMutableURLRequest(URL: NSURL(string: package.fullPath)!)
        request.HTTPMethod = package.apiMethod.description;
        request.HTTPBody = "hi".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        return request;
    }

    func execute() {
        conn = NSURLConnection(request: getRequest(), delegate: self);
        if let c = conn {
            Debug.log("** api-connection-start **");
        }

    }

relevant listeners (the class implements NSURLConnectionDataDelegate):
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
    Debug.log("** api-recieved-url-response? **")
    let httpResponse = response as NSHTTPURLResponse
    statusCode = httpResponse.statusCode
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
    Debug.log("** api-recieving-data **")
    self.responseData.appendData(data)
}

func connection(connection: NSURLConnection, didFailWithError error: NSError) {
    Debug.log("** api-fail-with-error **")
    ErrorClass.message(error)
    if let responseListener = listener {
        responseListener.onError(package, error:error)
    }
}

I have breakpoints on all those helper methods, only the didFailWith error is instantly called with an error containing:
2015-03-31 16:58:29.853 myappname[537:4136] {
    NSErrorFailingURLKey = "http://xxxxxxxx/valid/api/call";
    NSErrorFailingURLStringKey = "http://xxxxxxxx/valid/api/call";
    NSLocalizedDescription = "The network connection was lost.";
    NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1005 \"The network connection was lost.\" UserInfo=0x7fdf3bc465d0 {NSErrorFailingURLStringKey=http://xxxxxxxx/valid/api/call, NSErrorFailingURLKey=http://xxxxxxxx/valid/api/call, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4, NSLocalizedDescription=The network connection was lost.}";
    "_kCFStreamErrorCodeKey" = "-4";
    "_kCFStreamErrorDomainKey" = 4;
}

Obviously I replaced the company name and exact called url since I cannot share these, I can guarantee that these are correct though.
Does anyone see a mistake causing my tissues?

A: After crying lots of hours till I fell asleep and waking up and returning to work it magically works again.
Thanks Obama!
Anyway, just make sure you clear all data from xcode besides cleaning, this can sadly cause these issues too, not just restarting the simulator.

A: The error is "network connection lost".
That's an error that you have to expect at any time, because the user of your app can lose their network connection at any time. And it can come back at any time.
It is not in your power to fix the problem. You have to cope with it, for example by not crashing, and not hanging, when it happens. It's also not in the user's power to fix the problem.
The older app worked fine because you used it at a different time when the network connection wasn't lost. And it seems that instead of crying, you should have thought about what is happening. If your network connection is lost, there's nothing you can do except waiting.
And all these things you have been trying are completely pointless; nothing will fix a lost network connection. (Well, at my home making sure that nobody kicked the cable connecting the router to the phone plug would help).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find records of a column if the data type of a column has been changed using a where condition To know what the data types of the columns in a table are, we use 'desc schema.table_name'. If a particular column's data type has been changed from character to numeric.
How do I check if there are any records in that table with the data type character.
I see Select distinct column_1 from schema.table_name gives all the distinct values in that column
BUT Can we check if a data type of 'character' got into this table using a where condition?

A: If understand you correctly you probably want to use REGEXP in MySql
SELECT *
  FROM table1
 WHERE column1 NOT REGEXP '^[0-9]+$'

SQLFiddle (MySql)
And REGEXP_LIKE if it's Oracle
SELECT *
  FROM table1
 WHERE NOT REGEXP_LIKE(column1, '^[0-9]+$')

or without REGEXP_LIKE
SELECT *
  FROM table1
 WHERE LENGTH(TRIM(TRANSLATE (column1, '0123456789',' ')))  IS NOT NULL

SQLFiddle (Oracle 11g)

A: If you are using Sql. You can use this query.
select column_name from table_name where column_name not like [0-9]

A: Try this query if you are using oracle server
SELECT * FROM table_name WHERE  regexp_like(column_name,'[^0-9]+')


text:
Q: In re module what does \.- do in [\w\.-]+? I am writing a code to search for all the email addresses. I was wondering why I should write it as:
'[\w \.-]+@[\w \.-]+'
What does \.- do in [\w\.-]?

A: [\w.-] matches either a word character (\w), a dash (-) or a dot (.). This is called a character class.


text:
Q: What guidelines are appropriate for determining when to implement a class member as a property versus a method? The .NET coding standards PDF from SubMain that have started showing up in the "Sponsored By" area seems to indicate that properties are only appropriate for logical data members (see pages 34-35 of the document).  Methods are deemed appropriate in the following cases:

*

*The operation is a conversion, such as Object.ToString().

*The operation is expensive enough that you want to communicate to the user that they should consider caching the result.

*Obtaining a property value using the get accessor would have an observable side effect.

*Calling the member twice in succession produces different results.

*The order of execution is important.

*The member is static but returns a value that can be changed.

*The member returns an array.

Do most developers agree on the properties vs. methods argument above?  If so, why?  If not, why not?

A: They seem sound, and basically in line with MSDN member design guidelines:
http://msdn.microsoft.com/en-us/library/ms229059.aspx
One point that people sometimes seem to forget (*) is that callers should be able to set properties in any order.  Particularly important for classes that support designers, as you can't be sure of the order generated code will set properties.
(*) I remember early versions of the Ajax Control Toolkit on Codeplex had numerous bugs due to developers forgetting this one.
As for "Calling the member twice in succession produces different results", every rule has an exception, as the property DateTime.Now illustrates.

A: Those are interesting guidelines, and I agree with them.  It's interesting in that they are setting the rules based on "everything is a property except the following".  That said, they are good guidelines for avoiding problems by defining something as a property that can cause issues later.
At the end of the day a property is just a structured method, so the rule of thumb I use is based on Object Orientation -- if the member represents data owned by the entity, it should be defined as a property; if it represents behavior of the entity it should be implemented as a method.

A: Fully agreed.
According to the coding guidelines properties are "nouns" and methods are "verbs". Keep in mind that a user may call the property very often while thinking it would be a "cheap" operation.
On the other side it's usually expected that a method may "take more time", so a user considers about caching method results.

A: What's so interesting about those guidelines is that they are clearly an argument for having extension properties as well as extension methods. Shame.

A: I never personally came to the conclusion or had the gut feeling that properties are fast, but the guidelines say they should be, so I just accept it.
I always struggle with what to name my slow "get" methods while avoiding FxCop warnings.  GetPeopleList() sounds good to me, but then FxCop tells me it might be better as a property.


text:
Q: How to send Ping frame from play framework server to websocket client and get pong Frame? Using Play 2.4.x in Java.
I'm now in a project, that the websocket will need bidirection ping-pong via websocket, or the client will disconnect when timeout.
I'm using Actor way to handle websocket, and I cannot find ways to send ping frame with ActorRef directly.
Can any one has ideas?


text:
Q: Error: not found: value lit/when - spark scala I am using scala, spark, IntelliJ and maven.
I have used below code :
val joinCondition = when($"exp.fnal_expr_dt" >= $"exp.nonfnal_expr_dt",
$"exp.manr_cd"===$"score.MANR_CD")

val score = exprDF.as("exp").join(scoreDF.as("score"),joinCondition,"inner")

and
val score= list.withColumn("scr", lit(0))

But when try to build using maven, getting below errors -

error: not found: value when

and

error: not found: value lit

For $ and === I have used import sqlContext.implicits.StringToColumn and it is working fine. No error occurred at the time of maven build.But for lit(0) and when what I need to import or is there any other way resolve the issue.

A: Let's consider the following context :
val spark : SparkSession = _ // or val sqlContext: SQLContext = new SQLContext(sc) for 1.x
val list: DataFrame = ???

To use when and lit, you'll need to import the proper functions :
import org.apache.spark.sql.functions.{col, lit, when}

Now you can use them as followed :
list.select(when(col("column_name").isNotNull, lit(1)))

Now you can use lit also in your code :
val score = list.withColumn("scr", lit(0))


text:
Q: как вернуть массив объектов с нужными полями объектов js (name, team,goals) вот код
function getGoalsStat(players){

  }

  // examples
  const players = [
    {
      name: 'Jason Mount',
      birthdate: '19.12.1993',
      country: 'Deutschland',
      number: '21',
      team: 'Manchester United',
      position: 'MF',
      goals: 4,
    },
    {
      name: 'Jason Mount',
      birthdate: '01.01.2001',
      country: 'Deutschland',
      number: '16',
      team: 'Manchester United',
      position: 'MF',
      goals: 0,
    },
    {
      name: 'Finne Bard',
      birthdate: '13.02.1995',
      country: 'Norwegen',
      number: '26',
      position: 'FW',
      team: 'Fulham United',
      goals: 1,
    },
    {
      name: 'Gerhardt Yannick',
      birthdate: '13.03.1994',
      country: 'Deutschland',
      number: 31,
      position: 'MF',
      team: 'Liverpool',
      goals: 8,
    },
  ];

console.log(getGoalsStat(players));

A: Судя по заголовку, вам нужно из одного массива объектов сделать другой с более ограниченным набором полей. Если я правильно понимаю, можно так:

function getGoalsStat(players){
  return players.map(
    ({ name, team, goals }) => ({ name, team, goals })
  );
}

  // examples
  const players = [
    {
      name: 'Jason Mount',
      birthdate: '19.12.1993',
      country: 'Deutschland',
      number: '21',
      team: 'Manchester United',
      position: 'MF',
      goals: 4,
    },
    {
      name: 'Jason Mount',
      birthdate: '01.01.2001',
      country: 'Deutschland',
      number: '16',
      team: 'Manchester United',
      position: 'MF',
      goals: 0,
    },
    {
      name: 'Finne Bard',
      birthdate: '13.02.1995',
      country: 'Norwegen',
      number: '26',
      position: 'FW',
      team: 'Fulham United',
      goals: 1,
    },
    {
      name: 'Gerhardt Yannick',
      birthdate: '13.03.1994',
      country: 'Deutschland',
      number: 31,
      position: 'MF',
      team: 'Liverpool',
      goals: 8,
    },
  ];

console.log(getGoalsStat(players));

Если нет, приведите пример желаемого результата.


text:
Q: Python's subprocess.Popen() and source A third-party Python 2.5 script I'm trying to debug has got me stymied. The relevant part of the script is:
       proc = subprocess.Popen(
               "ls && source houdini_setup",
               shell = True,
               executable = "/bin/bash",
               )

There is a daemon that listens to port 5001 and runs the above script. When the script runs, it fails with the following error:
_cygwin.py
houdini_setup
... (more files) ...
/bin/sh: line 0: source: houdini_setup: file not found

There very much exists a file houdini_setup, as illustrated by the ls, and in fact if I change "source" to "cat" in the script above, the script prints the contents of houdini_setup as expected. Moreover, running the exact above command in a bona-fide bash shell also sources the file with no complaints.
Does anyone have any idea what's going on here?

A: source uses $PATH to find what you pass to it, if you don't specify a directory. Try source ./houdini_setup.

A: You can use strace to help diagnose problems like this. In this case running it with the -ff flag to follow subprocess would have revealed that your code was looking for "houdini_setup" in the wrong place:
stat64("/usr/local/bin/houdini_setup", 0xbf989e60) = -1 ENOENT (No such file or directory)
stat64("/usr/bin/houdini_setup", 0xbf989e60) = -1 ENOENT (No such file or directory)
stat64("/bin/houdini_setup", 0xbf989e60) = -1 ENOENT (No such file or directory)

That could have led you to check the documentation for the source builtin.

A: Maybe you can just use bash itself to do the job, if it's available on your system:
os.popen("/bin/bash -l -c 'source $HOME/.yourfiletobesourced'")


text:
Q: CATransform3DRotate with m34 parameter need to know angle to fit specific height I have the following transform code:
//preparing transform
CATransform3D basicTrans = CATransform3DIdentity;
basicTrans.m34 =1.0/-projection;

//calculating angle
double angle= [[self angleValueForBlockHeight:height] doubleValue];
double rangle;
if (up)
{
    rangle=angle/360*(2.0*M_PI);
}
else
{
    rangle=(360.0-angle)/360*(2.0*M_PI);
};

//NSLog(@"    angle: %g", angle);

//transforming
bView.layer.transform = CATransform3DRotate(basicTrans, rangle, 1.0f, 0.0f, 0.0f);

As you can see I'm rotating bView using specific angle to have a value of height variable after rotation. And as you can see I have a angleValueForBlockHeight method there. This method has very ugly code.
My question is how can I calculate the needed angle for this transform.
The formula or the piece of code would be great.
Help me , please.
Thanks for your attention.


text:
Q: OpenMP: synchronization inside parallel for I have a code that reads like this
void h(particles *p) {
    #pragma omp parallel for
    for (int i = 0; i < maxThreads; ++i) {
       int id = omp_get_thread_num();
       for (int j = 0; j < dtnum; ++j) {
           f( p, id);
           if ( j % 50 == 0 ) {
               if (id == 0) {
                   g(p);
               }
               #pragma omp barrier
           }
        }
    }
}
void f(particles *p, int id) {
   for (int i = id * prt_thread; i < (id + 1)*prt_thread; ++i) {
       x(p[i]);
   }
}

Basically I want to:
1)spawn a given amount of threads. each thread will process a chuck of p according to thread's id
2)each element of p must be processed dtnum times. The processing involve random events
3)every 50 iterations, one thread must perform another operation, while the other threads wait
Problem: gcc says warning: barrier region may not be closely nested inside of work-sharing, critical, ordered, master or explicit task region
what can I do?

A: I think your code is wrong. You said :

each element of p must be processed dtnum times.

But each element of p will be execute maxThreads*dtnum times.
Could you be more explicit on what your code's supposed to do ?

A: It's hard to tell from the very schematic code, but if all you want to do is sync up every so many iterations, it seems easiest to pull the iteration loop out of the parallel omp for loop - which seems clearer anyway - and just do
const int iterblocks=50;

#pragma omp parallel shared(p, dtnum) default(none)
for (int jblock=0; jblock<dtnum/iterblocks; jblock++) {
    for (int j=0; j<iterblocks; j++) {
       #pragma omp for nowait
       for (int i=0; i<prt; i++)
           x(p[i]);
    }
    #pragma omp barrier
    #pragma omp single
     g(p);
    #pragma omp barrier
}


text:
Q: Running a PHP "exec()" in the background on Windows? I've created a script that uses psexec to call another script which calls psexec to run a command line program of mine.
The reason for so many calls to psexec and other scripts is solely so that my PHP script doesn't have to wait for the process to finish before finishing it's output to the browser.
Is there a way I can do this without needing to use psexec? I'm having issues with psexec so I'd like to just completely remove it from my program.
I'm running Windows 2008
EDIT: I changed the title, I guess this would be a more accurate title. I found out the If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends. on php.net's page on exec(), but wasn't sure how to do that.

A: Include a redirection in the command line:
exec('program.exe > NUL')

or you could modify your program to explicitly close standard output, in C this would be
CloseHandle(GetStdHandle(STD_OUTPUT_HANDLE));

It is possible (the documentation doesn't say) that you might need to redirect/close both the standard output and standard error:
exec('program.exe > NUL 2> NUL')

or
CloseHandle(GetStdHandle(STD_OUTPUT_HANDLE));
CloseHandle(GetStdHandle(STD_ERROR_HANDLE));

A: $command = 'start /B program.exe  > NUL';
pclose( popen( $command, 'r' ) );

For more info:
http://humblecontributions.blogspot.com/2012/12/how-to-run-php-process-in-background.html

A: Try the Windows 'start' command: http://technet.microsoft.com/en-us/library/cc770297%28WS.10%29.aspx

A: Using start /B has certain limitations when calling scripts that are spawning sub-processes.
The following method spawns a sub-process using PowerShell to handle such cases:
function execInBackgroundWindows($filePath, $workingDirectory, $arguments)
{
    $cmd = "powershell.exe Start-Process -FilePath $filePath -WorkingDirectory $workingDirectory -ArgumentList '$arguments'";
    shell_exec($cmd);
}

execInBackgroundWindows('curl.exe','c:\temp','-X POST -H "Content-Type: application/json" -d @test.json http://127.0.0.1:4000/myapp');


text:
Q: How to open multiple connections using popen in python I am trying to copy a file from file system "A" to file system "B". So I need connections to both A and B at the same time using 2 different username/passwords.
My current implementation is like the following:
def main():
    CMD_src = 'NET USE ' + network_scr + ' /User:' + user_src + ' ' + password_src
    CMD_dst = 'NET USE ' + network_dst + ' /User:' + user_dst + ' ' + password_dst
    conn_src = subprocess.Popen(CMD_src, stdout=subprocess.PIPE, shell=True)
    conn_dst = subprocess.Popen(CMD_dst, stdout=subprocess.PIPE, shell=True)
    copy()
    conn_src.kill()
    conn_dst.kill()

This will give me an error "Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again."
Can anyone help me in this case? Thank you very much!!

A: You might try connecting to the two different servers in two different threads. http://docs.python.org/2/library/threading.html


text:
Q: How can we push each changes in input model class to parent component from child in Angular 13 How can we push each changes in input model class to parent component from child in Angular 13
Child Component
export class ChildComponent implements OnInit {
  @Input() mdlInData: any;
  @Output() mdlOutData = new EventEmitter<any>();

  ngOnInit(): void {
    this.mdlInData.subscribe((data) => {
      this.mdlOutData.emit(this.mdlInData);
    });

// This values Changes in HTML also -> TWO-WAY binding

  this.mdlInData.id = 1;
    this.mdlInData.Name = "Test";
   this.mdlInData.phone = ['7867878', '768689678'];

 //... More Properties
 }

A: You need to implement the OnChanges lifecycle hook:
export class ChildComponent implements OnChanges {
   @Input() input: any;
   @Output() output = new EventEmitter<any>();

   ngOnChanges(changes: SimpleChanges): void {
      // if input property received new value from parent, emit back its value
      if (changes?.input?.currentValue) {
         this.output.emit(changes.input.currentValue);
      }
   }
}


text:
Q: How to sort indexed object by alphabetical value in javascript I have an indexed object and need to sort it by alphabetic value. I tried sort() function but it remove the given indexes and assign new indexes starting from 0, and I want to keep the existing indexes but just sort by the value.
Here is my code.
var response = {3: 'Ab', 8: 'Fe', 10: 'Bc', 15: 'Eg'};
var sorted = Object.values(response).sort();

sorted output = {Ab, Bc, Eg, Fe} but I don't want to change the existing indexes of each value.
I need to sort the object like this.
var sorted = {3: 'Ab', 10: 'Bc', 15: 'Eg', 8: 'Fe'};

A: Using an object for your case will not work since the ordering will be by the numeric keys, I suggest you use a Map as follows:

const obj = {3: 'Ab', 8: 'Fe', 10: 'Bc', 15: 'Eg'};

const sorted = Object
  .entries(obj)
  .sort(([, a], [, b]) => a.localeCompare(b))
  .reduce((map, [key, value]) => map.set(+key, value), new Map);

console.log([...sorted]);


text:
Q: Sigmoid for regression i just started with data-science, so if this is a very dumb question then please excuse me...
So, i just learnt about the sigmoid neuron, and learnt that its range is [0, 1].
The question i have is that how can it be used in regression tasks, for example to predict the cost of any real estate property, or the imdb rating of a movie, or something
I am aware of the scaling method (multiplying the output of sigmoid with any number) to get real outputs, but that works only for outputs which have an upper limit, like the imdb rating, what about stuff like the price of a commodity or something?
Thanks in advance

A: In Regression tasks, The output layer of the Neural Net. shouldn't be Sigmoid function. You should use a function that does not have limits in its range. Sigmoid function often used in the middle layers of a Neural net.
You can use a Linear function or a Relu (Rectified Linear Unit) for Regression tasks.
Ps: Remember that Logistic regression is an algorithm for Classification in contrast to its name. Make sure you don't mix them up.


text:
Q: ethereum rpc , send transaction How to send a transaction using RPC on ethereum.?
On documentation I see this:
params: [{
  "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
  "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
  "gas": "0x76c0", // 30400,
  "gasPrice": "0x9184e72a000", // 10000000000000
  "value": "0x9184e72a", // 2441406250
  "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}]

Where do I find this:

data": "0xd46e.......72445675

Is there any simple library that I can input only amount and the address of transaction?

A: Web3.js is the de-facto library for interacting with ethereum which you can use. There's great documentation on how to send transactions.
web3.eth.sendTransaction(transactionObject [, callback])

The data field is either a byte string containing the associated data of the message, or in the case of a contract-creation transaction, the initialization code. Data of messages are encoded methods and their argument values. You can use the library ethereumjs-abi to encode and decode data fields.

A: *

*"data" parameter is not for you, if you just want to make a simple transaction.

*To make simple transaction, you can simply ignore all parameters except "from", "to" and "value" and call the method in this way:
params: [{
  "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
  "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
  "value": "0x9184e72a", // 2441406250
}]

*You asked for simple library with just amount and address. It seems by address you mean "to" address. Unlike bitcoin rpc, which simply uses all addresses belongs to wallet as source of transaction, you should define exact "from" address with ethereum rpc.

A: I have written a couple of wrappers around Web3 for NodeJS and Web browsers.
The latter one helps abstracting connections and contract development.
const { connect, useConnection, sendTransaction } = require("web3-wrap");

try {
    if(window.web3){
        await useConnection(window.web3);
    }
    else {
        await connect();
    }

    const receipt = await sendTransaction({
        to: "0x1234...",
        value: 10 // amount to transfer, in wei
    });
    console.log("Receipt:", receipt);
}
catch(err){
    console.error(err && err.message || err);
}

Hope it heps


text:
Q: Wordpress TOC+ plugin opens h1 headers at the top of the viewport. Any clues how I might open 3 of several headers at the BOTTOM of the viewport? Each header is actually a caption of the picture plate ABOVE the header/caption. So the usual TOC+ defaults do the opposite of what I'm intending.
As a newby I've spent several hours on jQuerie insert and w3-display-bottommiddle but neither seem appropriate. If someone could point me in the right direction I'll look forward to doing the work needed.
The butterfly complaining to the ladybug at https://russadamsjd.com/?page_id=4471&et_fb=1&PageSpeed=off shows the problem.
Thanks in advance for any shove-in-the-right-direction you might give me!


text:
Q: Некорректное чтение условий в цикле while while ((x > -1) && ((urav[x] != '+') || (urav[x] != '-')))
while ((x > -1) && !((urav[x] == '+') || (urav[x] == '-')))

В первой строчке условие после && полностью игнорируется, в при вынесении ! за скобку, как во второй строчке, оно учитывается. Кто знает, в чем причина?

A: Давайте сообразим...
(urav[x] != '+') || (urav[x] != '-')

Если urav[x] - +, мы получаем false||true == true.
Если urav[x] - -, мы получаем true||false == true.
Если urav[x] - что-то еще, получаем true||true==true.
Т.е. это всегда true. Условие &&true - это просто первая часть условия.
Вот оптимизатор и выбросил лишнее.
Надеюсь, то, что !a || !b совсем не то же, что и !(a||b), для вас очевидно? Т.е. что условие во втором цикле отличается от условия в первом цикле?
На всякий случай: !a || !b по-другому записывается как !(a&&b).
А !(a||b) - как (!a && !b)...

A: Предполагаем, что второе условие - исходное, а первое - то что у вас получилось после внесения отрицания в скобки. Но внесение отрицания в скобки вы не правильно выполнили, тут нужно применять законы де Моргана, т.е. при внесении/вынесении отрицания логическое ИЛИ (дизъюнкция) должно меняться на И (конъюнкция), и наоборот:
!(urav[x] == '+' || urav[x] == '-') <=> (эквивалентно) (urav[x] != '+' && urav[x] != '-')

(убрал лишние скобки, т.к. операции сравнения и так имеют более высокий приоритет, чем логические операции)
Если в первом выражении, наоборот, вынести отрицание за скобки, то получим:
!(urav[x] == '+' && urav[x] == '-')

Выражение в скобках всегда ложно, т.к. значение в ячейке массива не может одновременно быть равно двум значениям, применяем отрицание - получается true. Т.е., независимо от конкретного значения в ячейке массива данное условие всегда даст вам true.


text:
Q: How To Use nextTick() With Focus Ref in Vue I'm migrating my code from vue 2 to vu 3. I want to make the contents of a textarea on the autofocus, but what happens is an error message Uncaught (in promise) TypeError: content.value.focus is not a function. Here is my code:
<textarea
ref="content"
cols="30"
rows="10"
class="input"
placeholder="Paste your HTML here"
v-model="content">
</textarea>

<script setup>
import { nextTick, onMounted, ref } from 'vue';

const modalShown = ref(false);
let existingBlot = ref(null);
const content = ref('');

const applyHTML = () => {
    emit('adding', {
        content: content,
        existingBlot: existingBlot,
    });

    close();
}

const close = () => {
    modalShown.value = false;
    content.value = '';
    existingBlot = null;
}

onMounted(() => {
    emitter.on('openingHTMLEmbedder', data => {
        if (data) {
            content = data.content;
            existingBlot = data.existingBlot;
        }
        nextTick(() => { content.value.focus() })
        modalShown.value = true;
    });
});

</script>

i don't have any idea where is the mistake, or how to solve this.
so, I'm glad that anyone here can help me by giving me some suggestions to solve this problem.
Thank you in advance

A: you can try

setTimeout(()=>{content.value.focus()},0)


text:
Q: How to get user name to appear in Alerts Setting up some alerting in SQL server 2017 which get dispatched by email to certain DBAs.
Some examples of alerting I am trying to configure would be for Alert number 229 -  The EXECUTE permission was denied on the object 'X'
At the moment there is no details included in the email with regards to who had their permission denied - I am wondering, is it possible to include this?
Current notifications look like:

DATE/TIME:    7/2/2018 1:29:59 PM
DESCRIPTION:  The EXECUTE permission was denied on the object
  'sp_Price', database 'Customisations', schema 'dbo'.

A: Alerts generated by the SQL Server Agent don't include this information, and you can't add it, unfortunately.
One option would be to set up an Extended Events session to capture the error_reported event and filter by the specific error number. This will allow you to capture additional info such as program name, username, client machine etc.
Log this to a file and use an Agent job to periodically query the file and alert if entries are found.
Links:
Login Failures in Extended Events: https://www.mssqltips.com/sqlservertip/3214/use-extended-events-to-get-more-information-about-failed-sql-server-login-attempts/
Extended Events Quickstart Guide: https://learn.microsoft.com/en-us/sql/relational-databases/extended-events/quick-start-extended-events-in-sql-server?view=sql-server-2017


text:
Q: Hamiltonian Monte-Carlo with piecewise differentiable log likelihood This is a bit of a curious situation. I have an energy function $E=S+N$ which is the sum of a smooth differentiable function $S$ and a piecewise constant "noise" function $N$. This means that on average the gradient does point in the right direction, but even a tiny step in the gradient's direction will fall on a different piece.
Is there any way to adapt HMC to handle this situation? For all practical purposes, the "noise" function is a black-box.
So far I'm thinking of using HMC updates based only on the gradient of $S$, with a MH acceptance step at the end. The only difference with regular HMC being that the acceptance ratio may not be 1 (or close to 1). Is this correct or am I missing something?
P.S. I put "noise" in quotes because it does capture the look of the function (low spatial correlation), but it is not noise in the sense that I do not want to ignore its contribution to the energy function.

A: This paper is likely relevant.  Abstract:

Hamiltonian Monte Carlo (HMC) is a successful approach for sampling from continuous
  densities. However, it has difficulty simulating Hamiltonian dynamics
  with non-smooth functions, leading to poor performance. This paper is motivated
  by the behavior of Hamiltonian dynamics in physical systems like optics. We introduce
  a modification of the Leapfrog discretization of Hamiltonian dynamics on
  piecewise continuous energies, where intersections of the trajectory with discontinuities
  are detected, and the momentum is reflected or refracted to compensate for
  the change in energy.


text:
Q: Error building cordova windows8 When i build current project for wp8 , everything works fine. When i build for windows8 i get following error :

: error MSB4019: The imported project "C:\Program Files
  (x86)\MSBuild\Microsoft
  \VisualStudio\v12.0\JavaScript\Microsoft.VisualStudio.WJProject.Default.props"
  was not found. Confirm that the path in the  declaration is
  correct, an d that the file exists on disk.

I have spend a couple of hours searching for solution on the internet but to no avail.
Anyone have any ideas ???

A: I have been troubleshooting the same issue, but I am building for Windows 7.  However, when I searched, I found this, which is specific to Windows 8, and may be the key to your answer.
Found at http://gmc.yoyogames.com/index.php?showtopic=570925:

On that page under Visual Studio it states: "You will also need to install a version of Microsoft Visual Studio ... that supports Windows Store Javascript app creation.."

and

its Visual Studio Express for Windows 8. I had installed Visual Studio Express for Desktop which is not suitable.

A: In my case, the problem was that the project had VS 12.0 coded as a variable into the jsproj file while I was using VS 14.0 (VS2015). Changing the "12.0" to "14.0" fixed it for me, once I saved changes, closed and reopened the project
.


text:
Q: C++ public method definitions after class definition? class Car {

    private:
      int doors;

    public:
      void print();
      Car();
      Car(int doors);
 };

 Car :: Car (int doors)
 {
     doors = doors;
 }

Is this the proper syntax for a class definition in C++?
Why are methods (in the examples that I've seen) declared outside of the class defintion?
What does the :: syntax really mean?

A: Yes. it is valid.
Methods are not "declared" outside. They are "defined" outside to make the declaration and definition separate. You have included the declaration inside your class, which states their membership. You can include the definition inside as well for most of them. However, class implementations are usually done in separate implementation files.
The :: is called the scope resolution operator. "Car :: Car (int doors)" means "the constructor Car from the class Car that takes an int parameter"
Edit: Just to add, the scope resolution operator identifies which scope (in your example, which class) the artifact (in your example, the constructor) belongs to.


text:
Q: Why kubelet is running on kubernetes master node? I have deployed a kubernetes cluster (1 master and 2 worker)on my local laptop using kubeadm.
Noted that the kubelet is running on master node as well. From the articles i have read earlier, kubelet is only needed on worker nodes. Can someone let me know why the kubernetes master node has kubelet service running?

A: The reason is that kubeadm uses containers (pods) to deploy etcd and the api server components. For this static manifests are created as yaml-files which are picked up by the kubelet on the master node to provide the infrastructure pods.
An added benefit is that you have the master node metrics available from the kubernetes api.

A: Kubelet is Kubernetes agent for managing Pods.
There are some Pods running on your Master nodes, too. For example, your network Pods, your etcd Pods (if you haven't provided its cluster yourself), and any other Pods that you run on your Master nodes (a node exporter, log collector, etc.) or any DaemonSet that you didn't tolerate them not to get scheduled on your Master nodes are kinds of Pods that run on your Master. So Kubernetes needs Kubelet to manage them.


text:
Q: Better way to use Nearest I'm trying to write a snippet of code that, given an input value (value), checks a list of arbitrary length (data) for the closest value, and then outputs the index of that value in the list. I'm using the output as an argument, so it can't be in brackets -- it has to be just the value. I can use Nearest and Position to get what I want, but it ends up being in a bunch of brackets each time and I need to use First or Flatten to get it out! It looks ugly.
Right now I have:
First[Flatten[Position[data, First[Nearest[data, value, 1]]]]]

The output is a value of position, not in brackets.
Without that First modifying Nearest the output is {{}}
Without that First and Flatten modifying Position the output is {{position}}. I need the output to simply be position.
Hopefully, I have explained my needs well - does anyone know of a more elegant way to accomplish this?

A: I recommend not using Position, but rather giving Nearest a list of rules associating each item in your data list with its position.
data = {3, 4, 5, 6, 7};
rules = Thread[Rule[data, Range[Length[data]]]];
where[val_] := Nearest[rules, val, 1][[1]]

where /@ data

{1, 2, 3, 4, 5}


text:
Q: Fastest Formats for ArcGIS Online Our organization is going to be publishing many maps with multiple types of layers on ArcGIS Online through an ESRI institutional account.  What types considerations are there when publishing content in this way?  Specifically we are considering speed for the end user of the maps and also credits used for those layers stored on that account.

A: The best way to use ArcGIS Online is not to use ArcGIS Online. ;) But, if you must:

*

*Ensure that your data are in the Web Mercator projection

*Generalize your features to reduce the number of vertices and therefore the size/complexity of your data

*Delete any unnecessary attribute fields; if they aren't used by your end-users or by the application, then they only take up space

*Use the simplest data type possible for each attribute (e.g., don't store numbers in a string field; just make it a numeric field instead)

*

*Use coded value domains where possible

*It's a balance, but you can dissolve features to eliminate redundant table entries

I'm sure there are other tips and tricks, but these are the big ones.


text:
Q: Install BeautifulSoup for another Python version on Mac OS X I have three versions of Python on my Mac: 2.6.1 (built-in), 2.5.4 (Google App Engine development), and 2.7.2 (general Python programming).
I installed BeautifulSoup with python setup.py install. However, only 2.7.2 is able to work with it.
How do I install it for 2.5.4 as well?

A: /path/to/other/python setup.py install

It can be helpful to make aliases for your various system Pythons (e.g. python25, and so on) in your .bashrc.
In regards to changing what python points to from the default system Python, I know that this will work if you alias to a newer version, but it may cause issues with an older version, so be careful (just my $.02).

A: Set your PYTHONPATH environmental variable to point to the installation you want to install it for, and make sure you're using that version of Python when you run python setup.py install. Something like PYTHONPATH=/usr/lib/python25 /usr/bin/python25 setup.py install.


text:
Q: Apple App Store review rejection for in-app consumable purchases I have an app that uses in-app purchases and works in TestFlight as I would expect with the purchases, but keeps being rejected. This last rejection they say I need to submit a build with them in-app purchases enabled. But in my app it is enabled and it works in TestFlight. What am I missing?  Is there some hidden thing that I need to do?  The capability is enabled in the app manifest. I'm kind of lost, and they aren't giving me any specific feedback about the problem.

A: OK! Facepalm moment for me!  I forgot to:

*

*Add the in-app purchase screenshots

*Add the in-app purchase to the review request

I forgot totally that they are separately added, I would have come around to the answer days/hours/minutes faster if the responses from them were more descriptive, and I was more attentive...LOL


text:
Q: Gradle pass dynamic value as system property to method I have a gradle project that has a calculated variable I need to pass into an application.  When i attempt to do this is passes a null value, not the set value I want.
I have the below example file that demonstrates the issue to run just do gradle foo
I want both lines of output to be 4.
def String sum

task add {
    doLast {
        new ByteArrayOutputStream().withStream { os ->
            def result = exec {
                executable = 'sh'
                args = ['-c', 'echo $((2 + 2))']
                standardOutput = os
            }
            sum = os.toString()
            afterEvaluate {
                tasks.foo {
                    systemProperty "foo.bar", "${sum}"
                }
            }
        }
    }
}

task foo {
    doLast{
        println System.properties['foo.bar']
        println "${sum}"
    }
}

tasks.foo.dependsOn( add )

A: Given this (note the simple assignment to System.properties['foo.bar']):
def String sum

task add {
    doLast {
        new ByteArrayOutputStream().withStream { os ->
            def result = exec {
                executable = 'sh'
                args = ['-c', 'echo $((2 + 2))']
                standardOutput = os
            }
            sum = os.toString()
            System.properties['foo.bar'] = sum
        }
    }
}

task foo {
    doLast{
        println System.properties['foo.bar']
        println "${sum}"
    }
}

tasks.foo.dependsOn( add )

then this is the output:
$ gradle foo
:add
:foo
4

4


text:
Q: Probability estimation and trapezoidal rule proc iml;

call randseed(4545); * initialize the stream (like streaminit);

x = J(5000,1,.); * pre-allocate space for random numbers;

call randgen(x,'normal',0,1); * fill x with N(0,1) deviates;

y = y + (x**2 - 3*x**3 + 5x < 1);

p = y / 5000;  * MEAN acts on each matrix column;

se = sqrt(y*(1-y)/5000); * VAR, but not STD or STDERR, also acts on columns;

print "IML STEP: estimated mean of sqrt(abs(X)) is" p "with standard error" se;  * use PRINT, not PUT;

I'm trying to use monte carlo integration with proc iml to estimate the probability that x**2 - 3*x**3 + 5x is less than 1. What am I doing wrong? Do loops are not allowed by the way.
proc iml;

start tr(x,y); * create function called tr;
/* handle bad case */
/*if x<0 then do; return (.); end; * send back missing;*/

N = nrow(x);
dx = x[2:N] - x[1:N-1];
ymean = (y[2:N] + y[1:N-1]) / 2;
return(dx` * ymean );
finish tr;

x = do(-2,5,0.01);
print "Integral of y over x is" ( tr(x,sin(x##2)) );

I keep receiving the (execution) invalid subscript or subscript out of range. How do I solve this problem?

A: This worked for me:
proc iml;
call randseed(45056); *initialize the stream (like streaminit);
x = J(2000, 1, .); *pre-allocation space for random numbers;
call randgen(x, 'normal', 0, 1); *fill x with N(0,1) deviates;
y = (x##2) - (3#x##3) + 5#x;
count = ( y <= 1 )[+];  *count of obs where y < 1;
print "Probability that (X**2 - 3*X**3 + 5*X) < 1
        if X is N(0,1) is " (count/2000);


text:
Q: Colocar uma url dentro de option select Como colocar uma url dentro do option de um select? Quando o usuário selecionar a opção do select ele já redirecionaria para url dentro do option.
Da forma que tentei a url é concatenada com a anterior e o link fica quebrado.

A: Faça da seguinte forma:
<select id="link">
   <option value="" selected>Escolha o site</option>
   <option value="http://www.google.com">Google</option>
   <option value="http://www.youtube.com">YouTube</option>
   <option value="http://pt.stackoverflow.com/">Stack</option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
 $(document).ready(function(){

    $('#link').on('change', function () {
         var url = $(this).val();
         if (url) {
             window.open(url, '_blank');
          }
          return false;
        });
     });
</script>

A: Método simples:
<select onchange="location.href=this.value">
 <option value="#">Selecione</option>
 <option value="http://www.botafogo.com.br">Botafogo</option>
 <option value="http://www.flamengo.com.br">Flamengo</option>
 <option value="http://www.fluminense.com.br">Fluminense</option>
 <option value="http://www.vasco.com.br">Vasco da Gama</option>
</select>

A: Para colocar o link dentro de um único option faça como a seguir:
<script type="text/javascript">
function changeFunc($i) {
    if ($i == 'nova'){
        window.open('index.php?pg=cadastrar_categoria','_self');
    }
}
</script>

<select id="link"  onchange="changeFunc(value);">
   <option value="" >Escolha a categoria</option>
   <option value="animais">Animais</option>
   <option value="natureza">Natureza</option>
   <option value="nova">Adicionar nova categoria</option>
</select>


text:
Q: Top Slide Menu without plugin using Jquery Hi I am creating a top slide menu using Jquery and Css. As i click on the button the menu should appear on the top of the screen, and If i click on the button or any where in the window it should get close.
I am unable to get the nav bar, some thing is going wrong with my code. Here is the code what I have tried.
HTML:

Menu

        Celery seakale
        Dulse daikon
        Zucchini garlic
        Catsear azuki bean
        Dandelion bunya
        Rutabaga
        Celery seakale
        Dulse daikon
        Zucchini garlic
        Catsear azuki bean
        Dandelion bunya
        Rutabaga

                <button id="showTop" style="margin-top:300px;">Show/Hide Top Slide Menu</button>

JS:
$(document).ready(function(){
    $('#showTop').click(function() {
    debugger;
    $('#cbp-spmenu-s3').toggle();
    $('#cbp-spmenu-s3').toggleClass('active');
});
});

Css:
.cbp-spmenu-horizontal {
    width: 100%;
    height: 150px;
    left: 0;
    z-index: 1000;
    overflow: hidden;
}
.cbp-spmenu-horizontal a {
    float: left;
    width: 20%;
    padding: 0.8em;
    border-left: 1px solid #258ecd;
}
.cbp-spmenu,
.cbp-spmenu-push {
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
.cbp-spmenu-top {
    top: -150px;
    display:none;
}
.cbp-spmenu-top.cbp-spmenu-open {
    top: 0px;
}

demo Link:
Demo Code Link

A: EDIT
Had a look again and i noticed there is a fixed height applied to the nav, well you could possibly loosen it up.
The idea is to figure out nav's height via jquery and use that value as the top property.
Heres a quick way of going about it ( would need some refactoring )
var $nav = $(".cbp-spmenu");
var $navBtn = $("#showTop");
var navHeight = $nav.height() + "px";
var navTop = "-" + navHeight;
//$('.cbp-spmenu-top').hide();

$nav.css({top: navTop});

$navBtn.on("click", function(e) {
    e.preventDefault();
    if ( !$nav.hasClass("active") ) {
        $nav.addClass("active");
        $nav.removeAttr("style");
    } else {
        $nav.removeClass("active");
        $nav.css({top: navTop});
    }
});

Updated fiddle http://jsfiddle.net/Varinder/rC8Sk/15/
Well, there are few things goin on:
I'll try to touch on all of them:
Nav would probably need absolute positioning in order to correctly implement top position values.
.cbp-spmenu-horizontal {
    width: 100%;
    height: 150px;
    left: 0;
    z-index: 1000;
    overflow: hidden;
    position:absolute;
}

jQuery's .show() and .hide() methods work by toggling inlined display properties which will complicate transitions ( infact, i dont think its possible to transition from display:none to display:block)
$(document).ready(function(){
    //$('.cbp-spmenu-top').hide();
    $('#showTop').click(function() {
    $('.cbp-spmenu-top').toggleClass('cbp-spmenu-open');//.show();
});
});

Further amendments to css leads to this working sample: http://jsfiddle.net/Varinder/rC8Sk/7/

A: Try this...
$('.cbp-spmenu-top').hide();
$('#showTop').click(function() {
    $('.cbp-spmenu-top').toggle();
});

http://jsfiddle.net/rC8Sk/8/
http://api.jquery.com/toggle/
Display or hide the matched elements.
Or even better for effect...
$('.cbp-spmenu-top').hide();
$('#showTop').click(function() {
    $('.cbp-spmenu-top').slideToggle();
});

You do need to get rid of some of the style rules though. You dont need the transition rules as jQuery will do this.
http://jsfiddle.net/rC8Sk/14/ (updated CSS)
https://api.jquery.com/slideToggle/ Display or hide the matched elements with a sliding motion.

A: Try Dis: working Demo and import following scripts in your html form:

jquery:
$('.cbp-spmenu-top').hide();
$('#showTop').click(function() {
$('.cbp-spmenu-top').toggle();
});

A: Below code can help you as per your requirement. Slide toggle the menu and hide if you click any where on the document too.
$('#showTop').on('click',function(){
            $('.cbp-spmenu-top').slideToggle('slow')
            .toggleClass('active'); // if you wish to add/romove class
        });
        $('#showTop, .cbp-spmenu-top').on('click',function(event){
            event.stopPropagation(); // Stop propogation on selected element
        });
        $(document).on('click',function(){
            $('.cbp-spmenu-top').slideUp('slow'); // hide menu if you click anywhere in the document
        });

Update working example :Working example


text:
Q: Referring to elements directly with variable name vs. getElementById I recently learned that you could refer to an element in the DOM by directly using its id as a variable instead of using something like document.getElementById.
Example:

text

Other than that you can never access an id that falls outside of JavaScript's naming conventions, what are some cons to this method of accessing elements? I'm especially curious since I've never seen this before and I'm thinking that it's maybe for a good reason?


text:
Q: Is there anyway to specify filters for an xlink:href in svg? Is there anyway to specify filters for an xlink:href in an svg?  For example, I only want to reference 's from a specific parent/svg.  If I have multiple svgs on that page, and both happen to contain an element with the same id, it seems that the xlink:href will always reference the first instance, regardless of which svg the xlink:href is.
For example,

...

     <svg xmlns="http://www.w3.org/2000/svg">

     <symbol id="car" viewBox="214.7 0 182.6 792">
         <circle.../>
     </symbol>

   <svg xmlns="http://www.w3.org/2000/svg">

       <symbol id="car" viewBox="214.7 0 182.6 792">
           <rect.../>
       </symbol>

...

    <use xlink:href="#car" .../>
    </svg>
 `

Ideally, I would like to be able to use the unique div id's as reference.  For example,
<use xlink:href="#div2 #car" .../>


text:
Q: HTML Combobox disappearing right after appearing I have a simple web page which looks like this.

When clicked on the Load button, it should show up a small form under the combobox (the id given to that form is frmUpdateService).
The problem is when I click on the load button, it shows the form but it gets disappeared immediately after showing up!
Here's the HTML code of the page.

<link rel="stylesheet" type="text/css" href="stylesheets/styles.css" />

<?php

include_once 'DatabaseHandler.php';
$db = DatabaseHandler::getInstance();

//loading taxi service names for updating combobox
$queryLoadSids = $db->prepare("SELECT * FROM taxi_services ORDER BY SID");
$queryLoadSids->execute();
$dropdown = "<select name='serviceID'>";
while ($row = $queryLoadSids->fetch(PDO::FETCH_ASSOC))
{
    $dropdown .= "\r\n<option value='{$row['SID']}'>{$row['Name']}</option>";
}
$dropdown .= "\r\n</select>";

?>

<?php

if(isset($_POST['btnload']))
{
    $param = $_POST['serviceID'];

    $queryLoadToUpdate = $db->prepare("SELECT * FROM taxi_services WHERE SID = :serviceID");
    $queryLoadToUpdate->bindParam(':serviceID', $param, PDO::PARAM_STR);
    $queryLoadToUpdate->execute();
    $results = $queryLoadToUpdate->fetchAll(PDO::FETCH_ASSOC);

    $loadedSID = $results["SID"];
    $loadedName = $results["Name"];
    $loadedCost = $results["Cost"];
    $loadedActive = $results["Active"];
}

?>

Add a new taxi service

Update a taxi service

Delete a taxi service

View taxi services

<form id="cmbServiceIDs" name="sids">

    Select the Service ID
    <?php echo $dropdown; ?>
    <input id="load" type="submit" value="Load" name="btnload" />

</form>

<form id="frmUpdateService" name="Update" action="" method="post">

    Service ID
    <input type="text" name="sid" value="<?php echo $loadedSID; ?>" />

    Name
    <input type="text" name="name" value="<?php echo $loadedName; ?>" />

    Cost
    <input type="text" name="cost" value="<?php echo $loadedCost; ?>" />

    Active
    <input type="checkbox" name="active" value="<? echo $loadedActive; ?>" <?php echo $loadedActive ? 'checked="checked"' : ''; ?> />

    <input type="reset" value="Cancel" /> <input type="submit" value="Update" name="update" />

</form>

And I use jQuery for appearing show/hide effects.
$(function()
{
    $("#frmUpdateService").hide();
    $("#cmbServiceIDs").hide();

    $("#update").click(function()
    {
        $("#cmbServiceIDs").slideDown("slow");
        $("#frmUpdateService").hide();
    });
    $("#load").click(function()
    {
        $("#frmUpdateService").fadeIn("slow");
    });
});

Can anyone explain why this is happening and how to correct it?
Thank you.

A: The #load button does what you ask and then goes on submitting the page, refreshing everything. You should either use a normal button or some kind of clickable div, or use preventDefault()inside the clickhandler of your #load button.

A: The problem is caused by the submit button, which POSTs the page to the server, and reloads the response (which causes the line that hides the form to run).
Either change this
<input id="load" type="submit" value="Load" name="btnload" />

to this
<input id="load" type="button" value="Load" name="btnload" />

or change your click event to something like this:
$("#load").click(function(e)
{
    $("#frmUpdateService").fadeIn("slow");
    e.preventDefault();
});

A: It's because of these two statements:
$("#frmUpdateService").hide();
$("#cmbServiceIDs").hide();

They get executed each page load. This is something that could be solved nicely with Ajax.
If you wan't to solve this using full postbacks you should make sure the correct html, including what is visible and not visible is taken care of server side.


text:
Q: Pairwise column operations (such as dot product) with a PySpark Dataframe Apologies but I'm new to Spark and this does not seem like a trivial operation to pull off.
If I have a PySpark Dataframe like so:
    +-----+-----+-----+-----+-----+
    |  id |  A  |  B  | ... |  N  |
    +-----+-----+-----+-----+-----+
    |  0  | 0.1 | 0.5 | ... | 0.9 |
    |  1  | 0.2 | 0.2 | ... | 0.1 |
    |  2  | 0.4 | 0.4 | ... | 0.3 |
    |  3  | 0.7 | 0.2 | ... | 0.2 |
    +-----+-----+-----+-----+-----+

and I want to run a pairwise (column) operation like a dot product over all column combinations of the Dataframe's columns, how do I go about it?
What I want is a Dataframe such as this one:
+-------+--------+-------+
|  n_1  |  n_2   |  dot  |
+-------+--------+-------+
|   A   |   A    |  1.3  |
|   A   |   B    |  1.9  |
|   A   |   C    |  3.6  |
|   A   |   D    |  0.7  |
...
|   B   |   A    |  4.6  |
...
+-------+--------+-------+

which holds every combination of the N x N column products and their corresponding dot products.
Just for the record, I have around 1800 columns (N), and up to a few million ids.
Thank you!
Update: I made a mistake above. Now I've clarified that I want the column products, not row products.

A: Edit
To calculate the combinations between all columns as you described in your update,
you can first multiply each column with all the others and aggregate with sum.
The result columns are named X_Y = sum(x*y). And after this, you just need to transpose the result DataFrame. The following example is based on the same data as the first answer:
# get all possible combinations and calculate dot product
products = list()
for c in df.columns:
    if c != 'ID':
        for c2 in df.columns:
            if c2 != 'ID':
                products.append(sum(col(c) * col(c2)).alias(f"{c}_{c2}"))

dot_sums = df.select(*products)

# transpose columns to rows
col_values = explode(
    array(*[struct(lit(c).alias("col_name"), col(c).alias("val")) for c in dot_sums.columns])
).alias("cols_values")

# split the column name to get back the original columns
dot_sums.select(col_values) \
    .select(*[split(col("cols_values.col_name"), "_").getItem(0).alias("n_1"),
              split(col("cols_values.col_name"), "_").getItem(1).alias("n_2"),
              col("cols_values.val").alias("dot")]) \
    .show()

+---+---+------------------+
|n_1|n_2|               dot|
+---+---+------------------+
|  A|  A|               0.7|
|  A|  B|              0.39|
|  A|  C|              0.37|
|  B|  A|              0.39|
|  B|  B|0.4900000000000001|
|  B|  C|0.6300000000000001|
|  C|  A|              0.37|
|  C|  B|0.6300000000000001|
|  C|  C|0.9500000000000001|
+---+---+------------------+

Original answer
A possible approach is to get all the combinations of id_1 <-> id_2 columns by using crossJoin.
And you can put all the other columns A to N in an array so that you could calculate the dot product later.
In addition to the following solution, you might want to have a look at mlib dot function.
Here is an example:
data = [(0, 0.1, 0.5, 0.9), (1, 0.2, 0.2, 0.1),
        (2, 0.4, 0.4, 0.3), (3, 0.7, 0.2, 0.2)
        ]

df = spark.createDataFrame(data, ["ID", "A", "B", "C"])
df.show()

# get all cols except the ID col
op_cols = [c for c in df.columns if c != 'ID']

# transform those cols to array
df1 = df.select(col("ID").alias("ID_1"), array(*op_cols).alias("other_cols_array1"))
df2 = df.select(col("ID").alias("ID_2"), array(*op_cols).alias("other_cols_array2"))

# crossJoin
matrix = df1.crossJoin(df2)

Now, you have a DataFrame matrix with columns ID_1, other_cols_array1, ID_2, other_cols_array2.
So you can calculate the dot product for each combination ID_1 - ID_2 using UDF like this:
dot_product = udf(lambda v1, v2: sum([x*y for x, y in zip(v1, v2)]), DoubleType())

matrix.withColumn("dot", dot_product(col("other_cols_array1"), col("other_cols_array2")))\
      .select("ID_1", "ID_2", "dot")\
      .show()

A: If you consider only the data (i.e. without the row and col headers), it can be done in three lines with numpy:
import numpy as np

a = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
dot = np.dot(a,np.transpose(a))
idx = np.triu_indices(len(a))
out = np.array([idx[0],idx[1],dot[idx]]).T

print(out)

gives:
[[  0   0  14]
 [  0   1  32]
 [  0   2  50]
 [  0   3  68]
 [  1   1  77]
 [  1   2 122]
 [  1   3 167]
 [  2   2 194]
 [  2   3 266]
 [  3   3 365]]

And of course, converting PySpark DF to/from Numpy array is trivial...

A: In pyspark it is a bit less elegant than in scala. Yet, it is totally achievable even in a generic way (it will work without assuming that we know the number of columns and their names).
What we can do is a Cartesian product of the dataframe with itself (crossJoin) and then computing the dot product with a map/reduce scheme.
Here is how I would do it:
# creating sample data
data = [(0, .1, .5, .9), (1, .2, .2, .1), (2, .4, .4, .3), (3, .7, .2, .2)]
df = spark.createDataFrame(data, ['id', 'A', 'B', 'C'])

# all the columns but 'id'
cols = [c for c in df.columns if c != 'id']

# the same df with column names suffixed with '_2'
df2 = df.select(*[df[c].alias(c + '_2') for c in df.columns])

# the dot product
products = [F.col(c) * F.col(c+'_2') for c in cols]
dot_product = reduce(lambda a, b: a+b, products).alias('dot')

# and the cross join
df.crossJoin(df2).select(F.col('id'), F.col('id_2'), dot_product).show()

+---+----+-------------------+
| id|id_2|                dot|
+---+----+-------------------+
|  0|   0|               1.07|
|  0|   1|0.21000000000000002|
|  0|   2|               0.51|
|  0|   3|               0.35|
|  1|   0|0.21000000000000002|
|  1|   1|0.09000000000000002|
|  1|   2|0.19000000000000003|
|  1|   3|                0.2|
|  2|   0|               0.51|
|  2|   1|0.19000000000000003|
....

A: So basically you want to compute the dot product of each column with each other column and itself.
One solution would be to start by computing, for each row i, one column for each combination of col[j]*col[k] for all k and j. If you have thousands of columns, this is something that I do not recommend for Spark SQL tends to struggle with that many columns.
What I would do it start by exploding the dataframe and create one row per id and column name. Then I would join the dataframe with itself based on the id. This would result in a dataframe with one row per id and per combination of two column names.
Finally, I would multiply the values of the two columns, group by the two column names, sum the values to obtain the dot product.
The code would look like this:
from pyspark.sql import functions as F

data = [(0, .1, .5, .9), (1, .2, .2, .1), (2, .4, .4, .3), (3, .7, .2, .2)]
df = spark.createDataFrame(data, ['id', 'A', 'B', 'C'])
cols = [c for c in df.columns if c != 'id']

flat_df = df.select(F.col('id'),
          F.explode(F.array(*[F.struct(F.lit(c).alias('name'),
                                       F.col(c).alias('value')) for c in cols])))

The first part is done, the data has been flatten like this:
>>> flat_df.show()
+---+-------+
| id|    col|
+---+-------+
|  0|[A,0.1]|
|  0|[B,0.5]|
|  0|[C,0.9]|
|  1|[A,0.2]|
|  1|[B,0.2]|
|  1|[C,0.1]|
|  2|[A,0.4]|
|  2|[B,0.4]|
|  2|[C,0.3]|
|  3|[A,0.7]|
|  3|[B,0.2]|
|  3|[C,0.2]|
+---+-------+

Then the second part: joining, multiplying, grouping and summing:
flat_df_2 = flat_df.select('id',
                           F.col('col.name').alias('name2'),
                           F.col('col.value').alias('value2'))
result = flat_df\
    .join(flat_df_2, ['id'])\
    .withColumn('m', F.col('col.value') * F.col('value2'))\
    .groupBy(F.col('col.name').alias('n_1'), F.col('name2').alias('n_2'))\
    .agg(F.sum('m').alias('dot'))

which yields:
>>> result.show()
+---+---+------------------+
|n_1|n_2|               dot|
+---+---+------------------+
|  B|  C|              0.63|
|  A|  A|               0.7|
|  A|  C|              0.37|
|  C|  B|              0.63|
|  C|  C|0.9500000000000001|
|  C|  A|              0.37|
|  B|  B|0.4900000000000001|
|  B|  A|              0.39|
|  A|  B|              0.39|
+---+---+------------------+


text:
Q: Clickhouse Invalid DateTime value on INSERT INTO CSV I have the following table in Clickhouse :
CREATE TABLE mydb.mytable (
   `timestampMs`     DateTime,
   `someId`          String,
   `someValue`       Float64
)

I then use the following code to insert rows in this table :
Connection connection = DriverManager.getConnection("jdbc:clickhouse://" + clickhouseEndpoint, user, passwd);
ClickHouseStatement sth = (ClickHouseStatement) connection.createStatement();

String myRow = "1594806134000,myId1,58.8";
String myfields = "(timestampMs, someId, someValue)";

String myQuery = "INSERT INTO mydb.mytable " + myfields;

sth.write()
    .sql(myQuery)
    .data(new ByteArrayInputStream(myRow.getBytes()), ClickHouseFormat.CSV)
    .send();

The code run without any errors or warnings. But when I check the data stored in clickhouse :
curl -XGET https://my/clickhouse/endpoint/?query=SELECT * FROM mydb.mytable

I get the following output :
2013-07-02 15:49:44      myId1      58.8

Here, the fields someId and someValue have the expected value, but the timestamp field is wrong. The expected value was timestampMs = 2020-07-15 9:42:14
What might be the problem here and what should I do to fix it ?

A: It looks like you add extra three zeros - should be 1594806134 (the count of seconds from 1970-01-01 00:00:00 for type DateTime):
SELECT toDateTime(1594806134000)
/*
┌─toDateTime(1594806134000)─┐
│       2013-07-08 07:06:24 │
└───────────────────────────┘
*/

SELECT toDateTime(1594806134)
/*
┌─toDateTime(1594806134)─┐
│    2020-07-15 09:42:14 │
└────────────────────────┘
*/

A: By default CH expects DateTime in CSV as "2020-07-15 09:42:14", not a timestamp
Doc: The behavior of parsing incorrect dates is implementation specific. ClickHouse may return zero date, throw an exception or do "natural" overflow.
select toUInt32(1594806134000)
1373267184

select toDateTime(1373267184)
2013-07-08 07:06:24


text:
Q: why is the used +availabe space is less than the size of a filesystem Why is the total available space and used space less than the size of a filesystem.
Size Used Available Capacity
 5.5T 4.2T 1.2T 78% /u03
Here I see a discrepancy of 100G in the filesystem. Could you let me know why is this happening and where is the 100 G consumed?


text:
Q: Convert child nodes into a single string using XQuery in ML 10 We have an application whose backend ML response format is JSON and we have a element with both text and nodes as below.
<Title>Header <bold>abc</bold></Title>
Now, while converting the above node to JSON, we get the output as
"Title": {"bold": "abc","_value": "Header "}
But to apply formatting in the UI ,we need the complete(text + node) data as _value
"Title": {"_value": "Header <bold>abc</bold>"}
I tried using xdmp:quote() to convert node to string ,but I need to retain the <Title> as node.Could anyone please help me with this?

A: You could normalize the XML content, "flattening" out the inline elements with xdmp:quote() and turning them into escaped strings that are part of the title  value, so that the JSON conversion process is just turning that title element text() into a JSON property String.
A simple XSLT that achieves that with your sample XML:
import module namespace json = "http://marklogic.com/xdmp/json"
    at "/MarkLogic/json/json.xqy";

let $doc := <Title>Header <bold>abc</bold></Title>

let $xslt :=
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
  xmlns:xdmp="http://marklogic.com/xdmp" extension-element-prefixes="xdmp">

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!--quote any inline elements to make them escaped strings that are part of the parent element value, rather than child elements-->
  <xsl:template match="bold|italics|underline">
    <xsl:sequence select="xdmp:quote(.)"/>
  </xsl:template>

</xsl:stylesheet>
let $normalized-doc := xdmp:xslt-eval($xslt, $doc)

let $custom :=
  let $config := json:config("custom") => map:with("whitespace", "ignore" )
  return $config
return json:transform-to-json($normalized-doc, $custom)

and produces the following output:
{
"Title": "Header <bold>abc</bold>"
}


text:
Q: RowDataPacket returns empty object but it is not empty [React/Next] I've been stressing around trying to fix this and I've burnt myself out. I'm calling my serverless mysql trying to get kanbans from teams. I've used this method multiple times and all were working fine but that is most likely because of they only return single item whilst this returns multiple items.
This is my code which returns empty object.
async function getKanbans(team_id){
    let kanbans = [];
    await sql_query(`SELECT id, sName FROM table WHERE iTeam = ?`, [team_id])
    .then(result => {
        result.forEach(kanban => {
            // console.log(kanban);
            kanbans.push({
                id: kanban.id,
                name: kanban.sName
            });
        });
    })
    .catch(err => {
        console.log(err);
    });

    console.log(kanbans);
    return kanbans;
}

As you can see.. I am trying to print kanbans and I do get:
[
  { id: 1, name: 'Kanban_1' },
  { id: 2, name: 'Kanban_2' }
]

of out it. Then I'm trying to return it to the item that called this function and this is how that looks like:
teams.push({
   id : team.id,
   sName : team.sName,
   sColor : team.sColor,
   aKanbans : result[0]['selectedTeam'] == team.id ? getKanbans(team.id) : null,
});

(a small snippet of something bigger)
Okay, so now when I try and look at the data response (from the frontend) I get this:
{
  "success": true,
  "message": "Found teams",
  "teams": [
    {
      "id": 1,
      "sName": "Team1",
      "sColor": "#fcba03",
      "aKanbans": {}
    },
    {
      "id": 2,
      "sName": "Team2",
      "sColor": "#2200ff",
      "aKanbans": null
    }
  ]
}

aKanbans from Team1 is empty, empty object. What the **** do I do? I tried mapping it and still got an empty object. React/javascript is not my main language, I just like to learn. Any suggestions?

A: You are mixing async / await function with normal Promises handling.
Try to change your getKanbans code like this:
async function getKanbans(team_id) {
  let kanbans = [];
  try {
    const result = await sql_query(
      `SELECT id, sName FROM table WHERE iTeam = ?`,
      [team_id]
    );
    result.forEach((kanban) => {
      kanbans.push({
        id: kanban.id,
        name: kanban.sName,
      });
    });
  } catch (err) {
    console.log(err);
  }

  return kanbans;
}

And then populate the teams using (declare the parent async):
teams.push({
    id : team.id,
    sName : team.sName,
    sColor : team.sColor,
    aKanbans : result[0]['selectedTeam'] == team.id ? getKanbans(team.id) : null,
 });


text:
Q: How one process can wait for input from another in PHP? I'm using proc_open to run another process and after that in while loop I wan't to send some data (using pipes) to opened process and recieve it output. How can I do that?

A: You can use streams to create or connect to a socket and then select on the socket. or Semaphore
functions


text:
Q: Older OS' Apple ID Verification I run an older box that comes up with the iCloud panel, asking for a 2-factor ID verification.  I can't get past it.
It's asking me for my password followed by the ID that's sent to my iPhone.  It repeats itself and I can't get past it.
Anybody know how I can get past this?
This question is not a duplicate.  If you look at the image, which seems to be difficult for some people, it says right there, to enter the password followed by verification code.  It doesn't indicate where to enter this.  Entering it with that dialog box open, does nothing.  It does not state to use the password field specifically.  Apple should know better.


text:
Q: Keeping an icon and a word on the same line in HTML I use Font Awesome icons on my site next to links, and I can't figure out how to force the first word of the links to stay on the same line with the icon.
Here's a JSFiddle example http://jsfiddle.net/un5hwhca/

I'm trying to use   to keep them together, but it didn't do the trick, as you can see on the screenshot, it just get pushed to the beginning of the next line.

A: Add this CSS to your link:
style="white-space: nowrap;"

[ Updated fiddle ]
Or if you only want the image and the first word to stick together, but let the rest of the link wrap, put the image and the first word in a span and apply the style to that one instead, like

        some

    very interesting Asteroids

[ Fiddle ]


text:
Q: Cannot output correct rows from DB after using an IF statement I am trying to create a tsql stored procedure which will output rows based on some parameters. The ultimate aim is to move the rows to another table which is why I have counts - I want to keep track of how many rows I am moving. There are two tables - Notes and ExtraNotes. The ExtraNotes holds overflow info from the first table.
I am using the if statement to select the correct rows based on the parameter called NoteType but I don't know how to output the correct select statement within the if. I know the select statement within each if is wrong
select *
from dbo.Notes
left join dbo.ExtraNotes on Notes.NoteID = dbo.ExtraNotes.NoteID
where NoteDate <= @Date

Could anyone offer some pointers on how I can output the correct rows and possibly restructure this better?
The full code is here.
alter proc selectrows
   --external variables
   @Date datetime,
   @NoteType varchar(2)
as
--internal variables
--Count variables, before any changes
declare @count_rowsBefore int
declare @count_Extra_rowsBefore int

--Count variables of selected rows to be moved

declare @count_SelectedRows int
declare @count_Extra_SelectedRows int

select @count_rowsBefore = count(*)
from dbo.Notes

select @count_Extra_SelectedRows = count(*)
from dbo.ExtraNotes

if(@NoteType= 'B')
begin
select @count_SelectedRows = count(dbo.Notes.NoteID), @count_Extra_SelectedRows =            count(dbo.ExtraNotes.NoteID)
        from dbo.Notes
        left join dbo.ExtraNotes on
        Notes.NoteID = dbo.ExtraNotes.NoteID
        where NoteDate <= @Date

        select *
        from dbo.Notes
        left join dbo.ExtraNotes on
        Notes.NoteID = dbo.ExtraNotes.NoteID
        where NoteDate <= @Date
end
else if(@NoteType = 'S')
  begin
  select @count_SelectedRows = count(dbo.Notes.NoteID),
@count_Extra_SelectedRows = count(dbo.ExtraNotes.NoteID)
        from dbo.Notes
        left join dbo.ExtraNotes on
        Notes.NoteID = dbo.ExtraNotes.NoteID
        where NoteDate <= @Date
        and NoteType = 'S'

        select *
        from dbo.Notes
        left join dbo.ExtraNotes on
        Notes.NoteID = dbo.ExtraNotes.NoteID
        where NoteDate <= @Date
end
else if (@NoteType = 'M')
begin
select @count_SelectedRows = count(dbo.Notes.NoteID),
@count_Extra_SelectedRows =  count(dbo.ExtraNotes.NoteID)
        from dbo.Notes
        left join dbo.ExtraNotes on
        Notes.NoteID = dbo.ExtraNotes.NoteID
        where NoteDate <= @Date
        and NoteType = 'M'

        select *
        from dbo.Notes
        left join dbo.ExtraNotes on
        Notes.NoteID = dbo.ExtraNotes.NoteID
        where NoteDate <= @Date
  end
 else
  begin
  raiserror('Please enter a valid Note Read Type= M, S or B',16,1)
  end

Print 'Total Number of rows: ' + cast(@count_rowsBefore as varchar(10))
Print 'Total Number of "Extra" rows: ' + cast(@count_Extra_RowsBefore as varchar(10))

Print '-----------------------------------------------'
Print 'Total Number of rows to Move: ' + cast(@count_SelectedRows as varchar(10))
Print 'Total Number of "Extra" Rows to Move: ' + cast(@count_Extra_SelectedRows
as varchar(10))

Output screenshot

A: It is unclear what you are trying to do. It seems that you are looking for both the data, and some statistics about the data, but we don't know what data you actually want, or what the structure should be. Would it be easier to split these into seperate peice of logic? It may be simpler to map out what data you want output, and build code for each item seperately.
You could clarify if you could give a couple lines with columns and sample data, and the sample output you would like if that data was run through your code.
One suggestion,
If/then statements do not filter anything, so you will get back more data than you want in the second query, as the filter only applies to each query individually. If this makes sense to you: you already have a variable with the NoteType you can use to filter. This filters the data correctly, and should replace the entire set of if-else if statements, since the code now uses the variable to select the right data directly. So instead of using if statements, you can use
select @count_SelectedRows = count(dbo.Notes.NoteID),
        @count_Extra_SelectedRows =  count(dbo.ExtraNotes.NoteID)
  from dbo.Notes left join dbo.ExtraNotes
    on Notes.NoteID = dbo.ExtraNotes.NoteID
  where NoteDate <= @Date
  and NoteType = @NoteType

select *
  from dbo.Notes left join dbo.ExtraNotes
    on Notes.NoteID = dbo.ExtraNotes.NoteID
  where NoteDate <= @Date and NoteType = @NoteType

A: If you just want counts with your rows you could use the OVER clause to generate them.  If NoteType can only be S or M in the table, then passing a NULL and using ISNULL(, ) should get what you want.  The code below pulls all notes, all related notes, and the first two columns are overall counts of source rows from each table.  I know this is example code, so I won't get all twitchy about the select *.
The link at bottom goes over the OVER clause.
CREATE PROCEDURE selectRows
    ( @Date DATETIME
      , @NoteType VARCHAR(2) -- Pass NULL for both
    )
AS
    select count(dbo.notes.noteid)
               over() as notecount
           , count(dbo.ExtraNotes.NoteID)
               over() as extraNoteCount
           , *
    from dbo.Notes
    left join dbo.ExtraNotes
        on Notes.NoteID = dbo.ExtraNotes.NoteID
    where NoteDate <= @Date
      and NoteType = ISNULL(@NoteType, NoteType);

You don't necessarily need all of those copies of the counts, so unioning in a header row might be more what you had in mind.  The code below pulls all notes and a header row (noteid is null) with only counts:
CREATE PROCEDURE selectRows
    ( @Date DATETIME
      , @NoteType VARCHAR(2) -- Pass NULL for both
    )
AS
    select *
       , CAST(NULL AS INT) noteCount
       , CAST(NULL AS INT) extraNoteCount
    from dbo.Notes
    left join dbo.ExtraNotes
        on Notes.NoteID = dbo.ExtraNotes.NoteID
    where NoteDate <= @Date
      and NoteType = ISNULL(@NoteType, NoteType)
    UNION ALL
    SELECT NULL
       , NULL -- Repeat for as many columns as are in the select * above
       , count(dbo.Notes.NoteID)
       , count(dbo.ExtraNotes.NoteID)
    from dbo.Notes
    left join dbo.ExtraNotes
        on Notes.NoteID = dbo.ExtraNotes.NoteID
    where NoteDate <= @Date
      and NoteType = ISNULL(@NoteType, NoteType)

;
http://msdn.microsoft.com/en-us/library/ms189461.aspx


text:
Q: extjs 6.2 modern form add own validator How can I add an own-form validator in extjs 6.2.0 modern application? In classic:
validator : function(value){
    //do something
}

A: This surely depends on what you want, but for example what I did recently was adding validator using binding with a ViewModel (seems to work in both classic and modern toolkits). This sure may be overcomplicated for your needs, but it looks like ViewModel's binding with formula suits well for email validation.
Form:
Ext.define('App.login.LoginForm', {
    extend: 'Ext.form.Panel',

    requires: [ 'App.login.LoginModel' ],
    viewModel: {
        type: 'login'  // references alias "viewmodel.login"
    },

    layout: 'vbox',
    defaultType: 'textfield',
    items: [{
        name: 'login',
        itemId: 'login-fld',
        bind: '{credentials.login}'
    },{
        inputType: 'password',
        name: 'password',
        bind: '{credentials.password}'
    },{
        xtype: 'button',
        text: 'Submit',
        action: 'save',
        bind: {
            disabled: '{!isCredentialsOk}'
        }
    }]
});

ViewModel:
Ext.define("App.login.LoginViewModel", {
    extend: "Ext.app.ViewModel",
    alias: 'viewmodel.login',

    links: {
        credentials: {
            reference: 'App.login.LoginModel',
            create: true
        }
    },

    formulas: {
        isCredentialsOk: function (get) {
            return Boolean(get('credentials.login') && get('credentials.password'));
        }
    }

});

Model:
Ext.define('App.login.LoginModel', {
    extend: 'Ext.data.Model',

    fields: [
        {   name:   'login',    type: 'string', allowBlank: false   },
        {   name:   'password', type: 'string', allowBlank: false   }
    ],

    validators: [
        {   field: 'login',     type: 'presence',   message: 'Login empty'  },
        {   field: 'password',  type: 'presence',   message: 'Password empty'   }
    ]
});


text:
Q: show that this function is continuously differentiable ( application to Lebesgue theorem ?) Consider $R>0$ and $u \in C_{0}^{\infty}(B(0,R))$ (this is the set of smooth functions with compact support contained in $B(0,R)$).
Let $|\cdot|$ be the Lebesgue measure in $\mathbb R^n$.
Fix $  y \in \mathbb R^n$ and define the function :
$$ f(t) = \frac{\displaystyle\int_{B(y,t)} u(x) \ dx}{\left|B(y,t)\right|}$$
for $t>0$ .
Show that $f$ is continuously diferentiable in the interval $(0,\infty)$.
My idea :
With some calculus i obtain this :
$$ \frac{f(t) - f(t_0)}{t - t_0} = \frac{1}{t-t_0}\left( \frac{{t_0}^n \displaystyle\int_{B(y,t)} u(x) \ dx}{|B(0,1)| t^n {t_0}^n} -  \frac{{t}^n \displaystyle\int_{B(y,t_0)} u(x) \ dx}{|B(0,1)| t^n {t_0}^n}\right)  $$
where $t_0$ is fixed in the interval above. I am trying to aply the Lebesgue diferentiation
theorem in the quotient above ...
Someone can help me? Thanks

A: The function $t\mapsto \vert B(y,t)\vert$ is positive and $\mathcal C^1$ (in fact, it is $c\, t^n$ for some constant $c$); so you just need to show that $\varphi(t)=\int_{B(y,t)} u(x)\, dx$ is $\mathcal C^1$. If you put $x=y+t\xi$, then the change of variable formula gives
$\varphi (t)=t^n\int_{B(0,1)} u(y+t\xi )\, d\xi $, so you have to show that $\psi(t)=\int_{B(0,1)} u(y+t\xi)\, d\xi$ is $\mathcal C^1$. But this follows from the usual differentiation theorems under the integral sign.

A: Hint:
Let's begin with the expression
$$
\frac{f(t) - f(t_0)}{t - t_0} = \frac{1}{t-t_0}\left( \frac{{t_0}^n \displaystyle\int_{B(y,t)} u(x) \ dx}{|B(0,1)| t^n {t_0}^n} -  \frac{{t}^n \displaystyle\int_{B(y,t_0)} u(x) \ dx}{|B(0,1)| t^n {t_0}^n}\right)
$$
And rewrite that, saying $t=t_0+\Delta t$, as
$$
\frac{f(t_0+\Delta t) - f(t_0)}{\Delta t} = \frac{1}{\Delta t}\left( \frac{{t_0}^n \displaystyle\int_{B(y,t)} u(x) \ dx}{|B(0,1)| t^n {t_0}^n} -  \frac{(t_0+\Delta t)^n \displaystyle\int_{B(y,t_0)} u(x) \ dx}{|B(0,1)| t^n {t_0}^n}\right)
$$
Expand the second term and you can cancel the ${t_0}^n$ term, then use Lebesgue's theorem to evaluate the limit.


text:
Q: understanding of lower bound for comparison-based sorting algorithm First, I know

*

*lower bound is O(nlogn)

*and how to prove it

And I agree the lower bound should be O(nlogn).
What I don't quite understand is:
For some special cases, the # of comparisons could actually be even lower than the lower bound.  For example, use bubble sort to sort an already sorted array.  The # of comparisons is O(n).
So how to actually understand the idea of lower bound?
The classical definition on Wikipedial: http://en.wikipedia.org/wiki/Upper_and_lower_bounds does not help much.
My current understanding of this is:
lower bound of the comparison-based sorting is actually the upper bound for the worst case.
namely, how best you could in the worst case.
Is this correct?  Thanks.

A:
lower bound of the comparison-based sorting is actually the upper bound for the best case.

No.
The function that you are bounding is the worst-case running time of the best possible sorting algorithm.
Imagine the following game:

*

*We choose some number n.

*You pick your favorite sorting algorithm.

*After looking at your algorithm, I pick some input sequence of length n.

*We run your algorithm on my input, and you give me a dollar for every executed instruction.

The O(n log n) upper bound means you can limit your cost to at most O(n log n) dollars, no matter what input sequence I choose.
The Ω(n log n) lower bound means that I can force you to pay at least Ω(n log n) dollars, no matter what sorting algorithm you choose.

Also: "The lower bound is O(n log n)" doesn't make any sense.  O(f(n)) means "at most a constant times f(n)".  But "lower bound" means "at least ...".  So saying "a lower bound of O(n log n)" is exactly like saying "You can save up to 50% or more!" — it's completely meaningless!  The correct notation for lower bounds is Ω(...).

A: The problem of sorting can be viewed as following.
Input: A sequence of n numbers .
Output: A permutation (reordering)  of the input sequence such that a'1 <= a'2 ….. <= a'n.
A sorting algorithm is comparison based if it uses comparison operators to find the order between two numbers.  Comparison sorts can be viewed abstractly in terms of decision trees. A decision tree is a full binary tree that represents the comparisons between elements that are performed by a particular sorting algorithm operating on an input of a given size. The execution of the sorting algorithm corresponds to tracing a path from the root of the decision tree to a leaf. At each internal node, a comparison ai  aj is made. The left subtree then dictates subsequent comparisons for ai  aj, and the right subtree dictates subsequent comparisons for ai > aj. When we come to a leaf, the sorting algorithm has established the ordering. So we can say following about the decison tree.
1) Each of the n! permutations on n elements must appear as one of the leaves of the decision tree for the sorting algorithm to sort properly.
2) Let x be the maximum number of comparisons in a sorting algorithm. The maximum height of the decison tree would be x. A tree with maximum height x has at most 2^x leaves.
After combining the above two facts, we get following relation.
  n!  <= 2^x

Taking Log on both sides.
      \log_2n!  <= x
Since \log_2n!  = \Theta(nLogn),  we can say
      x = \Omega(nLog_2n)
Therefore, any comparison based sorting algorithm must make at least \Omega(nLog_2n) comparisons to sort the input array, and Heapsort and merge sort are asymptotically optimal comparison sorts.

A: Imagine all the possible arrays of things that could be sorted. Lets say they are arrays of length 'n' and ignore stuff like arrays with one element (which, of course, are always already sorted.
Imagine a long list of all possible value combinations for that array. Notice that we can simplify this a bit since the values in the array always have some sort of ordering. So if we replace the smallest one with the number 1, the next one with 1 or 2 (depending on whether its equal or greater) and so forth, we end up with the same sorting problem as if we allowed any value at all. (This means an array of length n will need, at most, the numbers 1-n. Maybe less if some are equal.)
Then put a number beside each one telling how much work it takes to sort that array with those values in it. You could put several numbers. For example, you could put the number of comparisons it takes. Or you could put the number of element moves or swaps it takes. Whatever number you put there indicates how many operations it takes. You could put the sum of them.
One thing you have to do is ignore any special information. For example, you can't know ahead of time that the arrangement of values in the array are already sorted. Your algorithm has to do the same steps with that array as with any other. (But the first step could be to check if its sorted. Usually that doesn't help in sorting, though.)
So. The largest number, measured by comparisons, is the typical number of comparisons when the values are arranged in a pathologically bad way. The smallest number, similarly, is the number of comparisons needed when the values are arranged in a really good way.
For a bubble sort, the best case (shortest or fastest) is if the values are in order already. But that's only if you use a flag to tell whether you swapped any values. In that best case, you look at each adjacent pair of elements one time and find they are already sorted and when you get to the end, you find you haven't swapped anything so you are done. that's n-1 comparisons total and forms the lowest number of comparisons you could ever do.
It would take me a while to figure out the worst case. I haven't looked at a bubble sort in decades. But I would guess its a case where they are reverse ordered. You do the 1st comparison and find the 1st element needs to move. You slide up to the top comparing to each one and finally swap it with the last element. So you did n-1 comparisons in that pass. The 2nd pass starts at the 2nd element and does n-2 comparisons and so forth. So you do (n-1)+(n-2)+(n-3)+...+1 comparisons in this case which is about (n**2)/2.
Maybe your variation on bubble sort is better than the one I described. No matter.
For bubble sort then, the lower bound is n-1 and the upper bound is (n**2)/2
Other sort algorithms have better performance.
You might want to remember that there are other operations that cost besides comparisons. We use comparisons because much sorting is done with strings and a string comparison is costly in compute time.
You could use element swaps to count (or the sum of swaps and elements swaps) but they are typically shorter than comparisons with strings. If you have numbers, they are similar.
You could also use more esoteric things like branch prediction failure or memory cache misses or for measuring.

A: When you do asymptotic analysis you derive an O or Θ or Ω for all input.
But you can also make analysis on whether properties of the input affect the runtime.
For example algorithms that take as input something almost sorted have better performance than the formal asymptotic formula due to the input characteristics and the structure of the algorithm. Examples are bubblesort and quicksort.
It is not that you can go bellow the lower boundaries. It only behavior of the implementation on specific input.


text:
Q: how to Convert base64 image path to real path using jquery. While image selection time the image path shows like (src="data:image/jpeg;base64,/9j) this how can i convert this to real path

A: This is full image source encoded in base64. That means there's no image file, or at least it isn't associated with this source in any way.


text:
Q: How to get Device Information Using HTML5 Javascript & Phonegap I'm developing a cross-platform mobile application using HTML5 Javascript & Phonegap. It's supposed to be an application which can display the Device Information and RAM & CPU status (using & free RAM CPU, name, size,...).
But I can find any API which can get the status of CPU&RAM. I'm just a beginner in Mobile HTML5&JavaScript. So, if you guys know anything that can help, please tell me. I'll be very appriciated.
Thank you!

A: In a plain web app you don't have access to this information. But since you mentioned Phonegap in your question, you can get basic device info using this:
http://docs.phonegap.com/en/3.0.0/cordova_device_device.model.md.html#device.model
There are also 2 cordova plugins which you can look into. Neither has iOS support at the time of this writing.
http://plugins.cordova.io/#/package/com.ankamagames.plugins.sysinfo
http://plugins.cordova.io/#/package/org.chromium.system.memory
You may want to look at Chrome packaged apps and the chrome.* apis for cross platform and mobile development here https://developer.chrome.com/apps/about_apps

A: Although I never worked on such area. But what I can suggest is- You will need to write android native plugin to achieve the same.
I think there should be android api to read memoryinfo and cpuinfo file if not you can directly read /proc/cpuinfo and /proc/memoryinfo to get ram and cpu related information.
Hope it will give you some insight. Below is the link of related question -
Android How do you get total memory RAM in the device?


text:
Q: Elasticsearch search length of array Here is my object profile:
{
  "mappings": {
    "_doc": {
      "properties": {
        "name": {
          "type": "text"
        },
        "posts": {
          "properties": {
            "id": {
              "type": "text"
            },
            "create_date": {
              "type": "long"
            }
          }
        }
      }
    }
  }
}

I want to make a search: return all profiles which
1. have name "bob"
2. and have more than 5 posts
Here is an example that I found, but it does not work
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "name": "bob"
          }
        }
      ],
      "filter": [
        {
          "script": {
            "script": "doc['posts'].values.size() > 5"
          }
        }
      ]
    }
  }
}

I get error "reason":"Variable [posts] is not defined."

update posts.id to keyword
{"id": {"type":"text"},"fields":{{"keyword":{"type":"keyword","ignore_above":256}}}}
Same error
"caused_by":{"type":"script_exception","reason":"compile error","script_stack":["doc[posts.id].values.size() > ...","    ^---- HERE"],"script":"doc[posts.id].values.size() > 5","lang":"painless","caused_by":{"type":"illegal_argument_exception","reason":"Variable [posts] is not defined."}}}}]},"status":400

A: According to https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting-fields.html this is because one document is missing the field posts (I suppose).
You could add a filter: "if field posts exists" or use in the script the condition "if doc.containsKey('posts')...."


text:
Q: Removing special characters from @hapi/joi error messages I'm using Joi from @hapi/joi to validate my data, but when I try to customize the error messages by removing the backward slashes and the double quotes; it doesn't work.
My validation function
const validateSignup = (user) => {

  const schema = Joi.object().keys({
    first_name: Joi.string().min(3).max(20)
      .required(),
    last_name: Joi.string().min(3).max(20)
      .required(),
    email: Joi.string().email({ minDomainSegments: 2 }).trim().required(),
    password: Joi.string().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/)
      .required()

  });

  const options = {
    abortEarly: false,
    key: '"{{key}}" ',
    escapeHtml: true,
    language: {
      string: {
          base: '{{key}} '
      }
  }
};
  return schema.validate(user, options);
};

I tried to search online but for some reason, it's not working. What am I doing wrong? Please, help.
Postman's response

A: Customizing error message in @hapi/joi to remove double quote is available after this release https://github.com/hapijs/joi/issues/2262. Default label:'"'. Though this feature is available, you may not get typings for it till https://www.npmjs.com/package/@types/hapi__joi/v/16.0.12, hope they will add soon.
    const options = {
      errors: {
        wrap: {
          label: ''
        }
      }
    };

    return schema.validate(user, options);

In your case, the above configuration removes the double quote.
Here is the output without double quote


text:
Q: How can I configure load balanceing multiple SharePoint2010 web server using Network Load Balancing? How can I configure load balanceing multiple SharePoint2010 web server using Network Load Balancing ? I googoled and binged , not much resources could be found on SharePoint2010.Can anyone point me to some useful resouces?I am pretty new to the IT Pro side of SharePoint , any general guidelines would also be useful.

A: In the past I have used this guide published by Combined-Knowledge, written by Steve Smith.

A: follow the folllowing posts
http://www.harbar.net/articles/spca.aspx
http://technet.microsoft.com/en-us/library/cc754833(WS.10).aspx


text:
Q: Cannot start windows I tried to install Ubuntu 12.10 LTS and I had made a partition in Windows, and I booted from a live CD and tried to install on that partition. The installation didn't work, so I checked the file, and there is a file missing from the .iso. Now I am unable to boot from Windows and I am running off a slow live session. Please help me!!
P.S When I try to boot windows, it stays on the splash screen trying to boot, and there isn't a way to access the recovery partition. I don't have windows discs either.

A: In my experience, such problems occur when you use re-writable cds. Obtain a live CD that is able to install ubuntu properly. Then install it on the partition that doesn't have any windows data. The installation should also install the grub, which will allow you to boot into either of your operating systems.
Even if you are not able to recover windows, you should be able to recover your files.

A: First, download the iso image again, check the MD5 or SHA checksum (to ensure that the downloaded iso is correct byte-per-byte), finally burn it at a slow speed (to reduce the likelihood of a write error).
The partition that Windows created is probably FAT or NTFS, and Ubuntu cannot be installed on either of them. In the Live CD, open Gparted, delete the partition you created in Windows. Then run the installer, choose "Install alongside Windows", and leave the partitioning work to the installer.
If the installation aborts, please tell us the exact error message.