text:
Q: SQL Server SSL connection - What am I missing? I am trying to set up my SQL Server 2008 R2 instance so that it only accepts SSL connections.  My understanding is that once this is set up, any client machine should need to have a certificate installed in order to connect.
I have followed the instructions on http://msdn.microsoft.com/en-us/library/ms191192(v=sql.105).aspx and done a lot of reading on a lot of other sites as well.  I have created a certificate, selected it in the SQL Server Configuration Manager (Network Configuration/Protocols/Properties), and I have set 'Force Encryption' to true.  I restarted the service running my instance.
After doing all this, when I try to connect to my instance remotely, I succeed.  Normally I like succeeding but in this case I haven't installed a certificate my development machine would recognize (this is where my instance is) and when I look at the connection properties, it says the connection is not encrypted.  If I choose to try an encrypted connection from the client (selecting this in SQL Server Management Studio's Options in the connection box), I get the certificate problem I expect.
So my questions are:  am I right that if things are set up correctly the connection from the client should fail (because it lacks an appropriate certificate) without my having to configure anything on the client?  And is there something obvious that I might be missing?  Some other place where I have to change a property, maybe?  I am hoping that someone who has done this before will have some ideas.
By the way, in creating my cert I followed SQL Dude's instructions at http://thesqldude.com/tag/makecert/.  The cert's name is my dev machine's full qualified domain name.

A: Note that when you force encryption on the server side, the connection will be encrypted by using ssl. You can use any certficate for this. Your connection will be encrypted, However the client will not check if the identity of the SQL Server is in fact valid. Without this check you could be open for a man in the middle attack.
If you choose force encryption on the client side, a full validity check will be performed. That way not only is the connection encrypted, also the client knows that the server it is connection to, is in fact the server mentioned in the certificate because it can trust that the certificate has not been tampered with.
For this to work, the certificate used on the SQL Server must be issued by a certificate authority that the client trust. This can be any well known certificate authority or for example when you have a windows domain and a CA in that domain, you can have that CA issue one. You then have to import the root certificate of that CA into all clients and that will work too.
to check if your connection is encrypted use the following:
SELECT session_id,encrypt_option
FROM sys.dm_exec_connections


text:
Q: Extending $\|H^{\frac{1}{2}}XK^{\frac{1}{2}}\|\leq\frac{1}{2}\|HX+XK\|$ from matrices to operators I saw in some literature that many author works in finite dimensional (matrix) is because it can be extended into infinite dimensional (operator). The case is as follows:
If the following inequality
$$\|H^{\frac{1}{2}}XK^{\frac{1}{2}}\|\leq\frac{1}{2}\|HX+XK\|$$ holds for any $n\in\mathbb{N}$ and for any $H,K,X\in M_{n}(\mathbb{C})$ with $H,K>0,$ then so is for any $H,K,X\in\mathcal{B}(\mathcal{H})$ with $H,K>0.$
Here $M_{n}(\mathbb{C})$ denotes the collection of $n\times n$ matrix with complex entries, $H>0$ denotes positive definite matrix (operator), $\mathcal{B}(\mathcal{H})$ denotes the collection of bounded linear operator on Hilbert space $\mathcal{H}.$
What I'm thinking is by involving (finite dimensional) projection and take the limit.
$$\lim_{n\rightarrow\infty}\|P_{n}H^{\frac{1}{2}}XK^{\frac{1}{2}}P_{n}\|\leq\frac{1}{2}\lim_{n\rightarrow\infty}\|P_{n}(HX+XK)P_{n}\|$$
where $\lim_{n\rightarrow\infty} P_{n}=I,$ ($I\in\mathcal{B}(\mathcal{H})$).
But I'm not sure, whether I'm on the right track or not.
Any help would be appreciated. Thank you

A: I dont'think you are on the right track. The limit $\lim_nP_n=I$ occurs in the strong operator topology (and other weak topologies on $B(H)$) but not in the norm topology.
If you are looking for the particular inequality mentioned in your question, the usual proof works the same for operators, you gain nothing by going to matrices first.
If your question is general, I don't think you can expect to have a general method that allows you to prove that any norm inequality for matrices holds for arbitrary operators.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Display Different CNN Activations using Keract? Recently I have been working with CNNs for about a month now and I am trying to use Keract to visualize the activations for each layer of a CNN given one image:
from keras import activations
from keract import get_activations, display_heatmaps, display_activations

keract_inputs = x_test[:1]
keract_targets = y_test[:0]
activations = get_activations(model, keract_inputs)
display_activations(activations=activations,cmap='YlGnBu')

OUTPUT:
Activations
Yet this code only displays the SECOND image and when I try to change the code so that this shows me the first image or the later images, it skips the layers every time:
from keras import activations
from keract import get_activations, display_heatmaps, display_activations

keract_inputs = x_test[:2]
keract_targets = y_test[:0]
activations = get_activations(model, keract_inputs)
display_activations(activations=activations,cmap='YlGnBu')

OUTPUT:
input_1 (32, 32, 3) -> Skipped. First dimension is not 1.
conv2d (2, 32, 32, 32) -> Skipped. First dimension is not 1.
conv2d_1 (2, 30, 30, 32) -> Skipped. First dimension is not 1.
max_pooling2d (2, 15, 15, 32) -> Skipped. First dimension is not 1.
conv2d_2 (2, 15, 15, 64) -> Skipped. First dimension is not 1.
conv2d_3 (2, 13, 13, 64) -> Skipped. First dimension is not 1.
max_pooling2d_1 (2, 6, 6, 64) -> Skipped. First dimension is not 1.
flatten (2, 2304) -> Skipped. First dimension is not 1.
dense (2, 512) -> Skipped. First dimension is not 1.
dense_1 (2, 10) -> Skipped. First dimension is not 1.

Any way I can change my code so that it displays the activations for other images?

A: Found the Solution:
Telling the program to set keract_inputs = x_test[:2] actually gives 2 dimensions from the first element to the second element, but if you change this to another 1 dimensional range, the program works perfectly
from keras import activations
from keract import get_activations, display_heatmaps, display_activations

keract_inputs = x_test[1:2]
keract_targets = y_test[:0]
activations = get_activations(model, keract_inputs)
display_activations(activations=activations,cmap='YlGnBu')

You have to define the range between the element you want and the one before it
This works when trying to find activations for image N by selecting x_test[N-1:N]


