text:
Q: how to detect if a file operation is currently done on a file on linux How can i detect if a file is open and a file operation is being done on it by another process on linux by using c or c++? I know lsof lists all open files but i dont how it gets that information.
Thx

A: I'm not sure lsof is actually working like this, but a way to implement it could be this:

*

*get your process' open files by looknig to /proc/$PID/fd/ files.

*look to any any other process' /proc/$PID/fd/ in order to see who is reading your same files.

A: Why don't you look at the lsof source code? It's probably a bit intimidating, but I'm sure you can isolate the two or three interesting syscalls that give it all the relevant information.

A: lsof iterates over all /proc/*/fd/* this can be seen if you do strace of the lsof command.


text:
Q: Understanding Synchronized I'm trying to teach myself threads but can't seem to get synchronized() to work. This is what I'm doing:
In a class Test I'm declaring a variable
static String toggy = "false";

Then a runnable (MyRunnable) with this run method:
@Override
public void run() {
    synchronized (toggy) {
        System.out.println("toggy for " + name + " BEFORE = " + toggy);
        int b = 0;
        for(int i=0; i<1000; i++) {
            b++;
        }
        System.out.println("toggy for " + name + " AFTER = " + toggy);
        System.out.println("--------------------------------------------\n");

        if(toggy.equals("false")) {
            toggy = "true";
        } else if(toggy.equals("true")) {
            toggy = "false";
        }
    }
}

I'm testing this here:
for (int i = 0; i < 90; i++) {
    Runnable task = new Test.MyRunnable(i+"");
    Thread worker = new Thread(task);
    worker.setName(String.valueOf(i));
    // Start the thread, never call method run() direct
    worker.start();
}

From what I understand, the synchronized block should prevent the value of "toggy" from changing while a certain thread is running. But when I run the program every now and then it does. What am I missing?

A: By assigning different values (String instances) to toggy, the synchronized block is locking different objects:
synchronized ("false")
{
}

or:
synchronized ("true")
{
}

This will allow multiple threads to enter the block code that the synchronized is meant to protect. Use a different object for locking:
static final Object lock = new Object();

synchronized (lock)
{
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get full stack trace with line numbers Is it possible to get a full StackTrace object WITH line numbers at any given point in the code
I found this:
var stackTrace = new StackTrace();

That gives me the full stacktrace from where I am in execution.  But it does not include line numbers.
I also found this:
var stackTrace = new StackTrace(new StackFrame(1, true));

That gives me the line numbers, but only for one frame of the StackTrace (not a full StackTrace).
Is there a way to get both together?
NOTE: I don't have an exception I am working with.  I am just at a point in the code where I want to log the stack trace in a custom way.
NOTE: I know about Environment.Properties.StackTrace.  But that returns a string, not a StackTrace object.

A: I suspect you just want to call the overload taking a bool:
var stackTrace = new StackTrace(true);

From the documentation:

Parameters
fNeedFileInfo
  Type: System.Boolean
true to capture the file name, line number, and column number; otherwise, false.


text:
Q: Request a connection after the form is opened as in postForm in statemachine I've shifted to barebone code from statemachine. Here I've code(connectionRequest) inside constructor.Hence connection is called before the new form is opened. What I need is that: after the new form is opened, the connection should be called. In statemachine, if I request a connection in postForm, the form will open and then the connectionRequest is called. How can I do that here?
Home.java
public class Home extends Form {
    public Home() {
        Button test = new Button("Test");
        add(test);

        test.addActionListener(e->{
            new Test().show();
        });
    }
}

Test.java
public class Test extends Form{
    public Test(){
        Label nameLabel = new Label("");
        add(nameLabel);

        ConnectionRequest cr = new ConnectionRequest() {

            @Override
            protected void readResponse(InputStream input) throws IOException {
                JSONParser jp = new JSONParser();
                Map parser = jp.parseJSON(new InputStreamReader(input));
                String name = (String) parser.get("name");
                nameLabel.setText(name);
            }
        };
        cr.setUrl("test.com");
        NetworkManager.getInstance().addToQueueAndWait(cr);
    }
}

A: You can use addShowListener and call the connection request there.


text:
Q: Building ZXing (Zebra Crossing) Library on Linux I'm currently struggling to get started with ZXing. So i downloaded the source, updated cmake to the required version, installed gcc 9 and tried to compile it using cmake. I did not succeed using the CMakeLists.txt in the root directory, but i succeeded in building the lib using the CMakeLists.txt in the core directory. The result was a libZXing.a, which i installed using the make install target. The lib was installed into /usr/local/lib. So far so good.
Now i try to build a very simple program, just to test, if building was successful.
#include "BarcodeFormat.h"

#include <iostream>
#include <string>

using namespace ZXing;

std::ostream& operator<<(std::ostream& os, BarcodeFormat bf) {
    os << ToString(bf);
    return os;
}

int main(int argc, char **argv) {
    for (auto f : BarcodeFormats::all()) {
        std::cout << f << std::endl;
    }
    return 0;
}

Compiling works, linking does not work: Undefined reference to BarcodeFormat::ToString(BarcodeFormat). So it seems to be not in the library. I compiled the BarcodeFormat.cpp in the core/src directory separately, copied the object file to my project directory, linked it, and that worked. I got a working executable.
So i assume i did something wrong while building the library. Any idea what could go wrong here? Of cource i added the necessary -I, -L and -l flags to the compile. The Makefile:
CC      := g++
CCFLAGS     := -std=c++17 -I/home/cnc/prj/zxing-cpp-master/core/src
LDFLAGS     := -L/usr/local/lib -lZXing

all:        zxtest

zxtest:     zxtest.o BarcodeFormat.o
            ${CC} -o $@ ${LDFLAGS} $^

zxtest.o:   zxtest.cpp
            ${CC} -c ${CCFLAGS} -o $@ $<

BarcodeFormat.o:    ../zxing-cpp-master/core/src/BarcodeFormat.cpp
            ${CC} -c ${CCFLAGS} -o $@ $<

Without that extra BarcodeFormat file it does not link
I'm quite old, so i do know C and basic C++. I'm not up to date with the new C++ features.
PS: Sorry, i forgot: This is about the ZXing c++ port (obviously, since the example is c++): https://github.com/nu-book/zxing-cpp

A: For anyone else trying to make ZXing C++ work on Linux, the following worked for me (Ubuntu 20+). You don't need to install any packages to make it work, as GCC was already installed on my version of Ubuntu, but YMMW.
I am using the following ZXing fork. It's a C++ port from the original Java. Seems to be the most up to date version I can find. I tried using the Java also, but the C++ version is faster, and a little bit less faffy to get working.
Ok, enough context, let's get straight to it.
Prep it
You'll need to install git and cmake.
sudo apt install git cmake

Clone it
Clone a copy of the page and make the folder we want build the package in
sudo git clone https://github.com/nu-book/zxing-cpp.git
sudo mkdir /usr/lib/zxing-cpp/

Build it
Build the package in the folder we made, go to the folder and install the package.
sudo cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local -G "Unix Makefiles" -S zxing-cpp/ -B /usr/lib/zxing-cpp/
cd /usr/lib/zxing-cpp/
sudo make install

A quick note, I got a bunch of depreciated warnings when I ran the sudo make install command. It still works though.
Use it
Now here' the bit that confused me a little. I was not able to just call ZXing from the command line as you might expect when you apt-install something.
I had to find the ZXingReader file (I was only interested in reading images, you can also create barcodes with the same package) that was created in the /usr/lib/zxing-cpp/example/ folder and reference it directly. Then I could call it directly from the command line like so
/usr/lib/zxing-cpp/example/ZXingReader image.jpg

This should give you the following result, if it finds a barcode.
Text:     "5901234123457"
Format:   EAN-13
Position: 81x363 1176x363 1176x363 81x363
Rotation: 0 deg
Error:    NoError
Country:  PL

Hope that helps. And, please, if you are a Linux expert, let me know in the comments where I am going wrong, or where I could be doing things in a more efficient manner. Compiling C++ programmes is very much on the periphery of my comfort zone!

A: At least we got it here working in some way. Instead of using the hand made Makefile, a collegue gave me a cmake input file:
project(zxtest)
cmake_minimum_required(VERSION 3.16)

set (CMAKE_CXX_STANDARD 11)

add_executable (zxtest zxtest.cpp)

include_directories(/usr/local/include/ZXing)

target_link_libraries (zxtest ZXing)

Then we created the Makefile using cmake and this input file. The resulting Makefile is over 5K big. But that works. We still do not know why resp. why it does not work with the hand made Makefile.
So the bug is somehow in the Makefile provided in the question above.


text:
Q: A topological space is compact iff each infinite subset has a complete accumulation point This is based on the comments and answers provided in this post. However, I have some questions on the proof and the hint given in Kelleys book p.163. I will highlight the hint of the book. My own thoughts will be preceded by a dot.

If $X$ is not compact choose an open cover $A$ with no finite subcover such that the cardinal number $c$ of $A$ is as small as possible.

*

*This is possible since assuming $X$ not to be compact there is at least one open cover $\mathcal{O}$ without finite subcover.

*If one then considers the non empty set $\mathfrak{M}$ of all coverings without finite subcovers, the well-ordering principle implies the existence of $A$ as above, i.e. an element of $\mathfrak{M}$ with minimal cardinality.

Let $C$ be a well-ordered set of cardinal $c$ such that the set of predecessors of each member has a cardinal less than $c$ (It is shown in the appendix that $c$ is such a set.)

*

*If we take the ordinal number corresponding to the cardinality $c$ this should be satisfied.

Let $f$ be a one-to-one map of $C$ onto $A$.
  Then for each member $b$ of $C$ the union
  $$\left[U_b :=\right]\quad \bigcup \, \{f(a):a<b\}$$
  does not cover $X$

*

*because if it did, there would exist an cover with cardinality strictly less than $c$.

and, in fact, the complement of this union must have cardinal number at least as great as $c$.

*

*Why?

It is therefore possible to choose $x_b$ from the complement such that $x_a \neq x_b$ for $a < b$.

*

*Why?

Consider the set of all $x_b$.

*

*Denote this set with $M$. It is infinite because for each Union $U_b$ there exists $x_b \in M$ with $x_a \neq x_b$ for $a < b$. This implies $|M| = c$.

*To show that $M$ has no limit point, consider $x \in X$. The covering property gives $O_x \in A$ such that $x \in O_x$. Then the following calculation should hold
$$ |M \cap O_x | \leq | \{x_b \mid b \leq a \} | \leq | a | < c = |M|.$$

*Consequently $M$ has no limit point.

Did I make any mistakes so far? Any suggestions on the points of the proof that still remain unclear to me?

A: For $b \in C$ let $A_b := \{ f(a) : a < b \}$ (so that $U_b = \bigcup A_b$).

*

*I'll back up a bit, and give a fairly full justification for why $A_b$ cannot cover $X$.
If $A_b$ covers $X$ (so that $U_b = X$), since $A_b$ is a subfamily of $A$ it must be that $A_b$ does not have a finite subcover (otherwise $A$ would). But the choice of the well-ordered set $C$ implies that $| A_b | < c$, which contradicts the choice of the cardinal $c$! Therefore $A_b$ cannot cover $X$.

*If $| X \setminus U_b | < c$, then for each $x \in X \setminus U_b$ pick any $V_x \in A$ containing $x$. Then $A_b \cup \{ V_x : x \in X \setminus U_b \}$ covers $X$ and is a subfamily of $A$. Similarly to the above, this cannot have a finite subcover, and it has cardinality $< c$, which then contradicts our choice of $c$. Therefore $| X \setminus U_b | \geq c$.

*Given any $b \in C$, as $\{ x_a : a < b \}$ has cardinality $< c$ and as $| X \setminus U_b | \geq c$, it follows that $X \setminus ( U_b \cup \{ x_a : a < b \} )$ is nonempty, and so we may choose $x_b$ from this set arbitrarily to be distinct from $x_a$ for $a < b$.

*Note that the set $M = \{ x_b : b \in C \}$ has cardinality $c$. It has no complete accumulation point because for each $x \in X$ if $b \in C$ is least such that $x \in U_b$, then $U_b$ is an open neighbourhood of $x$ and $U_b \cap M \subseteq \{ x_a : a < b \}$, and so has cardinality $<c$.


text:
Q: BackgroundWorker track method from another class [EDIT]
I edited my question with complete code and explanation and hope something can give me clearer explanation.
I have the following Class that has a backgroundworker to track the percentage progress of a loop and update the percentage progress on a Label on ProgressWin's XAML. The following code works perfectly. (My question is far below, after the code.)
public partial class ProgressWin : Window
{
    BackgroundWorker backgroundWorker1 = new BackgroundWorker();

    public ProgressWin()
    {
        InitializeComponent();
        InitializeBackgroundWorker();
        startAsync();
    }

    // Set up the BackgroundWorker object by
    // attaching event handlers.
    private void InitializeBackgroundWorker()
    {
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.WorkerSupportsCancellation = true;
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
    }

    private void startAsync()
    {
        backgroundWorker1.RunWorkerAsync();
    }

    public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        for (int i = 1; i <= 10; i++)
        {
            System.Threading.Thread.Sleep(500);
            worker.ReportProgress(i * 10);
        }
    }

    // This event handler updates the progress.
    public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        label1.Content = (e.ProgressPercentage.ToString() + "%");
    }

    // This event handler deals with the results of the background operation.
    public void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
         resultLabel.Content = "Done!";
    }
}

Here comes my problem, now instead of tracking the loop within the ProgressWin, I need to track the loop in my MainWindow:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        for (int i = 1; i <= 10; i++)
        {
            System.Threading.Thread.Sleep(500);
            ????.ReportProgress(i * 10);
        }
    }
}

And I have no idea where to go from here. I tried instantiating an object from ProgressWin and call the DoWork but I end up frozen the ProgressWin window.

A: You can simply call method of another class by doing
backgroudnWorker.DoWork += new DoWorkEventHandler(SomeClass.SomeStaticMethod);
or
backgroudnWorker.DoWork += new DoWorkEventHandler(SomeClassInstance.SomeMethod);
for calling a method of MainWindow class from another class ProgressScreen you should have reference of instance of MainWindow class in ProgressScreen then using that instance you can call any public method of MainWindow from ProgressScreen class
and as Oliver Said, you will need the instance of backgroundworker to send the progress updates from other method.

A: Due to the fact that the question was rewritten, i also rewrote my whole answer.
To get this to work your MainWindowhas a ProgressWindow and should use it like a background worker:
public partial class MainWindow : Window
{
    private ProgressWindow _Progress;

    public MainWindow()
    {
        InitializeComponent();

        _Progress = new ProgressWindow();
        _Progress.ProgressChanged += OnProgressChanged;

    }

    private void OnProgressChanged(object sender, ProjectChangedEventArgs e)
    {
        //ToDo: Update whatever you like in your MainWindow
    }
}

To accomplish this your ProgressWindow should simply subscribe to the worker event and rethrow it:
public partial class ProgressWin : Window
{
    // Add this to your class above in your question
    public event ProgressChangedEventHandler ProgressChanged;

    // Change or merge this with your existing function
    private void backgroundWorker1_ProgressChanged(object sender, ProjectChangedEventArgs e)
    {
        var temp = ProgressChanged;
        if(temp !=null)
            temp(this, e);
    }
}


text:
Q: Convert array of hashes to json I want to convert an array of hashes that I create like this:
while(...)
{
    ...
    push(@ranks, {id => $id, time => $time});
}

To JSON:
use JSON;
$j = new JSON;
print $j->encode_json({ranks => @ranks});

But it is outputting this:
{"ranks":{"time":"3","id":"tiago"},
 "HASH(0x905bf70)":{"time":"10","id":"bla"}}

As you can see it isnt able to write on of the hashes and there's no array...
I would like to output a JSON string that looked like this:
 {"ranks":[{"time":"3","id":"tiago"},
           {"time":"40","id":"fhddhf"},
           {"time":"10","id":"bla"}]}

A: All of these are the same:
ranks => @ranks

'ranks', @ranks

'ranks', $ranks[0], $ranks[1], $ranks[2]

ranks => $ranks[0], $ranks[1] => $ranks[2]

So you're creating a hash with two elements when you mean to create a hash with one element.
You tried to use an array as a hash value, but hash values can only be scalars. It is common, however, to use a reference to an array as a hash value since references are scalars, and this is what encode_json expects.
print $j->encode_json( { ranks => @ranks } );

should be
print $j->encode_json( { ranks => \@ranks } );

A: print $j->encode_json({ranks => @ranks});

should be:
print $j->encode_json({ranks => \@ranks});

A: Try passing the array as a reference.
to_json({ranks => \@ranks},{ascii => 1,pretty => 1});


text:
Q: C# Core Interop Attach/Add picture file into a generated Word document I am generating a Word Document using Interop and it is working perfectly fine.
I have a template file and inside that template I have a tag #name#, to which my code passes a value. I am just wondering how do I tweak my code so that it can add a picture as well?
Let's say the image file location is Path.Combine(_hostingEnvironment.WebRootPath, "template\image" + ".jpg")
(I would also like to resize that image to a certain dimensions)
public FileResult Download()
    {

        var stream = new MemoryStream();

        string TemplateLoc = "template\\Template.docx";
        string path = Path.Combine(_hostingEnvironment.WebRootPath, TemplateLoc);

        string sourceFile = Path.Combine(path);
        string destinationFile = Path.Combine(_hostingEnvironment.WebRootPath, "template\\Test" + ".docx");

            try
            {
                System.IO.File.Copy(sourceFile, destinationFile);

                Dictionary<string, string> keyValues = new Dictionary<string, string>();

                keyValues.Add("#name#", "Sarah");

                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                word.Visible = false;
                word.ScreenUpdating = false;

                Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(destinationFile);
                Microsoft.Office.Interop.Word.Range range = word.ActiveDocument.Content;

                doc.Activate();

                object missing = Type.Missing;
                object sourceDoc = sourceFile;
                object destinationDoc = destinationFile;
                object matchCase = false;
                object matchWholeWord = true;
                object findWrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
                object findFormat = true;
                object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                object fileFormat2 = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                //

                //Replace text ##
                foreach (KeyValuePair<string, string> kvp in keyValues)
                {
                    object findText = kvp.Key;
                    object replaceText = kvp.Value;

                    if (range.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref missing,
                        ref missing, ref missing, ref missing, ref findWrap, ref missing,
                        ref replaceText, ref replaceAll, ref missing, ref missing, ref missing, ref missing))
                    {
                        //Console.WriteLine("Found " + findText + ", replaced with " + replaceText);
                        continue;
                    }
                }

                doc.SaveAs(destinationFile);
                doc.Close();
                word.Quit();

            }
            catch (Exception e)
            {
                throw e;
            }

        byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(_hostingEnvironment.WebRootPath, "template\\Test" + ".docx"));
        string fileName = "test.docx";
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    }

A: Word has two ways to insert graphics: as Shapes or as InlineShapes. InlineShapes are placed in-line with the text; Shapes have text wrap formatting. The code below shows the syntax for InlineShapes. The syntax for Shapes is very similar and you should get Intellisense if you type doc.Shapes.AddPicture. If I have a choice I use an InlineShape because it's placement on the page is more predictable/stable.
No matter which you use it's important to specify the Range argument in order to correctly position the graphic.
            foreach (KeyValuePair<string, string> kvp in keyValues)
            {
                object findText = kvp.Key;
                object replaceText = kvp.Value;

                if (range.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref missing,
                    ref missing, ref missing, ref missing, ref findWrap, ref missing,
                    ref replaceText, ref replaceAll, ref missing, ref missing, ref missing, ref missing))
                {
                    //Console.WriteLine("Found " + findText + ", replaced with " + replaceText);
                   object oRange = range;
                   object oTrue = true;
                   Microsoft.Office.Interop.Word.InlineShape ils = doc.InlineShapes.AddPicture(Path.Combine(_hostingEnvironment.WebRootPath, "template\image" + ".jpg"),
                       ref missing, ref oTrue, ref oRange);
                   ils.Height = 100;
                   ils.Width = 100;

                    //Replace text ##
                    continue;
                }
            }


text:
Q: Can't install gns3,Err 502 bad gateway I have Ubuntu 17.04 and I'm trying to install gns3 by using these commands:
sudo add-apt-repository ppa:gns3/ppa

Output:
 PPA for GNS3 and Supporting Packages. Please see http://www.gns3.com for more details
 More info: https://launchpad.net/~gns3/+archive/ubuntu/ppa
Press [ENTER] to continue or ctrl-c to cancel adding it

gpg: keybox '/tmp/tmpji7mkxvk/pubring.gpg' created
Error: retrieving gpg key timed out.

Then:
sudo apt-get update
sudo apt-get install gns3-gui

Output:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  linux-headers-4.10.0-37 linux-headers-4.10.0-37-generic
  linux-image-4.10.0-37-generic linux-image-extra-4.10.0-37-generic
  linux-signed-image-4.10.0-37-generic
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  augeas-lenses bridge-utils cpu-checker cpulimit dmeventd dns-root-data
  dnsmasq-base dynamips ebtables gns3-server ipxe-qemu libaio1 libaugeas0
  libboost-random1.62.0 libdevmapper-event1.02.1 libfdt1 libiscsi7
  liblvm2app2.2 liblvm2cmd2.02 libnetcf1 libqt5websockets5 librados2 librbd1
  libreadline5 libspice-server1 libvirt-bin libvirt-clients libvirt-daemon
  libvirt-daemon-system libvirt0 libvncserver1 libxen-4.8 libxenstore3.0
  libxml2-utils lvm2 msr-tools python3-pyqt5.qtsvg python3-pyqt5.qtwebsockets
  qemu-block-extra qemu-kvm qemu-system-arm qemu-system-common qemu-system-x86
  qemu-utils seabios sharutils ubridge vpcs x11vnc x11vnc-data xvfb
Suggested packages:
  augeas-doc gns3 augeas-tools numad radvd auditd systemtap nfs-common
  zfsutils pm-utils thin-provisioning-tools samba vde2 qemu-efi sgabios ovmf
  debootstrap sharutils-doc bsd-mailx | mailx
The following NEW packages will be installed:
  augeas-lenses bridge-utils cpu-checker cpulimit dmeventd dns-root-data
  dnsmasq-base dynamips ebtables gns3-gui gns3-server ipxe-qemu libaio1
  libaugeas0 libboost-random1.62.0 libdevmapper-event1.02.1 libfdt1 libiscsi7
  liblvm2app2.2 liblvm2cmd2.02 libnetcf1 libqt5websockets5 librados2 librbd1
  libreadline5 libspice-server1 libvirt-bin libvirt-clients libvirt-daemon
  libvirt-daemon-system libvirt0 libvncserver1 libxen-4.8 libxenstore3.0
  libxml2-utils lvm2 msr-tools python3-pyqt5.qtsvg python3-pyqt5.qtwebsockets
  qemu-block-extra qemu-kvm qemu-system-arm qemu-system-common qemu-system-x86
  qemu-utils seabios sharutils ubridge vpcs x11vnc x11vnc-data xvfb
0 upgraded, 52 newly installed, 0 to remove and 0 not upgraded.
Need to get 384 kB/42.9 MB of archives.
After this operation, 170 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://us.archive.ubuntu.com/ubuntu zesty-updates/main amd64 libxenstore3.0 amd64 4.8.0-1ubuntu2.4 [19.8 kB]
Err:2 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 libnetcf1 amd64 1:0.2.8-1ubuntu2
  502  Bad Gateway [IP: ...]
Get:3 http://us.archive.ubuntu.com/ubuntu zesty-updates/main amd64 qemu-block-extra amd64 1:2.8+dfsg-3ubuntu2.7 [38.1 kB]
Err:4 http://us.archive.ubuntu.com/ubuntu zesty/universe amd64 python3-pyqt5.qtwebsockets amd64 5.7+dfsg-5
  502  Bad Gateway [IP: ...]
Get:5 http://us.archive.ubuntu.com/ubuntu zesty-updates/main amd64 qemu-kvm amd64 1:2.8+dfsg-3ubuntu2.7 [13.2 kB]
Err:6 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 libvncserver1 amd64 0.9.11+dfsg-1
  502  Bad Gateway [IP: ...]
Get:7 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 cpu-checker amd64 0.7-0ubuntu7 [6,862 B]
Ign:8 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 dns-root-data all 2015052300+h+1
Get:9 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 libreadline5 amd64 5.2+dfsg-3build1 [99.5 kB]
Err:8 http://us.archive.ubuntu.com/ubuntu zesty/main i386 dns-root-data all 2015052300+h+1
  502  Bad Gateway [IP: ...]
Fetched 177 kB in 1min 10s (2,525 B/s)
E: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/n/netcf/libnetcf1_0.2.8-1ubuntu2_amd64.deb  502  Bad Gateway [IP: ...]
E: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/universe/p/pyqt5/python3-pyqt5.qtwebsockets_5.7+dfsg-5_amd64.deb  502  Bad Gateway [IP: ...]
E: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/libv/libvncserver/libvncserver1_0.9.11+dfsg-1_amd64.deb  502  Bad Gateway [IP: ...]
E: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/d/dns-root-data/dns-root-data_2015052300+h+1_all.deb  502  Bad Gateway [IP: ...]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

Note that: I tried to install it several times by these commands.
The last line of above output says: run apt-get update or try with --fix-missing
I updated and upgraded system several times,then i tried to install gns3 again,But it didn't work.
And i don't know how to run --fix-missing.
Output of --fix-missing:
--fix-missing: command not found

These commands use Ubuntu-based distributions:
sudo add-apt-repository ppa:gns3/ppa
sudo apt-get update
sudo apt-get install gns3-gui

When i couldn't install it that way,I decided to install it with these commands:
 Debian-based distributions:
deb http://ppa.launchpad.net/gns3/ppa/ubuntu trusty main
deb-src http://ppa.launchpad.net/gns3/ppa/ubuntu trusty main

Then
Adding the following lines to your /etc/apt/sources.list:
deb http://ppa.launchpad.net/gns3/ppa/ubuntu trusty main
deb-src http://ppa.launchpad.net/gns3/ppa/ubuntu trusty main

Then running the following commands in terminal:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F88F6D313016330404F710FC9A2FD067A2E3EF7B
sudo apt-get update
sudo apt-get install gns3-gui

I couldn't install it again

Error: 502 bad gateway

After these,i typed gns3 in terminal,Output:
The program 'gns3' is currently not installed. You can install it by typing:
sudo apt install gns3

So i tried to install it with above command:
sudo apt install gns3

Output:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  dynamips libqt4-designer libqt4-help libqt4-scripttools libqt4-svg
  libqt4-test libqtassistantclient4 libxdo3 python-qt4 python-sip xdotool
Suggested packages:
  python-qt4-dbg
The following NEW packages will be installed:
  dynamips gns3 libqt4-designer libqt4-help libqt4-scripttools libqt4-svg
  libqt4-test libqtassistantclient4 libxdo3 python-qt4 python-sip xdotool
0 upgraded, 12 newly installed, 0 to remove and 0 not upgraded.
Need to get 438 kB/10.2 MB of archives.
After this operation, 50.1 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 libqt4-help amd64 4:4.8.7+dfsg-7ubuntu1 [207 kB]
Err:2 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 libqt4-svg amd64 4:4.8.7+dfsg-7ubuntu1
  502  Bad Gateway [IP: ...]
Get:3 http://us.archive.ubuntu.com/ubuntu zesty/universe amd64 python-sip amd64 4.18.1+dfsg-1 [71.8 kB]
Err:4 http://us.archive.ubuntu.com/ubuntu zesty/universe amd64 libxdo3 amd64 1:3.20160805.1-3
  502  Bad Gateway [IP: ...]
Fetched 279 kB in 1min 4s (4,290 B/s)
E: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/q/qt4-x11/libqt4-svg_4.8.7+dfsg-7ubuntu1_amd64.deb  502  Bad Gateway [IP: 91.189.91.23 80]
E: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/universe/x/xdotool/libxdo3_3.20160805.1-3_amd64.deb  502  Bad Gateway    Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  dynamips libqt4-designer libqt4-help libqt4-scripttools libqt4-svg
  libqt4-test libqtassistantclient4 libxdo3 python-qt4 python-sip xdotool
Suggested packages:
  python-qt4-dbg
The following NEW packages will be installed:
  dynamips gns3 libqt4-designer libqt4-help libqt4-scripttools libqt4-svg
  libqt4-test libqtassistantclient4 libxdo3 python-qt4 python-sip xdotool
0 upgraded, 12 newly installed, 0 to remove and 0 not upgraded.
Need to get 438 kB/10.2 MB of archives.
After this operation, 50.1 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 libqt4-help amd64 4:4.8.7+dfsg-7ubuntu1 [207 kB]
Err:2 http://us.archive.ubuntu.com/ubuntu zesty/main amd64 libqt4-svg amd64 4:4.8.7+dfsg-7ubuntu1
  502  Bad Gateway [IP: ...]
Get:3 http://us.archive.ubuntu.com/ubuntu zesty/universe amd64 python-sip amd64 4.18.1+dfsg-1 [71.8 kB]
Err:4 http://us.archive.ubuntu.com/ubuntu zesty/universe amd64 libxdo3 amd64 1:3.20160805.1-3
  502  Bad Gateway [IP: ...]
Fetched 279 kB in 1min 4s (4,290 B/s)
E: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/q/qt4-x11/libqt4-svg_4.8.7+dfsg-7ubuntu1_amd64.deb  502  Bad Gateway [IP: ...]
E: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/universe/x/xdotool/libxdo3_3.20160805.1-3_amd64.deb  502  Bad Gateway [IP: ...]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing? [IP:...]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

Now,What should i do?

A: I managed to install it...
I needed to change the server from Software Center, from US to the best server in my area
Then:
sudo add-apt-repository ppa:gns3/ppa
sudo apt-get update
sudo apt-get install gns3

Not this one:
sudo apt-get install gns3-gui


text:
Q: Instantiating a new object with a different constructor EDIT: Sorry if this seem a little obvious/simple, I tried finding an answer but I'm not sure how to word it correctly
I've been studying a little C# and I'm having some trouble with getting my head around instantiated new objects, where the constructor and the class type are different. So a regular object would be instantiated by:
Object obj = new Object();

That's pretty obvious, but since I've been studying interfaces I've come across some syntax like follows:
interface ISaveable {
    string Save();
}

public class Catalog : ISaveable {
    string Save() {
        return "Catalog Save";
    }

    string ISaveable.Save(){
        return "ISaveable Save";
    }
}

And then the tutorial went on to do something along the lines of this:
Catalog c1 = new Catalog();

So I know here a new instance of the catalog class is being instantiated, however I can't for the life of me figure out this next line:
ISaveable c2 = new Catalog();

Now the actual code itself is no problem (I understand explicit and implicit implementation of interfaces etc.), but it's just the part about the actual instantiation of the above object c2. Why is the class type (ISaveable) different to the constructor ( new Catalog() )?
Any explanation will be very appreciated!

A: To my understanding, the actual type of the objects created by
Catalog c1 = new Catalog();

and
ISaveable c2 = new Catalog();

is the same, namely Catalog (as the same constructor is called), however the type of the referece is different; a call of Save on c1 and c2 will result in calls to the different implementations.

A:
Now the actual code itself is no problem (I understand explicit and
  implicit implementation of interfaces etc.), but it's just the part
  about the actual instantiation of the above object c2. Why is the
  class type (ISaveable) different to the constructor ( new Catalog() )?
ISaveable c2 = new Catalog();

In the above code, you're:

*

*creating a new Catalog object

*using a variable of type ISaveable to reference it

So basically you have a concrete implementation of Catalog, but you'll have to use it as ISaveable.


text:
Q: For $t \geq 3$, if $n \geq R^{(3)}(t,t)$, then n points in $\mathbb{R}^2$ always contain either t collinear points, or t points in convex position. Here $R^{(3)}(t,t)$ is the 3-uniform Ramsey number in the two colors red and blue.
I'd like to ask for some hints. I've tried giving the 3-sets of $n$ points a meaningful coloring (e.g. red if the 3 points are collinear, blue otherwise), and then using the property of the number $R^{(3)}(t,t)$ to force one of the two arrangements to occur, but none of my idea has worked so far.

A: You need to use the property of convexity somehow, but a 3-set by itself is always in convex position, so you need to introduce a way to further distinguish the 3-sets.  If you draw some coordinate axes, giving each point a distinct $x$ coordinate, then you can distinguish between an "upward-pointing" or "downward-pointing" 3-set, i.e., one whose point with middle $x$ coordinate is above or below the segment connecting the other two points.  See if that helps.


text:
Q: How can I generate code coverage for .Net Core 2.x from integration tests on linux/mac? I am doing .NET core 2 work on a mac (and my build server is linux) and I'm looking for a way to generate code coverage for integration tests that use and embedded web server as the system under test.  I can get coverage for my unit tests but not for my Integration style tests.
Im relatively new to .NET but I've familiarized myself with the testing ecosystem as best I can in the last few months.
Currently I'm testing a .NET core 2.2 API using xUnit as my test framework and using the Microsoft supplied Microsoft.AspNetCore.Mvc.Testing package to generate the test server inside of my tests. Very similar to this reference
Then I have tests that use the TestClient to make HTTP requests to the embedded SUT and assert on the response.
I can generate code coverage for my Unit tests using AltCover and this works great! But when i run altcover over my integration test project, I get no coverage results.
I Have DebugType set to Full on the projects, and debug symbol files appear to be generated for all of the relevant code.
The xUnit test fixture for my SUT
namespace Redbox.Product.Tests.Integration.Util
{
    public class TestConfigurationFixture
    {
        private readonly WebApplicationFactory<TestStartup> _webApplicationFactory;

        public TestConfigurationFixture()
        {
            _webApplicationFactory = new CustomWebApplicationFactory<TestStartup>();
        }

        public HttpClient CreateClient()
        {
            return _webApplicationFactory.CreateClient();
        }
    }
}

A Test that executes against this test fixture
    [Fact]
    public async Task ResultsForQueryFound_RespondsOK()
    {
        var response = await _client.PostAsJsonAsync("/products/search",
                                                     new ProductSearchRequest
                                                     {
                                                         Query = "foo"
                                                     })
                                    .ToHelper();

        response.Should().HaveStatus(OK);
    }

I can generate code coverage for my Unit tests using AltCover and this works great! But when i run altcover over my integration test project, I get no coverage results.
Has anyone been able to generate coverage for this type of test?


text:
Q: How to end the "loop" really the def? I AM USING RUBY
def foo()
    puts "First name: "
    first_name = gets.chomp.capitalize
    puts
    puts "Last name: "
    last_name = gets.chomp.capitalize
    puts
    puts "Age: "
    input_age = gets.chomp
    begin
        age = Integer(input_age)
        if age > 0 and age <= 130 then
            puts
            puts "You are #{first_name} #{last_name}. You have been living for #{input_age} years now. Is entered information correct?  [y/n]"
            true_false = gets.chomp
            if true_false == "y"
                puts
                puts "Good!"
                puts
                puts ".........ENTERING STAGE~2........."
            else true_false == "n"
                puts
                puts "Please correct the information and then proceed to next stage."
                puts
                foo()
            end
        end
    end
end
first_name = foo()
    puts
    last_name = foo()
    puts
    age = foo()
    puts "You are #{first_name} #{last_name}. You have been living for #{input_age} years now."

I am asking how to close "the loop". (really it isnt). Because the program keeps repeating after i answer y (yes, the info is correct).
I HAVE BEFORE THE CODE AND AFTER THE CODE ALSO SOME CODING.

A: Me again. Use conditional statements to achieve this.
puts "Age: "
input_age = gets.chomp
begin
  age = Integer(input_age)
  if age > 0 and age <= 130 then

    puts ""
    puts "You are #{input_age} yo."

  else
    puts "Put a valid age please."
  end
end

And if you want to keep asking until the user inputs a valid age, try using a recursive function Thanks to @dutow for the education, don't use recursion here. Use a loop:
def getAge()
  finished = false
  puts "Age: "
  input_age = gets.chomp

  until finished do
    age = Integer(input_age)
    if age > 0 and age <= 130 then

      puts ""
      puts "You are #{input_age} yo."

      finished = true

    else
      puts "Put a valid age please."

    end
  end
  input_age
end

getAge()

MASSIVE EDIT:
In the scope of your whole program, here is a working solution:
def getName(prompt_text)
  finished = false
  result = ""

  until finished do
    puts prompt_text
    result = gets.chomp

    puts "You entered: #{result}. Is this correct? [y/n]"
    response = gets.chomp
    if response == "y"
      finished = true
    end
  end
  return result
end

def getAge()
  finished = false
  puts "Age: "
  input_age = gets.chomp

  until finished do
    age = Integer(input_age)
    if age > 0 and age <= 130 then

      puts ""
      puts "You are #{input_age} yo."

      finished = true

    else
      puts "Put a valid age please."

    end
  end
  input_age
end

puts "ENTERING STAGE~1"
puts ""
first_name = getName("First Name: ")
puts
last_name = getName("Last Name: ")
puts
input_age = getAge()
puts
puts "You are #{first_name} #{last_name}. You have been living for #{input_age} years now."

The code you have in your question is ridiculously broken. You have a lot of different things going on, but the moral of the story is: use functions. Use them a lot. They are really useful. Thanks to @Jack Bracken on this question for some of the updated code.


text:
Q: Вращение фигуры вокруг своей оси в движении в Opengl(glut) Смог сделать обычное движение фигуры треугольник:
Rectanglee::Rectanglee() {
    float temp_x = rand() % 100 / 1000.f;
    float temp_y = rand() % 100 / 1000.f;

    this->point[0].x = temp_x;
    this->point[0].y = temp_y;

    this->point[1].x = -temp_x;
    this->point[1].y = temp_y;

    this->point[2].x = -temp_x;
    this->point[2].y = -temp_y;

    this->point[3].x = temp_x;
    this->point[3].y = -temp_y;

    printf("constructor Rectanglee\n");
}

void Rectanglee::Draw()
{
    glPushMatrix();
    glBegin(GL_QUADS);
    glColor3ub(point[0].r, point[0].g, point[0].b);
    glVertex2d(point[0].x, point[0].y);
    glColor3ub(point[1].r, point[1].g, point[1].b);
    glVertex2d(point[1].x, point[1].y);
    glColor3ub(point[2].r, point[2].g, point[2].b);
    glVertex2d(point[2].x, point[2].y);
    glColor3ub(point[3].r, point[3].g, point[3].b);
    glVertex2d(point[3].x, point[3].y);
    glEnd();
    glPopMatrix();
}

void Rectanglee::Move() {
    point[0].x += speedX;
    point[0].y += speedY;
    point[1].x += speedX;
    point[1].y += speedY;
    point[2].x += speedX;
    point[2].y += speedY;
    point[3].x += speedX;
    point[3].y += speedY;

    if (point[0].x > ballXMax || point[1].x > ballXMax || point[2].x > ballXMax || point[3].x > ballXMax) {
        speedX = -speedX;
    }
    else if (point[0].x < ballXMin || point[1].x < ballXMin || point[2].x < ballXMin || point[3].x < ballXMin) {
        speedX = -speedX;
    }
    if (point[0].y > ballYMax || point[1].y > ballYMax || point[2].y > ballYMax || point[3].y > ballYMax) {
        speedY = -speedY;
    }
    else if (point[0].y < ballYMin || point[1].y < ballYMin || point[2].y < ballYMin || point[3].y < ballYMin) {
        speedY = -speedY;
    }
}

Как можно добавить вращение вокруг своей оси в движении?


text:
Q: Inserv warning missing LSB tags and overrides I installed Jetty 8 to my Debian server. When I added jetty to update-rc.d, it gives following warning. What is this and should I care about it?
insserv: warning: script 'jetty.sh' missing LSB tags and overrides

A: This warning means that your script misses special text comment which specifies services which your service depends on, runlevels on which it should be started or stopped (including ordering), etc.
See http://wiki.debian.org/LSBInitScripts/DependencyBasedBoot for particular details on Debian.


text:
Q: How to call "super" from a callback in coffeescript class Foo
    a: ->
        x.call =>
            super

will not compile as I can't call super from anonymous class. However my
intention is to call the superclass method for 'a'. Is this a missing
capability in coffeescript?
Note that I change the code to
class Foo
    a: ->
        x.call =>
                return Foo.__super__.a.apply(this, arguments)

to make it work but that just ain't coffeescript right!

A: Your proposed solution of writing out Foo.__super__.a.apply(this, arguments) is, I'm afraid, basically as good as you're going to get. CoffeeScript allows you to write things like
a = ->
  b = ->
    super

(in which case super points to b's super function), so it would be a bit confusing to have super within
a: ->
  x =>
    super

point to a's super function. You could raise an issue to ask for this to be allowed, though. It's not ambiguous from a compilation standpoint, just a bit odd-looking.
Here's something you could try to be a little more elegant:
class Foo
  constructor: ->
    @sup = Foo.__super__

  a: ->
    x =>
      @sup.a.apply this, arguments

A: I've encountered the same problem and solved it like this:
ChainSuper = (classType, memberName, useFatArrow) ->
  original = classType::[memberName]
  superf  = classType.__super__.constructor.prototype[memberName]
  callSuper = (thisRef, args, superArgs) ->
    for i in [0...superArgs.length]
      args[i] = superArgs[i]
    superf.apply thisRef, args

  classType::[memberName] = if useFatArrow
    (args...) ->
      original.call @, args..., (superArgs...) =>
        callSuper @, args, superArgs
  else
    (args...) ->
      original.call @, args..., (thisRef, superArgs...) ->
        callSuper thisRef, args, superArgs

This is very non-kosher and will probably break if the Coffeescript compiler's class semantics change. While waiting for that, however, I'm able to say:
CheckSuper = (ref, message) ->
  if ref instanceof Superclass
    alert "Works with #{message}"

class Superclass
  plus: (values...) ->
    CheckSuper @, 'plus'
    @val = 0
    for i in values
      @val += i
    alert @val

  minusBase: 0
  minus: (values...) ->
    CheckSuper @, 'minus'
    @val = @minusBase
    for i in values
      @val -= i
    alert @val

class Subclass extends Superclass
  plus: (values..., Super) ->
    setTimeout (=> Super @), 0
  ChainSuper @, 'plus'

  minus: (values..., Super) =>
    @minusBase = values[0]
    setTimeout (-> Super values[1...]..., 0), 0
  ChainSuper @, 'minus', true

subInstance = new Subclass()
subInstance.plus 1, 2, 3, 4
minus = subInstance.minus
minus 100, 10, 1

Please notice, that with this solution, if you pass n arguments to a Super() when the method has been called with more than n arguments, only the first n arguments get overwritten in the call to the super method and the rest will be passed on unchanged.

A: Now you can use
    super::method()
instead.


text:
Q: Delphi и Linux Можно ли работать в Delphi на линуксе и создавать W приложения? У меня стоит убунта 11,04 надо на делфняке написать приложение для винды. Может есть у кого какие мысли как оболочку поставить?
A: Lazarus+FreePascal
A: Глобально вариантов три:

*

*виртуальная машина с Windows, в ней Delphi нативно. Из виртуалок рекомендую virtualbox (бесплатный), vmware (коммерческий) и parallels (особо хорош под mac).

*запуск Delphi через эмулятор wine. Статус поддержки см. здесь

*использование аналогичных Delphi сред. Например, Lazarus
Всех упомянувших какой-либо вариант плюсанул. Все варианты пробовал самолично.
Могу от себя добавить, что никто не мешает при наличии windows-компьютера с доступом по сети, подключиться к нему по интерфейсу RDP и удаленно сидеть на нем. И писать программы в Delphi - какая им разница: запущены ли они локально или через remote desktop!?
A: Где-то я читал, как умельцы ставили под вайном старые версии дельфов и вроде бы даже у них работало.
A: Oracle Virtualbox спасет мир.
Вайн мир не спасет, но может слегка помочь.

A: Есть ещё одна малоизвестная кросплатформенная среда похожая на Delphi - MseIDE и MseGNU, но по ней очень мало русской литературы, работает она с компилятором Free Pascal. Информацию по установке можно найти на сайте http://freepascal.ru/. Я в ней пока ничего писать не пробовал. Embarcadero недавно объявила о выпуске новой среды Rad Studio XE 2, там можно писать под несколько платформ, но про Линукс вроде ничего не было сказано.


text:
Q: Python regular expression: remove non-ASCII characters and words ending in number I am trying to substitute with " " from a string all non-ASCII characters (accents, symbols), then substitute all words ending with numbers.
I thought r'\W|\b[^a-z]*[^a-z]\b'  would do it because I think it says "remove non-ASCII characters, or remove whole words starting with 0 or more non-letters and ending with non-letters". By non-letters I mean everythign that is not matched by [a-z]. However, "hey2","a2","1a3" are still there
#remove all these words:
re.sub(r'\W|\b[^a-z]*[^a-z]\b',' ', "1 123 - hey2 a2 1a3 ".lower())
>>>' hey2 a2 1a3 '
#keep all these words:
re.sub(r'\W|\b[^a-z]*[^a-z]\b',' ', "1st first a2a 2bb esta' ".lower())
>>>'1st first a2a 2bb esta  '          #This works

What am I missing?

A:
Remove non-unicode characters and words ending in number

It seems you want to remove any non-word char (matched with \W pattern) and any "word" (a sequence of letters/digit/_, \w pattern) ending with a digit.
So, you may use
re.sub(r'\W|\b\w*\d\b', ' ', s)

Note that in case you are dealing with Unicode strings in Python 2.x, you need to pass the re.UNICODE flag to make \W and \w Unicode aware.
Pattern details

*

*\W - a non-word char (any char that is not a letter, digit or _)

*| - or

*\b - a leading word boundary

*\w* - zero or more (*) word chars

*\d - a digit

*\b - a trailing word boundary.

Note that if you want to treat a _ char as a non-word char, replace \W with [\W_] and \w with [^\W_].

A: You're missing a (dot). before the "*".
".*" means 0 or more number of any character(s).
  re.sub(r'\W|\b[^a-z]*[^a-z]\b',' ', "1 123 - hey2 a2 1a3 ".lower())

In [6]: re.sub(r'\W|\b[^a-z].*[^a-z]\b',' ', "1 123 - hey2 a2 1a3 asdasd".lower())
Out[6]: ' asdasd'


text:
Q: How to put a group of integers in a row in a text file into a list? I have a text file composed mostly of numbers something like this:
3  011236547892X
9  02321489764 Q
4  031246547873B

I would like to extract each of the following (spaces 5 to 14 (counting from zero)) into a list:
1236547892
321489764
1246547873

(Please note: each "number" is 10 "characters" long - the second row has a space at the end.)
and then perform analysis on the contents of each list.
I have umpteen versions, however I think I am closest with:
with open('k_d_m.txt') as f:
        for line in f:
            range = line.split()
            num_lst = [x for x in range(3,10)]

print(num_lst)

However I have: TypeError: 'list' object is not callable
What is the best way forward?
What I want to do with num_lst is, amongst other things, as follows:
num_lst = list(map(int, str(num)))
print(num_lst)
nth = 2
odd_total = sum(num_lst[0::nth])
even_total = sum(num_lst[1::nth])
print(odd_total)
print(even_total)
if odd_total - even_total == 0 or odd_total - even_total == 11:
print("The number is ok")
else:
print("The number is not ok")

A: Use a simple slice:
with open('k_d_m.txt') as f:
    num_lst = [x[5:15] for x in f]

Response to comment:
with open('k_d_m.txt') as f:
    for line in f:
        num_lst = list(line[5:15])
        print(num_lst)

A: First of all, you shouldn't name your variable range, because that is already taken for the range() function. You can easily get the 5 to 14th chars of a string using string[5:15]. Try this:
num_lst = []
with open('k_d_m.txt') as f:
    for line in f:
        num_lst.append(line[5:15])
print(num_lst)


text:
Q: How to pass Curl answer to a static text component in matlab I'm trying to find the curl in Cartesian Coordinates for a specific equation in which the user's input is typed in a text box using matlab. In CLI, I used the following equation and it worked: curl([2*x+3*y, 2*y, 2*z], [x, y, z])
Using the GUI I created (for simplicity) one text box (let's say it's for x coefficient) static text label will show the answer and a push button will trigger my code.
the text box tag is inputTxt
the static text lable tag is inputValue
The button callback is:
txtValue=get(handles.inputTxt, 'String');
set(handles.inputValue, 'String', curl([textValue*x, 0, 0], [x, y, z]));

When pushing the button I hear a ding sound which fires an error in matlab cli and nothing appears in the static text label. Even when I set the curl parameters myself just like I did in the CLI first:
curl([2*x+3*y, 2*y, 2*z], [x, y, z])
I get the same result (a ding sound) and nothing appears in the label text.
Thanks in advance.

A: Just found the answer and it did work out.
To pass the curl results to static text use
char(curl([x^3*y^2*z, y^3*z^2*x, z^3*x^2*y], [x, y, z]));

complete code
syms x y z;
set(handles.txtAns, 'String', char(curl([x^3*y^2*z, y^3*z^2*x, z^3*x^2*y], [x, y, z])));

txtAns is static text lable and it should shows the following answer after clicking a push button (if you placed the above lines in push button callback)
matrix[(x^2*z^3 - 2*x*y^3*z) (x^3*y^2 - 2*x*y*z^3 (-2*x^3*y*z + y^3*z^2)]

A: mmounirf, can you try changing:
txtValue=get(handles.inputTxt, 'String');
set(handles.inputValue, 'String', curl([textValue*x, 0, 0], [x, y, z]));

to this:
txtValue=str2num(get(handles.inputTxt, 'String'));
set(handles.inputValue, 'String', num2str(curl([txtValue*x, 0, 0], [x, y, z])));

Can you also post the error please? Basically you're getting a string from the edit box which you need to convert to a number. Then, when you're setting the text, you need to convert the number you get from curl to a string. I also noticed that you changed txtValue to textValue which will cause errors as well.


text:
Q: In efficient EF generated query for odata related entity filtering request, doesn't apply Inner Join with And Clause I have 2 classes ( EF Models ) exposed as odata entityset,
public class Customer
{
    public int Id { get; set; }

    public string Name { get; set; }

    [Required]
    public Address Address { get; set; }
}

public class Address
{
    public int Id { get; set; }

    public string State { get; set; }

    public string City { get; set; }
}

When I query for Customers in specific city using odata filter like

http://localhost:62680/odata/Customers?$expand=Address&$filter=Address/City eq 'Chennai'

It generates the following inefficient sql with City filtering done in WHERE Clause,
SELECT
    [Extent1].[Id] AS [Id],
    N'462b9c81-0a7a-4015-aa08-bcdb2ec067ec' AS [C1],
    [Extent1].[Name] AS [Name],
    [Extent1].[Address_Id] AS [Address_Id],
    cast(1 as bit) AS [C2],
    N'Address' AS [C3],
    N'462b9c81-0a7a-4015-aa08-bcdb2ec067ec' AS [C4],
    [Extent2].[Id] AS [Id1],
    [Extent2].[State] AS [State],
    [Extent2].[City] AS [City],
    cast(1 as bit) AS [C5],
    cast(0 as bit) AS [C6]
    FROM  [dbo].[Customers] AS [Extent1]
    INNER JOIN [dbo].[Addresses] AS [Extent2] ON [Extent1].[Address_Id] = [Extent2].[Id]
    WHERE ([Extent2].[City] = @p__linq__0)

Ideally, it should have generated query with And clause in Inner join for filtering the city like the one below
    SELECT
        [Extent1].[Id] AS [Id],
        N'462b9c81-0a7a-4015-aa08-bcdb2ec067ec' AS [C1],
        [Extent1].[Name] AS [Name],
        [Extent1].[Address_Id] AS [Address_Id],
        cast(1 as bit) AS [C2],
        N'Address' AS [C3],
        N'462b9c81-0a7a-4015-aa08-bcdb2ec067ec' AS [C4],
        [Extent2].[Id] AS [Id1],
        [Extent2].[State] AS [State],
        [Extent2].[City] AS [City],
        cast(1 as bit) AS [C5],
        cast(0 as bit) AS [C6]
        FROM  [dbo].[Customers] AS [Extent1]
        INNER JOIN [dbo].[Addresses] AS [Extent2] ON [Extent1].[Address_Id] = [Extent2].[Id]
and ([Extent2].[City] = @p__linq__0)

Is there any way I can influence the query generation process for Odata request. Please advise.
Library Info :
Microsoft.AspNet.OData : 7.0.1
Entity Framework : 6.2


text:
Q: Symfony2/Doctrine2 innerJoin using QueryBuilder I'm trying to build a innerJoin query using Doctrine2/QueryBuilder.
$repo =  $this->getDoctrine()
        ->getRepository('MyBundle:Models');
$query = $repo->createQueryBuilder('m')
        ->where('m.id = :id')
        ->setParameter('id', $id);

Doctrine says:

A join always belongs to one part of the from clause. This is why you
  have to specify the alias of the FROM part the join belongs to as the
  first argument.
As a second and third argument you can then specify the name and alias
  of the join-table and the fourth argument contains the ON clause.

Ex.
$queryBuilder
->innerJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');

What I can't understand is that 'phonenumbers' table is referencing to Entity Name or DB Table Name.
What I actually want is, is there any way to explicitly refer to entity like
innerJoin('u', 'MyBundle:phonenumbers', 'p', 'u.id = p.user_id')?
It's a bit confusing when it joins just like that. Can please someone explain that to me?
Help!!

A: In fact, you're already referencing explicitely your entity phonenumbers in your second argument of your innerJoin function.
You read the doc and i'll retake it point by point with your request :

*

*Argument 1 :  alias of the FROM part, here your m (alias of your models)

*Argument 2 : The full name of your entity you want join with your models

*Argument 3 : an alias to access it (just like the 'm' of models)

*Argument 4 : The join condition. (like the ON part of a sql request)

But with symfony and if you have a relation between your two entities like that :
//AppBundle/Entity/Models

    class Models {
        /**
         * ...
        **/
        private $id;

        /**
         * ...
         * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\Phone", inversedBy="models")
         **/
        private $phonenumbers;

        ...
    }

