text:
Q: Using strcmp() in my cgi code, for an html webpage, is causing a server error I am making an html webpage that uses cgi to access a table/database in mysql. I input a .csv file containing info on my class schedule and the html displays it in the usual schedule table.
My problem is that I can't seem to use strcmp in my parsing cgi as it causes a server error. here is an excerpt of my code where I uses strcmp.
void parse2(char *queu)
{
//---------------------------------------------------------------
    char *saveptr[1024];
    char *subtoken;
    char *Subject;
    char *Day;
    char *Start;
    char *End;
    char *Room;
    char *Teacher;
    int check = 1;
//---------------------------------------------------------------
    subtoken = strtok_r(queu, ",", saveptr);

    check = strcmp(subtoken, "\0");
    printf("%d
", check);

    if(check == 0){
        printf("Error!");
    } else {
        Subject = subtoken;
        Day = strtok_r(NULL, ",", saveptr);
        Start = strtok_r(NULL, ",", saveptr);
        End = strtok_r(NULL, ",", saveptr);
        Room = strtok_r(NULL, ",", saveptr);
        Teacher = strtok_r(NULL, ",", saveptr);

        printf("%s\n
%s\n
%s\n
%s\n
%s\n
%s\n", Subject, Day, Start, End, Room, Teacher);

        //inputsql(Subject, Day, Start, End, Room, Teacher);
    }
//---------------------------------------------------------------
}

Note that, I have tested this code and it works fine without me calling strcmp().
I am using strcmp() to prevent a line of unwanted characters, generated after the info when retrieved using POST method, from being entered into my database.
As you can see from the above code, I used strtok() to parse the line of info. Since the line of unwanted characters do not contain a comma (which is my delimiter) it should return a NULL value. correct?
Can anyone help me out? I welcome suggestions to use a different way on solving the problem I chose to solve using strcmp().

A: I think you should be checking subtoken == NULL, not strcmp(subtoken, "\0") == 0.
"\0" is a string containing a NUL byte, then another NUL (the terminator), so the standard library's string functions will just see an empty string. That's different to a NULL pointer (i.e. a pointer with value zero).
From STRTOK(3):
   Each call to strtok() returns a pointer to a null-terminated string
   containing the next token.  This string does not include the
   delimiting byte.  If no more tokens are found, strtok() returns NULL.


text:
Q: Covariance equality for independent Gaussians $X = Y + Z$ are independent Gaussians with zero means. I'm told that:$$Cov(Y,X) = \sigma_{Y}^2$$
Could someone show me the intermediate steps to get there?

A: Because $$\text{Cov}(Y,X)=\text{Cov}(Y,Y+Z)=\text{Cov}(Y,Y)+\text{Cov}(Y,Z)=\text{Var}(Y)$$
Since $\text{Cov}(Y,Z)=0$ because of their independence.

Remember that
$$\mathbb{E}\left[ \sum X_i\right]=\sum \mathbb{E}[X_i]=\sum \mu_i$$
Then $$\begin{align} \text{Cov}\left (\sum X_i, \sum Y_i\right) &= \mathbb{E}\left [\left(\sum X_i-\sum \mu_i\right)\left(\sum Y_i-\sum \nu_i\right)\right] \\
&= \mathbb{E}\left [\sum \left(X_i- \mu_i\right)\sum\left( Y_i- \nu_i\right)\right]\\ &=\mathbb{E}\left [\sum \sum \left(X_i- \mu_i\right)\left( Y_i- \nu_i\right)\right]\\ &=\sum \sum \mathbb{E}\left [\left(X_i- \mu_i\right)\left( Y_i- \nu_i\right)\right]\end{align}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Class gives "None in the ouptut" I have the following code:
class StudentData:
    "Contains information of all students"
    studentNumber = 0;
    def __init__(self,name,age,marks):
        self.name = name;
        self.age = age;
        self.marks = marks;
        StudentData.studentNumber += 1;
    def displayStudentNumber(self):
        print 'Total Number of students = ',StudentData.studentNumber;
    def displayinfo(self):
        print 'Name of the Student: ',self.name;
        print 'Age of the Student: ', self.age;
        print 'Marks of the Student: ', self.marks;

student1 = StudentData('Ayesha',12,90)
student2 = StudentData('Sarah',13,89)
print "*Student number in case of student 1*\n",student1.displayStudentNumber();
print "Information of the Student",student1.displayinfo();
print "*Student number in case of student 2*\n",student2.displayStudentNumber();
print "Information of the Student",student2.displayinfo();

And the output is:

*Student number in case of student 1*

Total Number of students =  2

None

Information of the Student Name of the Student:  Ayesha

Age of the Student:  12

Marks of the Student:  90

None

*Student number in case of student 2*

Total Number of students =  2

None

Information of the Student Name of the Student:  Sarah

Age of the Student:  13

Marks of the Student:  89

None

I can't understand why do I get these "None" in my output. Can anyone explain it?

A: You should be returning those strings, not printing them. A function with no return value, returns None. Also please don't use semicolons in Python.
def displayStudentNumber(self):
      return 'Total Number of students = {0}'.format(StudentData.studentNumber)
def displayinfo(self):
      return '''\
Name of the Student: {0}
Age of the Student: {1}
Marks of the Student {2}'''.format(self.name, self.age, self.marks)

A: Because your functions displayStudentNumber() and displayinfo() do not return anything.
Try changing them to:
def displayStudentNumber(self):
    return 'Total Number of students = ' + str(StudentData.studentNumber)

def displayinfo(self):
    print 'Name of the Student: ',self.name;
    print 'Age of the Student: ', self.age;
    print 'Marks of the Student: ', self.marks;
    return ''

As the function does not return anything, it defaults to None. That is why it is getting returned.
By the way, semi-colons are not needed in python.

A: You get None in your output because you are printing the return value of calling the method displayStudentNumber. By default this returns None.
You either want to print the return value of a method or you just want to print. Try something like this,
print "Student number in case of student 1"
student1.displayStudentNumber()

or
def displayStudentNumber(self):
    return 'Total Number of students = %d' % StudentData.studentNumber

and
print "Student number in case of student 1", student1.displayStudentNumber()


text:
Q: Execute a command every minute forever using 'date' I'm looking for a way (bash script or other) to make a command run every minute using date - I've been looking around for similar solutions but they all suggest either cron or watch but what I want to do is to execute the command according to the output of date so that I could make the command run when the second hand hits 30, example
12:50:30
12:51:30
12:52:30
12:53:30
...
any help will be highly appreciated.

A: #!/bin/bash
until [[ $(date +%S) -eq 30 ]]
do
  sleep 0.75
done

while true
do
  #command &
  #here your cmds should be forked to background to avoid delaying
  date +%S
  sleep 30
done

edit
as you wanted to see date +%S stdout and check if = 30 and execute somthing!
#!/bin/bash
foo(){
  echo yay
  #add commands here
}
while true
do
  date +%S | grep '30' && foo
  sleep 1
done

or
#!/bin/bash
foo(){
  echo yay
  #add commands here
}
while true
do
  date +%S
  [[ $(date +%S) -eq 30 ]] && foo
  sleep 1
done


text:
Q: Как проверить url на изображение? У меня есть база данных.
Один из столбцов в ней image. В нём указан url изображения, но данные могут быть некорректными.
Как мне проверить элемент массива на картинку?
На пустоту и null проверяю так:
<?
$a="../img/animal.png";
if ((ltrim($result['image'], ' ') === '')||$result['image']==''||$result['image']==NULL){
$result['image']=$a;
}
 ?>

A: Допустим есть картинка в урл я её парсю;
$url = "https://celebniymir.ru/images/product/s/452e1eaa.jpg";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 0);
$page = curl_exec($curl);

$file='text0001.txt';
file_put_contents($file, $page);

Получаю кодированный текст абракадабра,
затем делаю ссылку битой 452e1eaa.jpg  добовляю 1 к 452e1eaa.jpg
выходит так:

<title>404 Not Found</title>

404 Not Found

nginx


text:
Q: Can an oauthed cordova app auth a in-app webview? I have a cordova app that oauths into outside services like Facebook. Once authed, in some situations, the app will open facebook.com in an in-app browser to display the a post or message. But when navigating to Facebook.com/post/... the user is often asked to log in again; the webview isn't authorized...
Is there any way for the app, which is authorized, to inject the Facebook auth token into the web view somehow (cookie?) to avoid that login screen?
Thanks.

A: If you're using the InAppBrowser plugin, you can get the url back from Facebook login.  The Facebook auth token should be a part of that.
Similar to whats happening here (OpenFB):
 /**
 * Called either by oauthcallback.html (when the app is running the browser) or by the loginWindow loadstart event
 * handler defined in the login() function (when the app is running in the Cordova/PhoneGap container).
 * @param url - The oautchRedictURL called by Facebook with the access_token in the querystring at the ned of the
 * OAuth workflow.
 */
function oauthCallback(url) {
    // Parse the OAuth data received from Facebook
    var queryString,
        obj;

    loginProcessed = true;
    if (url.indexOf("access_token=") > 0) {
        queryString = url.substr(url.indexOf('#') + 1);
        obj = parseQueryString(queryString);
        tokenStore['fbtoken'] = obj['access_token'];
        if (loginCallback) loginCallback({status: 'connected', authResponse: {token: obj['access_token']}});
    } else if (url.indexOf("error=") > 0) {
        queryString = url.substring(url.indexOf('?') + 1, url.indexOf('#'));
        obj = parseQueryString(queryString);
        if (loginCallback) loginCallback({status: 'not_authorized', error: obj.error});
    } else {
        if (loginCallback) loginCallback({status: 'not_authorized'});
    }
}


text:
Q: Can I delay the the loss of hope? One of the goals of the first story drives you to send scouts south to make contact with another town.  Getting to a particular landmark triggers a change in the residents, dropping Hope and raising Dissatisfaction.  Can I delay this action by postponing when I visit the landmark?

A: Partially. You can take your time, but around day 15 a lone survivor arrives and triggers the Londoners event as if you had found the city.
Additionally, this survivor dies and counts as one of your people dead, this means an additional loss of hope and you are forced to get a corpse disposal law if you haven't.


text:
Q: Runtime Error 6: OverFlow, in vb6 code execution time I am getting Runtime error 6 Overflow when iam executing my vb6 application.
i am getting this error on this line.
Sections("Section5").Controls("lblcap").Caption = Format(((lTotOperMins - KPIDown) / lTotOperMins) * 100, "#0.00")

the values lTotOperMins=0 , KPIDown=0 , and Data Types as Long
what is wrong with this code. Suggest me, i am not familiar to VB6.

A: As jac said, it's because you're not checking first for a division by zero. I know that seems misleading because you're not getting that error, you're getting an Overflow.
As to why you're getting that instead of a division by zero is not something I'm awake enough to think deeply about, but simply checking first fixes the overflow. Here is an example resulting in an overflow followed by a working example with no errors:
Edit:### see very bottom showing how dividing TWO zeros results in an overflow, if one number is not 0 then it becomes a division by 0 error. Code at bottom.
Overflow error:
Image showing where overflow is occurring (can't upload, not enough reputation):
Click to view the image
Private Sub Form_Load()
  Dim lTotOperMins As Long, KPIDown As Long
  Dim lonDifference As Long

  lTotOperMins = 0
  KPIDown = 0

  ' Prevent / by 0
  lonDifference = lTotOperMins - KPIDown

  'If 0 = lonDifference Then
    'Label1.Caption = Format(0, "#0.00")
  'Else
    Label1.Caption = Format(((lonDifference) / lTotOperMins) * 100, "#0.00")
  'End If

End Sub

Working example:
Private Sub Form_Load()
  Dim lTotOperMins As Long, KPIDown As Long
  Dim lonDifference As Long

  lTotOperMins = 0
  KPIDown = 0

  ' Prevent / by 0
  lonDifference = lTotOperMins - KPIDown

  If 0 = lonDifference Then
    Label1.Caption = "0.00"
  Else
    Label1.Caption = Format(((lonDifference) / lTotOperMins) * 100, "#0.00")
  End If

End Sub

Dividing two zeros results in overflow error
Private Sub Form_Load()
  Dim a As Long, b As Long

  a = 0
  b = 0

  Debug.Print a / b
End Sub


text:
Q: java: ClassCastException when upcasting Animation to CustomAnimation I have a class that extends android.view.Animation:
package diffusi.on.com.fifteen_puzzle;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

public class CustomAnimation extends Animation {

    private boolean _isLast = false;

    private View _currentTarget = null;

    public interface AnimationListener {
        void onAnimationEnd(CustomAnimation animation);
        void onAnimationRepeat(CustomAnimation animation);
        void onAnimationStart(CustomAnimation animation);
    }

    public static void animateSetOfViews(
            View[] viewsSet,
            int animResId,
            int[] startTimeOffsets,
            Context context,
            AnimationListener animationListener
        ) {
        CustomAnimation animation;
        int startTimeOffset;
        boolean isLastAnim;

        for (int intA = 0; intA < viewsSet.length; intA++) {
            isLastAnim = intA == viewsSet.length - 1;
            animation = (CustomAnimation) AnimationUtils.loadAnimation(context, animResId);
            if (intA <= startTimeOffsets.length - 1) {
                startTimeOffset = startTimeOffsets[intA];
            } else startTimeOffset = 0;
            animation.applyToView(viewsSet[intA], startTimeOffset, isLastAnim, animationListener);
        }
    }

    public CustomAnimation() {

    }

    public CustomAnimation(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public boolean isLast() {
        return this._isLast;
    }

    public View getCurrentTarget() {
        return this._currentTarget;
    }

    private void applyToView(View view, int startTimeOffset, boolean isLast, AnimationListener listener) {
        this._isLast = isLast;
        this._currentTarget = view;
        this.setStartOffset(startTimeOffset);
        this.setAnimationListener((Animation.AnimationListener) listener);
        this._currentTarget.startAnimation(this);
    }

}

It compiles in IDE without errors. But in runtame, it throws an exception (ClassCastEcxeption) on line:
animation = (CustomAnimation) AnimationUtils.loadAnimation(context, animResId)
Why does I can't upcast Animation instance to my CustomAnimation, which extends Animation ?

A: It's not upcasting, it is downcasting. Upcasting would be of the form CustomAnimation to Animation.
Presumably AnimationUtils.loadAnimation returns a reference to an object which isn't actually a CustomAnimation - so you can't cast to it. You can only cast to a type when the actual type of the object at execution time is compatible with the type you're casting to. For example:
Object x = new Integer(10);
String y = (String) x; // Bang - invalid cast

Object a = "Foo";
String b = (String) a; // This is fine


text:
Q: Simple proof that holomorphic functions maps dense sets to dense sets As stated in the title I'm searching a simple way to prove that:

*

*$\Omega \subset \mathbb{C}$ dense in $\mathbb{C}$

*$f$ a holomorphic map $f$ from $\Omega $ to $\mathbb{C}$

*f is not constant

$\implies f(\Omega)$ is also dense in $\mathbb{C}$.
Thanks in advance !

A: It is not sufficient that $\Omega$ is dense in $\mathbb{C}$. A simple counterexample is the principal branch of the square root, which is holomorphic
on $\mathbb{C} \setminus (-\infty, 0]$.
However, if we add the condition that $\mathbb{C} \setminus \Omega$ is closed and discrete, I think the following should work.
We can proceed by contraposition. Suppose that $\overline{f(\Omega)} \neq \mathbb{C}$. Then there are $w \in \mathbb{C}, r > 0$
such that $|f(z) - w| \ge r$ for all $z \in \Omega$, which implies that the function $g(z) = 1/(f(z) - w)$ is a bounded holomorphic function on $\Omega$. Because the singularities of $g$ are isolated, it follows by Riemann's theorem
that $g$ can be extended to an bounded entire function, which by Liouville's theorem
must be constant. Then of course $f(z) = w + 1/g(z)$ is also constant, which contradicts the hypothesis.

Edit: I noticed only when rereading the proof that there was no real need to treat essential singularities separately, so I removed that part.


text:
Q: What is the difference between using std::random_device with pRNG e.g. std::mt19937 and without? In C++11 one can generate numbers with the use of std::random_device with or without a pseudo random number generator like mt19937.
What will be the difference using this in this exemplar code:
#include <random>
#include <iostream>

int main() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(1, 10);

    for (int i=0; i<16; ++i)
        std::cout << dist(rd) << "\t" << dist(mt) << "\n";
}

A: std::random_device is supposed to get you a seed for engines like mt19937. The quality of successive numbers produced is completely undefined and may easily be insufficient for practical purposes (such as cryptography), so relying on that is out of question.
Apart from that, mt19937 will give you the same sequence when given the same seed. A random_devices values can be only influenced by the string given to its constructor... which implies implementation-defined behavior.

A: There are two differences that I know of:

*

*Using mt199937 will be faster but less cryptographically secure.

*std::random_device will always be random, but if you initialize your mt19937 with a constant seed it will always give you the same random numbers:
std::mt19937 mt(2014);
Will give the same sequence of random bits every time. This can be useful if you want to test a specific behavior over and over again. The standard requires this in 26.5.5/4:

Required behavior: The 10000th consecutive invocation of a default-constructed object of type mt19937 shall produce the value 4123659995.

There is no such equivalent consistency with std::random_device.


text:
Q: Difference between SnakeGrid and latitude and longitude I am not a geography subject expert and maybe my this comparison make no sense as i don't have enough knowledge (one of the reason to ask this question here).
I have a project where I am doing conversion from unity co-ordinate system to GPS(Lat/Lon) using a library. The conversion working fine but now I got the environment model which is based on SnakeGrid  and the same conversion is not accurate. So my question is  how is a SnakeGrid based environment different from a latitude and longitude based coordinate system?

A: SnakeGrid is a type of Snake Projection: a projected coordinate system with grid coordinates in metres Easting/Northing.  There are many SnakeGrid coordinate systems available; each one is tailored to a particular project.  The most typical project it is used on is long linear engineering projects such as rail infrastructure: for the designed route the Snake projection has virtually zero scale factor distortion at track level within a corridor of approx +/- 20km.
SnakeGrids are usually defined using a '.dat' parameter file.  This file will enable conversions between latitude/longitude and SnakeGrid Easting/Northing. The SnakeGrid parameter file is compatible with SnakeGrid enabled software only.  This includes:

*

*SnakeGrid PointWise.  A free desktop tool for converting between
SnakeGrid E/N and lat/lon; for points and ASCII text.  Requires the correct parameter file.

*SnakeGrid Projector.  A suite of plugins for
FME for converting between SnakeGrid E/N and lat/lon for all formats that
FME supports.  Costs £500 on top of the FME licence costs. Requires the correct parameter file.
The above tools will also convert to/from SnakeGrid and UTM, US State Plane and British National Grid.
There are alternative methods of using Snake Projections using NTv2 transforms which are more generally compatible within geospatial software systems.  This may or may not be available depending on which SnakeGrid you are working with.
Suggest going back to your data supplier for further information.


text:
Q: How can I change the size and position that an application appears when first launched? When ever I launch Chrome it manifests at a specific size at the top left corner of my screen. Everytime I have to manually resize it and position it in the center of the screen.
How can I change the window size and position on the screen upon launch?

A: If so, you can specify a window position at launch with Compiz' "Place Windows" plugins:
"System -> Preferences -> CompizConfig Settings Manager -> Window Management -> Place Windows"
Try to adjust the "Placement Mode" ("General" tab) first, it seems like you have "Center" selected there, the default is "Smart".


text:
Q: AssertionError: Padding_idx must be within num_embeddings Some older code of mine was working fine for the last 2 months until it suddenly started giving this error today. I can't figure out what changed because I didn't touch this code. But I don't understand this new error:
INFO:pytorch_transformers.tokenization_utils:loading file https://s3.amazonaws.com/models.huggingface.co/bert/xlm-clm-ende-1024-vocab.json from cache at /root/.cache/torch/pytorch_transformers/6e42a59f5e60f1efc6116fd1a2c05a72ecf713a3022b9c274b727ed6469e6ac1.2c29a4b393decdd458e6a9744fa1d6b533212e4003a4012731d2bc2261dc35f3
INFO:pytorch_transformers.tokenization_utils:loading file https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-ende-1024-merges.txt from cache at /root/.cache/torch/pytorch_transformers/85d878ffb1bc2c3395b785d10ce7fc91452780316140d7a26201d7a912483e44.42fa32826c068642fdcf24adbf3ef8158b3b81e210a3d03f3102cf5a899f92a0
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-31-c365f437b895> in <module>()
      9 tokenizer = tokenizer_class.from_pretrained(args['model_name'])
     10
---> 11 model = model_class.from_pretrained(args['model_name'])
     12 model.to(device);
     13

3 frames
/usr/local/lib/python3.6/dist-packages/pytorch_transformers/modeling_utils.py in from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs)
    534
    535         # Instantiate model.
--> 536         model = cls(config, *model_args, **model_kwargs)
    537
    538         if state_dict is None and not from_tf:

/usr/local/lib/python3.6/dist-packages/pytorch_transformers/modeling_xlm.py in __init__(self, config)
    842         self.num_labels = config.num_labels
    843
--> 844         self.transformer = XLMModel(config)
    845         self.sequence_summary = SequenceSummary(config)
    846

/usr/local/lib/python3.6/dist-packages/pytorch_transformers/modeling_xlm.py in __init__(self, config)
    543         if config.n_langs > 1 and config.use_lang_emb:
    544             self.lang_embeddings = nn.Embedding(self.n_langs, self.dim)
--> 545         self.embeddings = nn.Embedding(self.n_words, self.dim, padding_idx=self.pad_index)
    546         self.layer_norm_emb = nn.LayerNorm(self.dim, eps=config.layer_norm_eps)
    547

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/sparse.py in __init__(self, num_embeddings, embedding_dim, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse, _weight)
     86         if padding_idx is not None:
     87             if padding_idx > 0:
---> 88                 assert padding_idx < self.num_embeddings, 'Padding_idx must be within num_embeddings'
     89             elif padding_idx < 0:
     90                 assert padding_idx >= -self.num_embeddings, 'Padding_idx must be within num_embeddings'

AssertionError: Padding_idx must be within num_embeddings

Can someone shed any light on what might be happening?
Thanks a lot!

A: https://discuss.pytorch.org/t/assertionerror-padding-idx-must-be-within-num-embeddings/78295?u=lenyabloko
Turns out some classes were moved out of pytorch_transformers package into transformers. I still had to use pytorch_transformers for other classes. Just needed to replace the package name in the following import statement
from pytorch_transformers import XLMConfig, XLMTokenizer, ...


text:
Q: npm ERR! code E401 npm ERR! Incorrect or missing password My Node version is 10.15.0 and NPM version is 6.8.4
On running npm install after upgrading
npm to 14.16.0 and npm to 7.6.2
Getting this error -
npm ERR! code E401
npm ERR! Incorrect or missing password.
npm ERR! If you were trying to login, change your password, create an
npm ERR! authentication token or enable two-factor authentication then
npm ERR! that means you likely typed your password in incorrectly.
npm ERR! Please try again, or recover your password at:
npm ERR!     https://www.npmjs.com/forgot
npm ERR!
npm ERR! If you were doing some other operation then your saved credentials are
npm ERR! probably out of date. To correct this please try logging in again with:
npm ERR!     npm login

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/xyz/.npm/_logs/2021-04-15T18_55_07_993Z-debug.log

A: In the directory C/Users/your-windows-username/
delete the following files:
.cache
.package
.package-lock
.npmrc

After that, go to your project and run the following command in your terminal
npm i

A: I had the same error with the company registry configured in .npmrc
registry=https:<company-registry-url>

Node version : 19.1.0
NPM version : 8.19.3
Solution:
Execute npm login
$ npm login
npm notice Log in on https:<registry-url>
Username: xxxx
Password:
Email: (this IS public) (xxxx)
Logged in as xxx on https:<registry-url>.

After this .npmrc got updated with
//<registry-url>/:_authToken=xxxxx

A: *

*Try Deleting the package-lock.json file before running the command "npm install" after upgrading the node versions, if you have not done that.

*If that will not work try removing the .npmrc file in $HOME directory as mentioned in this post.
NPM ERR Code E401: Unable to authenticate, need: Bearer authorization
Note - Deleting package-lock.json can have its own issues as mentioned in this posts, so go with this solution unless you find any better solution.
Deleting `package-lock.json` to Resolve Conflicts quickly

A: I have been getting the same error recently on various projects after running npm run dev:
npm ERR! code E401
npm ERR! Incorrect or missing password.

What fixed it for me was to delete my package-lock.json file (and any yarn.lock files, which might create conflicts with npm) and the node_modules directory. Then I updated my npm packages with npm update. (CAUTION: Before updating any npm packages, you should probably create a new Git branch and run npm update in that new branch. If you run into bigger problems after the updates, then you can revert back to your previous branch.)
After my packages were updated, then running my npm startup script (e.g. npm run dev) worked again without errors.
NOTE: You can run npm outdated to see which of your npm packages could use an update.

A: Your password in .npmrc must be base64 encoded. Easy to screw up just copy-pasting the password, need to base64 encode that.

A: Had the same issue with Node 16.x.x.
I have done everything from this topic and those topics which were mentioned here and nothing helped me!
The only thing that helped me to login was that I have deleted Node 16.x.x and installed Node 14.8.1 from here - https://nodejs.org/en/download/releases/

A: It can be happening because of a bug on npm. This was happening to me with npm v7. Switched to v6 and it worked.
More context: https://github.com/npm/cli/pull/2153

A: Look at the specified log file (e. g. /Users/xyz/.npm/_logs/2021-04-15T18_55_07_993Z-debug.log). It could be that a 3rd party or corporate package to be installed requires authentication.
For example, if you try to install the pro icons of FontAwesome and the authentication (token) is missing, this error occurs.

A: Reinstall the lastest node.js. That fixed my issue.


text:
Q: Analyze multiple response field from google doc form One of my questionnary made with Google Doc have a multi response set.
Let's say the three possible questions are :

*

*foo

*bar

*foobar

People where allowed to tick one or more answers.
In my google spreadsheet results, I have :
answer1 : foo
answer2 : foo, bar
answer3 : bar, foobar
answer4 : foo, foobar
anwser5 : foobar
etc.

How could I analyze this type of result in SPSS ?
I have the intuition that the values could be split in multiple answers to multiple questions by I don't know how to do this.
Thanks

A: You could also try to use the index function when creating a new variable in SPSS.
For example if the answers to be processed are in the ANSWER variable, you can choose Transform / Compute variable..., and make a new numeric variable named FOO, using this function:
CHAR.INDEX(UPCASE(ANSWER),'FOO') > 0
This will result a 1 if foo is found in the ANSWER variable, and 0 if not. Then do the same with the other possible answers.
Or you can simply run this syntax:
COMPUTE FOO=CHAR.INDEX(UPCASE(ANSWER),'FOO') > 0.
EXECUTE.

A: I do not have SPSS to test it, but this solution could help you http://www.spsstools.net/Syntax/MultipleResp/ParseCommaSeparatedLetters.txt

A: To split this string into three variables:
Create the three variables, copy the strings, paste in Excel and use the special text option, choose delimiter = comma. This will split the text of the string into three Excel cells. Then you copy and paste into SPSS, all three variables at once.
Dealing with text/data, SPSS splits by variables whenever it meets tabulation (paste into Excel adds the tabulation character where there was a comma). Alternatively plain text editors (free: TextPad, Notepad++) can be used to alter the text.


text:
Q: Using BFS algorithm to find the shortest path std::list <int> q;
std::vector<bool> visited(cols + 1);
for(int i = 1; i <= cols; i++) visited[i] = false;
visited[x] = true;
if(!l[x].empty())
{
    for(std::list<int>::iterator i = l[x].begin(); i != l[x].end(); i++)
    {
        q.push_back(x); q.push_back(* i);
    }
    while(!q.empty())
    {
        y = q.back(); q.pop_back();
        x = q.back(); q.pop_back();
        if(!visited[y])
        {
            visited[y] = true;
            if(!l[y].empty())
            for(std::list<int>::iterator i = l[y].begin(); i != l[y].end(); i++)
            {
                if(!visited[*i])
                {q.push_back(y); q.push_back(* i);}
            }
            dfst[x].push_back(y);
            if(flag != 0) dfst[y].push_back(x);
        }
    }
}

This is my DFS algorithm for finding the spanning tree in a graph. I need to convert it to the BFS algorithm finding the shortest path between two vertices. Well...how can I do this? Is the BFS algorithm somewhat similar to the one above? Or do I need to write it from the beginning?
l - adjacency list
dfst - array holding spanning tree at the end
x - starting vertex
y - helper variable

A: DFS and BFS are essentially the same algorithms. The trick is which data structure you use, or  rather which nodes you are exploring first.
A depth-first search utilizes a stack and would thus go as far down as possible before moving back in the algorithm.
To utilize a breadth first search, you would need to use a queue of nodes, and explore each node, add their neighbors (if not visited already) to the queue, and then process the rest of the parent node's neighbors before continuing onwards.
It wouldn't be a drastic change of your code, just a change in how you get nodes from your list.
Rather than popping off the back you would simply use q.pop_front() to get your nodes.

A: BFS is similar to DFS. Instead of going as deep as you can, backtracking and repeating, you look at all nodes at depth 1, then all nodes of depth 2, etc, until you've visited all nodes.
Basic Algorithm:
 -Choose a starting node and add to LookQueue
 -look at all nodes directly touching and add them to LookQueue
 -when you've looked at them all
    -look at all nodes in LookQueue (removing them as you do)
    and look at all nodes touching them (adding them as you do)
       -repeat until all nodes are visited

A: For Finding Shortest Path
(Written in C++ / C++11)
I think this important to add here, especially because the title is on shortest paths! (the code below that actually allow you to find one)
In addition:
As mentioned above (in the comments to the second reply) DFS and BFS are pretty much not(!) the same algorithms, the similarity in the code in which replacing the stack with a queue and allowing you to jump from one to another does not make them "essentially the same". BFS is by far the better/right one (between the two) to find the shortest path in an unweighted graph. BFS is building layers from the source and DFS is going as deep as it can.
Actually when running BFS (to find the shortest path) you should initialize your nodes with a "distance" parameter with a very large number and instead using the visited DS, you update it to the parent's distance + 1 (only if it's still with the initialized value).
A simple example would be:
#include <iostream>
#include <vector>
#include <queue>
#include <limits>