text:
Q: In C++, with the linux api available, is there a way to have an event occur after a time t has passed? So far I have been using the linux api and boost libraries in this project so ideally I'd like to stick to those.
I am trying to find out how many bytes my server is sending in a second. My plan is to just have a variable which will reset every second that I append the return value of the send() function to every time I send(the return value is the # of bytes sent).
The problem is: how will I know when to stop appending to the variable? I would like some type of interrupt event which would tell me "Hey, it has been a second! Record the bytes sent and reset the variable before appending to it again!" I already have an epoll setup so if I could add some type of file descriptor that I would poll with epoll that would be ideal!
Any and all advice/suggestions are appreciated. Thank you in advance!
P.S: An idea I have is to have a timer thread. It sleeps for a second then when it wakes up it writes to a message queue. Since message queue's can be polled by epoll I would get the event and know. The sleeper thread would just continue looping. Any better ideas?

A: Set up a SIGALRM handler to terminate the measurement, then call alarm(2) with the time you want to measure for in seconds.

A: If you use boost then you perhaps should use boost::asio for asynchronous IO. It wraps most things you need into platform-independent interface. It contains timer and timer has expires_at().

A: As gettimeofday has precision up to microseconds you can use it to grab timestamps after every send and calculate your instant speed. Also one can aggregate number of bytes for roughly one second (you don't need to be precise at all), divide number of bytes by actual number of microseconds elapsed and send it out to subscribers interested.


text:
Q: How can I extract the fb:profile-pic uid attribute value using jQuery? From the following XML, I must extract the value of the uid attribute (557103888) on the fb:profile-pic element:

      <fb:profile-pic height="32" width="32" linked="false" uid="557103888" style="width: 32px; height: 32px;" class=" fb_profile_pic_rendered">

      </fb:profile-pic>

I'm using jQuery, and so far have the following code:
function deleteImage($item) {
    $item.fadeOut(function() {
    var $list = $('ul',$trash).length ? $('ul',$trash) : $('
').appendTo($trash);
    $item.find('a.ui-icon-trash').remove();
    $item.appendTo($list).fadeIn(function() {
     //alert($('.fb_profile_pic_rendered').attr('uid'));
    //alert("added "+ $count + " " + $item.find('img').attr('src'));
    findUserID($item.find('img').attr('src'));
    $item.animate({ width: '48px' }).find('img').animate({ height: '36px' });
    $count++;
     })
 });
}

A: Try this:
alert($('.fb_profile_pic_rendered').attr('uid'));


text:
Q: raw buffer to Eigen::Map::Matrix of complex I'm getting a raw buffer stream in from a source.
unsigned char *data = ...; // of know length

I would like to map that into MyMapMatrixXci.
typedef Eigen::Matrix<std::complex<uint16_t>, Eigen::Dynamic, Eigen::Dynamic>
    MyMatrixXci;
typedef Eigen::Map<MyMatrixXci> MyMapMatrixXci;

I'm struggling to find the right steps to get this mapped.
If I already have my data in a type matching the map I can get things to work.  Example below...
std::complex<uint16_t> *data = new std::complex<uint16_t>[rows * cols];
for (int i = 0; i < rows * cols; ++i) {
    data[i] = {i, i};
}
Eigen::Map<MyMatrixXci, Eigen::RowMajor> mat(&data[0], rows, cols);
std::cout << mat << std::endl;

Where I'm struggling is reinterpreted casting of the 'unsigned char *data' buffer to the 'std::complex<uint16_> *'.  Or going directly to the Map.  In the casting case I always end up in a cast 'not allowed' error.  In the direct case I end up on not matching a candidate constructor.
(I can get a mapping of a raw buffer to a non complex matrix map to work.  It seems the addition of the complex aspect is introducing issues for the direct map.  This page was great but didn't have a n example for my specific issue. https://eigen.tuxfamily.org/dox-devel/group__TutorialMapClass.html)

A: Well, As normal just as I posted the question I tried a new option which worked.  Curious if there is a better solution out there...
 // my types
 typedef Eigen::Matrix<std::complex<uint16_t>, Eigen::Dynamic, Eigen::Dynamic>
  MyMatrixXci;
  typedef Eigen::Map<MyMatrixXci> MyMapMatrixXci;

 // some consts
 const size_t rows = 3;
 const size_t cols = 4;

 // fake some raw data. (2 below is for complex real,imag)
 uint8_t *raw = new uint8_t[rows * cols * sizeof(uint16_t) * 2];
 for (size_t i = 0; i < rows * cols * 2; ++i) {
     raw[i * 2] = i;
 }

 // answer
 const MyMapMatrixXci mat(
     reinterpret_cast<std::complex<uint16_t> *>(raw),
     rows,
     cols);

 // Verify answer
 std::cout << mat << std::endl;

This seems to match my expected answer...
 (0,1)   (6,7) (12,13) (18,19)
 (2,3)   (8,9) (14,15) (20,21)
 (4,5) (10,11) (16,17) (22,23)


text:
Q: One canvas, two dom elements? Is it possible to have two dom elements reference the same canvas, so that one canvas is shown in two places without requiring a second canvas?

A: Sure!
Use the html5 canvas data url as a background for multiple elements:
$('.bk').css('background-image','url('+canvas.toDataURL()+')');

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

ctx.fillStyle='skyblue';
ctx.strokeStyle='gray';
ctx.lineWidth=3;
ctx.beginPath();
ctx.arc(50,50,40,0,Math.PI*2);
ctx.closePath();
ctx.fill();
ctx.stroke();

$('.bk').css('background-image','url('+canvas.toDataURL()+')');
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
.bk{width:100px;height:100px;border:1px solid green;}

Canvas

<canvas id="canvas" width=100 height=100></canvas>

Two Divs containing the same canvas background

One

Two


text:
Q: How to assign null to a hive table column using pyspark My pyspark script is populating a hive table and one column need to be initialized as null so that the consuming code can check when(df.columname.isNull()) during select statement,
please advise how to set column name to null when writing to the hive table.

A: lit(None).alias(Column_name) will give the result
Inside hive or beeline Column_name is null will return true


text:
Q: Coding the R-ight way - avoiding the for loop I am going through one of my .R files and by cleaning it up a little bit I am trying to get more familiar with writing the code the r-ight way. As a beginner, one of my favorite starting points is to get rid of the for() loops and try to transform the expression into a functional programming form.
So here is the scenario:
I am assembling a bunch of data.frames into a list for later usage.
dataList <- list (dataA,
                  dataB,
                  dataC,
                  dataD,
                  dataE
                  )

Now I like to take a look at each data.frame's column names and substitute certain character strings. Eg I like to substitute each "foo" and "bar" with "baz". At the moment I am getting the job done with a for() loop which looks a bit awkward.
colnames(dataList[[1]])
[1] "foo"        "code" "lp15"       "bar"       "lh15"
colnames(dataList[[2]])
[1] "a"        "code" "lp50"       "ls50"       "foo"

matchVec <- c("foo", "bar")
for (i in seq(dataList)) {
  for (j in seq(matchVec)) {
    colnames (dataList[[i]])[grep(pattern=matchVec[j], x=colnames (dataList[[i]]))] <- c("baz")
  }
}

Since I am working here with a list I thought about the lapply function. My attempts handling the job with the lapply function all seem to look alright but only at first sight. If I write
f <- function(i, xList) {
  gsub(pattern=c("foo"), replacement=c("baz"), x=colnames(xList[[i]]))
}
lapply(seq(dataList), f, xList=dataList)

the last line prints out almost what I am looking for. However, if i take another look at the actual names of the data.frames in dataList:
lapply (dataList, colnames)

I see that no changes have been made to the initial character strings.
So how can I rewrite the for() loop and transform it into a functional programming form?
And how do I substitute both strings, "foo" and "bar", in an efficient way? Since the gsub() function takes as its pattern argument only a character vector of length one.

A: Your code almost works -- but remember that R creates copies of the objects that you modify (i.e. pass-by-value semantics).  So you need to explicitly assign the new string to colnames, like so:
dataA <- dataB <- data.frame(matrix(1:20,ncol=5))
names(dataA) <- c("foo","code","lp15","bar","lh15")
names(dataB) <- c("a","code","lp50","ls50","foo")
dataList <- list(dataA, dataB)
f <- function(i, xList) {
  colnames(xList[[i]]) <- gsub(pattern=c("foo|bar"), replacement=c("baz"), x=colnames(xList[[i]]))
  xList[[i]]
}
dataList <- lapply(seq(dataList), f, xList=dataList)

The new list will have data frames with the replaced names.  In terms of replacing both foo and bar, just use an alternate pattern in the regex in gsub ("foo|bar").
Note, by the way, that you don't have to do this by indexing into your list -- just use a function that operates on the elements of your list directly:
f <- function(df) {
  colnames(df) <- gsub(pattern=c("foo|bar"), replacement=c("baz"), x=colnames(df))
  df
}
dataList <- lapply(dataList, f)


text:
Q: How can I make it so that I can only type once per day? I want to save and manage a bool value in userDefaults so that I cannot input the exercise time again until the date is changed after the first exercise time is entered.
 func nextDate(){
        var compoenet = Calendar.current.dateComponents([.year, .month, .day], from: Date())
        compoenet.timeZone = TimeZone(abbreviation: "UTC")

        let dateWithoutTime = Calendar.current.date(from: compoenet)!

        let date = Date()

        inputDateAvailable.value = UserDefaults.standard.bool(forKey: "inputDateAvailable")
        print("userDefaults = \(UserDefaults.standard.bool(forKey: "inputDateAvailable"))")
        print("date \(date)")
        print(dateWithoutTime)

        if date == dateWithoutTime {
            inputDateAvailable.value = true
            print("present 됨")
        } else {
            inputDateAvailable.value = false
            print("present 안됨")
        }
    }

    func saveInputDateAvailable() {
        UserDefaults.standard.set(false, forKey: "inputDateAvailable")
    }

it's my ViewModel code.
and

    @objc func profileBtnDidTap(_ sender: UIButton) {
        guard viewModel.inputDateAvailable.value else {
            viewModel.pushProfileGraphVC()
            return
        }
        viewModel.profileBtnDidTap()
        viewModel.nextDate()
    }

    override func configureVC() {
        viewModel.saveInputDateAvailable()
}

it's my ViewController code
I've been thinking too much.
It's too hard for me to create the logic I want. please help me

A: With the sparse information you provided it seems way easier to store the date whenever the pushProfileGraphVC func is executed and check it before execution.
Change this:
func saveInputDateAvailable() {
    UserDefaults.standard.set(Calendar.current.startOfDay(for: Date()), forKey: "inputDate")
}

and add this
func isInputDateValid() -> Bool{
    UserDefaults.standard.object(forKey: "inputDate") as? Date != Calendar.current.startOfDay(for: Date())
}

function to your viewmodel.
change your profileBtnDidTap function to:
@objc func profileBtnDidTap(_ sender: UIButton) {
    guard viewModel.isInputDateValid() else {
        viewModel.pushProfileGraphVC()
        return
    }
    viewModel.profileBtnDidTap()
}

You can remove nextDate.
Be aware! saveInputDateAvailable should only be executed when whatever Viewcontroller you are pushing with pushProfileGraphVC is shown. So the function should either be called from within pushProfileGraphVC function or
override func configureVC() {
        viewModel.saveInputDateAvailable()

should reside in the pushed Viewcontroller.


text:
Q: iframe with colorbox not working my head part is
<title></title>
<link href="css/style-custom.php.css" rel="stylesheet" type="text/css" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/layout-responsive.css" rel="stylesheet" type="text/css" />
<link href="css/skeleton-responsive.css" rel="stylesheet" type="text/css" />

<link href="css/superfish.css" rel="stylesheet" type="text/css" />
<link href="css/flexslider.css" rel="stylesheet" type="text/css" />

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

and the link which open iframe is here....initially it was working but after adding master page it stopped working...please provide me solution for it.
Forgot Password

A: Check your developer console for errors.  And you probably don't mean to be loading jQuery twice (both the unminified and minified versions).


text:
Q: Refreshing Integer Value After Disabling Button I'm trying to complete a fairly basic login style page using Android Studio. If the user logs in incorrectly 3 times, the login button is disabled for a period of time, before being enabled again. I was wondering how to get the value 'counter' to reset to the original value of three again once the login button is re-enabled.
 /* switch statement which changes colour of background depending on value of counter*/
                switch (counter) {
                    case 2:
                        tx1.setBackgroundColor(Color.YELLOW);
                        break;
                    case 1:
                        tx1.setBackgroundColor(Color.RED);
                        break;
                    case 0:
                        b1.setEnabled(false);
                        check.setVisibility(View.VISIBLE);

                        b1.setEnabled(false);

                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                                MainActivity.this.runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        b1.setEnabled(true);

                                    }
                                });
                            }
                        }).start();
                }
            }
        }
    });
}

A: You have to define the value counter as member variable of a class and set it back to anything in the run method.

A: I don't see any implementation which includes counter over here. Can you modify your question and show where and how are you defining and decreasing a counter?