you want to join you just can do :
$repo =  $this->getDoctrine()
        ->getRepository('MyBundle:Models');
$query = $repo->createQueryBuilder('m')
        ->innerJoin('m.phonenumbers', 'p')
        ->where('m.id = :id')
        ->setParameter('id', $id);

To explain that : You just have to pass as first argument, the entity property you want to join (here the phone number of your model) and define it as alias (p for phonenumber to access it in a select)

A: You are working on a DQL level with tables, which means that you actually joining a table, so you just need the table name, not the entity name. The table "phonenumbers might not even had an entity to begin with, this is why Doctrine requests a table name and not an entity name.
Edit
It is actually possible to work with entity names as well as follows (taken from my own code which is working as a charm):
$builder = $this->createQueryBuilder('m');
$builder->innerJoin(
    'YourBundle:Category',
    'c',
    Join::WITH,
    $builder->expr()->eq('m.id', 'c.mdl_id')
);

To use the constants from Join you should first:
use Doctrine\ORM\Query\Expr\Join;

But this should also work (taken from documentation which means should work like a charm):
$queryBuilder
    ->select('id', 'name')
    ->from('users', 'u')
    ->innerJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');

This is taken form: http://doctrine-orm.readthedocs.org/projects/doctrine-dbal/en/latest/reference/query-builder.html#join-clauses