using namespace std;
const int imax = std::numeric_limits<int>::max();
using vi = vector<int>;

/* printPath - implementation at the end */
void
printPath(int s, int t, const vi &path);

/*input:
* n is number of the nodes in the Graph
* adjList holds a neighbors vector for each Node
* s is the source node
*/

void dfs(int n, vector<vi> adjList, int s)
{
    //imax declared above as the max value for int (in C++)
    vector<int> distance(n, imax);
    vi path;
    queue<int> q; q.push(s); distance[s] = 0;

    while (!q.empty()) {
        auto curr = q.front(); q.pop();

        for (int i = 0; i < (int)adjList[curr].size(); ++i) {
            if (distance[i] == imax) {
                distance[i] = distance[curr] + 1;
                //save the parent to have the path at the end of the algo.
                path[i] = curr;
            }
        }//for
    }//while
     /* t can be anything you want */
    int t = 5;
    printPath(s, t, path); cout << endl;
}

/* print the shortest path from s to t */
void
printPath(int s, int t, const vi &path)
{
    if (t == s) {
        return;
    }
    printPath(s, path[t], path);
    cout << path[t];
}

Inspired by Steven & Felix, from:
Competitive Programming 3

A: No,you don't have to change much in your code. just replace replace stack in case of DFS with Queue and it will become BFS.
Difference in implementation of BFS and DFS is that "BFS is implemented using Queue and DFS is using Stack" (Reason is obvious that DFS does depth like in maze.)
SEE changes for yourself:
DFS:
void dfs(int start)
{
    int j,temp;
    stack<int> s; //STACK
    s.push(start);
    vector<int>:: iterator it;
    while(s.empty()==0)
    {
        temp=s.top(); // Top element from Stack
        s.pop();
        status[temp]=1; // marked as visited , 0 means unvisited
        cout<<temp<<endl; // visited element
        for(it=list[temp].begin();it!=list[temp].end();it++)
        {
            j=*it;
            if(status[j]==0)
            {
                s.push(j);
                status[j]=2;    // means that it is in stack
            }
        }

    }
}