text:
Q: Distance to a hyperplane Let $c \in \mathbb{R}$, $\alpha =(\alpha_1, \ldots, \alpha_n )$ and $L= \{ x \in \mathbb{R}^n : \langle \alpha,x\rangle=c  \}$ (hyperplane).  Show that for all $a \in \mathbb{R}^n$, $\mathrm{d}(a,L)=\frac{ |\langle a, \alpha \rangle-c|} {\| \alpha\|}$.
We know from the projection theorem that for all $x \in \mathbb{R}^n$, $\| x- \pi_L(x)\|=\inf_{z \in L} \| x-z \|=\mathrm{d}(a,L) $
How I can write $\pi_L(x)$ ?

A: You have to consider an orthogonal from $x$ to $L$. As $L$ is parallel to the hyperplane $\{x\mid \langle \alpha,x\rangle = 0\}$, exactly $\alpha$ will give a normalvector to $L$, so
$$\pi_L(x) = x -u\alpha$$
for some $u\in\mathbb R$. Now write this into the equation of $L$ and find $u$ in terms of $c$, $\alpha$ and scalar product with $x$.


text:
Q: Faster way to multiply in javascript? I'm looking at ways to multiply faster in JavaScript, and I found this
https://medium.com/@p_arithmetic/4-more-javascript-hacks-to-make-your-javascript-faster-1f5fd88a219e#.306ophng2
which has this text
Instead of multiplying, use the bit shift operation. it looks a little more complex, but once you get the hang of it, it's pretty simple. The formula to multiply x * y is simply x << (y-1)

As a bonus, everyone else will think you're really smart!

// multiply by 1
[1,2,3,4].forEach(function(n){ return n<<0; }) // 1,2,3,4
// multiply by 2
[1,2,3,4].forEach(function(n){ return n<<1; }) // 2,4,6,8
// multiply by 3
[1,2,3,4].forEach(function(n){ return n<<2; }) // 3,6,9,12
// etc

However this doesn't seem to work for me. Does anyone know what's wrong?
Thanks

A: Ignore that article. It's intended as humor -- the advice it's giving is intentionally terrible and wrong.

*

*Multiplication does not involve "expensive logarithmic look up tables and extremely lucky guesses" with "dozens of guesses per second". It is a highly optimized hardware operation, and any modern CPU can perform hundreds of millions (or more!) of these operations per second.

*Bitwise operations are not faster than multiplication in Javascript. In fact, they're much slower -- numbers are generally stored as double-precision floating point by default, so performing a bitwise operation requires them to be converted to integers, then back.

*Bit-shifting is not equivalent to multiplication in the way that the article implies. While left-shifting by 0 and 1 are equivalent to multiplication by 1 and 2, the pattern continues with <<2 and <<3 being equivalent to a multiplication by 4 and 8, not 3 and 4.

*Array.forEach does not return a value. The appropriate function to use here would be Array.map.
The other "Javascript hacks" described in the article are even worse. I won't bother going into details.

A: Incidentally, if you want to know why it isn't working for you, you will want to use map instead of forEach since forEach ignores the return.
So do this instead:
// multiply by 1
[1,2,3,4].map(function(n){ return n<<0; }) // 1,2,3,4
// multiply by 2
[1,2,3,4].map(function(n){ return n<<1; }) // 2,4,6,8
// multiply by 4
[1,2,3,4].map(function(n){ return n<<2; }) // 4,8,12,16
// multiply by 8
[1,2,3,4].map(function(n){ return n<<3; })  // 8, 16, 24, 32

And as others have mentioned - don't use this for multiplication. Just take this as a clarity of forEach vs map...

A: Bit shift is not the same as multiplying by any number. This is how bit shift works in decimal for example:
1234 >> 0 = 1234
1234 >> 1 = 0123 #discards the last digit.
0123 >> 2 = 0001 #discards the last two digit

So in decimal, shifting digits to the right is like integer division by 10. When shifted by two digits it's the same as dividing by 10^2.
Now computers work with binary words. So instead of a digit shift, we have bit shifts.
10101011 >> 1 = 01010101

This is basically dividing by 2^1.
10101011 >> n is simply dividing by 2^n.
Now in the same manner,
10101011 << n is multiplying by by 2^n. This adds n zeroes behind the binary word.
Hope it's clearer now :)
Cheers


text:
Q: How to clean terminal(cmd) , after opening another file in terminal From this question, I solved that problem but now another problem is occured.Now my first .exe file is opening by these codes in Pygame;
process = subprocess.Popen(["wtf.exe"])
output, errors = process.communicate()

This file (wtf.exe) asking information to user before opening the Pygame and putting that information in to the Pygame;

When I confirm these informations, it's opening the Pygame screen with information I gave in first program and closing the first program;

So far everything is fine, when I click to the 'play' , it's opening another file in terminal; but last file's datas still there.

You see, first picture's datas here, it should be without these datas. Why terminal is didn't clean itself? It's another .exe file running in terminal, a new file on a 'new' terminal, but it looks it's not new. How do I clean the terminal after first file processed? As you know these are .exe files working on terminal, and I can't clear the terminal manually, I have to write some codes into that files, but I have no idea what to do.

Edit: I gave some unacceptable informations on purpose and check this picture please:

Edit2: Here is the video of my problem.

A: cls internal command (Windows) / clear command on *nix clear the terminal screen and its scrollback buffer if possible:
import os

os.system('cls')

Try it before making a comment.
As an alternative, you could start a new console window (creationflags=CREATE_NEW_CONSOLE on Windows) for each command or just the last command instead i.e., when a command ends its window is closed and therefore there is nothing to clean.
You could also run your parent script as a GUI program (use .pyw file extension) without the console i.e., if a child process needs the console; it has to allocate its own.

A: @J.F. Sebastian gave you one approach, which is to clear the screen from within your code.
However, as you are already using pygame, you can use the inputbox module to prompt the user for their input.
This way, you eliminate the problem completely.


text:
Q: Problem inserting on first match only using GNU sed 4 on my linux machine (I checked w/ sed --version).
Currently, I have a myfile.txt with the following content:
---
title: hello
author: Jan King
foo: bar
author: Jan King
---

I know in GNU sed, I can append after the first occurrence of a match if I prepend the sed command with 0,.
So, if I want to insert goodbye after the first occurrence of ---, I can do that:
 sed -i '0,/---/a goodbye' myfile.txt

expected/correct result:
---
goodbye
title: hello
author: Jan King
foo: bar
author: Jan King
---

But now, I am trying to insert goodbye after the first occurrence of author: Jan King.
However, the following sed command doesn't work and appends goodbye 3 times, which is not what I want:
 sed -i '0,/^author:.*/a goodbye' myfile.txt

incorrect/unexpected result:
---
goodbye
title: hello
goodbye
author: Jan King
goodbye
foo: bar
author: Jan King
---

If I remove 0, from the above sed command, then goodbye is appended twice after author: Jan King:
 sed -i '/^author:.*/a goodbye' myfile.txt

expected result:
---
title: hello
author: Jan King
goodbye
foo: bar
author: Jan King
goodbye
---

So I'm having trouble appending goodbye on first match only of author: Jan King (even though it is fine on first match of ---).
Can someone please explain why my sed command isn't working? And how to fix it?

A: You need to use the two conditions:

*

*the range of lines 0,/^author:/

*the specific line inside this range /^author:/
You can write it like this:
sed -i '0,/^author:/{/^author:/a goodbye
}' file

A: The link you show in the comment is not quite the same command sequence that you're trying to use. If you want to use the same technique, try:
sed -i '0,/^\(author:.*\)/s//\1\nNew Inserted Line/' myfile.txt

A: This might work for you (GNU sed):
sed -i -e '/^author:/{a goodbye' -e ':a;n;ba}' file

Focus on the first line containing author:, then append goodbye and loop through all remaining lines.


text:
Q: I can´t run my tests using mvn test in Maven I have the following POM:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.manning.junitbook</groupId>
<artifactId>ch13-continuous</artifactId>
<version>1.0-SNAPSHOT</version>

<name>ch13-continuous</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>

    <sonar.coverage.jacoco.xmlReportPaths>target\site\jacoco\jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
    <sonar.junit.reportPaths>target\surefire-reports</sonar.junit.reportPaths>

</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.5</version>
            <executions>
                <execution>
                    <id>report</id>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <phase>verify</phase>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.1</version>
        </plugin>
    </plugins>

</build>

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.6.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.6.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>

</dependencies>

And I have some test called "FlightTests" and "PassengerTests" into my directory /test/java/es.ull/flights and /test/java/es.ull/passenger respectly. However, when I launch mvn test on IntelliJ it ended up showing this:
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

Why is this happening?? I assume that it can´t localice my tests, but I don´t know why.

A: Maybe you can try with new version.
   <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
            <configuration>
              <includes>
                <include>*Test.java</include>
              </includes>
            </configuration>
  </plugin>

Also you can use jupiter and try junit5 with jupiter depedencies.
For example use @Test annotation from jupiter dependency.

A: You have some test files called "FlightTests" and "PassengerTests" and that is the issue, Could you please change the name as "FlightTest" and "PassengerTest" , by removing the s at the end, or it will not recognize the tests. I have verified it .


text:
Q: Is this correct event to observe: To fire once order is completely paid? I have a working observer using sales_order_place_after and I am changing it to use sales_order_invoice_pay. Is this is the correct method? Will this to fire only if the invoice is fully paid, front-end or admin? My test seems to indicate this is correct but I'd appreciate a look.
in Observer.php
   $invoice = $observer->getEvent()->getInvoice();
   $order = $invoice->getOrder();
        if (!$order->canInvoice() ) {
            Mage::getModel('myapps_orderman/export_mscrmapi')
            ->exportOrder($order);
        }