text:
Q: Separate date and time in the input type I am using  in the React. This defines a date picker. This date picker is working in my components. Now my problem is how to separate time and date into two different input types?
For example datetime-local show the date picker below:

But now I want to separate the date and time into 2 input types.
For example, I want to show the only date in the input type like below:

For example, I want to show the only time in the input type like below:

This one is my existing coding show the datetime picker in the react:
<Form.Control
type="datetime-local"
name="appointmentDate"
value={selectedDate}
min={newDateValue}
onChange={(e) => handleDateChange(e.target.value)}
format={SAASDateTimeFormat}
/>

Reasons:
Why do I want to use the datetime-local input type to separate time and date? Because I want to standardize to the same UI for all Date & Time on the webpage, some pages use dateime-local input type to show the date picker with time, some pages only use time input type, some pages only use date input. So I want to try to use datetime-local type to separate date and time.
May I know if is it possible to separate date and time in the datetime-local type? Hope someone can guide me on how to solve these problems. Thanks.

A: You can just define the date and time in your input type.
For example:
Time-
type="time"
Date-
type="date"


text:
Q: htmlwidgets::saveWidget produces html file with default style="padding: 40px" By default, the html document created by the htmlwidgets::saveWidget which use htmltools (for example, htmlwidgets::saveWidget (reactable(iris))) has the following attributes in the body tag: <body class="vsc-initialized" style='margin: 9px; padding: 40px; "> that leads to excessive padding from the top of the page.
I have tried to find any documentation how to change the "style='padding: 40px;'" but there is no documentation, and in the code of the save_html function no styles are defined.
Please could you suggest how it is possible to change the style of the body tag and adjust the "padding: 40px" to the desired level?