BFS:
void bfs(int start)
{
    int j,temp;
    queue<int> q; // QUEUE
    q.push(start);
    vector<int>:: iterator it;
    while(q.empty()==0)
    {
        temp=q.front(); // Front element from Queue
        q.pop();
        status[temp]=1; // marked as visited , 0 means unvisited
        cout<<temp<<endl; // visited element
        for(it=list[temp].begin();it!=list[temp].end();it++)
        {
            j=*it;
            if(status[j]==0)
            {
                q.push(j);
                status[j]=2;    // means that it is in queue
            }
        }

    }
}

As you can see implementation of both just differ "in use of STACK and QUEUE".
Hope this helps !


text:
Q: Can BDD and Lean methodologies be used together? I was chatting with my product manager last week and he was bemoaning the lack of progress on our product.  It's a fair criticism, too.  So we got to talking about to describe the writing of requirements.  I'm a big fan of BDD and using something like the Gherkin syntax to describe how the system should behave in terms of a user or actor.
He was pretty dismissive of BDD and said we should be using Lean methodologies like SBCE (set based concurrent engineering) and other stuff which I don't know a massive amount about given I've not read much on Lean practices so far.
Are these two methodologies mutually exclusive? If not BDD then there would need to be some other way of describing what the system should do.  Does Lean have its own language for requirements?