A: Hard question. theoretically should all payment methods use $order->pay() to mark the order as pays and create an invoice. I would use this, sales_order_invoice_pay.
If you want to be really sure, no one sets the order beside this method to paid, you can flag the order in the sales_order_load_after event, if it is not yet paid and check for the flag in the sales_order_save_after event, whether it is now paid. Additionally you can check whether the grand_total and the total_paid is the same.
But I recommend to use sales_order_invoice_pay.


text:
Q: Using Mockito test super class method

    class Sup {
          public void someMethod(){
              // do something
          }
    }

    class Sub extends Sup {
            public void method(Object obj) {
                  if (obj == null) {
                      super.someMethod();
                      return;
                  }

                 // do something
            }
    }

    class SubTest {

        @Test
        public void testMethodArgIsNull() {
                 Sub s = new Sub();
                 Sub spyS = spy(s);

                 spyS.method(null);

                 //test case fails
                 verify(spyS).someMethod();

         }
    }

if I redefine the method "method" in Sub like, instead of calling super.someMethod(), if i call someMethod(), the test case passed. But I don't want to make any changes in code. help me to test the code..

A: I don't know why you want to avoid changing code, but you may have your reasons.  You can't simply verify that the super method was called on a spy.  However, you may still be able to test this method without changing the code.  The only way to do that, though, is without the spy.  In other words, you will have to verify the functionality of someMethod with assertions or verifications on other mocks.  For example, if the Sup class were implemented trivially thus:
class Sup {
      private boolean somethingDone = false;
      public boolean isSomethingDone() {
          return somethingDone;
      }

      public void someMethod(){
          somethingDone = true;
      }
}

Then you could write your test case thus:
@Test
public void testMethodArgIsNull() {
    Sub s = new Sub();
    s.method(null);
    assertThat(s.isSomethingDone(), is(true));
}