A: style="" should be double quotes. You have a single quote and a double.
<body class="vsc-initialized" style="margin: 9px; padding: 40px;">

You can try overwriting with !important
.vsc-initialized{padding: 0px!important;}

A: The direction to the solution has been provided by cpsievert in this thread
The final solution is the following:
object2save <- reactable(iris)
object2save$sizingPolicy$padding <- 4
htmlwidgets::saveWidget(object2save, file = "example.html",
            selfcontained = FALSE, libdir = "lib")


text:
Q: Getting error while installing salesforce.com plugins into Eclipse This is error I am getting, using windows xp and eclipse indigo
An error occurred while collecting items to be installed
    session context was:(profile=epp.package.java, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
    Problems downloading artifact: osgi.bundle,com.salesforce.ide.api,24.0.0.201202291629.
    MD5 hash is not as expected. Expected: 7251ab037ae632a5a9835c7c07210451 and found 2d2903c04b9d1291c5486b08bed1c3f3.
    Problems downloading artifact: osgi.bundle,com.salesforce.ide.core,24.0.0.201202291629.
    MD5 hash is not as expected. Expected: 44db36699ca7fdd38917fced4e63c3b3 and found abbb32934dccfa8e090445d70db3ee00.
    Problems downloading artifact: osgi.bundle,com.salesforce.ide.documentation,24.0.0.201202291629.
    MD5 hash is not as expected. Expected: 6d87eb2e76e7e19f7b709682e5272dfc and found b53354a2eed289832ef9d4f81fa4511d.

A: The messages seem pretty clear: the MD5 hash of the plugins you're trying to install don't match what they are supposed to be. It suggest that salesforce.com has a problem in their p2 repository - you should contact them about it through whatever support channel they provide.

A: The Force.com IDE isn't supported in Eclipse Indigo (3.7), so I wouldn't bother contacting support about it. You'll have to use an earlier version of Eclipse like Helios (3.6/3.5/3.4 are supported).  Or just install the standalone Force.com IDE.

A: I recommend Eclipse Helios (3.6) with force.com plugin


text:
Q: Binding in Phonegap I'm building an app using Phonegap and I am running into a strange issue where the binding to click events is not working, does anyone know why?
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);

    $('._jsClick').on('click', function() {
        alert('Hi!')
    });