A: To my understanding, Lean development intends to optimize the development process of your team, with the focus on balancing between quality, costs and time. It is an organizational method, which does not embrace a specific syntax, language or notation. BDD, however, has its focus on "building the right software", and getting the requirements right, by using a specific modeling and a specific form of testing - so BDD is a less an organizational, but more a technical approach. So if you want to take some notations, terms or testing methodology from BDD, this will not contradict Lean - BDD and Lean are somewhat orthogonal.
However, if you try introducing BDD and it turns out it will slow down your processes even more, don't be surprised when your manager in favor of a Lean development process might identify BDD as "waste" (in the Lean sense), and throws the BDD stuff out. So when you suggest BDD, be sure it aims at problems you really have in your team, and it is not just because you "are a big fan of BDD" - fanboyism is a big warning sign for most experienced managers. Since you did not tell us so far the reasons why the speed of progress does not meet your expectations, I cannot tell you if BDD is the right or wrong tool for your problem. But be careful not to attempt to use a technical solution for an organizational problem, that will most probably fail.

A: Most of our Lean knowledge comes from the work that Deming did at Toyota. There are two main ways in which I look at Lean:

*

*Lean Product Development

*Lean Production.

Lean Product Development is the equivalent to designing new cars, and is more like software development than production is. We're busy creating new things, not producing the same old thing again and again predictably. It's about minimizing work in progress, getting fast feedback and using those metrics to work out what to build.
Lean Production is more like a factory. The idea is to minimize variability to ensure high-quality. The only bit of software that's even vaguely like this is the build system, but even that's more like designing the factory along with the car. Particularly, Lean Six Sigma is about reducing the variability enormously, and is completely, totally inappropriate for SW dev.
The one thing they do both have in common is that minimization of work in progress. (It's a bit more complicated than this, but this is a light overview for you.)
I would be very careful, when looking at "Lean", regarding which of the techniques you apply. Fortunately SBCE is from the first, not the second, so your boss is mostly on the right page. Lean Start-Up approaches (which is where I'm guessing he read about SBCE) are also part of that group.
Lean and BDD are completely compatible; in fact, I recommend a Kanban System approach with BDD anyway. In shorthand, this translates to reducing the gap between the conversations around scenarios happening, and the actual work on those scenarios being done, while minimising the number of conversations which aren't being progressed to software (because you'll forget what you talked about over time).
SBCE is a method for running multiple concurrent experiments, which is useful when there's uncertainty around the work that needs to be done. BDD is really great at helping to work out which bits of work are uncertain, and which are well-understood or require expertise. The Specification-By-Example bit of BDD is only one part of BDD, though it's the part most people are familiar with, and that's probably why your boss is dismissing it (unnecessarily).
For more info, try this blog I wrote on using BDD as a sensemaking technique (finding those borders I just talked about), this one on estimating complexity, or watch any of my talks on BDD and Cynefin. Your boss may find the first blog I've linked reassuring as well.


text:
Q: Java Spring Data MongoDB and Java 8 Time I am trying to use the Java 8 LocalDate and LocalDateTime in my Java Spring project, but I get problems saving and retrieving the dates from my MongoDB.
I am using Spring Data Mongo (1.6.1.Release). I've followed this answer and implemented my own converter (After it didn't work I tried to directly convert LocalDate to String).
The problem I guess, is that Spring Data is not using the converter, since my database entry looks like this:
{ "_id" : "frank@steiler.eu", "_class" : "de.steilerdev.myVerein.server.model.User", "firstName" : "Frank", "lastName" : "Steiler", "password" : "ef9aa46dd6f98af4878ed72eac69134ac236b5581e1207bd8e9d4f691ed20a48f4ed8d2b80229e4a649f1e7b5302c2c6166fc783b9cbfff6d8a18ad820652b1e", "salt" : "6b912cac277c6656", "memberSince" : { "year" : 2000, "month" : 1, "day" : 1 }, "birthday" : { "year" : 1994, "month" : 6, "day" : 28 } }

Here is my code (If I am missing anything out, my complete project can be found here):
database-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans  xmlns="http://www.springframework.org/schema/data/mongo"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:beans="http://www.springframework.org/schema/beans"
              xmlns:context="http://www.springframework.org/schema/context"
              xsi:schemaLocation=" http://www.springframework.org/schema/beans
                                   http://www.springframework.org/schema/beans/spring-beans.xsd
                                   http://www.springframework.org/schema/context
                                   http://www.springframework.org/schema/context/spring-context.xsd
                                   http://www.springframework.org/schema/data/mongo
                                   http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

        <!-- Including database configuration files -->
        <context:property-placeholder location="classpath:mongo.properties"/>

        <mapping-converter id="javaTimeConverter">
            <custom-converters>
                <converter>
                    <beans:bean class="de.steilerdev.myVerein.server.time.StringToLocalDateConverter" />
                </converter>
                <converter>
                    <beans:bean class="de.steilerdev.myVerein.server.time.StringToLocalDateTimeConverter" />
                </converter>
                <converter>
                    <beans:bean class="de.steilerdev.myVerein.server.time.LocalDateTimeToStringConverter" />
                </converter>
                <converter>
                    <beans:bean class="de.steilerdev.myVerein.server.time.LocalDateToStringConverter" />
                </converter>
            </custom-converters>
        </mapping-converter>

       <!-- Database configuration -->
       <repositories base-package="de.steilerdev.myVerein.server.model" />
       <template db-factory-ref="mongoDbFactory" converter-ref="javaTimeConverter"/>

       <db-factory host="${dbHost}"
                   port="${dbPort}"
                   dbname="${dbName}"
                   username="${dbUsername}"
                   password="${dbPassword}"/>

       <!-- Data Validation using Hibernate Validator and JavaX validation interface -->
       <beans:bean id="dataValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

       <beans:bean id="mongoValidator" class="org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener">
              <beans:constructor-arg name="validator" ref="dataValidator"/>
       </beans:bean>

</beans:beans>

One of the convertes (The others are similiar)
package de.steilerdev.myVerein.server.time;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * This class is a converter used by SpringData, to convert a Java 8 LocalDateTime to a Java 7 Date
 */
@Component
public class LocalDateTimeToStringConverter implements Converter<LocalDateTime, String>
{
    @Override
    public String convert(LocalDateTime source) {
        return source == null ? null : source.toString();
    }
}

My user object (without the getter and setter)
package de.steilerdev.myVerein.server.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import de.steilerdev.myVerein.server.security.PasswordEncoder;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.keygen.KeyGenerators;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

public class User implements UserDetails
{
    @NotBlank
    private String firstName;
    @NotBlank
    private String lastName;

    @Id
    @Indexed
    @NotBlank
    @Email
    private String email;

    @JsonIgnore
    @NotBlank
    private String password;

    @JsonIgnore
    @NotBlank
    private String salt;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private HashMap<String,String> privateInformation;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private HashMap<String,String> publicInformation;

    @DBRef
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private List<Division> divisions;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private LocalDate memberSince;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private LocalDate passiveSince;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private LocalDate birthday;

    @Transient
    @JsonIgnore
    Collection<? extends GrantedAuthority> authorities;

    @Transient
    @JsonInclude(JsonInclude.Include.NON_NULL)
    boolean administrationAllowed;
}