That being said, calling super.someMethod() from anything other than Sub.someMethod() (which doesn't exist) looks like a gotcha waiting to happen.  If Sub.someMethod() does not exist, then super.someMethod() is equivalent to someMethod().  But, if someone were to override it in the future, would you really want method(Object o) to sneakily bypass the overridden one and call the super implementation anyway?
By calling super.someMethod() you gain nothing but risk future bugs.


text:
Q: Do photons interact only with single particles or can a single photon be absorbed by 2 or more particles simultaneously? Say I have 100 particles in a vacuum that are spread out such that their movement caused by a time variant electromagnetic field does not have an effect on each other. That is the particles can not exchange any energy among themselves. The varying electromagnetic field must be experienced in quanta (a photon particle). Does this mean that it will take at least 100 photons worth of light to excite all the particles?

A: Let us be clear of what type of particles we are talking about. At the atomic and elementary particle level the quantum nature of light is important. At the macroscopic level it is meaningless to talk about photons because the macroscopic wave is composed out of zillions of photons.
Let us take a hydrogen gas in a vacuum tube. It is neutral and not interacting other than with the random scatters of the gas molecules.
A single photon can interact with the spill over electric field of an atom , lose part of its energy, and continue to hit another atom or even more as long as it can find one and there is enough energy left to the end photon. Now  the probability of this happening has to be computed given the boundary conditions of the density of the gas, the volume etc etc.
The answer for single photons impinging on 100 neutral atoms/molecules is that fewer than 100 might do the job.

A: Yes, it must happen at once.
From the point of view of the EM field, you have created one large entity - so it can only react as an entity.
You confuse the issue by assuming that the energy required to get to the next energy level for this object is 100 times that of one particle. The arrangement could be anything, and indeed, larger objects usually have smaller energy steps to get to the next level. So when the object is excited, the individual particles don't notice anything, in much the same way as a passenger on an jet does not feel the effects of the air hitting the craft at 1000km/hr.
A single photon is absorbed by a single 'thing' at once. Whether that thing is made of 100 particles, or a trillion does not make a difference. An atom absorbs a photon, changing its energy level, not an electron. Or you can have a molecule absorb a single photon.

A: When you say the particles cannot interact, yes it will take at least 100 photons to excite all the particles.  You could have one particle absorb a photon, then radiate a lower energy photon that is absorbed by another particle but you have ruled that out by saying no interaction.


text:
Q: Create an array of function pointer in heap I have an array of 6 function pointers:
int (*arrayOfFunPointers[6])();

What I want to do now, is to allocate that array in heap
Because I create the array in a function and return a pointer to that array:
int (*(*fun2())[6])(){

    int (*funPointer)();
    int (*arrayOfFunPointers[6])();
    int (*(*pointerToArrayOfFunPointers)[6])();

    funPointer = &fun;
    arrayOfFunPointers[0] = funPointer;
    pointerToArrayOfFunPointers = &arrayOfFunPointers;

    return pointerToArrayOfFunPointers;
}

Outside of the method, the arrayOfFunPointers lose his validity area and the returned pointer point to "nothing"
I tried a lot like:
int (*arrayOfFunPointers[6])() = new int (*[6])();

or with typedef:
typedef int (*arrayOfFunPointers[6])();
arrayOfFunPointerss *array = new arrayOfFunPointers;

or by assignment to the returned pointer:
pointerToArrayOfFunPointers = new arrayOfFunPointers;
pointerToArrayOfFunPointers = new arrayOfFunPointers[]; //or

But nothing works.
Maybe I do not understand the use of the keyword new correctly, then it would be very helpful if anyone could tell me where I make a thinking mistake
Can anyone help me please? That would be nice

A: You can simplify your life with tools from C++11. What about:
std::array<FunPointer, 6> getFunctions()
{
    std::array<FunPointer, 6> result;
    // ...
    return result;
}

isn't it just nice? Ne need to bother with dynamic memory, just copy those 6 pointers around, it is relatively cheap.


text:
Q: Python - Beautifulsoup - Nonetype Morning folks.
I am scraping some data from a letting site using Beautifulsoup and Requests.
I am managing to get the data as needed but keep getting an error when I add .text any help would be appreciated, Code below and error further down.  The ANC code does return correctly just with the error
for item in house_link_list:
    url = item
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')

    result = soup.find_all('table', class_="tableproperty")

    for item in result:
        advert = item.find('td', attrs={'data-title': 'Advert'})
        post_code = item.find('td', attrs={'data-title': 'Post code'})
        house_area = item.find('td', attrs={'data-title': 'Area'})
        landlord = item.find('td', attrs={'data-title': 'Landlord'})
        property_type = item.find('td', attrs={'data-title': 'Property type'})
        floor_level = item.find('td', attrs={'data-title': 'Floor level'})
        opening_data = item.find('td', attrs={'data-title': 'Opening date'})
        closing_date = item.find('td', attrs={'data-title': 'Closing date'})
        bedrooms = item.find('td', attrs={'data-title': 'Bedrooms'})
        heating_type = item.find('td', attrs={'data-title': 'Heating type'})
        double_glazed = item.find('td', attrs={'data-title': 'Double glazed'})
        garden = item.find('td', attrs={'data-title': 'Garden'})
        pets = item.find('td', attrs={'data-title': 'Pet allowed'})
        rent = item.find('td', attrs={'data-title': 'Rent'})

        print(advert.text)
        print(post_code)
        print(house_area)
        print(landlord)
        print(property_type)
        print(floor_level)
        print(opening_data)
        print(closing_date)
        print(bedrooms)
        print(heating_type)
        print(double_glazed)
        print(garden)
        print(pets)
        print(rent)

> Traceback (most recent call last):
  File "C:\Users\natha\PycharmProjects\pythonProject2\main.py", line 87, in <module>
    get_details()
  File "C:\Users\natha\PycharmProjects\pythonProject2\main.py", line 67, in get_details
    print(advert.text)
AttributeError: 'NoneType' object has no attribute 'text'
ANC302774
DD9 6BE
BRECHIN NORTH AREA
Angus Council
Flat
Ground floor
29/10/2021
05/11/2021
1
None
None
None
None
None

A: What the docs say beautifulsoup documentation:

AttributeError: 'NoneType' object has no attribute 'foo' - This usually happens because you called find() and then tried to access the .foo attribute of the result. But in your case, find() didn't find anything, so it returned None, instead of returning a tag or a string. You need to figure out why your find() call isn't returning anything.

How to check?
print(advert.text if advert else 'no advert' )

or
advert = item.find('td', attrs={'data-title': 'Advert'}) if item.find('td', attrs={'data-title': 'Advert'}) else None


text:
Q: PHP 5.3.0 USE keyword -- how to backport in 5.2? I have some code that has been written in for php 5.3.0 using the USE function within PHP
can someone help me change this to work for 5.2.9?
$available  = array_filter($objects, function ($object) use ($week) {
    return !in_array($object, $week);
});

thanks for the help

A: Not nice, but this would be an equivalent implementation.
class MyWeekFilter {
    protected $_week;

    public function __construct($week) {
        $this->_week = $week;
    }

    public function filter($object) {
        return !in_array($object, $this->_week);
    }
}

$filter    = new MyWeekFilter($week);
$available = array_filter($objects, array($filter, 'filter'));

A: Is there any difference between author's code
$available = array_filter($objects, function ($object) use ($week) {
    return !in_array($object, $week);
});

and
$available = array_diff($objects, $week);

?

A: $available  = array_filter($objects, create_function('$object', '
    $week = '.var_export($week,true).';
    return !in_array($object, $week);
'));

A: Try this:
$week = array(...); // defined and instantiated before...

function callback($object) {
    return !in_array($object, $week);
}
$available  = array_filter($objects, "callback");


text:
Q: Vue and Vuex: Handling dependent computed properties My application is a cut-down spreadsheet built in Vue with Vuex.  The key components are TableCollection, Table and Row.  The TableCollection has an array with multiple Table objects.  Each Table has an array with multiple Row objects.
The Row component has a property named calculatedField.  This simply combines two fields in the row to produce a third field.  My options are to implement calculatedField as a computed property, local to the Row component, or as a getter in the Vuex store.
The Table component requires a subTotal value, which is calculated by adding the calculatedField for all rows in the table.  As you can see, the subTotal calculation is dependent on the calculatedField calculation.
If I implement calculatedField as a local computed property of Row, it is cached.  The problem is however that I can't seem to access the calculated field from a Table parent.  I tried the following in Table:
computed : {
    subTotal : function () {
        let total = 0;
        this.table.rows.forEach(function (row) {
           total += row.calculatedField;
        });
        return total;
    }
}

The result was NaN.
One solution would be to duplicate the logic from calculatedField in the computed property of Table, but that's not DRY.
The other alternative would be to implement both subTotal and calculatedField as getters in the store, however this would mean passing arguments to the gettter (tableId, rowId, or both), and so the results would not be cached.  This seems really inefficient.
The final possibility is that I implement my calculatedField logic in a global helper or mixin.  This would avoid code duplication and getter inefficiency, but doesn't feel quite right - the code relates specifically to Table and Row, and would ideally be kept there.
Are there other solutions I have overlooked?  What is the ideal 'Vue-way'?

A: If performance is an issue and caching is important right now, you might want to implement caching on the Table component.
In the Row component, emit the new value so the parent component can cache it.
  computed: {
    calculatedField() {
      const result = this.data.field + this.data.other;
      this.$emit('change', this.data.id, result);
      return result;
    }
  },

In the Table component, handle the event and cache the new values.
  data() {
    return { cache: {} };
  },
  computed: {
    subTotal() {
      return Object.values(this.cache).reduce((total, value) => total + value, 0);
    }
  },
  methods: {
    onChange(rowId, val) {
      // important for reactivity
      this.$set(this.cache, rowId, val);
    }
  },

When a Row's data is updated, it triggers a change event with the new calculated value and the parent Table keeps track of the calculated values, using this cache to get the subtotal.
You can see in the following example that the computed properties are hit once, then on row changes (click the Rand button), only the relevant computed properties are refreshed.

const MyRow = {
  props: {
    data: {
      type: Object
    }
  },
  computed: {
    calculatedField() {
      console.log("row computed for", this.data.id);
      const result = this.data.field + this.data.other;
      this.$emit('change', this.data.id, result);
      return result;
    }
  },
  methods: {
    onClick() {
      this.data.other = Math.floor(Math.random() * 10);
    }
  },
  template: `

        {{ data.field }}
        {{ data.other }}
        {{ calculatedField }}
        <button type="button" @click="onClick">Rand</button>

  `
};

const MyTable = {
  props: {
    rows: {
      type: Array
    }
  },
  components: {
    MyRow
  },
  data() {
    return {
      cache: {}
    }
  },
  computed: {
    subTotal() {
      console.log("Table subTotal");
      return Object.values(this.cache).reduce((total, value) => total + value, 0);
    }
  },
  methods: {
    onChange(rowId, val) {
      console.log("onChange", rowId, val);
      this.$set(this.cache, rowId, val);
    }
  },
  template: `

field	other	calculated

            <my-row v-for="row in rows" @change="onChange" :key="row.id" :data="row"></my-row>

        Subtotal: {{ subTotal }}

  `
};

var app = new Vue({
  el: '#app',
  components: {
    MyTable
  },
  data: {
    rows: [{
        id: 1,
        field: 1,
        other: 1
      },
      {
        id: 2,
        field: 2,
        other: 2
      },
      {
        id: 3,
        field: 3,
        other: 3
      },
    ]
  },
  template: `<my-table :rows="rows"></my-table>`
});


text:
Q: Unable to resolve sequelize package I'm trying to install sequelize-cli in my Mac OS 10.12.6.
In Terminal, I did
npm install -g sequelize-cli
I got
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
/usr/local/bin/sequelize -> /usr/local/lib/node_modules/sequelize-cli/bin/sequelize
/usr/local/lib
└── sequelize-cli@2.8.0

Then, I tried
sequelize model:create --name User --attributes name:string,complete:boolean
I got

Unable to resolve sequelize package in /Users/bheng/Sites/BASE

I even try with the --save as this post suggested.
npm install -g sequelize-cli --save
I got same result.
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
/usr/local/bin/sequelize -> /usr/local/lib/node_modules/sequelize-cli/bin/sequelize
/usr/local/lib
└── sequelize-cli@2.8.0

sequelize model:create --name User --attributes name:string,complete:boolean

Unable to resolve sequelize package in /Users/bheng/Sites/BASE

What else should I try ?

A: In sequelize-cli package.json file, sequelize is mentioned as a devdependency which means it does not install it when you do npm install sequelize-cli. My guess is you have not installed sequelize itself and this is what the error says.

Unable to resolve sequelize package in /Users/bheng/Sites/BASE

install sequelize npm install --save sequelize  (or global) and things should be good.
PS: Great answer on different dependencies and what they mean

A: You will need to install sequelize globally.

npm install -g sequelize

A: you can try this one
npm install --save-dev sequelize sequelize-cli
npx sequelize-cli init
Once you get models migrations folders, means sequelize is working.

A: I had the same issue. I installed sequelize-cli forgetting to add  sequelize itself:
npm install sequelize

A: First you have need to install sequelize package, after then execute cli command.

A: I had a similar case where when I was trying to run any sequelize command.
ie. sequelize init or sequelize --help
I would get the error:
Unable to resolve sequelize package in <my-project-directory>
None of the solutions above where helping my case but after farther digging I found this article talking about the importance of the order in which one installs dependencies.
I had installed my my development dependencies first (sequelize-cli before sequelize) and that's why it wasn't working.
Because this is a new project I just removed my yarn files and the package.json (left my other files untouched) and started over and this time I did:

*

*yarn init

*yarn add <my dependencies>

*yarn add --dev <my development dependencies>
This solved my issue.

A: Yes. This is "normal" the CLI will try to find the sequelize package in your current working directory and/or in the node paths. So you could either install the package in your local dir or in any parent directory or in the global space.
more answers


text:
Q: What are intention shared and intention exclusive locks in mongodb? Can anyone explain intention shared and intention exclusive locks in mongodb by examples?
I read about their functionality but I can't figure out what are their actual usage in real db examples.
Update: (More information)
Assumption: mongodb version is above 3.0.0
What happens when a document is created? Which locks are acquired in different layer:DB, Collection or document?(S, X, IS or IX)

A: Intent locks are higher level locks acquired before lower level locks are put in place and are called this way as they signal the intent of these lower level locks. Regarding the different types, intent shared locks are put in place for read operations that do not change or update data, such as a find() query  whereas intend exclusive locks are put in place for  data-modification operations, such as save(), update and remove.
To illustrate this, take this example collection:
db.data.save({"name":"John"})
db.data.save({"name":"Jane"})

if you run the find query below, an intent shared lock is requested on the Jane record.  As this query does not update the data, other users can run the same query or with other words, there can be multiple intent shared locks on the same record.
db.data.find({"name":"Jane"})

However, if you now run this query:
db.data.update({name:"Jane"},{name:"Janet"})

and intent exclusive lock is requested as this operation changes the record.  This lock can't be put in place until all other locks have been released on this record (or collection). While the exclusive lock is in place, no other intent locks can be applied on the record (or collection). This means, that if the update operation would take a considerable amount of time, any find operation would be blocked during the duration of the exclusive lock is in place.
Please note that the locking behaviour has significantly improved since version 2.4. In version 2.4 intent exclusive locks where applied at the database level, whereas for version 3.0 locks are only at collection level when using the MMAPv1 storage engine and at record level when using the WiredTiger storage engine (default in 3.2).
Regarding the difference between the intent locks IS and IX and the lower level locks S and X, the intent locks are high level locks that act as a traffic signal. Once the intent locks are in place (e.g. at collection level), the lower level locks are put in place (e.g. at document level).  This design reduces the processing needed for managing locks as a concurrent sessions only has to read the intent locks and not all the lower level locks.


text:
Q: Number of possible solutions in modular equation I have given the result value $z$. I know that
$$z \equiv x\cdot(x-1)\pmod p$$
where $p$ is prime and the value $p$ is fixed and given. I have also given the information, that $x \in \{m, M\}$, where $m, M \in \mathbb Z_p$. From this equation I want to compute value $x$.
Can I figure how many possible values of $x$ satisfy the given equation? Does this number of possible values depends on value $p$?

A: From Lagrange's theorem, there can be at most two solutions.
Note that
$$4z \equiv 4x^2-4x \pmod{p} \implies 4z+1 \equiv (2x-1)^2\pmod{p}$$
Hence, for a solution to exist, $4z+1$ must be a quadratic residue.

*

*If $4z+1$ is not a quadratic residue, then there is no solution.

*If $4z+1$ is zero, then there is only one solution, namely,
$$(2x-1)^2 \equiv 0 \pmod{p} \implies (2x-1) \equiv 0 \pmod{p} \implies x = \dfrac{p+1}2\pmod{p}$$

*If $4z+1$ is a non-zero quadratic residue, i.e., $a^2 \equiv (4z+1) \pmod{p}$, then there are two solution, namely
\begin{align}
(2x-1)^2 \equiv a^2 \pmod{p} \implies (2x-1+a)(2x-1-a) \equiv 0 \pmod{p}\\ (2x-1+a)(2x-1-a) \equiv 0 \pmod{p} \implies x \equiv \dfrac{1\pm a}2\pmod{p}
\end{align}


text:
Q: Is it ok to check the Heroku queue depth/wait_time and set dynos accordingly after every action in my app? I am trying to work out how to respond to increasing/decreasing traffic to my Heroku site with dynos management from within the app itself.
I know you can access HTTP_X_HEROKU_QUEUE_DEPTH or HTTP_X_HEROKU_QUEUE_WAIT_TIME and use those to set the amount of dynos. What I'm wondering is what process to use to do the checking.
Is it okay to add an after_filter to every action in the app to do a check against some threshold, and if a threshold has been met, change the number of dynos? I would only have 5/6 thresholds, so for vast majority of users the only impact would be the increased time it takes to do the check, and then for a handful of users it would be the check + the changing of dynos time.
Would it be too much of an inconvenience to the users? Is there a better way?

A: This could slow every request down to the point of turning away users. I haven't tried it though. There are ways of tackling this by using background processes.
Have a look at what others have done:

*

*http://blog.darkhax.com/2010/07/30/auto-scale-your-resque-workers-on-heroku

*https://www.heroscale.com/ is actually a business that's built around what you're trying to do.

Other examples:

*

*https://github.com/ddollar/heroku-autoscale

*https://github.com/pedro/delayed_job/tree/autoscaling


text:
Q: Copy all the cells in a column I have a sheet which has 200 rows with some blanks in between.
I cannot use End(xlDown) or End(xlUp) to get the entire range because there are blank rows.
How can I copy up to the last range which has data in columns?
Also, I don't want to copy the headers.
Kindly suggest how I can do this in Excel VBA.

A: The best way to copy them is to use Autofilter and filter them on Blanks and then copy the visible range
For Example
Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim rngToCopy As Range, rRange As Range

    Set ws = Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        Set rRange = .Range("A1:A" & lRow)

        '~~> Remove any filters
        .AutoFilterMode = False

        With rRange 'Filter, offset(to exclude headers) and copy visible rows
            .AutoFilter Field:=1, Criteria1:="<>"
            Set rngToCopy = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        '~~> Remove any filters
        .AutoFilterMode = False

        rngToCopy.Copy

        '
        '~~> Rest of the Code
        '
    End With
End Sub

A: You can get the last used row in column A of the active sheet with the code below (it works also if you have blank cells in the middle of the column) - amend as required if you need to run it on a different sheet / column.
With ActiveSheet
    lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A2:A" & lastRow).Copy 'copies column A used range, excluding header row
End With


text:
Q: Finding a current in a given circuit The problem has given the following circuit:

And asked to find the value(s) of Ix if the elements absorb the power(s) given.
I tired to set up KCL/KVL but I keep getting stuck.
I first drew this:

And set KVL1 = (Ra)(i1)-(Rb)(i2)
        KVL2 = (Rb)(i2)+(Rc)(i3)
After that I am confused on how to continue without knowing the resistances.

A: Redrawing things can sometimes help a little. Here's how I might attempt to redraw your schematic:

simulate this circuit – Schematic created using CircuitLab
Note that you have 5 equations and 5 unknowns. (Substitution could reduce that, if you like.) A quick check suggests that you will find two equally valid answers for the problem, though. You should also find (in both cases) that \$I_\text{B}\$ is negative (goes opposite to the indicated arrow.)

A: You could use the fact that the power in a closed system is conserved. That is,
the sum,
$$\sum_i P_i = 0$$
Where,
$$ 0=P_{V_0}+P_{R_1}+P_A+P_B+P_C.$$
So,
$$ 0=-I_XV_0+R_1I_X^2+48-8+40.$$
Hence,
$$ 0=-48I_X+4I_X^2+80.$$
This will give you two possible values for \$I_X\$. Maybe both results are ok, or there is a way to further determine which of the \$I_X\$ is the right one. If someone wants to further deduce it, please go-ahead.


text:
Q: Ember 2.8: Unit testing for HTML5 audio tag playing I'm writing some acceptance tests for my main route, and in my app some audio plays on load time. I would like to write up a test for this. This is what I'm thinking:
test('audio should be playing at startup', function(assert) {
  var isPaused = function () {
    return //some sort of indicator that audio is paused
  }
  visit('/');
  andThen(function () {
    assert.equal(isPaused(), false);
  })

})

I tried implementing something similar to this answer, but it did not work for me. Any and all help is appreciated. Thanks.


text:
Q: Reducing Unity Android build size I'm trying to get the Unity mobile Android APK build size to below 150mb, but it's currently at 170mb. I'm reading through many online docs, but can't find anything that so far reduced my build size. (For reference, I'm creating a "Virtual OS" where many virtual apps are bundled into one, and can be experienced in many different environments, so that increases size.)
My main question is, how can I find the biggest file size "offenders" in my project? Unity's doc tells me to look into the Editor Log's Build Report list, but the files mentioned in the top there (as "uncompressed", e.g. my 20k something PNG becomes a 1+mb file in that list), mainly textures, do not actually help when I next time remove them in another test build. Neither does it relevantly help when I change the Android texture setting to something more highly compressed (e.g. 1024 max Mitchell, which I had for most of my files anyway).
I've tried both APK building, as well as ABB, but both results are quite big. (Switching the API Compatibility Level from .NET 4x to 2 doesn't help either.) I'm compiling to 64bit architecture.
Edit: A first big improvement became removing an (unneeded for Android) Oculus directory (and accompanying Package Manager packages). But this wasn't shown in any charts.
Thanks for any pointers!


text:
Q: Unable to get data from shared preferences I am saving phone no. in shared preference and in another activity I am trying to get phone no. from shared preference.
private static final String KEY_PHONE = "keyphone";

SharedPreferences sharedPreferences = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putString(KEY_PHONE, "3454534565");
                                editor.apply();

In another activity I am using something like this:
SharedPreferences sp = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
String phone_id = sp.getString("keyphone","");

Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();

My problem is here I am not getting phone no in toast message and I am getting empty toast.
Someone please let me know how can I get phone no in another activity.Any help would be appreciated.
THANKS

A: You can use this to store a value in Shared Preferences:
SharedPreferences sharedPreferences =
getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =
sharedPreferences.edit();
editor.putString("keyphone", "3454534565");
editor.apply();

And then this to retrieve it:
SharedPreferences sp = getSharedPreferences("simplifiedcodingsharedpref",
Context.MODE_PRIVATE);
String phone_id = sp.getString("keyphone","");

Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();

A: The Main Problem is in here :  editor.putString(KEY_PHONE, "3454534565");

To Write:

SharedPreferences preferences = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
 editor.putString("KEY_PHONE", "3454534565");
editor.apply();

To Read:

SharedPreferences prfs = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
String phone_id= prfs.getString("KEY_PHONE", "");
Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();

A: You did everything right except one thing.
When retrieving a String value you cannot just set the value field to "".
When retrieving a String, the default value is null, when retrieving boolean, default value is false and when retrieving a boolean, the default value is false.
So instead of using
String phone_id = sp.getString("keyphone","");

you need to use
String phone_id = sp.getString("keyphone", null);


text:
Q: Is it possible to add duplicates in Set? Recently I have attend one interview. In my manager round he asked how to make Set to allow duplicate .I told doesn't allow duplicate its not possible .but he is not accepting my answer.Is there any tricky way ??.I have searched in Google I haven't get any proper answer..Please help me

A: It may depend on what kind of set you are using.
Scenario for HashSet
HashSet is storing its element in buckets which are grouping elements with similar hashcodes (each bucket stores elements which give same result for formula objectHashCode%numberOfBuckets). For instance if there will be two buckets, one will store elements with odd hashes, and one with even hashes. Also this buckets doesn't have access to other buckets (and they shouldn't since equal objects should have same hash, so should be placed in same bucket)
Lets say we have class which hashcode is calculated using mutable field
class SomeClass{

    private int x;

    @Override
    public int hashCode() {
        return x;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        SomeClass other = (SomeClass) obj;
        if (x != other.x)
            return false;
        return true;
    }

    //getters, setters, constructor, toString
}

If we add into HashSet object with hashcode 1 it will end up in first bucket. But if we edit this object so it will have hash 2 and try to add it to set, we will be able to do so, because it will end up in second bucket which doesn't check if object is in other buckets (which is why HashSets are so fast).
Demo:
Set<SomeClass> set = new HashSet<>();

SomeClass v = new SomeClass(1);
set.add(v);

v.setX(2);
set.add(v);

System.out.println(set);

Output:
[Value [x=2], Value [x=2]]

This shows why we should not modify objects after placing them into set. Or why we should prefer to chose constant fields over mutable fields while implementing hashcode method. Or why immutable classes are safer than mutable ones.

A: To build a set that can hold duplicates (=a multiset by definition) from a set you could store elements with counters. I think this is the only "sane" meaning one could find in this question (some others are ruled out in the comments above already). It's still interesting because the tricky part is to make sure element matching still works. So in Java it would be something along these lines:
class MultiSet<T> {
  private Set<CountingContainer<T>> set = new HashSet<T>();

  public void add(T value) {
    CountingContainer<T> container = new CountingContainer<T>(value);
    CountingContainer<T> existing = set.get(container);
    if (existing == null) {
      set.add(container);
    } else {
      existing.count++;
    }
  }

  public int getCount(T value) {
    CountingContainer<T> container = new CountingContainer<T>(value);
    CountingContainer<T> existing = set.get(container);
    return existing == null ? 0 : existing.count;
  }

  private static class CountingContainer<T> {
    int count;
    T value;
    private CountingContainer(T value) {
      this.value = value;
    }

    public int hashCode() {
      return value.hashCode();
    }
    public boolean equals(Object o) {
      return (o instanceof CountingContainer)
          && value.equals(((CountingContainer) o).value);
    }
  }

A "real" Java MultiSet implementation would just use a Map to map elements to counts though.

A: This is a weird question so my answer is also a bit weird but I have seen people doing this kind of mistake often. In my program I have overridden equals and hashCode to correctly. Whereas my compareTo method is written to sort Employees as per there names.
And we are using a TreeSet here but as TreeSet uses compareTo not equals to mark Object duplicate we can see we have 3 object in output instead of one.
public static void main(String[] args)  {
    final class Employee implements Comparable<Employee>{
        private int id;
        private String name;

        public Employee(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + id;
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Employee other = (Employee) obj;
            if (id != other.id)
                return false;
            return true;
        }

        @Override
        public int compareTo(Employee o) {
            return name.compareTo(o.name);
        }

    }

    Set<Employee> empSet = new TreeSet<>();
    empSet.add(new Employee(1,"Adam"));
    empSet.add(new Employee(1,"John"));
    empSet.add(new Employee(1,"Smith"));

    System.out.println(empSet.size());
}

A: the set collection not permit values duplicate, the list permit duplicated values
and map are key and value


text:
Q: help me prove ($B \subset A$. where elements of both sets are given by modulo) Let $A =${$ m \in \mathbb{Z} | m = 4a + 3 $ for  $a \in \mathbb{Z}$ } and let
$B =$ {$n\in \mathbb{Z} | n = 12b + 7$ for $b \in \mathbb{Z}$}. Prove that $B \subset A$.
this is what i have gathered so far, i think these are meaningful to the proof but i need some help bringing it all together.
so $A$ contains all integers where $m \equiv 3(mod 4)$
and $B$ contains all integers where $n \equiv 7(mod 12)$
if something is divisible by 12 then it is also divisible by 4 because $12 = 4\cdot 3$
i know that $4(a) +3$ is equal to 7

A: This follows directly from the definitions of $A$ and $B$ and some simple manipulation.
Proof
Consider $b \in B$.
$b = 12x + 7$ for some $x \in \Bbb Z$.
$b = 12x + 7 = 4(3x + 1) + 3$.
Hence, $b \in A$.
Since $b$ was arbitrary, $B \subseteq A$


text:
Q: azure-iot-sdk-c submodule/library versions I want to know how to choose the versions of the dependencies used by azure-iot-sdk-c.
for example, I plan to use:
azure-iot-sdk-c from github.com/Azure/azure-iot-sdk-c.git, release_2018_02_09_after_bump_version(3deb0ca3a8e2d220a50175bef71d16d1650a3a79),
then how do I know the right submodule/library versions for it? for example, the sub-modules in https://github.com/Azure/azure-uamqp-c/releases, github.com/Azure/azure-umqtt-c.git ...?
Thanks in advance.

A: Software and library is managed using the version. And libraries should be designed backwards-compatible when the MAJOR version is same.
A common way to find the suitable version for GitHub project's sub-modules is looking the release date of that project. For example of Azure-iot-sdk-c_release_2018_02_09, the version sub-module of azure-uamqp-c is 1.x.x published before 09/02/2018, so we can use any version of 1.x.x azure-uamqp-c. And of cause, the recommend version should be the latest version of that major version(1.2.3) at present.
More detail about concept of version and sub-modules, you can refer the links below:
Working with submodules
Semantic Versioning 2.0.0

A: If anyone else lands here after searching the error message of 3deb0ca3a8e2d220a50175bef71d16d1650a3a79;
I found this (https://github.com/Azure/azure-iot-sdk-c/blob/main/doc/master_to_main_rename.md) which refers to azure iot branchn renaming from master -> main on Dec 1st -21, which may explain the trouble finding the reference.
By updating my *.bb file which refers to the github with:
git@linktoyourgit.com ;main
This will reference the specific branch main to find the correct revision.


text:
Q: Prove that every $ A \in M_n\left ( \mathbb{C} \right )$ is similar to a matrix with at most one non-zero element in the first column I need that prove that every $ A \in M_n\left ( \mathbb{C} \right )$ is similar to a matrix $B$ where $B$'s first column is of the form $\begin{pmatrix}\lambda\\0\\\vdots\\ 0\\ \end{pmatrix}$
where $M_n\left ( \mathbb{C} \right ) $ is the set of all square matrices above $\mathbb{C}$.
I haven't been able to make much progress with this question - any help would be appreciated.

A: If $A$ is a complex $n\times n$ matrix, then it has an eigenvalue $\lambda$. Hence we can choose a basis $\mathcal{B}=\{v_1,\dots,v_n\}$ for $\mathbb{C}^n$ such that $v_1$ is an eigenvector for $A$ with eigenvalue $\lambda$, and the matrix of $A$ with respect to $\mathcal{B}$ will have the desired form.

A: Every complex matrix is triangularizable, because its characteristic polynomial factorises completely into linear factors. Hence A is similar to an upper-triangular matrix. The first column of such a matrix has the desired form.

A: $A$ is similar to its Jordan normal form $J$ which has the desired form.


text:
Q: Rails issue with rendering so I'm new to rails and currently going through a tutorial for it on tutorialspoint. What I've gotten so far is a controller and a corresponding view for it which is an erb file. This is the code for the view:
<% if @books.blank? %>

There are not any books currently in the system.

<% else %>

These are the current books in our system

   <% @books.each do |c| %>

<%= link_to c.title, {:action => 'show', :id => c.id} -%>

   <% end %>

<% end %>

<%= link_to "Add new Book", {:action => 'new' }%>

However, when I try to view this through localhost:3000 while having the
rails server

command running a WEBrick server in the background on localhost:3000,
it keeps directing me to the default view on my browser,which is being rendered by the server from the following path:
/Users/hassanali/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/templates/rails/welcome/index.html.erb
instead of the actual view within my rails application folder's view folder..which is
/Users/hassanali/Desktop/library/app/views/book/list.html.erb
I've been trying to fix this for ages now and no avail. Does anyone know what I can do?

A: Because you not define root_path for your app.
In config/routes.rb define root_path for it, ex:
root 'book#list'

A: You can tell Rails what you want '/' to route to by using root controller#action.
For example say you had a controller that looked like this.
class BooksController < ActionController::Base
  def index
    @books = Books.all
  end

  def show
    @book = Books.find(params[:id])
  end
end

If you wanted '/' to route to your index method, you would do the following in config/routes.rb.
Rails.application.routes.draw do

  root 'books#index'

  # Other routes here...

end

As a side note, if you add two root method calls, it will use the last one in the routes file.
http://guides.rubyonrails.org/routing.html#using-root
Since you have show and new action referenced you'll also likely want those routes as well. It's recommended to use RESTful routing schemes. Rails provides a useful method called resources which creates all the routes and helper methods needed to CRUD a resource.
That might look like the following.
Rails.application.routes.draw do

  root 'books#index'

  # A books resource
  resources :books

end

http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions
I encourage you to read the Rails Guide on routing so you understand your options.


text:
Q: Element in a series takes on a different value when assigned to a dataframe I am really puzzled by this... I have an existing DataFrame and when I assign a series of values (of the same length) to a new column somehow the last element in the series takes on a different value when in the DataFrame. This code
    print('Standalone 2nd to last: ' + series.iloc[-2])
    print('Standalone last: ' + series.iloc[-1])
    delta['Etf'] = series
    print('In a frame 2nd to last: ' + delta['Etf'].iloc[-2])
    print('In a frame last: ' + str(delta['Etf'].iloc[-1]))

produces this output:
Standalone 2nd to last: ZHY CN
Standalone last: IBDB US
In a frame 2nd to last: ZHY CN
In a frame last: nan

I appreciate any explanation of this.

A: Per @emmet02 comment, the index of the data frame was different from the one in the series and hence they did not align perfectly


text:
Q: How to handle a new window in selenium when I opened it by javascript Using selenium in internet explorer I have opened a new window with javascript code:
((JavascriptExecutor) driver).executeScript("windows.open('www.google.com')");

When I try to move to that new window selenium does not detect the window. At the time of printing the number of windows opened by the driver I only get 1:
Set<String> handlesSet = visor.getWindowHandles();
List<String> handlesList = new ArrayList<String>(handlesSet);
System.out.println("open windows: " + handlesList.size());

My question: ¿Is it possible to manage that new window opened from javascript?
Thank you.

A: It doesn't work because windows, it should window, without s:
((JavascriptExecutor) driver).executeScript("window.open('https://www.google.com')");

Don't forget to put full url with https://


text:
Q: Function giving negative value when it should be positive I am trying to evaluate
$$\displaystyle J=A\sum_{k=0}^{n-2}(-1)^k{n-2 \choose k}B^{n-2-k}\left(\frac{C_1}{k+n}-\frac{C_2}{k+n+1}+\frac{C_3}{k+n+2}-\frac{2}{k+n+3}\right)$$
in Mathematica as a function of n (i.e. J[n])
Note that B, C1, C2, etc are just coefficients for some parameters I have in the model. I assign their values before I enter the function. They are given below for reference
$$\left\{\begin{array}{cc}\left((n-1)nv^{-2n}\lambda^{-n}\right)=A \\ v+\lambda v=B\end{array}\right.$$
$$\left\{\begin{array}{cc}(v^2B\lambda)=C_1 \\ (vB+(B+2v)\lambda v)=C_2 \\ (2\lambda v+B+2v)=C_3 \end{array}\right.$$
Currently I have J[n] coded as:
J[n_] :=
  a Sum[(-1^k) Binomial[n - 2, k] (b^(n - 2 - k))
      ((c1/(k + n)) - (c2/(k + n + 1)) - (c3/(k + n + 2)) - (2/(k + n + 3))),
    {k, 0, n - 2}]

But when I call it by J[5] with {v, lambda} = {1.3, 2.1}, for instance, I get a negative value when it should be positive!
Another user, Dolma, who helped me derive the function (it's a definite integral of another function) claims it is positive here.
I trust that I am doing something wrong more so than Dolma's derivation being wrong, though I should mention Mathematica provides a MUCH more complex answer to this integral than in the post above.
Can anyone spot where I am making a mistake?
I appreciate your time and insight!

A: Note that in Mathematica there is a difference between (-1)^k and -1^k
This should solve the problem in this case.


text:
Q: How to Install High Sierra on External Drive I'll try to keep this as simple as possible but it's a little complicated.
I am trying to install High Sierra on an external disk. The computer I'm using is running Mojave, however, so it won't run the High Sierra Installer.
I created a bootable USB installer for High Sierra. (I got the 5.2 GB Install macOS High Sierra application here: https://support.apple.com/en-us/HT208969. I created the bootable installer using the instructions here: https://support.apple.com/en-us/HT201372.)
Using Disk Utility, I created a Mac OS Extended (Journaled) partition on the external drive as my destination for the installation.
I rebooted with both the bootable USB installer and the external drive plugged into USB ports and selected the bootable USB installer as my startup drive. I then designated the partition on the external hard drive as my destination for the installation.
Everything seemed to go fine until the installer rebooted my computer. Instead of the completing the installation, my computer just booted up using the OS on the internal drive. When restart was complete, the external drive had a new folder called "macOS Install Data."
I tried multiple times, including pressing Option at the point of restart, but I cannot get the installation on the external drive to complete.
I imagine the "macOS Install Data" may contain the components that should be used to create High Sierra during restart but I can't get the installation to complete.
Can you help?
Thank you!
Daniel


text:
Q: Read json file in and write without indentation The following code take a folder of json files (saved with indentation) open it, get content and serialize to json and write to file a new file.
Same code task in python works, so it is not the data. But the rust version you see in here:
extern crate rustc_serialize;
use rustc_serialize::json;
use std::io::Read;
use std::fs::read_dir;
use std::fs::File;
use std::io::Write;
use std::io;
use std::str;

fn write_data(filepath: &str, data: json::Json) -> io::Result<()> {

    let mut ofile = try!(File::create(filepath));
    let encoded: String = json::encode(&data).unwrap();
    try!(ofile.write(encoded.as_bytes()));
    Ok(())
}

fn main() {

    let root = "/Users/bling/github/data/".to_string();
    let folder_path = root + &"texts";
    let paths = read_dir(folder_path).unwrap();

    for path in paths {
        let input_filename = format!("{}", path.unwrap().path().display());
        let output_filename = str::replace(&input_filename, "texts", "texts2");

        let mut data = String::new();
        let mut f = File::open(input_filename).unwrap();
        f.read_to_string(&mut data).unwrap();
        let json = json::Json::from_str(&data).unwrap();

        write_data(&output_filename, json).unwrap();
    }
}

Do you have spot an Error in my code already or did I get some language concepts wrong. Is the rustc-serialize cargo wrongly used. At the end it does not work as expected - to outperform python.
± % cargo run --release --verbose
       Fresh rustc-serialize v0.3.16
       Fresh fileprocessing v0.1.0 (file:///Users/bling/github/rust/fileprocessing)
     Running `target/release/fileprocessing`
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: SyntaxError("unescaped control character in string", 759, 55)', ../src/libcore/result.rs:736
Process didn't exit successfully: `target/release/fileprocessing` (exit code: 101)

Why does it throw an error is my serializing json done wrong?
Can I get the object it fails on? What about encoding?
...is the code right or is there something obvious wrong with some more experience?

A: Wild guess: if the same input file can be parsed by other JSON parsers (e.g. in Python), you may be hitting a rustc-serialize bug that was fixed in https://github.com/rust-lang-nursery/rustc-serialize/pull/142. Try to update?


text:
Q: Inout/output error when writing to SD card connected via a camera So I have my camera connected to the computer, and have been able to access the files located on the SD card. I can view them, I can copy them, and I can even delete them. However, I cannot write to the card.
The location appears to be gphoto2://Canon_Inc._Canon_Digital_Camera, and I found this actually located at /run/user/1000/gvfs/gphoto2:host=Canon_Inc._Canon_Digital_Camera.
Permissions are fine:
drwx------ 1 user user 0 Jan  1  1970 'gphoto2:host=Canon_Inc._Canon_Digital_Camera'

drwx------ 1 user user 0 Jan  1  1970 DCIM
drwx------ 1 user user 0 Jan  1  1970 MISC

I try to create a directory and I get mkdir: cannot create directory 'test': Input/output error
I try to create a file and I get touch: setting times of 'test': Operation not supported
I cannot find this mounted using lsblk
Honestly, I have no idea where to go from here.
OS: Ubuntu 20.04.5 LTS
Edit: I have just noticed the date modified is Jan 1 1970. Don't know whether that means anything.


text:
Q: Redirect into SilverStripe's pages I'm trying to set up a redirect on my SilverStripe site.
I have created my own module, and now I want the user to be redirected to that after log in.
I've tried with Director::redirect($Url_base . 'myModule'), but it doesn't work.
Does anyone have any suggestions?

A: Try this: http://www.ssbits.com/customize-the-redirect-after-a-successful-member-login/

A: I did something like this:
class MyLoginForm extends MemberLoginForm {
    public function dologin($data) {
        parent::dologin($data);
        if (Director::redirected_to() && $Member = Member::currentUser()) {
            $this->controller->response->removeHeader('Location');
            if ($Member->Email == 'admin') {
                $destination = '/admin';
            } else {
                $destination = '/user/' . $Member->Username;
            }
            Director::redirect($destination);
        }
    }
}

If it is the admin user I redirect them to /admin. If it is another user I redirect them to /user/username.


text:
Q: Allowing users to create pages I would like to allow users to create pages on my site.  Not full pages, but just content for the default template.
I am currently using http://ckeditor.com/ then saving the content into a database.
Is this the best way to go about doing this?

A: That's awfully vague. Is giving users an editor and then saving the content in a database the best approach? Sure. In fact, it'd be hard to come up with any other reasonable approach.
Is CKEditor the best editor? That's up to you and your users. Stack Overflow uses a simple textarea with some buttons to add markdown code. That's far more efficient, but non-technical users would hate it. I personally tend to use TinyMCE which many users recognize from its use in WordPress.
Which editor is right for your site depends on you and your users.
And as far as saving it in a database, where else could you put it? Obviously you'll have to save what the visitors write in a database of some kind.
You're asking about some very, very broad decisions that are hardly part of the "best practice" for this sort of solution. More interesting questions are: how is it saved in the database, how do you control who has access, how do you keep track of previous versions, how do you validate which content to display, how do you prevent multiple users from overwriting each other's edits, how do users get from viewing the page to editing the page?

A: Perhaps it would be easier (and safer, and prettier, etc.) to use something like Simple CMS?


text:
Q: What's the motivation behind the action principle?
*

*What's the motivation behind the action principle?

*Why does the action principle lead to Newtonian law?

*If Newton's law of motion is more fundamental so why doesn't one derive Lagrangians and Hamilton principle from it?

*Also does all Lagrangians obey $L=T-V$?

*I think that it's related to the fact that the kinetic energy of the particle at all points on the path or it's travel time is as small as possible?

*If so, How can we derive the principle of least action from this fact in detail?

A: *

*The motivation is that it works. It was a major discovery that this unifies mechanics (in the absence of friction).

*It doesn't lead to newton's law, as it is far mor general than the latter, but applied to the problems Newton was interested, it implies these laws.

*Action is more fundamental than newton's laws. The latter are more intutive, though, hence were found much earlier in history and can be taught much earlier in education.

*No. This is only the form of Lagrangians for $n$-particle systems in Cartesian coordinates - the stuff with which one begins in theoretical mechanics.

*What is related? Minimal travel time is a vartiational principle different from the action principle and gives the same answers only in very special cases.

*is not applicable.


text:
Q: All objects in $\bf{FinVect}$ have finite length I want to show that every object $X$ of $\bf{FinVect}$ has finite length. i.e. there is a sequence of monos
$$
  0=X_0 \hookrightarrow X_1 \hookrightarrow ... \hookrightarrow X_{n-1} \hookrightarrow X_n = X
$$
such that $\forall i,{X_i}/{X_{i-1}}$ is simple.
I think this is supposed to be a trivial case, but I do not see how. If we use just the zero map $0\xrightarrow{0} X$ it does not work, since $X/\{0\}\cong X$ need not be simple.

A: The simple objects in $\mathbf{FinVect}$ are exactly the 1-dimensional vector spaces. Take any ordered basis $(a_1,\ldots,a_n)$ of $X$ (which exists, since $X$ is a finite dimensional vector space), and take $X_k = \mathop{\mathrm{Span}}\{a_1,\ldots,a_k\}$.

A: Hints.  Let $\mathbb{K}$ be the base field.  The simple objects of $\mathbf{C}:=\mathbf{FinVect}(\mathbb{K})$ are $1$-dimensional $\mathbb{K}$-vector spaces, i.e., they are all isomorphic to $\mathbb{K}$.  This shows that, if $X\in \mathbf{C}$ has a filtration
$$0=X_0\hookrightarrow X_1 \hookrightarrow X_2\hookrightarrow \ldots \hookrightarrow X_{l-1}\hookrightarrow X_l=X\tag{*}$$
in which $X_i/X_{i-1}$ are simple (whence $1$-dimensional), then $$\dim_\mathbb{K}(X)=\dim_\mathbb{K}(X_0)+\sum_{i=1}^l\,\dim_\mathbb{K}\left(X_i/X_{i-1}\right)=0+\sum_{i=1}^l\,1=l\,$$
For convenience, we call (*) a composition series of $X$.  Ergo, you have the following statement: "if $X\in\mathbb{C}$ has a composition series of length $l$, then $\dim_\mathbb{K}(X)=l$."  How would you show that the converse of this statement is also true?  That is, show that any composition series of $X\in\mathbf{C}$ exists and is of length $\dim_\mathbb{K}(X)$.

  Try induction on $\dim_\mathbb{K}(X)$.