And here is the HTML
<button class="_jsClick">Click Here!</button>

A: First you should change click function to:
$('._jsClick').on('click', function(event) {
        alert('Hi!')
    });

Also you should:
$('div:jqmData(role="page")').on('pagebeforeshow', function(){
    $('._jsClick').on('click', function() {
        alert('Hi!')
    });
});

$('div:jqmData(role="page")').live('pagebeforeshow', function(){
        $('._jsClick').on('click', function() {
            alert('Hi!')
        });
    });

Not document.ready
Check this link out: how can I make jquery mobile "pagebeforeshow" event fire every time, not just on refresh. The code above will be called when $.mobile.changePage is called.
This should look like this:
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
    $('div:jqmData(role="page")').die('pagebeforeshow');
    $('div:jqmData(role="page")').live('pagebeforeshow', function(){
       $('._jsClick').off('click');
       $('._jsClick').on('click', function() {
        alert('Hi!')
       });
     });
    }


text:
Q: optimize the query, my query taking more than 5 minutes to execute my query taking more than 5 minutes to execute can anyone tell me what's wrong in this query, below is the query I try to optimize it but no luck
SELECT DISTINCT
       'Freight' AS Expr1000,
       'Acknowledged Trip Details' AS detailtype,
       sCompanyDesc,
       VehicleRegistration.sVehicleRegistrationNumber,
       Token.iTokenId,
       sTokenNumber,
       Token.dtTokenGenerating AS TokenDate,
       LoadAssign.sCustomerInvoiceNumber,
       dtCustomerInvoiceDate,
       FillingPoint.sFillingPointName AS [From],
       DecantingPoint.sDecantingPointName AS [To],
       CloseLoad.fExpectedFreightAmount AS fExpectedFreightAmount,
       ISNULL(PayAdvance.fAdvanceAmount, 0) AS fAdvanceAmount,
       CloseLoad.fCommissionAmount AS fCommissionAmount,
       CloseLoad.fDecantedQuantity,
       0 AS [Shortage Quantity],
       0 AS [Shortage Rate],
       0 AS [Shortage Amount],
       sProductName,
       ISNULL((SELECT SUM(ISNULL(JVDetails.fCreditAmount, 0))
               FROM Transactions
                    INNER JOIN JV ON JV.sJVCode = Transactions.sTransactionCode
                    INNER JOIN JVDetails ON JVDetails.iJVId = JV.iJVId
               WHERE CloseLoad.iTokenId = Transactions.iTokenId
                 AND JV.sDescription = 'Munshiana'),
              0) AS Munshiana,
       ISNULL(JV.sJVCode, '') + ISNULL(PV.sPVCode, '') AS advdocnum