My error occurs during log in and is the following:
org.springframework.security.authentication.InternalAuthenticationServiceException: No property null found on entity class java.time.LocalDate to bind constructor parameter to!
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110)
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.data.mapping.model.MappingException: No property null found on entity class java.time.LocalDate to bind constructor parameter to!
    at org.springframework.data.mapping.model.PersistentEntityParameterValueProvider.getParameterValue(PersistentEntityParameterValueProvider.java:74)
    at org.springframework.data.mapping.model.SpELExpressionParameterValueProvider.getParameterValue(SpELExpressionParameterValueProvider.java:63)
    at org.springframework.data.convert.ReflectionEntityInstantiator.createInstance(ReflectionEntityInstantiator.java:71)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:249)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:230)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1129)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.access$200(MappingMongoConverter.java:77)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1078)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getValueInternal(MappingMongoConverter.java:829)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter$1.doWithPersistentProperty(MappingMongoConverter.java:278)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter$1.doWithPersistentProperty(MappingMongoConverter.java:266)
    at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:294)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:266)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:230)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:190)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:186)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:77)
    at org.springframework.data.mongodb.core.MongoTemplate$ReadDbObjectCallback.doWith(MongoTemplate.java:2121)
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindOneInternal(MongoTemplate.java:1760)
    at org.springframework.data.mongodb.core.MongoTemplate.doFindOne(MongoTemplate.java:1577)
    at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:497)
    at org.springframework.data.mongodb.repository.query.AbstractMongoQuery$SingleEntityExecution.execute(AbstractMongoQuery.java:307)
    at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:107)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:421)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:381)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:512)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy1100.findByEmail(Unknown Source)
    at de.steilerdev.myVerein.server.security.UserAuthenticationService.loadUserByUsername(UserAuthenticationService.java:48)
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
    ... 36 more

A: Ok so I do think I may have something for you :)
You have 4 converters:

*

*LocalDate -> String

*String -> LocalDate

*LocalDateTime -> String

*String -> LocalDateTime

Now, see your class declarations:
public class LocalDateToStringConverter implements Converter<LocalDateTime, String>

public class StringToLocalDateConverter implements Converter<String, LocalDate>

public class LocalDateTimeToStringConverter implements Converter<LocalDateTime, String>

public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime>

What is wrong with the first one? You are mapping LocalDateTime to String, while your class name says you should be mapping LocalDate to String.
Copy/paste is a mean and evil thing sometimes. Let me know if it had helped!
Ps. you are creating your converters two times: one time in database-config.xml while the second one through @Component annotation.


text:
Q: Swift live preview cropper In my application, I am trying to recreate a live preview picture cropper like in the popular application "Photomath".

Initially, I divided my code into three different classes. The Live preview view (a UIView), an Overlay View (a UIView also), and the actual Cropper View.
Currently, my thought process is to add the CropperView into the Overlay and then the Overlay into the Live Preview View. So far that's working.
I have a UIPanGesture hooked up to the CropperView in order to have it move around eventually. However, here is where the problem resides.
The inside of the cropper is clear or less dark than the surrounding overlay. I've heard that you can achieve this using a mask but have not been successful.
Here is the code for the Live Preview View
class NotationCameraView : UIView {

private var session : AVCaptureSession!
private var stillImageOutput : AVCapturePhotoOutput!
private var videoPreviewLayer : AVCaptureVideoPreviewLayer!
private var previewCropper : OverlayCropper!

override init(frame: CGRect) {
    super.init(frame: frame)
    self.commonInitializer()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.commonInitializer()
}

private func commonInitializer() {
    if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {

        self.setUpLivePreview()
        self.setUpOverlayCropper()
        print("Set up view")
    } else {
        AVCaptureDevice.requestAccess(for: .video) { (success) in
            if success {

                self.setUpLivePreview()
                self.setUpOverlayCropper()
            } else {
                print("Give me your camera REEEEEEEEEEE")
            }
        }
    }
}

/**
 Sets up the live preview of the back camera
 */
private func setUpLivePreview() {
    self.session = AVCaptureSession()
    self.session.sessionPreset = .high
    let backCamera = AVCaptureDevice.default(for: AVMediaType.video)

    //MARK: Need to have an overlay view so that the user does not see the video preview frame being upscaled

    do {
        let input = try AVCaptureDeviceInput(device: backCamera!)

        self.stillImageOutput = AVCapturePhotoOutput()

        if self.session.canAddInput(input) && self.session.canAddOutput(self.stillImageOutput) {
            self.session.addInput(input)
            self.session.addOutput(self.stillImageOutput)

            self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
            self.videoPreviewLayer.videoGravity = .resizeAspectFill
            self.videoPreviewLayer.connection?.videoOrientation = .portrait
            self.layer.addSublayer(videoPreviewLayer)

            //Have public methods for starting or stopping the capture session
            DispatchQueue.global(qos: .userInitiated).async {
                self.session.startRunning()
                DispatchQueue.main.async {
                    self.videoPreviewLayer.frame = self.bounds
                }
            }
        }

    } catch {
        print("Need to allow permission to the back camera")
    }
}

/**
 Sets up the overlay cropper for the live preview.
 */
private func setUpOverlayCropper() {
    self.previewCropper = OverlayCropper(frame: self.bounds)
    self.previewCropper.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(self.previewCropper)
}

}
Here is the code for the Overlay.
class OverlayCropper : UIView {

private var cropperView : CropperView!

override init(frame: CGRect) {
    super.init(frame: frame)
    self.commonInitializer()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.commonInitializer()
}

private func commonInitializer() {
    self.cropperView = CropperView(frame: CGRect(x: 50, y: 100, width: 100, height: 100))
    self.cropperView.backgroundColor = UIColor.blue
    self.cropperView.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(cropperView)

    self.backgroundColor = UIColor.black.withAlphaComponent(0.25)

}

}
and lastly here is the code for the CropperView
class CropperView : UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
    self.commonInitializer()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.commonInitializer()
}

private func commonInitializer() {
    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.handlePanGesture(_:)))
    self.addGestureRecognizer(panGesture)
    self.makeMask()
}

@objc private func handlePanGesture(_ panGesture : UIPanGestureRecognizer) {
    let translation = panGesture.translation(in: self)
    //print(translation.x, translation.y)

    self.center = CGPoint(x: self.center.x + translation.x, y: self.center.y + translation.y)
    panGesture.setTranslation(CGPoint.zero, in: self)
}

private func makeMask() {
    let path = CGMutablePath()
    path.addRect(CGRect(origin: .zero, size: self.frame.size))
    let maskLayer = CAShapeLayer()
    maskLayer.backgroundColor = UIColor.clear.cgColor
    maskLayer.path = path
    maskLayer.fillRule = .evenOdd
    self.layer.mask = maskLayer
    self.clipsToBounds = true
}

}


text:
Q: How can Antlr4 extract interesting parts from a large file I have the following Antlr4 grammar.
grammar Paradox;

paradox:
  kvPair+;

kvPair
  : atom '=' atom
  | atom '=' scope
  | scope
  ;

scope
  : '{' (paradox|atom+)? '}'
  ;

atom
  : STRING
  | NUMBER
  | ID (':' ID)?
  ;

STRING
  : '"' (~'"')*? '"'  ;

ID : [0-9a-zA-Z_]+ ;

NUMBER
    : '-'?[0-9]+ ('.' [0-9]+)?
    ;

WS : [ \t\r\n]+ -> skip ;

The file is 20 MB, looks like this
version="Boulle v1.9.1"
version_control_revision=31493
name="泰布理同胞体"
date="2269.02.09"
planet= { ... }
...
country = {
    0 = {
        ...
        name="USA"
        ...
        food_surplus=3.598
        ...
    }
    1 = {
        ...
        name="ENG"
        ...
        food_surplus=2.001
        ...
    }
    ...
}
...

... means omitted lines by me. The actual file has valid grammar there.
Say I only need to know the number of countries, and for each country, record its name and food_surplus.
Currently what I do is
ICharStream cstream = CharStreams.fromstring(input);
ITokenSource lexer = new ParadoxLexer(cstream);
ITokenStream tokens = new CommonTokenStream(lexer);
var parser = new ParadoxParser(tokens);
// find kvPair with key "country".
// Then .ChildCount is the number of country,
// find kvPair with key "name" to get the name of the country.

This approach works, but the drawback is that it consumes as large as 1GB memory when it's running. Notice I'm not using and don't know how to use visitor pattern or listener pattern.
I understand the large memory consumption is because of the ..., the lines I omitted, which can be millions of lines. Antlr is building parse tree for these uninterested things.
How do I reduce the memory consumption?

A: A parser is not the right tool for such kind of processing, as it is supposed to validate all the input it gets. That's the main/primary goal of a parser per se. If you are only interested in parts of your input then split it first by other means (e.g. search for certain delimiters) and only feed the interesting parts to your parser.
Update:
By request: the ANTLR4 docs have a short description for listeners/visitors, to be used with a parse tree generated by a parser run. In order to use a listener during parsing you just need to register your listener (which is exactly like the one used after parsing):
JavaLexer lexer = new JavaLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
JavaParser parser = new JavaParser(tokens);
MyListener extractor = new MyListener(parser);
parser.addParseListener(extractor);
JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse a compilationUnit


text:
Q: What did Cersei mean when she said "You flowered little dove"? In one of the episodes of Game of Thrones, Sansa woke up to found blood on her bed. She became fearful and started to hide this from Cersei. I didn't understand it. Cersei was cruel to Sansa, but I don't think she wouldn't have given Sansa medical attention. Afterall, Sansa was going to marry Joffrey.
And then, things got more confusing. Instead of calling a maester, Cersei simply said "You flowered little dove". If Sansa had pooped that much blood, that situation could kill her.
I know the meaning of the verb flower. From Google/ Oxford:

*

*(of a plant) produce flowers; bloom.
  "Michaelmas daisies can flower as late as October"

*be in or reach an optimum stage of development; develop fully and richly.
  "she flowered into as striking a beauty as her mother"

I believe second definition has some context, but what has a disease to do with this?
Did Cersei make fun of Sansa by secretly meaning that Sansa lost her youth because of a serious health issue? What exactly did Cersei mean when she said "You flowered little dove"?

A: It's a euphemism for having her period. Cersei is the Queen and Sansa is also a noble lady, gently born and of the highest birth. Cersei was not going to speak as if she were a commoner to such. Not to mention, it was Sansa's first period and her reaction made Cersei think Lady Catelyn may not have had "The Talk" with her, which is why a softer touch was needed, even if you disregard the need for courteous speech.
As to why Sansa was afraid, Betrothals turn into marriage once the woman has her first period (Since that is the definition of majority in Westeros). Sansa at that point had seen what Joffrey was and had no wish to be his bride. She was afraid that they will now make her marry Joff and that's why she tried to burn the evidence.

SANSA: No, no! No. Oh, no.
SERVING GIRL: It's all right. Give me that.
SANSA: If the queen sees, I can have Joffrey's children now. Help me flip it over. Where are you going?
SERVING GIRL:To tell Her Grace.
SANSA: You'll say nothing to anyone. Do you understand?
[SCENE CHANGES]
CERSEI: Your mother might have prepared you. You flowered, my dear. No more.
SANSA: My mother told me, but I thought it would be different.
CERSEI: In what way?
SANSA: I thought it would be less… Less messy.
CERSEI: Wait until you birth a child. You're a woman now. Do you have any idea what that means?
SANSA: I'm fit to bear children for the king?
CERSEI: A prospect that once delighted you, bringing little princes and princesses into the world, the greatest honour for a
  queen.S02E07 - A MAN WITHOUT HONOUR


text:
Q: SQL: return values when PK equals two specific values in two different rows on the same field I am trying to return the rows where the SAME id is both in 23 and 12 (this is just an example... I have 30K records)
ID: ASDJKGFJKBQGW Number:23
ID: ASDJKGFJKBQGW Number:12
ID: ASDJKGFJKBQGW Number:43
ID: ASDJKGFJKBQGW Number:67
ID: ASDJKGFJKBQGW Number:32

Doing: select * from table where Number=23 and Number=12 won't do.
Do I need to declare a variable for the ID and do a while loop?
While @ID is the same
select * from table where Number = 23 and Number = 12

Thanks

A: this should do the trick
select * from table where Number in (23, 12)

or
select * from table where Number = 23 or Number = 12

EDIT
something like this:
   select id from table where number in (23,12)
   group by id
   having count(*) = 2

if the numbers can appear multiple times for each id then you may use a subquery
   select id from
   ( select distinct id, number from table ) x
   where number in (23,12)
   group by id
   having count(*) = 2

A: Select * from table1
Where number in (14,23) and id in(
Select id from table1
Where number in (14,23)
Group by id
Having count(distinct number) = 2)

The inner subquery uses the having clause that gives the exact number of rows 2. Together with the distinct you are sure to get these rows


text:
Q: Conditional Show/Hide in Active Admin I have this form in Active Admin:
form(:html => { :multipart => true }) do |f|
  f.inputs 'Home Carousel Image' do
    f.input :name
    f.input :file, as: :file
    f.input :headline_text, as: :html_editor
    f.input :button_text
    f.input :featured_image?
    f.input :headline_text
    f.input :button_text
  end

  actions
end

featured_image? is a boolean. I was hoping to see if a user selects this (switching it to true), only then would the input fields for :headline_text and :button_text be displayed. Otherwise, these two fields will be hidden on the form.
Is this possible?
Thanks

A: Yes, just use if:
f.input :featured_image?
if f.object.featured_image?
  f.input :headline_text
  f.input :button_text
end

Use f.object to take instance of your model.


text:
Q: codeigniter and ajax form error I am having troubles with this code, I am trying to do ajax on codeigniter, I have a form with the username to select . If I click on an user I don't get the other variables from the database. The SQL query works fine. The code is divided into view/controller/model. The model code seems to work fine, the problem should be into the view and/or the controller.
I visualize correctly the front end form, but when I click on the names I get no output from the queries, there is no explicit error.
view code:
<!doctype html>

   <title>How to send AJAX request in Codeigniter</title>

  Select Username : <select id='sel_user'>
   <option value='abc'>abc</option>
   <option value='ad'>ad</option>
   <option value='admin'>admin</option>
   <option value='sunil'>sunil</option>
  </select>

   Username :

   Name :

   Email :

controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class user_ajax extends CI_Controller {

 public function index(){

  // load base_url
  $this->load->helper('url');

  // load view
  $this->load->view('user_view_ajax');
 }

 public function userDetails(){
  // POST data
  $postData = $this->input->post();
  # echo $postData;
  //load model
  $this->load->model('model_ajax');

  // get data
  $data = $this->model_ajax->getUserDetails($postData);

  echo json_encode($data);
 }

}

model code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class model_ajax extends CI_Model {

 function getUserDetails($postData){

  $response = array();

  if($postData['username'] ){
    /*
   // Select record
   $this->db->select('*');
   $this->db->where('username', $postData['username']);
   $q = $this->db->get('users');
   $response = $q->result_array();
   */
    // Create connection
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "anubi";
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    #$sql = $conn->query("SELECT username, password, email from users WHERE username=".$postData['username']);
    #$response=$sql->result_array();
    $sql = $conn->query("SELECT username, password, email from users WHERE username=".$postData['username']);
    $array = array();
     while ($row = $sql->fetch_assoc()) {
        $array[] = $row;

     }
     $response=$array;
  }

  return $response;
 }

}

A: why you are using core php mysql connect functionality ? just put db details in database.php and use CodeIgniter Query builder for mysql queries.
Please Check this link --
https://www.codeigniter.com/userguide3/database/query_builder.html#selecting-data

A: data: {"username": username}
do this type


text:
Q: On an isomorphism of rings Let $k$ be a field, it's claimed in algebraic geometry textbook that $k[v^2, v^3]\cong k[t, u]/(t^2-u^3)$ via $v^2\mapsto u, v^3\mapsto t$. But I can't show it's well-defined, since an integer can have many ways to write as $2i+3j$. Any idea?

A: Instead you should try to show that $\phi : k[t,u] \longrightarrow k[v^2,v^3]$ has kernel generated by $(t^2-u^3).$ This map will be surjective, and well defined.The first isomorphism theorem will give you the desired result.


text:
Q: Load image to image box using C# I am trying to load an image to picture box the below way worked with me.
image1.Image = Properties.Resources._0;

what it i want make the code reading from resources as variable name like the way below.
var imagename = _0;

image1.Image = Properties.Resources.imagename;

Thanks

A: Use the ResourceManager and pass it a string:
var imageName = "_0";
image1.Image = (Image)Properties.Resources.ResourceManager.GetObject(imageName);


text:
Q: Export/import in client JavaScript without build system In ES6 added new feature - using construction export and import. Example:
import name from "module-name";
export let name = 'test'

But browsers not supported this. If connected Babel, this feature will not work. Manuals recommended use Build system. How use this features in browser without build system? Babel, Babel + RequireJS do not give result.


text:
Q: How do I split a string into separate lists? I am given this as a string:
Orville Wright 21 July 1988 \n
Rogelio Holloway 13 September 1988 \n
Marjorie Figueroa 9 October 1988 \n

I need to separate the names from the dates and print it like this:
Birthdate:
21 July 1988 \n
13 September 1988 \n
9 October 1988 \n
etc..

I tried to save the string into a variable and split it into a list
content = ""

temp = content.strip()
temp = temp.split()

A: You can use regex for this problem:
import re
str = 'Orville Wright 21 July 1988 \n Rogelio Holloway 13 September 1988 \n Marjorie Figueroa 9 October 1988 \n'
Birthdate = re.findall(r'(\d+ \w+ \d+)', str)
>>> ['21 July 1988', '13 September 1988', '9 October 1988']

A: Assuming this is how the content will be
content = 'Orville Wright 21 July 1988 \n Rogelio Holloway 13 September 1988 \n Marjorie Figueroa 9 October 1988 \n'

and then we do
content = content.strip().split('\n')

BirthDate = ''

for a in aa:
    a = a.strip().split(' ')
    date = f'{a[2]} {a[3]} {a[4]} \n '
    BirthDate = BirthDate + date


text:
Q: jQuery/Moment to PHP date time conversion This is the jQuery/Moment Code that a friend made