FROM CloseLoad
     INNER JOIN Token ON CloseLoad.iTokenId = Token.iTokenId
     INNER JOIN LoadAssign ON CloseLoad.iLoadId = LoadAssign.iLoadId
     INNER JOIN FillingPoint ON Token.iFillingPointId = FillingPoint.iFillingPointId
     INNER JOIN DecantingPoint ON LoadAssign.iDecantingPointId = DecantingPoint.iDecantingPointId
     INNER JOIN Product ON LoadAssign.iProductId = Product.iProductId
     INNER JOIN VehicleRegistration ON Token.iVehicleRegistrationId = VehicleRegistration.iVehicleRegistrationId
     INNER JOIN Company ON Token.iCompanyId = Company.iCompanyId
     LEFT JOIN PayAdvance ON PayAdvance.iTokenId = Token.iTokenId
                         AND PayAdvance.bIsApproved = 1
     LEFT JOIN PV ON PV.iPayAdvanceId = PayAdvance.iPayAdvanceId
                 AND PayAdvance.bIsApproved = 1
                 AND PV.bIsApproved = 1
     LEFT JOIN JV ON JV.iPayAdvanceId = PayAdvance.iPayAdvanceId
                 AND PayAdvance.bIsApproved = 1
                 AND JV.bIsApproved = 1
WHERE CloseLoad.iLoadId NOT IN (SELECT tfrli.iLoadId
                                FROM TempFreightReceiptLoadInfo tfrli
                                     INNER JOIN FreightReceiptChqInfo ci ON ci.iFreightReceiptChqInfoId = tfrli.iFreightReceiptChqInfoId
                                     INNER JOIN LoadAssign l1 ON l1.iLoadId = tfrli.iLoadId
                                WHERE ci.bIsApproved = 1
                                  AND l1.dtCustomerInvoiceDate BETWEEN '8/1/2020' AND '8/30/2020'
                                  AND tfrli.sAllocationType = 'Freight')
  AND LoadAssign.bIsLoadClose = 1
  AND Token.iVehicleRegistrationId = 2644
  AND LoadAssign.dtCustomerInvoiceDate BETWEEN '8/1/2020' AND '8/30/2020'
  AND Token.iCompanyId IN (1, 2, 3)
  AND Token.sDecantingPointType IN ('Domestic', 'Export')
  AND LoadAssign.bIsActive = 1
  AND Token.bIsLoadVerify = 1;

A: Execute EXPLAIN to find bottleneck.
EXPLAIN SELECT DISTINCT ...


text:
Q: Differentiate an exponential operator I have an operator defined as: $$ \exp \Bigg[  \lambda \ \frac{\partial}{\partial R} \Bigg] $$
I'm trying to optimize this with respect to the parameter $\lambda$.
In other words, I'm trying to get an expression for
$$ \frac{\partial}{\partial \lambda} \Bigg[\exp \Big[  \lambda \  \frac{\partial}{\partial R} \Big] \Bigg]$$
I read about Sneddon's formula but that doesn't seem to solve the problem. Any suggestions on how I should approach this?

A: $$\exp(\lambda \partial_R)f(R) = \sum_{k=0}^\infty \frac{\lambda^k f^{(k)}(R)}{k!}.$$
Taking derivatives in $\lambda$ gives:
$$\sum_{k=0}^\infty \frac{\lambda^k f^{(k+1)}(R)}{k!},$$
or $$\exp(\lambda \partial_R)f'(R).$$


text:
Q: Hive sql: count and avg I'm recently trying to learn Hive and i have a problem with a sql consult.
I have a json file with some information. I want to get the average for each register. Better in example:
country  times
USA      1
USA      1
USA      1
ES       1
ES       1
ENG      1
FR       1

then with next consult:
select country, count(*) from data;

I obtain:
country   times
USA        3
ES         2
ENG        1
FR         1

then i should get next out:
country   avg
USA       0,42  (3/7)
ES        0,28  (2/7)
ENG       0,14  (1/7)
FR        0,14  (1/7)

I don't know how i can obtain this out from the first table.
I tried:
select t1.country, avg(t1.tm),
from (
    select country,count(*)as tm from data where not country is null group by country
) t1
group by t1.country;

but my out is wrong.
Thanks for help!! BR.

A: Divide the each group count by total count to get the result. Use Sub-Query to find the total number of records in your table
Try this
select t1.country, count(*)/IFNULL((select cast(count(*) as float) from data),0)
from data
group by t1.country;


text:
Q: Listen to port from docker I have a php app running inside a docker container. The app uses SMTP for mailing. Pre-docker we used a tool called FakeSMTP that allowed us to intercept outgoing e-mails.
We entered the port 2525 into the FakeSMTP tool, and it would listen on this port for e-mails. Whenever our app would send mails on port 2525 we could intercept them. I want to do the same, but with docker.
I tried mapping the port (-p 2525:2525) from docker to host, but that means that the port can not be bound to by any other tools.
Is expose the way to go?
Or is this even possible?

A: Why not map the port to something else on the container, then have FakeSMTP listen to that other port?
-p 41950:2525
Then have FakeSMTP listen to port 41950 and send the intercepted mail out on port 2525.


text:
Q: Can anyone explain me how to install this file? I was reading a Linux magazine PDF ( Linux magazine special edition [US] , July 2021)
[ 101 cool LINUX hacks]
and at hack 86, (as shown in the image below):

( I'm not using Windows 7 , it's just a theme)
it said about a git manager, but I just couldn't install it properly (I have installed github) , I wonder if anyone could describe me how install it.
As you may have noticed, I'm a newbie to git repositories.
[Solved]

A: The instructions are there on the Github site, but they are quite concise and intended for experienced users, so I'll elaborate a bit. Look under the "Linux" header. Three commands are given:

*

*A wget command that allows you to download the program. This command will store the program in the current directory, so you may want to create a directory just for this purpose, let's say /home/[username]/grv, and cd into this directory. This program doesn't need to be installed, and apparently it doesn't need any additional packages or libraries.

*A chmod command. Downloaded files are never executable straightaway, for security reasons. You must set the executable bit yourself. This command does that.

*The command to actually launch the grv program. The path to the git repro to be viewed is a parameter. You may want to create a desktop shortcut for this program. Use /home/[username]/grv/grv as the executable path.

That is all.


text:
Q: Adding infiinity to set of even numbers? I've defined even numbers via the following format:
Inductive even : nat -> Prop :=
| ev0: even 0
| evSS: forall n, even n -> even S (S n) .

I want to add infinity to the list, so something like (even inf) as a Proposition. How can I do this?

A: The definition of nat in Coq does not have an infinite value. Thus, the first step is to add such an element. Here is one possible definition:
Inductive nat_inf :=
| Fin : nat -> nat_inf
| Inf.