$(document).ready(function() {
      //get current time
      moment.tz.add('America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0');
      var currTime = moment().tz('America/New_York');
      $('.currTime').text(currTime.format("YYYY-MM-DD HH:mm:ss"));
      $('input[name="gmt_offset"]').val(new Date().getTimezoneOffset() / 60);

      //calculate window time
      var tblRows = $('tbody > tr').each(function() {

        var windowOpen = moment($(this).find('td.windowOpen').text());
        var windowClose = moment($(this).find('td.windowClose').text());
        var estTime = moment($('.currTime').text());
        if (parseInt(windowOpen.format("X")) > parseInt(estTime.format("X"))) {
          //Window Open Days
          if (parseInt(windowOpen.diff(estTime, "days")) > 0) {
            $(this).find('td.winOpenDay').text(windowOpen.diff(estTime, "days"));
          } else {
            $(this).find('td.winOpenDay').text("0").addClass("danger");
          }
          //Window Open Hours
          if (parseInt(windowOpen.diff(estTime, "hours")) < 24 && parseInt(windowOpen.diff(estTime, "hours")) > 0) {
            $(this).find('td.winOpenHr').text(windowOpen.diff(estTime, "hours"));
          } else if (parseInt(windowOpen.diff(estTime, "hours")) < 0 || parseInt(windowOpen.diff(estTime, "hours")) % 24 < 0 || parseInt(windowOpen.diff(estTime, "hours")) === 0) {
            $(this).find('td.winOpenHr').text("0").addClass("danger");
          } else if (parseInt(windowOpen.diff(estTime, "hours")) > 24) {
            $(this).find('td.winOpenHr').text(parseInt(windowOpen.diff(estTime, "hours")) % 24);
          }
          //Window Open Min
          if (parseInt(windowOpen.diff(estTime, "minutes")) < 60 && parseInt(windowOpen.diff(estTime, "minutes")) > 0) {
            $(this).find('td.winOpenMin').text(windowOpen.diff(estTime, "minutes"));
          } else if (parseInt(windowOpen.diff(estTime, "minutes")) < 0 || parseInt(windowOpen.diff(estTime, "minutes")) % 60 < 0 || parseInt(windowOpen.diff(estTime, "minutes")) === 0) {
            $(this).find('td.winOpenMin').text("0").addClass("danger");
          } else if (parseInt(windowOpen.diff(estTime, "minutes")) > 60) {
            $(this).find('td.winOpenMin').text(parseInt(windowOpen.diff(estTime, "minutes")) % 60);
          }
        } else {
          $(this).find('td.winOpenDay').text("0").addClass("danger");
          $(this).find('td.winOpenHr').text("0").addClass("danger");
          $(this).find('td.winOpenMin').text("0").addClass("danger");
        }

        if (parseInt(windowClose.format("X")) > parseInt(estTime.format("X")) && parseInt(windowOpen.format("X")) < parseInt(estTime.format("X"))) {
          //Window Close Hours
          if (parseInt(windowClose.diff(estTime, "hours")) < 24 && parseInt(windowClose.diff(estTime, "hours")) > 0) {
            $(this).find('td.winCloseHr').text(windowClose.diff(estTime, "hours"));
          } else if (parseInt(windowClose.diff(estTime, "hours")) < 0 || parseInt(windowClose.diff(estTime, "hours")) % 24 < 0 || parseInt(windowClose.diff(estTime, "hours")) === 0) {
            $(this).find('td.winCloseHr').text("0").addClass("danger");
          } else if (parseInt(windowClose.diff(estTime, "hours")) > 24) {
            $(this).find('td.winCloseHr').text(parseInt(windowClose.diff(estTime, "hours")) % 24);
          }
          //Window Open Min
          if (parseInt(windowClose.diff(estTime, "minutes")) < 60 && parseInt(windowClose.diff(estTime, "minutes")) > 0) {
            $(this).find('td.winCloseMin').text(windowClose.diff(estTime, "minutes"));
          } else if (parseInt(windowClose.diff(estTime, "minutes")) < 0 || parseInt(windowClose.diff(estTime, "minutes")) % 60 < 0 || parseInt(windowClose.diff(estTime, "minutes")) === 0) {
            $(this).find('td.winCloseMin').text("0").addClass("danger");
          } else if (parseInt(windowClose.diff(estTime, "minutes")) > 60) {
            $(this).find('td.winCloseMin').text(parseInt(windowClose.diff(estTime, "minutes")) % 60);
          }
        } else {
          $(this).find('td.winCloseHr').text("0").addClass("danger");
          $(this).find('td.winCloseMin').text("0").addClass("danger");
        }

      });

    });
.tableHeader{background-color:rgb(38,50,72);color:rgb(192,152,0);}

        Kill Info
        Current Time (EST)
        2015-09-18 17:03:27
        Windows Open In
        Window Closes In

        Target
        Death (EST)
        Window Opens (EST)
        Window Closes (EST)
        Days
        Hours
        Minutes
        Hours
        Minutes

        Mob1
        2015-09-18 14:18:51
        2015-09-19 14:18:51
        2015-09-20 10:18:51
        0
        0
        0
        0
        0

        Mob2
        2015-09-17 11:01:45
        2015-09-18 11:01:45
        2015-09-19 07:01:45
        0
        0
        0
        0
        0

        Mob3
        2015-09-18 05:27:01
        2015-09-19 05:27:01
        2015-09-20 01:27:01
        0
        0
        0
        0
        0

I have been trying to recreated it in PHP, This is what I got
function diff_time($diff_timestamp1, $diff_timestamp2) {

    $diff_seconds  = $diff_timestamp1 - $diff_timestamp2;
    $diff_days     = floor($diff_seconds/86400);
    $diff_seconds -= $diff_days*86400;
    $diff_hours    = floor($diff_seconds/3600);
    $diff_seconds -= $diff_hours*3600;
    $diff_minutes  = floor($diff_seconds/60);

    return array('d' => $diff_days, 'h' => $diff_hours, 'm' => $diff_minutes);
}

    Kill Info
    Current Time (EST)
    <?php echo date('m-d-Y h:i A', time()); ?>
    Windows Open In
    Window Closes In

    Target
    Death (EST)
    Window Opens (EST)
    Window Closes (EST)

            Days
            Hours
            Minutes

            Hours
            Minutes

    <?php
    for ($i = 0; $i < $mobs["count"]; $i++) {
    read_times($mobs[$i]["kill_mob"], $times);
    switch($mobs[$i]["kill_mob"]){
        case "Mob1":
        case "Mob2":
        case "Mob3":
        case "Mob4":
        $mobWinOpen = "+ 16 hours";
        $mobWinClose = "+ 26 hours";
        break;
        case "Mob5":
        $mobWinOpen = "+ 40 hours";
        $mobWinClose = "+ 60 hours";
        break;
        default:
        $mobWinOpen = "+ 24 hours";
        $mobWinClose = "+ 44 hours";
        break;
    }
    $winopen = strtotime($mobWinOpen, $times["kill_time"]);
    $winclose = strtotime($mobWinClose, $times["kill_time"]);
    $open_time  = diff_time($winopen, time());
    $close_time = diff_time($winclose, time());
    ?>

        <?php echo $times["kill_mob"]; ?>
        <?php echo date('m-d-Y h:i A', $times["kill_time"]); ?>
        <?php echo date('m-d-Y h:i A', $winopen); ?>
        <?php echo date('m-d-Y h:i A', $winclose); ?>

            <?php
            if ($winopen > time()) {
                ?>

                <?php
                if ($open_time["d"] > 0) {
                    echo $open_time["d"];
                } else {
                    echo "0";
                }
                ?>

                <?php
                if (($open_time["h"] < 86400) && ($open_time["h"] > 0)) {
                    echo $open_time["h"];
                } elseif (($open_time["h"] < 0) || ($open_time["h"] % 86400) < 0 || ($open_time["h"] == 0)) {
                    echo "0";
                } elseif ($open_time["h"] > 86400) {
                    echo $open_time["h"] % 86400;
                }
                ?>

                <?php
                if (($open_time["m"] < 60) && ($open_time["m"] > 0)) {
                    echo $open_time["m"];
                } else if (($open_time["m"] < 0) || ($open_time["m"] % 60 < 0) || ($open_time["m"] == 0)) {
                    echo "0";
                } else if ($open_time["m"] > 60) {
                    echo $open_time["m"] % 60;
                }
                ?>

            <?php
            } else {
                ?>
                0
                0
                0
            <?php
            }
            ?>

            <?php
            if (($winclose > time()) && ($winopen < time())) {
                ?>

                <?php
                if (($close_time["h"] < 86400) && ($close_time["h"] > 0)) {
                    echo $close_time["h"];
                } elseif (($close_time["h"] < 0) || ($close_time["h"] % 86400) < 0 || ($close_time["h"] == 0)) {
                    echo "0";
                } elseif ($close_time["h"] > 86400) {
                    echo $close_time["h"] % 86400;
                }
                ?>

                <?php
                if (($close_time["m"] < 60) && ($close_time["m"] > 0)) {
                    echo $close_time["m"];
                } else if (($close_time["m"] < 0) || ($close_time["m"] % 60 < 0) || ($close_time["m"] == 0)) {
                    echo "0";
                } else if ($close_time["m"] > 60) {
                    echo $close_time["m"] % 60;
                }
                ?>

            <?php
            } else {
                ?>
                0
                0
            <?php
            }
            ?>

    <?php
    }
    ?>

My Code is ok, it outputs the correct "Death", "Window Opens" and "Window Closes" Times. The problem seems to be with the Days/Hours/Min and Hours/Min for each mob. I tried to recreate the jQuery/Moment code in PHP but it just doesn't work and I can't figure out what is causing it to mess up.


text:
Q: Typescript: Class that implements at least a specific interface I have the following question. Let's say i have an Interface like this
interface Animal<T>{
   children: Array<T>
}

now i want to write a method which will later take in e.g. a bird (a class that implements Animal). At the time writing the method the definition for bird does not exist yet. It could also be it would be given an instance of Shark. But the minimal requirement will be that any object it receives will be an instance of a class that implements Animal.
function doSomething(AnAnimal){
   //Do something with animal
}

// Implementation with a class that implements Animal

class Bird<T> implements Animal{
   children: Array<T>;
   color: string;
   chirp(){console.log('peep')}

   constructor(Color:string){
      this.color = Color;
   }
}

let tweety = new Bird('yellow');

doSomething(Tweety)

I hope I could make clear what I'm trying to do and you have an idea how i could solve this in TypeScript.

A: You need to flow your type arguments throughout your example...
interface Animal<T>{
   children: Array<T>
}

function doSomething<T>(arg: Animal<T>){
   //Do something with animal
}

class Bird<T> implements Animal<T>{
   children: Array<T>;
   color: string;
   chirp(){console.log('peep')}

   constructor(Color:string){
      this.color = Color;
   }
}

let tweety = new Bird('yellow');

doSomething(tweety);

For example, Bird<T> must implement Animal<T>. The doSomething function must be generic in order to deal with an argument of type Animal<T>.
Non-Generic Version
You might find that you are tying yourself up unnecesarily in type arguments here - so you might want to try the non-generic version.
interface Animal {
    children: Array<Animal>;
}

function doSomething(arg: Animal) {
    //Do something with animal
}

class Bird implements Animal {
    children: Array<Bird>;
    biggestEnemy: Animal;
    color: string;
    chirp() { console.log('peep') }

    constructor(Color: string) {
        this.color = Color;
    }
}

let tweety = new Bird('yellow');

doSomething(tweety);


text:
Q: Exponent rules with negative numbers Hello if you could answer this please what is the difference between  -2^2 and (-2)^2

A: $$-2^2=(-1)2^2=-4$$  and $$(-2)^2=(-1)^2(2)^2=(-1)(-1)(4)=4$$

A: Just an extra here, Derrick. Please do NOT resort to the scientific calculator. The TI30 will show -2 to the power 2 as 4 without brackets, whereas Ti84 for example will show -4. I deal with this issue in class every semester. Calculators mean it well, but their order of operations is not always the "same" as what we have in our minds. Learn the rules of exponents without the calculator. It's better.

A: In view of the other answers here: the difference between -2^2 and (-2)^2 is 8. :-)

A: It is assumed that
$$-2^2=-(2^2)=-4\;,\;\;\text{whereas}\;\;(-2)^2=4$$


text:
Q: Mystery users with active processes appear in 'who -a' 'who -a' returns a bunch of mystery log-ins. Apparently empty pts/# are logged out users, but active processes are assigned to the so-called terminated users.
           run-level 5  2019-06-13 19:14