You can now define evenness as follows:
Inductive even : nat_inf -> Prop :=
| ev0   : even (Fin 0)
| evSS  : forall n, even (Fin n) -> even (Fin (S (S n)))
| evInf : even Inf.


text:
Q: Is there a better approach on this MySQL query? The following query finds the directors of all shops. I think that there is a simpler solution to this, something that I will prefer to use. Thank you.
SELECT s.ShopID, (EmployeeName+' '+EmployeeSurname) AS FullName FROM shop AS s
JOIN WorksOn AS w ON s.ShopID = w.ShopID
JOIN employee AS e ON w.EmployeeID = e.EmployeeID
JOIN director AS d ON e.EmployeeID = d.EmployeeID

TABLES
employee : EmployeeID, EmployeeName,EmployeeSurname
shop: ShopID, Name, Address
WorksOn: EmployeeID, ShopID
director: EmployeeID

A: It's a very simple query. According to information you provided I don't see anything simpler.
Pardon. Yes you can do it in 2 joins:
SELECT
    w.ShopID, (EmployeeName+' '+EmployeeSurname) AS FullName
FROM
    WorksOn AS w
    JOIN employee AS e ON w.EmployeeID = e.EmployeeID
    JOIN director AS d ON e.EmployeeID = d.EmployeeID

A: THere are a few practical concerns with that query. They might not be issues depending upon how you are using it. But, I'm guessing that in your case you aren't satisfied. So here are my issues:

*

*if there isn't a director etc for a store you get no results for that store. LEFT JOIN it.

*if there are 2 directors and 2 employees, you'll get 4 records. So, you can fix that by having separate queries or by GROUP BY and GROUP_CONCAT or some other aggregate function.


text:
Q: VS Code Remote-SSH: The vscode server failed to start SSH I'm trying to connect to a server via remote-ssh extension for Visual Studio Code, however, I'm getting the following error:

The vscode server failed to start SSH

Everything is fine on the server-side, and the connection to this host worked fine for a while.
Any suggestions to re-access the server via remote-ssh extension?

A: In my case it was ssh plugin issue. I updated remote ssh plugin then it worked

A: After a while, I found a solution that can be useful to others.
In VS Code press:

CTRL + SHIFT + P

Type or select the option:

Remote-SSH: kill VS Code Server on Host...

Select the host name:

And after this procedure, try connecting again to the host.
That worked for me.

A: wrong proxy setting may cause problem.
If Remote-SSH: kill VS Code Server on Host command not work for you, open settings and clear proxy setting and retry.

A:
Everything is fine on the server-side, and the connection to this host worked fine for a while.

In case it is a simple intermittent network issue, VSCode 1.70 (July 2022) will retry the connection for you (up to 5 times)
See issue 127565 and PR 156444

Retry up to 5 times the initial authority resolving and also retry up to 5 times the initial connection
When connecting to a remote, if the initial connection fails, we will give up. The idea was that retrying would be useless, since the initial setup might have failed.
But it is possible that perhaps it was an intermittent network error.

This is available in VSCode insiders today.

A: Update the Remote ssh
check file groups belongs to same group if you manually copied .vscode-server

A:
Remote-SSH: kill VS Code Server on Host...

Didn't work for me, so I tried the other option:

Remote-SSH: Uninstall VS Code Server from Host...

It took a bit more time but worked for me!


text:
Q: Why spark lazy loading slower than wildcarding or passing folders in array? I have a dataset which is partitioned and written to s3 as a set of JSON files.
The partitions structure is:
uid - usually <20 partitions. Int, possible values: 1-100, 70000-70100, 80000-80100
type - String 2 partitions
date - As a usual date. Usually in a range of 2 months.
hour - Obvious 24 partitions.
There is one JSON file inside a partition. The common amount of data ~30GB
When I pass the root folder as it took ~3 min 30 sec to print schema of files.
val df = spark.read.json("s3://path/to/root/folder")
df.printSchema()

When I pass the root folder but perform initial filtering it also took ~3 min 30 sec.
val df = spark.read.json("s3://path/to/root/folder")
  .filter(col("uid") === 1 || col("uid") === 80004)
df.printSchema()

I reduced loading time to 2 min 31 sec by wildcarding all partitions
val df = spark.read.json("s3://path/to/root/folder/uid=*/type=*/date=*/hour=*")
df.printSchema()

I tried to bracket all needed uid's it worked. I reduced loading time to ~34secs
val df = spark.read
  .option("basePath", "s3://path/to/root/folder")
  .json("s3://path/to/root/folder/uid={1,80004}")
df.printSchema()

I also tried to add needed folders in an array and got the same time.
val df = spark.read
  .option("basePath", "s3://path/to/root/folder/")
  .json("s3://path/to/root/folder/uid=1/type=OW/date=2019-07-24/",
        "s3://path/to/root/folder/uid=1/type=OW/date=2019-07-25/",
        "s3://path/to/root/folder/
        ...
        "s3://path/to/root/folder/uid=80004/type=OW/date=2019-08-13")

I thought lazy loading should help me but it didn't. Could someone explain to me why?

A: I'm not sure why you are getting faster time with wildcarding.. but for the explicit folders vs full data the time difference is probably due to the fact that the spark reader needs to do a full scan of all the data in order to infer the schema.  The schema inference step happens immediately when you call read because spark needs to know the schema to proceed and results in Spark executing actions under the hood for you.
You can try reducing the samplingRatio option from it's default of 1.0:
val df = spark.read.option("samplingRatio", "0.1").json("s3://...")

Or you can try explicitly specifying the schema:
import org.apache.spark.sql.types._

val schema = StructType(
    StructField("uid",IntegerType,true) ::
    StructField("type",StringType,true) ::
    ... :: Nil
)

val df = spark.read.schema(schema).json("s3://.....")