LOGIN      tty2         2019-07-13 07:21             13232 id=tty2
LOGIN      console      2019-06-13 19:14               419 id=cons
           pts/0        2019-07-13 07:36             13592 id=ts/0  term=0 exit=0
           pts/1        2019-07-13 07:51             14072 id=ts/1  term=0 exit=0
           pts/2        2019-07-13 01:11              4344 id=ts/2  term=0 exit=0
           pts/3        2019-07-13 07:37             13700 id=ts/3  term=0 exit=0
user + pts/4        2019-07-13 19:48 01:15       14097 (xxx.xxx.x.xxx via mosh [xxxxx])
user + pts/5        2019-07-13 20:26   .         30505 (xxx.xxx.x.xxx)

How can pts/0 to pts/4 and tty2 be kicked out, plus and is run-level 5?

A: You are NOT seeing any users there and there is nobody to be "kicked out"
By default who -a also shows -d ; dead processes.
Terminals that closed down and the exit code of the process that was running there and stopped/died.


text:
Q: How to make this query simple and short. (my_sql) and PHP I provide two php which contain two type of query, can someone help me to make this query shorter than this. Thanks in advance
<?php $sel = mysql_query("SELECT COUNT( form ) AS ML FROM webcm WHERE department ='PDN-ML' AND DATE = CURDATE()");
$get_sel = mysql_fetch_array($sel);
$PDNML1 = $get_sel['ML'];

$sel1 = mysql_query("SELECT COUNT( form ) AS HM FROM webcm WHERE department ='PDN-HM' AND DATE = CURDATE()");
$get_sel1 = mysql_fetch_array($sel1);
$PDNHM1 = $get_sel1['HM'];

$sel2 = mysql_query("SELECT COUNT( form ) AS AI FROM webcm WHERE department ='AI' AND DATE = CURDATE()");
$get_sel2 = mysql_fetch_array($sel2);
$AI1 = $get_sel2['AI'];

$sel3 = mysql_query("SELECT COUNT( form ) AS SMT FROM webcm WHERE department ='SMT' AND DATE = CURDATE()");
$get_sel3 = mysql_fetch_array($sel3);
$SMT1 = $get_sel3['SMT'];?>

A: SELECT SUM(`ML`) AS `ML`,
       SUM(`HM`) AS `HM`,
       SUM(`AI`) AS `AI`,
       SUM(`SMT`) AS `SMT`
FROM (
SELECT SUM( CASE WHEN department='PDN-ML' THEN 1 ELSE 0 END) AS `ML`,
       SUM( CASE WHEN department='PDN-HM' THEN 1 ELSE 0 END) AS `HM`,
       SUM( CASE WHEN department='AI' THEN 1 ELSE 0 END) AS `AI`,
       SUM( CASE WHEN department='SMT' THEN 1 ELSE 0 END) AS `SMT`
FROM webcm
WHERE DEPARTMENT IN ('PDN-ML','PDN-HM', 'AI', 'SMT')
AND DATE = CURDATE()
) AS T

DEMO

http://sqlfiddle.com/#!9/9e8fcf/1

A: Maybe you can do is :
SELECT COUNT( form ) AS ML, department
FROM webcm WHERE DATE = CURDATE()
AND DEPARTMENT IN ('PDN-ML','PDN-HM', 'AI', 'SMT')
group by department

you can access all , $get_sel2['ML'] will give you count and $get_sel2['department'] will give you department name or code.
Then you will have one query result with count and corresponding department.

A: try this
<?php $sel = mysql_query("SELECT count(*) as ML,department from webcm where DATE = CURDATE() GROUP BY department  ");
$get_sel = mysql_fetch_array($sel);
$PDNML1 = $get_sel['ML'];

OR
<?php $sel = mysql_query("SELECT count(*) as ML,department from webcm where DATE = CURDATE() and DEPARTMENT IN ('PDN-ML','PDN-HM', 'AI', 'SMT') GROUP BY department  ");
$get_sel = mysql_fetch_array($sel);
$PDNML1 = $get_sel['ML'];

A: SELECT department,
   case when department='PDN-ML' then COUNT( form ) else 0 end AS ML ,
   case when department='PDN-HM' then COUNT( form ) else 0 end AS HM,
   case when department='AI' then COUNT( form ) else 0 end AS AI,
   case when department='SMT' then COUNT( form ) else 0 end AS SMT,
FROM webcm
WHERE DEPARTMENT IN ('PDN-ML','PDN-HM', 'AI', 'SMT')
AND DATE = CURDATE()
GROUP BY department


text:
Q: ViewModelProviders.of(activity) only accept fragment or fragmentactivity i have a problem using mvvm in splash activity and relate the viewmodel to the activity,i don't won't to create fragment for it .
in AppCompatActivity:
fun <T : ViewModel> AppCompatActivity.obtainViewModel(viewModelClass: Class<T>) =
    ViewModelProviders.of(this, ViewModelFactory.getInstance(application)).get(viewModelClass)

it says that .of(this,factor) only accept fragment and fragmentActivity
i already read  link but it doesn't solve the problem
my build.grable:
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.attendance.myproject.begory"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    // to prevent the addition of jvm-target
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildFeatures {
        dataBinding true
    }
}

dependencies {
    def room_version = "2.2.3" // check latest version from docs

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.10"
    implementation "androidx.recyclerview:recyclerview:$rootProject.recyclerViewVersion"
    implementation "androidx.cardview:cardview:$rootProject.cardViewVersion"
    implementation "androidx.constraintlayout:constraintlayout:2.0.2"
    //noinspection GradleCompatible

    implementation 'androidx.appcompat:appcompat:1.3.0-alpha02'
//room

    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"

    implementation "com.google.android.material:material:1.3.0-alpha03"
    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.1'
    implementation 'androidx.navigation:navigation-ui-ktx:2.3.1'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:17.5.1'
    implementation 'com.google.firebase:firebase-auth:19.4.0'
    implementation 'com.google.firebase:firebase-database:19.5.1'
    implementation 'com.firebase:firebase-client-android:2.3.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'me.dm7.barcodescanner:zxing:1.9.8'

    //    Add Zxing library to generate barcode
    implementation 'com.google.zxing:core:3.2.1'
    implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    implementation "org.jetbrains.kotlin:kotlin-script-runtime:1.4.10"
    //curved bottom navigation
    implementation 'np.com.susanthapa.curved_bottom_navigation:curved_bottom_navigation:0.6.3'

    implementation "androidx.lifecycle:lifecycle-extensions:$archLifecycleVersion"
    kapt "androidx.lifecycle:lifecycle-compiler:$archLifecycleVersion"
    implementation "androidx.core:core-ktx:1.3.2"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
    implementation'android.arch.lifecycle:extensions:1.1.1'
}
apply plugin: 'com.google.gms.google-services'

I'm using androidx and the activity is extended from the appcompatActivitty .I had initiate the viewmodel in the on create fun .
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_splash)
    if(!Internet.isOnline(applicationContext)) showMessage(getString(R.string.no_internet_connection))

    binding= DataBindingUtil.setContentView(this, R.layout.activity_splash)
    splashViewModel = obtainViewModel()
    binding.splashViewModel
    subscribeToNavigationChanges(splashViewModel)

}

I really takes days searching in this problem if any one can help it will be very thankful.

A: The problem is that you're using the wrong ViewModelProviders import. You need to remove this line from your dependencies:
implementation 'android.arch.lifecycle:extensions:1.1.1'

android.arch.lifecycle is the old, pre-AndroidX artifacts that you should not and cannot use when using AndroidX dependencies. You already have the androidx.lifecycle:lifecycle-extensions dependency, which is the full replacement for android.arch.lifecycle:extensions, which actually has the right version of ViewModelProviders that works with the AndroidX version of AppCompatActivity.
Note that there's no reason to write or use any method like your obtainViewModel since this is already provided for you by val viewModel: YourViewModel by viewModels() that is part of the activity-ktx dependency (that you already get as a transitive dependency through navigation-fragment-ktx.


text:
Q: JBossMQ - Clustered Queues/NameNotFoundException: QueueConnectionFactory error I am trying to get an application working on a JBoss Cluster.  It uses Queues internally, and the developer claims that it should work correctly in a clustered environment.  I have jbossmq setup as a ha-singleton on the cluster.  The application works correctly on whichever node currently is running the queue, but fails on the other nodes with a: "javax.naming.NameNotFoundException: QueueConnectionFactory not bound"  error.  I can look at JNDIview from the jmx-console and see that indeed the QueueConnectionFactory class only appears on the primary node in the Global context.  Is there a way to see the Cluster's JNDI listing instead of each server?
The steps I took from a default Jboss 4.2.3.GA installation were to use the "all" configuration. Then removed /server/all/deploy/hsqldb-ds.xml and /deploy-hasingleton/jms/hsqldb-jdbc2-service.xml, copying the example/jms/mysq-jdbc2-service.xml file into its place (editing that file to use DefaultDS instead of MySqlDS).  Finally I created a mysql-ds.xml file in the deploy directory pointing "DefaultDS" at an empty database.  I created a -services.xml file in the deploy directory with the queue definition. like the one below:
<server>
        <mbean code="org.jboss.mq.server.jmx.Queue"
                name="jboss.mq.destination:service=Queue,name=myfirstqueue">
                <depends optional-attribute-name="DestinationManager">
                        jboss.mq:service=DestinationManager
                </depends>
        </mbean>
</server>

All of the other cluster features of working, the servers list each other in the view, and sessions are replicating back and forth.  The JBoss documentation is somewhat light in this area, is there another setting I might have missed?  Or is this likely to be a code issue (is there different code to do a JNDI lookup in a clusted environment?)
Thanks

A: The problem was with the code.  The @resource syntax is apparently not cluster compliant.  The developer tried another method and it works correctly.


text:
Q: Is there a way to import the js library file to my DIH script? I am importing some data using DIH, I'd like to use script transformer in order to perform some transformations before indexing.
As the transformations are a bit complex I am using an external js library.
My question is: Is there a way to import the js library file to my DIH script?
like:
<script src="lib/proj4js.js"></script>

A: Unfortunately it seems that there is no way to import js files into DIH data conf file.
Here is the answer I got from solr user's mailing list:
solr-user-mailing-list
It seems that, there is no where in script transformer code, where the script import is handled.
:(