The predicate push-down optimization where it only loads some partitions of your data does happen, but it won't happen until you execute an action against that loaded dataframe.  You can confirm this by running explain and looking at the Physical Plan like below, in the PartitionFilters section:
df.filter($"uid" === "1" && $"type" === "bob").explain(true)
== Parsed Logical Plan ==
'Filter (('uid = 1) && ('type = bob))
+- Relation[key#70,key2#71,uid#72,type#73] json

== Analyzed Logical Plan ==
key: string, key2: string, uid: int, type: string
Filter ((uid#72 = cast(1 as int)) && (type#73 = bob))
+- Relation[key#70,key2#71,uid#72,type#73] json

== Optimized Logical Plan ==
Filter (((isnotnull(uid#72) && isnotnull(type#73)) && (uid#72 = 1)) && (type#73 = bob))
+- Relation[key#70,key2#71,uid#72,type#73] json

== Physical Plan ==
*(1) FileScan json [key#70,key2#71,uid#72,type#73] Batched: false, Format: JSON, Location: InMemoryFileIndex[file:/.../test/stackoverflow], PartitionCount: 1, PartitionFilters: [isnotnull(uid#72), isnotnull(type#73), (uid#72 = 1), (type#73 = bob)], PushedFilters: [], ReadSchema: struct<key:string,key2:string>


text:
Q: Can we test the methods written in Kotlin with Mockito? Can we test the Mobile Application methods written in Kotlin with Mockito tool?
Have a mobile application which uses the library written in kotlin. Can Mockito supports to test these library methods.

A: Yes, Mockito can be used with Kotlin.


text:
Q: Limit the number of characters on input() function Usually when I have to deal with multiple integers on one line I do the following:
line = input().split()
... work with the integers here ...

This never was a problem but now I have to read a line with up to 10^6 integers and which one is on range [0, 10^6].
Everytime a submit a solution to the online judge it gives me a Runtime Error and on the error log it shows:

My question is: is there a generic way of reading part of the input and leaving some of it at stdin or somehow limit my input() by spaces?
I found nothing about it on Python3 docs or searching here at StackOverflow!
PS: You can find the problem here https://www.urionlinejudge.com.br/judge/en/problems/view/1973

A: Use sys.stdin.read to control how many characters you're reading at a time:
import sys
a = sys.stdin.read(32)
assert len(a) <= 32

The assertion will never fire.
Note: Be aware you may be cutting some integers off when specifying a size. For example if you do read(4) on input 12 3456 you may get 3 as the second number when it's actually 3456.
Also pay attention to performance issues.


text:
Q: Auto generate token does not functioning properly in php I am now creating a project. In this I am stuck. I want that an 8 digit pin number is generate. If this pin is already in the database then another pin number is generated. After counting 100 times if in all 100 times the generated pin number is in the database then a 9 digit pin number is generated.
My Code is given below :
$t=$this->generate_string(8);
$th= Booking::Where('token',$t)->first();
$count = 0 ;
if(isset($th)) {
    if($count >= 100){
        $t   = $this->generate_string(9);
    }else{
        $t   = $this->generate_string(8);
    }
    $count++;
}
$booking->token = $t;

And generate_string function are
private function generate_string($length)
{
    $character = '0123456789';
    $character .= 'abcdefghijklmnopqrstuvwxyz';
    $quantity_character = strlen($character);
    $quantity_character--;
    $Hash = NULL;
    for ($x = 1; $x <= $length; $x++) {
        $position = rand(0, $quantity_character);
        $Hash .= substr($character, $position, 1);
    }
    return $Hash;
}

My code is not functioning properly. Please help me

A: Your code will not increment the counter because you did not do it.
I created an example based on your code, i used recursion to get the token.
Generate Token Function:
private function generate_string($length)
{
    $character = '0123456789';
    $character .= 'abcdefghijklmnopqrstuvwxyz';
    $quantity_character = strlen($character);
    $quantity_character--;
    $Hash = NULL;
    for ($x = 1; $x <= $length; $x++) {
        $position = rand(0, $quantity_character);
        $Hash .= substr($character, $position, 1);
    }
    return $Hash;
}

Check token function:
private function check_token($t){
    return Booking::Where('token',$t)->first();
}

Get token function:
private function get_token($length, $count){
    $t=$this->generate_string($length);

    $r = check_token($t);
    if(!isset($r)) // base case 1
        return $t;
    if($count <= 0) // base case 2
        return $this->generate_string(9);

    return $this->get_token($length, --$count); // decrements the $count and do recursion.
}

Usage:
$token = $this->get_token(9, 5); //token length = 9, max tries = 5
Get token function uses recursion to generate the token, how the recursion will stop? we have to base cases,

*

*When !isset(check_token($t)) mean that there is not possible token duplicate.

*When $count <= 0 mean that we reach the max possible tries.

If no one of base cases matched, the function call it self again with decremented $count.
Check and update it to fit your needs.
UPDATE:
To get token if the token matches n times, update the get_token function as following:
private function get_token($length, $count){
    $t=generate_string($length);

    $r = check_token($t);
    if(isset($r)){ // token matches, then decrements $count
        --$count;
    }else{
        return $t; // token did not matched, then return the token
    }
    if($count <= 0) // if we reaches the max tries, return token of length '$length + 1'
        return $this->generate_string($length + 1);

    return $this->get_token($length, $count);
}


text:
Q: Why does the value become a string after each function in jquery? I want to create a search function by using jQuery. When I like to search the target, why the result becomes a string instead of divided value? For example, there are AAA, BBB, CCC, and abc, and I want to search for AAA, but the displayValue shows 'AAABBBCCCabc'. Thank you!

  $(".stream_navbar__search_form_input").on("keyup", () => {
    const inputValue = $(".stream_navbar__search_form_input").val();
    console.log(inputValue)
    $(".stream-body__streamer--name").each(() => {
      let displayName = $(".stream-body__streamer--name").text();
      console.log(displayName)
      if (displayName.indexOf(inputValue) != -1) {
        $(".stream-body__streamer--name").parent().parent().parent().show();
      } else {
        $(".stream-body__streamer--name").parent().parent().parent().hide();
      }
    })
  })

          <input class="form-control mr-sm-2 stream_navbar__search_form_input" type="text" placeholder="Search"
            aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="button">Search</button>

BBB

CCC

abc

AAA


text:
Q: sqlite memory usage issue for db file size > 2GB when creating index I have a simple sqlite database with two tables.
Table 1:
    Col1: int index;
    Col2: text;
    Col3: int;
Table 2:
    Col1: int;
    Col2: int;
    Col3: int;

The first table goes up to millions of rows. Table 2 can have hundreds of millions rows. Table 1, Col2 is indexed after all data are entered. Indexes are also  created for Table 2 col1, col2.
The index creation works fine when the database file size is small - < 3.5GB.   When the database file system is > 3.5GB, I will see memory error.
This is Linux system, on 32 bit kernel, the file size >2GB seems to cause memory error during index creation.  On 64 bit kernel, the limit is > 3.5GB.
From "top" program, I see the VM and RSS usage goes up to 3.5GB on 64 bit system before it die.
Have anyone seen this?  Any suggestions on how to work around the issue.  Does Anyone have luck with sqlite with Multi GB file size + index creation?

A: Use a newer SQLite version to avoid eating up memory. (3.7.16 works for me.)
Ensure that there is enough free space on /tmp, or move TMPDIR elsewhere.

A: I had the same problem and found it was caused by the temp_store pragma. I had it set to
pragma temp_store = memory;

but clearly there is a limit to how much memory is available.  I fixed it using
pragma temp_store = file;

If you know that a particular index will cause a problem like this, then you can just set the pragma around the "create" statement and change it again afterwards:
pragma temp_store = file;
create index if not exists table_1_index on table_1(Col1);
pragma temp_store = memory;


text:
Q: Rails 3.0.9 Ajax response not executed I'm using Rails 3.0.9 and jQuery 1.6.2 with jQuery-ujs.
Basically I'd like to ajaxfy my "add to cart" action.
In my view:
<%= button_to "Add to cart", line_items_path(:coupon_id => coupon, :format => :js), :remote => true %>

In my controller:
def create
@cart = current_cart
coupon = Coupon.find(params[:coupon_id])
@line_item = @cart.add_coupon(coupon.id)

respond_to do |format|
  if @line_item.save
    format.html { redirect_to(@line_item.cart) }
    format.js   {render :layout => false, :content_type => 'text/javascript'}
    format.xml  { render :xml => @line_item, :status => :created, :location => @line_item }
  else
    format.html { render :action => "new" }
    format.js   {render :layout => false, :content_type => 'text/javascript'}
    format.xml  { render :xml => @line_item.errors, :status => :unprocessable_entity }
  end
end

end
I've also created a create.js.erb:
$("#my_cart").html("<%= escape_javascript(render(:partial => 'layouts/mycart')) %>");

to update the cart item number whenever a new item is added.
When I click the "add to cart" button, a JS POST request is sent to the server:
    Started POST "/line_items.js?coupon_id=1" for 127.0.0.1 at Thu Aug 18 00:04:31 +0800 2011
  Processing by LineItemsController#create as JS

And the response from the server is:
Rendered layouts/_mycart.html.erb (5.3ms)
Rendered line_items/create.js.erb (28.9ms)
Completed 200 OK in 127ms (Views: 58.7ms | ActiveRecord: 3.0ms)

The response's body contains the javascript code to update my cart:
$("#my_cart").html("
My cart(1)<\/a>\n<\/li>");

However, the web page is not updated. I tried different browsers (Chrome, Firefox, Safari). But if I manually run this code in Firebug's console, the page got updated. I've googled for a day and tried different solutions. None of them worked me. Could someone solve my problem?
Here's the code generated for button_to:
<form method="post" action="/line_items.js?coupon_id=1" data-remote="true" class="button_to">
<input type="submit" value="Add to cart" /><input name="authenticity_token" type="hidden" value="MdHScf0JVNu2UFXLxuindDvZ5TPBztfMMzv57w1LWX8=" />
</form>

A: It looks pretty good as far as I can tell.  Some things I would try in a mystery like this: try taking out the :format=>'js' in your button url (I am pretty sure rails knows it is to be formatted for js). Instead of the respond_to do |format| block, try getting rid of all that and use respond_with(@line_item)
In the top of your controller make sure to specify respond_to :js.
I agree with the comments asking to do a simple alert instead of the escape_javascript render partial.
If still not getting anything, switch to a link_to and see if you can get any results.

A: Problem solved!
I created a new project with the same settings and tried if ajax worked there. Surprisingly, it did. So I concluded that there must be some wrong settings in my project.
And I found and removed this from my application_controller.rb:
  def set_charset
      headers["Content-Type"] = "text/html; charset=utf-8"
  end

  def configure_charsets
      response.headers["Content-Type"] = "text/html; charset=utf-8"
      suppress(ActiveRecord::StatementInvalid) do
        ActiveRecord::Base.connection.execute 'SET NAMES UTF8'
      end
  end

I copied this code from a tutorial to configure character set. Don't exactly know why it screwed everything up but I could move on with my project now!


text:
Q: Paraview - simple no-frills vector field plot from analytical formula Does anyone know of a good tutorial for using Paraview to make a vector field plot, not from a set of numerical data but from a vector-valued function? For example, if the X- and Y-components of my vector field are:
U(x,y) = x^2 + 2y & V(x,y) = sin(x) + 1/y respectively,
then how would I plot it in Paraview on, for instance, the unit square? I'm trying to make a LIC plot similar to this: https://www.paraview.org/Wiki/File:Lic-b-427-hr-crop_small.png
I have researched Paraview extensively but can only find tutorials for graphing numerical data generated in some other complicated piece of software using a file format that I can neither understand nor find any examples of which to follow.
Also, an important clarification: I understand that in any case I must "translate" the math into a numerical data set in order to implement it into any software.
The thing is, I cannot find a simple, general procedure to graph a vector field from an equation in Paraview. There seems to only be specialized knowledge about everyone's particular situations (which are far, far more complex than mine), but few, if any, high-level instructions about how to import two scalar fields with no frills.


text:
Q: What is rank in Python? I've curious about rank in Python. How did the output arrive as printed below?
   What did rank do the data?
Input obj = pd.Series([7,-5,7,4,2,0,4])

Output:
    print(obj)
    0    7
    1   -5
    2    7
    3    4
    4    2
    5    0
    6    4

Rank
    print(obj.rank())
    0    6.5
    1    1.0
    2    6.5
    3    4.5
    4    3.0
    5    2.0
    6    4.5

A: According to the official Pandas Documentation, it does the following:

Compute numerical data ranks (1 through n) along axis. Equal values
  are assigned a rank that is the average of the ranks of those values

This means that essencially all values get assigned a "highscore". The Value 7 is the highest and therefore gets the highest ranking but since the value 7 is there twice, it both gets the highscore 7 AND 6. But since the value 7 can not have 2 different "highscores", it gets assigned the average of both rankings. (6+7)/2 is 6.5 -> that is the ranking of the data Value 7. other values are more straight forward, for example -5 is the lowest and therefore gets the worst rank.


text:
Q: Display specific row details from database into PDF page in php I have an issue, I have retrieved all the details of a row into pdf page but the issue is, when i click it echo's the id in the browser but not the specific id record from database.
On a little change, shows first row from mysql on every id button clicked.
Sometime displays all the record on the PDF page.
Example: If one record covers 2 pages of PDF page then it shows like 10 pages of all the rows showing in pdf page.
When I change the sql query like Select * from students where id = '$id' then this gives this error.

(Undefined variable: id in C:\xampp\htdocs\login Registration
  system\admin\includes\pdf\index.php on line 13)

Please help me out .
Its the Button from Where i call the pdf page:
<a href="includes/pdf/index.php?action=select&id=<?php echo $id; ?>"  class="btn btn-success">Print

Now its the PDF index page :
<?php
require('library/fpdf.php');
include("pconnect.php");

$sql = "SELECT * FROM students ";
$result = mysqli_query($con, $sql);

while($rows = mysqli_fetch_array($result))
{
  $pdf = new FPDF();
  $pdf->AddPage();
  $pdf->SetFont('Arial', 'B', 10);
  $pdf->Ln();
  $pdf->Ln();

  $pdf->Ln();

  $pdf->SetFont('times', 'B', 10);
  $pdf->Cell(30, 20, 'Name on Passport', 1, 0);
  $pdf->Cell(60, 10, $rows['firstname'], 1, 0, 'C');

  $pdf->SetX(40);
  $pdf->Cell(60, 10, $rows['lastname'], 1, 0, 'C');

  $pdf->Cell(30, 10, 'Nationality', 1, 0, 'C');
  $pdf->Cell(45, 10, $rows['nationality'], 1, 0, 'C');

  $pdf->SetX(85);
  $pdf->Cell(28, 10, 'Place of Birth', 1, 0);
  $pdf->Cell(42, 10, $rows['placeofbirth'], 1, 1, 'C');

  $pdf->Cell(30, 10, 'Date of Birth', 1, 0);
  $pdf->Cell(73, 10, $rows['dateofbirth'], 1, 0, 'C');
  $pdf->Cell(42, 10, $rows['gender'], 1, 0, 'C');

  $pdf->SetY(60);
  $pdf->SetX(155);
  $pdf->Cell(45, 40, $rows['Photo'], 1, 1, 'C');

  $pdf->Output();
}?>

A: Thankyou so much for your comments, I have solved it out by myself. The Issue was i was calling the action but in the index page there was no action.
if(($_GET['action'] == 'select') && isset($_GET['id'])) {

$id = $_GET['id'];
$sql = "Select * FROM students WHERE id = '$id'";
$query = mysqli_query($con, $sql);

$pdf=new FPDF();
$pdf->AddPage();
while($rows=mysqli_fetch_array($query))
   {

        $pdf->SetFont('Arial','B',10);
        $pdf->Ln();
        $pdf->Ln();
   }
   $pdf->Output();
  }


text:
Q: Table layout not displaying I have a form as follows-
var mainForm = new Ext.form.FormPanel({
            layout: 'tableForm',
            border: false,
            title: 'This is title',
            bodyStyle: 'padding:5px',
            layoutConfig: { columns: 1 },
            defaults: { border: false, layout: 'form' },
            items: [
                {
                    xtype: 'radiogroup',
                    columns: 3,
                    fieldLabel: 'Please select an option',
                    items: [
                        { boxLabel: 'Yes',  inputValue: '1', checked: true },
                        { boxLabel: 'No', inputValue: '2' },
                        { boxLabel: 'Not Sure',  inputValue: '3' }
                    ]
                },
                {
                    border: false,
                    layout: 'tableform',
                    autoHeight: true,
                    layoutConfig: { columns: 2 },
                    items: [
                         { text: 'Enter value:', xtype: 'label', labelSeparator: ' ' },
                         new Ext.form.NumberField({ fieldLabel: ' ', hideLabel: true, width: 30, allowNegative: false, allowDecimals: false, minValue: 0, maxLength: 10 })
                    ]
               }
            ]
        });

But in this form, only radioGroup is displaying and the second panel (table layout) is not displaying below radiogroup at all.
However, if I add only a sinlge control like
{
    text: 'Enter value:',
    xtype: 'label',
    labelSeparator: ' '
},

it displays below radiogroup.
What I am doing wrong here?

A: Second item is missing the xtype, as per docs:
If an xtype is not explicitly specified, the defaultType for the Container is used, which by default is usually panel.