text:
Q: Handshaking Lemma and existence of the graph Handshaking lemma in graph theory basically says that The degree sum is equal to twice the number of edges.
The doubt I have is, does this condition enough to prove the existence of the graph.
That is if the degree sum is even then a graph exists with that corresponding degree sequence.
This may not be true when the simple graphs are considered. But what if we allow loops and multiple edges

A: Sure, per David Eppstein's contribution to Wikipedia:

The construction of such a graph is straightforward: connect vertices with odd degrees in pairs by a matching, and fill out the remaining even degree counts by self-loops.

A: Chris Culter has your answer when (multiple) loops are allowed.
For simple graphs, you can use the Havel–Hakimi algorithm to establish whether a given set of vertex degree values - a degree sequence - corresponds to a graph.
The process is that you sort the degree sequence descending then generate a new sequence by removing a highest-degree node of degree $d$ and subtract one off  each of the following $d$ degree values, to produce a new shorter sequence.
The process can be applied repeatedly until you reach a sequence that is trivial to recognize as possible or impossible. (In principle, for a graphical sequence - one that corresponds to a realizable graph - this process can be continued to finish with all zeroes).
Working a sample degree sequence:
$\begin{array}{c}
&3&3&3&3&2\\
&&2&2&2&2\\
&&&1&1&2\\
\text{re-sort}&&&2&1&1\\
&&&&0&0&\checkmark \\
\end{array}$


text:
Q: 16.04 Stuck at login (amd radeon gpu) tried all the methods First, my system works fine as 16.04 version for 2 months now, and it suddenly stuck at the login loop yesterday.
I already tried the following methods
mv .Xauthority .Xauthority.backup

after reboot, nothing happens. Then, ls -ld /tmp output
drwxrwxrwt 15 root root 4096 Nov 28 21:05 /tmp

after this, I see .xsession-errors and .xsession-errors.old, no output.
then,
sudo dpkg-reconfigure lightdm
sudo service lightdm restart

still not working, then I tried
sudo apt-get install --reinstall ubuntu-session ubuntu-desktop

I even created new user sudo adduser newguest, still not a chance.
also, I tried to install new desktop environment
sudo apt-get install gnome-shell ubuntu-gnome-desktop
sudo reboot

still not working...

A: When I had this issue, it was because my system partition was full. Removing around 150 MB didn't do the trick, so I made the partition bigger with the live USB stick.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can objects define new sibling or child classes in OOP? Why or why not? Is it possible for a class itself to define a new class in OOP? Are there any languages (Lisp, etc.) that may allow this to happen? Is this something that can be done in OOP at all, or are there logical flaws in this concept (possibly something along the lines of the base "object" class being unable to redefine a new "object" class?)
For example; If class "B" is a subclass of superclass "A", could you theoretically code a catch block within "B" to create a new sibling class "C" of superclass "A" whenever a specific error is caught? Or would that be completely out of reach for conventional programming languages?
I did some reading regarding Lisp for the first time today, and the concept of editing the actual data structures within the language made me curious about this. Thanks.

A: Sure, Common Lisp let's you create classes at runtime.

A: Languages such as Javascript and Python treat functions and methods as objects, and by replacing those functions and methods a developer can dynamically modify an object and its behavior at runtime. This could be compared to "defining a new class", but in dynamically-typed (or duck-typed) languages this means very little.
In strongly-typed languages such as Java, a developer can create an "anonymous inner class" without a name but with a reference to final variables set in the scope.
abstract class CustomAdder {
  abstract int add(int datum);

  static CustomAdder createCustomAdder(final int numberToAdd) {
    return new CustomAdder() {
      @Override int add(int datum) {
        return numberToAdd + datum;
      }
    };
  }
}

// elsewhere
CustomAdder fiveAdder = CustomAdder.createCustomAdder(5);
fiveAdder.add(4); // returns 9
CustomAdder tenAdder = CustomAdder.createCustomAdder(10);
tenAdder.add(20); // returns 30

You could claim that an anonymous inner class is nothing more than a normal class missing a name, with some implicit constructor parameters, and you'd be right; in fact, these classes compile into separate numbered class files. Don't worry too much about that, though: One way or another, the code the program executes is code that some developer typed in that particular language, regardless of which file happens to contain it.
Of course, programs can also generate and dynamically compile/load code in assembly or computer languages, but I assume that's not what you mean. :)


text:
Q: How to delete the space between QLabel and QLineEdit I have a QDialog window like this and I want to delete the space between 'Length', 'n', 'm' and corresponding QLineEdit input boxes. How can I achieve that ?

A: If you use gridlayout, I am not sure why your output looks like that. Generally Qt will not leave huge empty space like that, There are three possibility I can think of:

*

*You have many SPACE after Length:, M: or N:

*The layoutHorizontalSpacing is too large in your grid manager.

*The layoutColumnStretch was set to in favor of label in your grid manager, should be "0,0", not "1,0". I mean, stretch of Label should not be higher than lineedit.

Still, I would use a simple form layout in your application.

A: All you need to do is reset the alignment of the labels:
    label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlighVCenter)

This can also be done in via the Property Editor in Qt Designer.

A: You have to decide what to do with the space you want to remove :

*

*Reduce the whole widget : it depends on the surrounding layout, adding an horizontal layout on right or left of it will put the space out of your widget.

*Space on the left of your labels : you can align the label text to the right as ekhumoro suggested, or directly reduce and align to the right the whole frame by adding an horizontal spacer on its left (in the surrounding layout).

*Space on the right of your line-edits : like above you can add horizontal spacers or reduce and align the frame.

*Expand the line-edits : remove their fixed width (default horizontal policy is expanding) or set a bigger one.

The point is : the space has to be somewhere except if you reduce the parent widget or enlarge some the inner widgets. Size-policy is useful to tell which widget should take the available space, spacers are useful to let empty space between widgets.


text:
Q: What's the difference in serving file through express and through public html folder? What's the difference between those two:

and

First file is put in public html folder I've checked it's headers and as can I see:
Content-Type, Content-Length, Connection, Accept-Ranges are the same.
But... for file put in html folder I can use it's link for twitter's card and i can see video preview, and for file returned by nestjs backend it's not shown there.
Both pages got their required meta tags and are served over https.


text:
Q: How to deserialize JSON array with different types? I have a JSON array like this:
[
  "0",
  {
    "number": 1,
    "field": "value"
  },
  {
    "number": 2,
    "field": "value"
  }
]

The first element to the array is a string.
Is it possible to deserialize it with FasterXML Jackson?
I know how to do it with different objects.
I need to use @JsonSubTypes (Here is an example https://stackoverflow.com/a/38877862/2564509)
The problem with this array is that the first element is String type.

A: Caveat: Your situation is an unfortunate edge case.
As such,
the solution is likely to be not wonderful.
This works,
but is not wonderful:

*

*First, deserialize as a List<Object>.
In your case, this will result in a List of three elements;
String,
LinkedHashMap,
and LinkedHashMap

*Next, process each element in the array and,
process based on the element type;
a String will be your String element,
a LinkedHashMap will be the representation of your number-field class.


text:
Q: Hadoop shell command VS Java APIs I faced a performance issue while writing an utility to delete files and directories from hdfs iteratively within a loop (was invoking the shell command from shell script) that were older than a week. Also I had certain checks to be performed on each file/sub-directory before deleting, so that I could not just delete the entire root directory. For each delete, the shell command was taking around 2 sec. So If I had to delete 1600 files and subdirectories, it was taking close to 1 hr to accomplish them. When I instead used the JAVA APIs (FileStatus and FileSystem), I got a drastic performance gain. It completed under 5 secs. I would like to know in detail the fundamental reason behind this. I read that shell commands (like -rm) intrenally use the JAVA APIs but is that the sole reason for this huge difference in response time ?

A: Well invoking the shell command iterative, you have the JVM startup time to contend with for each iteration, while the API approach you only have one JVM startup. Along these lines you have to connect to the name node multiple times etc.


text:
Q: How to prevent onmouseover function from firing continuously When I mouseover a button, a function activated by onmouseover fires continuously every fraction of a second. I want it to fire only once.
I need to use onmouseover on a button to call a submit function because I cannot use onclick because it interferes with another function that is called onclick. If I use onmouseout it works ok and only fires once, but onmouseout is not satisfactory for my purpose. I have tried other event handlers including onmouseenter, and onmousedown, but they suffer from the same problem. I also tried this: onmouseover="submitForm(); button.onmouseover = null;"
<script language="javascript" type="text/javascript">
function submitForm() {

 $("#pform").submit();

}
</script>

<input type="button" onmouseover="submitForm();" />

When the button is moused over, the function fires continuously, several times per second. I want it to fire only once.

A: You can use simple logic to check whether the mouse over event enters first time. Use local storage, if local storage is no set initially, it is the first time the mouse over event.
else if local storage is already set to true, then don't trigger the form submit.
<script language="javascript" type="text/javascript">
function submitForm() {

if(sessionStorage.getItem("mouse_over") == undefined){

 sessionStorage.setItem("mouse_over","true");
 $("#pform").submit();

}else{

}

}
</script>

<input type="button" onmouseover="submitForm();" />

A: $(element).one('mouseover' function(){
 // your function here
});

A: Apparently, when you submit the form, the page is reloaded. After the reload, the mouse is still on the button and the event is fired again.
It is not common to use onmouseover to submit a form. You wrote that you don't use onclick, because it interferes with another function that is called onclick. If that is the only reason, then please try to prevent the interference as follows.
Change the button as follows:
<input type="button" id="clickbutton" />

Find the $(document).ready(function() { ... }); in your page and add the following code inside:
$("#clickbutton").click(function(e) {
  e.stopPropagation();
  $("#pform").submit();
});

A: Admiraalit -
I'm trying your last suggestion. This is client side called onmouseover
    <script>
    function checkLoginStatus() {
        jQuery.ajax({
                type: "POST",
                url: "checkstatus.php",
                success: function(res){
                    if(res == "0") {
                         alert("Login Required");
                    }
                }
        });
    }
    </script>
and this is checkstatus.php

    <?php
      session_start();
    echo "checking status";
      if(isset($_SESSION["username"]))
      {
         echo "1";
      } else {
         echo "0";
      }
     ?>

I have verified with an alert box that checkLoginStatus() is being called, but nothing happens otherwise. What is wrong?

A: Have you tried adding a variable to track whether you have already submitted? For example:
<script language="javascript" type="text/javascript">
var formSubmitted = false;
function submitForm() {
  if (!formSubmitted){
    $("#pform").submit();
    formSubmitted = true;
  }
}
</script>

<input type="button" onmouseover="submitForm();" />

That should ensure it only happens once (even if submitForm() is getting called many times).

A: This works. I think the problem was the extra echo statement I put in checkstatus.php for testing.
<script>
function checkLoginStatus() {

    jQuery.ajax({
            type: "POST",
            url: "checkstatus.php",
            success: function(res){
                if(res == "0") {
                     alert("need to log in");
                }
            }
    });
}

</script>

<?php
  session_start();

  if(isset($_SESSION["username"]))
  {
     echo "1";
  } else {
     echo "0";
  }
 ?>

    <?php
      session_start();

      if(isset($_SESSION["username"]))
      {
         echo "1";
      } else {
         echo "0";
      }
     ?>

This provides the not logged in message and I can submit using onmouseout so all is good. Thanks everyone.


text:
Q: How recreate thread with new parameters? I have multithreading program, which send email to my clients.
In my code: thread have some troubles - code just close window of firefox and that's it.
I want to create these algorithm: thread have some troubles - window of firefox (+selenium) just close(only one thread is closing, another threads should continue working), get another parameters data from my DB and start thread again with new parameters
And all of time should working 5-10 threads non-stop. If something goes wrong with thread - firefox window should be closed, program get another data from DB(i'll create these code, it's easy) and should open new firefox window and continue working with new parameters.
Main method:
static String path = "C:\\Users\\Admin\\Desktop\\clients.txt";
static String path_ok = "C:\\Users\\Admin\\Desktop\\clients2.txt";
static Integer numberMail = 1; //id рассылки
static List<User> users = new ArrayList<User>();

YandexConfig config1 = new YandexConfig("login1", "password1", "cookies", port1);
YandexConfig config2 = new YandexConfig("login2", "password2", "cookies", port2);
ExecutorService executor = Executors.newFixedThreadPool(50);
CompletableFuture.runAsync(new DoThread("thread 1", path, path_ok, numberMail, users, config1), executor);
CompletableFuture.runAsync(new DoThread("thread 2", path, path_ok, numberMail, users, config2), executor);

doThread:
class DoThread implements Runnable {
    private String threadName;
    private Integer numberMail;
    private String themeMessage = "Your order";
    private String messageDefault = "blabla";
    private final List<User> users;
    private final String fileWait;
    private final String fileOk;
    private final YandexConfig config;

    DoThread(String threadName, String fileWait, String fileOk, Integer numberMail, List<User> users, YandexConfig config) {
        this.threadName = threadName;
        this.fileWait = fileWait;
        this.fileOk = fileOk;
        this.numberMail = numberMail;
        this.users = users;
        this.config = config;
    }

    public void run() {
        System.out.println("Thread #" + threadName + " started");

        while (true) {
        try {
                auth(threadName, config.login, config.password);
                break;
            } catch (InterruptedException e) {

                System.out.println("Something goes wrong");

                e.printStackTrace();
            }
        }
            //another a lot of strings of code
    }
}

Question is: how I can restart thread with new parameters based on my code?

A: You need a way to modify the parameters for the next thread. You need to supply setters for the data and then just start up another thread.
class DoThread implements Runnable {
    ...
    void setThreadName(String name) { ... }
    void setFileOK(String fileOK) { ... }
}

class UseDoThread {
    void f() {
        DoThread r = new DoThread(...);
        new Thread(r).start();
        ...
        r.setThreadName("?");
        r.setFileOK("I think so");
        new Thread(r).start();
}

However, warning: You would need to wait for the thread to finish before modifying the values and restarting. Otherwise, the first run will use the modified values and your data will be essentially corrupt. You can wait for the thread to finish in a number of wait, most simply by using the join method on it.
But if you can simply join it, then you might not be benefitting from making this multithreaded in the first place.
A better approach might be to make a new instance of DoThread and start that.
void f() {
    new Thread(new DoThread("thread1", ...)).start();
    new Thread(new DoThread("thread2", ...)).start();
}

It is for this type of reason that throwaway classes with final values are used more in concurrent programming. Each thread needs its own variant, and if they are all going at once it does not make sense to try to recycle this type of class. So you could declare all of the fields in DoThread to be final if you plan to create a new DoThread each time.


text:
Q: linking *.o files in Windows When I'm linking .o files with the LD linker using MinGW on Windows, it gives me the error "file.o: File not recognized: file format not recognized". I've tried to do it with cygwin instread, but the same thing happens. Any suggestions?

A: Most likely you have a object file in a format that the linker does not understand. There are lots of different formats out there: COFF, OMF, ELF (the list goes on..)
Fortunately there is a free tool that lets you convert from one format to another. It also lets you take a look into the internals of the object format and tells you in which format a object file is encoded.
http://www.agner.org/optimize/#objconv
That little command line utility solved all the object format problems I ever had. It can even disassemble libs, object files, DLLs and executables.


text:
Q: Show ZF2 request execution time I want to print in every page of my site, which is in ZF2, the request execution time.
I have already defined a constant within the index.php (which is the first file the request access) with the request initial microtime(true).
Now, where should I get the request final microtime(true)?
My plan is to have something like this:
$executionTime = ($finalTime - $initialTime) / 1000000; // in seconds
$executionTime = number_format($executionTime, 2);

A: The problem is that you probably want to add this information to the view (so the user can see it) which would mean adding the time before you render the view (before MvcEvent::EVENT_RENDER). The problem is though that the view is rendered way before MvcEvent::EVENT_FINISH is triggered so the time would not be accurate. This won't be easy to solve...

You could consider adding some time related header inside your response.
Here an interesting related question about adding your custom headers.

*

*There is for example a $request_time variable for NGinx which you could use out-of-the-box:

$request_time
  request processing time in seconds with a milliseconds resolution (1.3.9, 1.2.6); time elapsed since the first bytes were read from the client

add_header X-Request-Time $request_time always;

*There is also an Age response header field. You can find it here in the Header Field Definitions section 14.6 in RFC2616.

The Age response-header field conveys the sender's estimate of the
  amount of time since the response (or its revalidation) was
  generated at the origin server. A cached response is "fresh" if
  its age does not exceed its freshness lifetime. Age values are
  calculated as specified in section 13.2.3.

Maybe you could use it to calculate the time it took to process the request on the server.
You could also add a custom header in your ZF2 application by adding some code to your Module.php like this:
function onBootstrap(MvcEvent $event) {
    $application = $event->getApplication();
    $eventManager = $application->getEventManager();
    $eventManager->attach(MvcEvent::EVENT_FINISH, [$this, 'addTimeHeader']);

    //...
}

function addTimeHeader(MvcEvent $event) {
    $time = // get your time value
    $response = $event->getResponse();
    $response->getHeaders()->addHeaderLine('X-Request-Time', $time);
}

The issue will still be to get this data inside your view. If you use an AJAX request it will be easy to get the header from the response, but if you don't use AJAX it is a whole different story. Read more here in this answer.

A: To achieve what you ask, and some more, in a development environment, you could use the Zend Developer Tools modules, which will automatically give you some informations regarding your application.
In a production environment, you could instead listen to the MvcEvent::EVENT_FINISH, that is the last event emitted by the Zend framework MVC

A: If you want to be a really dirty, add in your index.php file at beginning:
$_GET['the_time'] = round(microtime(true) * 1000);

Wherever you want in the view or layout print:
echo round(microtime(true) * 1000) - $_GET['the_time'];
// Use $_GET as global variable

Note: The rest of developers will probably hate you.

A: My solution is based on this answer.
Every view of mine has a footer.phtml attached to it, so if I print it there, there will be no need to change many files.
To print the time there, first I wrote something specific to that footer.phtml, for example Execution time:
Than in module/Application/Module.php I added this code to onBootstrap()
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_FINISH, function($e) {
    $time = microtime(true) - REQUEST_MICROTIME;

    // formatting time to be more friendly
    if ($time <= 60) {
        $timeF = number_format($time, 2, ',', '.').'s'; // conversion to seconds

    } else {
        $resto  = fmod($time, 60);
        $minuto = number_format($time / 60, 0);
        $timeF = sprintf('%dm%02ds', $minuto, $resto); // conversion to minutes and seconds
    }

    // Search static content and replace for execution time
    $response = $e->getResponse();
    $response->setContent(str_replace(
        'Execution time:', 'Execution time: '.$timeF, $response->getContent()));

}, 100000);

A: You can capture time to variable in index.php and then use register_shutdown_function to print time difference between:
index.php
define('APP_START_TIME', microtime(true));

register_shutdown_function(function(){
 echo 'Request time(sec): ' . number_format(microtime(true) - APP_START_TIME, 3);
});


text:
Q: Ubuntu installed on an external hard disk but not working I have installed Ubuntu on my external hard disk (1TB Western Digital, My Passport). I have only 30GB of free space in my external hard disk, so I partitioned as:

*

*1st partition is for my backup data which is of around 900GB

*2nd partition is for Ubuntu, which is of 30GB, in which i have made sub-partitions using GParted

For that, I have already have Ubuntu setup in my USB drive of 2GB, which I created using universal USB installer. The sub-partition is like:
/boot - 512MB
/ - 20GB
swap - 4GB
/home - rest space left in that 30GB

Now I have completely installed Ubuntu with the help of pendrive of 2GB in / partition. And, boot loader in /boot.
When I restart my computer, it is straightly loading Windows. Then, I searched for the problem here and tried many things such as booting from an external drive active in boot menu. Pressing F2, F8, F9, F10, F12. But the Ubuntu boot is not appearing and the computer directly loads the Windows installed in my internal hard disk. I have a Sony laptop.
How can I boot Ubuntu?

A: Because you are installing to an external drive, you need to configure the bootloader to be in the MBR of the drive itself. As such, you do not want to choose the /boot partition for the installation target of the bootloader.
Instead, select the bootloader installation target as /dev/sdX, replacing X with which ever letter the rest of your partitions are under. /dev/sda is usually the hard drive, so you normally don't want that. Since you are using a USB drive to install and a USB drive as the target, you will see /dev/sdb and /dev/sdc. Choose the one that is the external drive. Please not that the letters can show up in any order and can be associated with any drive, so look carefully.
This will make it so that the drive now has a valid bootloader. If there is no loader in the MBR, the computer does not know how to load. For example, when I was running install on a pen drive, I had three partitions. /, /home, and /storage, where /storage was a NTFS partition to be shared between Windows and Ubuntu. / was /dev/sdc1, /home, was /dev/sdc2, and so on. I had the Ubuntu installer point to just /dev/sdc when installing GRUB so that the drive itself would be receiving the install, rather than one of the partitions.


text:
Q: Need to check some flags are active in the table Need to check some flags are active in the table column.
If Only flags are active update statement should execute.
(My Flags are HR_Active and User_Active if only those flags are "1" update statement should execute) if "0" should pass the passage in web service.
Table Name is : HS_HR_EMPLOYEE
Below I have mention the my code snippets.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

namespace XXX_WebService
{

    [WebService(Namespace = "http://XXXXXXX.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class EmployeeService : System.Web.Services.WebService
    {

        [WebMethod(Description = "Update Employee Email Address")]
        public int Update(string USRACC_USER_ID, string EMP_OFFICE_EMAIL)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("UPDATE HS_HR_EMPLOYEE SET EMP_OFFICE_EMAIL = @EMP_OFFICE_EMAIL FROM HS_SM_USER_ACCOUNT WHERE HS_SM_USER_ACCOUNT.EMP_NUMBER = HS_HR_EMPLOYEE.EMP_NUMBER AND USRACC_USER_ID = @USRACC_USER_ID"))
                {
                    cmd.Parameters.AddWithValue("@USRACC_USER_ID", USRACC_USER_ID);
                    cmd.Parameters.AddWithValue("@EMP_OFFICE_EMAIL", EMP_OFFICE_EMAIL);
                    cmd.Connection = con;
                    con.Open();
                    int row = cmd.ExecuteNonQuery();
                    con.Close();
                 //return row;
                }

                string emp_number ="-1";
                 using (SqlCommand cmd = new SqlCommand("SELECT EMP_NUMBER FROM HS_SM_USER_ACCOUNT WHERE USRACC_USER_ID=@USRACC_USER_ID"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                    cmd.Parameters.AddWithValue("@USRACC_USER_ID", USRACC_USER_ID);
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            dt.TableName = "HS_SM_USER_ACCOUNT";
                            sda.Fill(dt);
                            if(dt.Rows.Count > 0)
                            emp_number =  dt.Rows[0][0]==DBNull.Value ? "-1" : dt.Rows[0][0].ToString();
                        }
                    }
                }

                using (SqlCommand cmd = new SqlCommand("INSERT INTO HS_EMP_EMAIL_TEMP_LOG (EMP_NUMBER,USRACC_USER_ID,EMP_OFFICE_EMAIL,LOG_DATE_TIME) VALUES(@EMP_NUMBER,@USRACC_USER_ID,@EMP_OFFICE_EMAIL,GETDATE())"))
                {
                    cmd.Parameters.AddWithValue("@EMP_NUMBER", emp_number);
                    cmd.Parameters.AddWithValue("@USRACC_USER_ID", USRACC_USER_ID);
                    cmd.Parameters.AddWithValue("@EMP_OFFICE_EMAIL", EMP_OFFICE_EMAIL);
                    cmd.Connection = con;
                    con.Open();
                    int row = cmd.ExecuteNonQuery();
                    con.Close();
                   // return row;
                }
                return 1;
            }
        }
    }
}

A: Add Flag filters in your update statement in where clause
UPDATE HS_HR_EMPLOYEE SET EMP_OFFICE_EMAIL = @EMP_OFFICE_EMAIL FROM HS_SM_USER_ACCOUNT WHERE HS_SM_USER_ACCOUNT.EMP_NUMBER = HS_HR_EMPLOYEE.EMP_NUMBER AND USRACC_USER_ID = @USRACC_USER_ID" and HS_HR_EMPLOYEE.HR_Active = 1 and User_Active = 1))

or you can first check the flags in table by using select statement.


text:
Q: Scrape historical economic data from investing.com The code from here shows nicely how to extract economic data from https://www.investing.com/economic-calendar/. However, the code just scrapes the data from the current economic data table that is from today. There is a calendar icon where the timeframe can be set manually and past economic events can be viewed (highlighted red on the screenshot):

Is there a way to scrape the past econonomic event data? So far, I have not really an idea ...

A: I'm not 100% sure if you are looking excactly for this BUT have you tried  investpy? It is a great python module, that seems to do exactly what you are trying to achieve but with less pain.

investpy is a Python package to retrieve data from Investing.com...
investpy allows the user to download both recent and historical data from all the financial products indexed at Investing.com. It includes data from all over the world, from countries such as United States, France, India, Spain, Russia, or Germany, amongst many others.

pip install investpy

and then use it as seen below (and also here):
import investpy

data = investpy.economic_calendar(
    from_date='12/09/2021',
    to_date  ='13/09/2021'
)
print(data.head())

       id        date   time                  zone currency importance                                     event  actual forecast previous
0  436810  12/09/2021  09:59  united arab emirates      AED        low         Private Sector Loans (YoY)  (Jul)  -1.80%     None   -1.20%
1  435581  13/09/2021  01:45           new zealand      NZD        low                          FPI (MoM)  (Aug)    0.3%     None     1.3%
2  435584  13/09/2021  02:50                 japan      JPY     medium  BSI Large Manufacturing Conditions  (Q3)     7.0     None     -1.4
3  435583  13/09/2021  02:50                 japan      JPY        low                          PPI (YoY)  (Aug)    5.5%     5.6%     5.6%
4  435582  13/09/2021  02:50                 japan      JPY        low                          PPI (MoM)  (Aug)    0.0%     0.2%     1.1%

Related projects:

*

*trendet - Trend detection on stock time series data

*pyrtfolio - Python package to generate stock portfolios


text:
Q: Generate Alert message for @Html.Actionlink in jquery I have one ActionLink in view page like :-
@Html.ActionLink("Edit","Index", new { id="actedit"})

but i want to use this id in javascript like :
$(document).ready(function () {

    $("#actedit").click(function () {
    alert("Working okay");
    $('#trdata *').attr('contenteditable', 'true');
});

});

I just try to make it conent editable process using this actionlink id but i could not able to fetch the id from view page by using action link. I can get the id by using anchor link.. Is there any idea to get the id value from view to jquery..

A: If you are using a link to trigger some jQuery, you should just use Edit instead, as an action link will always redirect to that action.
EDIT: You still want to use an action link, here is the code needed to create the action link you want:
@Html.ActionLink("Edit", "Index", null, new { id="actedit"})

However, as it is an ActionLink as soon as you click on it, it will redirect to that action. You will also need to supress that event in your javascript like this:
$(document).ready(function () {
  $("#actedit").click(function (e) {
    alert("Working okay");
    $('#trdata *').attr('contenteditable', 'true');
    e.preventDefault();
  });
});


text:
Q: I have string with number, how to get number out of this string in SQL Server I have string something like ACGI SHIPPING (3471) and I need to get 3471 number out of it.
If there is no number just print 0, in SQL Server

A: Here is a solution:
DECLARE @s VARCHAR(100) = 'ACGI SHIPPING (3471)'
SELECT CASE WHEN PATINDEX('%[0-9]%', @s) > 0
            THEN REPLACE(SUBSTRING(@s, PATINDEX('%[0-9]%', @s), LEN(@s)), ')', '')
            ELSE 0 END

You are searching for first digit and take substring from that position to end. And then replace ')' with blank.


text:
Q: Como calcular valor de duas subquery no Oracle SQL Como se calcula duas subquery no Oracle?
Poderiam me explicar como faço a soma do VALOR_1 + VALOR_2?
SELECT COL1
, (SELECT SUM(TAB1.VLRTOTAL)
    FROM TABELA TAB1
    WHERE TAB1.ID = TAB3.ID) AS VALOR_1

, (SELECT SUM(TAB2.VLRTOTAL)
    FROM TABELA2 TAB2
    WHERE TAB2.ID = TAB4.ID) AS VALOR_2

FROM TABELA3 TAB3, TABELA4 TAB4
WHERE TAB4.ID = TAB2.ID
AND TAB2.ID <= 10

A: Tenta realizar um subselect dessas informações:
select dados1+dados2
  from (Select (select seuselectdados1) as dados1
             , (select seuselectdados2) as dados2
          from table
      ) as tab_temp

A: Obrigado a colaboração de todos, mais resolvi desse modo:
Muito obrigado.
, (SELECT NVL(SUM(TAB1.VLRTOTAL),0)
    FROM TABELA TAB1
    WHERE TAB1.ID = TAB3.ID) AS VALOR_1

, (SELECT NVL(SUM(TAB2.VLRTOTAL),0)
    FROM TABELA2 TAB2
    WHERE TAB2.ID = TAB4.ID) AS VALOR_2

, (SELECT NVL(SUM(TAB1.VLRTOTAL),0)
    FROM TABELA TAB1
    WHERE TAB1.ID = TAB3.ID)+
, (SELECT NVL(SUM(TAB2.VLRTOTAL),0)
    FROM TABELA2 TAB2
    WHERE TAB2.ID = TAB4.ID) AS AS SOMATOTAL

FROM TABELA3 TAB3, TABELA4 TAB4
WHERE TAB4.ID = TAB2.ID
AND TAB2.ID <= 10


text:
Q: Google Chrome - запрет загрузки определённого SWF Здравствуйте!
В общем такой вопрос:
В Google Chrome нужно запретить загрузку определённого SWF, т.е. только единственного, только по 1 ссылке (назовём её http://site.ru/ads.swf) - как это можно сделать?
A: Под Chrome же есть Adblock Plus.


text:
Q: Sumif and countif criteria isn't working in Excel VBA I am writing an excel vba code for expected shortfall evaluation.
My sumif and countif functions return value 0 if I put in criteria ' "<" & Var ' (value at risk - percentile of array at 2,5%), if I reverse that criteria (">") these functions sum/count all values in range.
I can't find the mistake, can anyone help?
Here is a part of the code:
Dim RiskHorizon As Integer
RiskHorizon = InputBox("Set the Risk Horizon!", "Risk Horizon", 10)
Dim SigLev As Double
SigLev = InputBox("Set the Significance Level!", "Significance Level", 0.025)
Dim CountDates As Integer
CountDates = Application.CountIf(Sheets("ExpSh").Columns("A"), "<>" & "") - 1
Dim ReturnRange As Range
Set ReturnRange = Sheets("ExpSh").Range("C2:C" & CountDates - RiskHorizon + 1)
Dim Var As Double
Dim ES As Double
Dim Sums As Double
Dim Counts As Double
Var = Application.WorksheetFunction.Percentile(ReturnRange, SigLev)
Sums = Application.WorksheetFunction.SumIf(ReturnRange, "<" & Var)
Counts = Application.WorksheetFunction.CountIf(ReturnRange, "<" & Var)
ES = Sums / Counts

A: Perhaps:
Sums = Application.WorksheetFunction.SumIf(ReturnRange, ""<"" & Var)
Counts = Application.WorksheetFunction.CountIf(ReturnRange, ""<"" & Var)


text:
Q: Convert to PDF and EXCEL from google sheet (value only) and email straighaway (2 attachments) - AppsScript I have a apps script that convert from Google sheet to PDF and EXCEL & emails straightaway with 2 attachments. My problem is, the excel in one sheet that i need to export and email as attachment is got formula inside.
My question is how to export the value & formatting, so that it is not turn up #N/A.

    var changedFlag = false;
var TEMPLATESHEET='M-Email Me';

function emailSpreadsheetAsPDF() {
  DocumentApp.getActiveDocument();
  DriveApp.getFiles();

  // This is the link to my spreadsheet with the Form responses and the Invoice Template sheets
  // Add the link to your spreadsheet here
  // or you can just replace the text in the link between "d/" and "/edit"
  // In my case is the text: 17I8-QDce0Nug7amrZeYTB3IYbGCGxvUj-XMt8uUUyvI
  const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1Zgs1jzjIeaBpd5Ms7emQgxhVJBMtlEOlDNDfxlhSRiY/edit");

  // We are going to get the email address from the cell "B7" from the "Invoice" sheet
  // Change the reference of the cell or the name of the sheet if it is different
  const value = ss.getSheetByName("M-Generate").getRange("F3").getValue();
  const email = value.toString();

  // Subject of the email message
  const subject = ss.getSheetByName("M-Generate").getRange("B3").getValue();

    // Email Text. You can add HTML code here - see ctrlq.org/html-mail
  const body = "Automated Quotation - Sent via Auto Generate from Glideapps";

  // Again, the URL to your spreadsheet but now with "/export" at the end
  // Change it to the link of your spreadsheet, but leave the "/export"
  const url = 'https://docs.google.com/spreadsheets/d/1Zgs1jzjIeaBpd5Ms7emQgxhVJBMtlEOlDNDfxlhSRiY/export?';

  const exportOptions =
    'exportFormat=pdf&format=pdf' + // export as pdf
    '&size=A4' + // paper size letter / You can use A4 or legal
    '&portrait=true' + // orientation portal, use false for landscape
    '&fitw=true' + // fit to page width false, to get the actual size
    '&sheetnames=false&printtitle=false' + // hide optional headers and footers
    '&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
    '&fzr=true' + // do not repeat row headers (frozen rows) on each page
    '&gid=101637384'; // the sheet's Id. Change it to your sheet ID.

      const exportOptionss =
    'exportFormat=xlsx' +
    '&gid=1200037229'+
    '&gid=101637384'+
    '&gid=557878560';// export as pdf

    // You can find the sheet ID in the link bar.
  // Select the sheet that you want to print and check the link,
  // the gid number of the sheet is on the end of your link.

  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};

  // Generate the PDF file
  var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
  var responsee = UrlFetchApp.fetch(url+exportOptionss, params).getBlob();

  // Send the PDF file as an attachement
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      attachments: [{
            fileName: ss.getSheetByName("M-Generate").getRange("B3").getValue().toString() +".pdf",
            content: response.getBytes(),
            mimeType: "application/pdf"
        },{
            fileName: ss.getSheetByName("M-Generate").getRange("B3").getValue().toString() +".xlsx",
            content: responsee.getBytes(),
            mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        }]
    });

  // Save the PDF to Drive. (in the folder) The name of the PDF is going to be the name of the Company (cell B5)
  const nameFile = ss.getSheetByName("M-Generate").getRange("B3").getValue().toString() +".pdf"
  const folderID = "1SHKAXCyXmNMwv1QKPYW0QCwey-yzpJih";
  DriveApp.getFolderById(folderID).createFile(response).setName(nameFile);
}

function on_sheet_change(event) {
  var sheetname = event.source.getActiveSheet().getName();
  var sheet = event.source.getActiveSheet();

  if (sheetname == 'M-Email Me') {
    emailSpreadsheetAsPDF() ;
  } else return;
}


text:
Q: Is it possible to call a static Java Class Method as defaultValueComputed? I like to fill a not nullable string in a liquibase schema generation (for postgres DB) with a value generated by an own class method.
Can't I use defaultValueComputed to call a static method of a class? e.g.
        <column name="downloadkey" type="VARCHAR(40)" defaultValueComputed="ch.util.HashUtil.randomSha1()">
            <constraints nullable="false" unique="true" />
        </column>

And the Java Class:
package ch.util;

public class HashUtil {
    public static String randomSha1() {
        ...
    }
}

If I try this, an exception is raised:
liquibase.exception.MigrationFailedException: Migration failed for change set ...
    Reason: liquibase.exception.DatabaseException: ERROR: improper qualified name (too many dotted names): ch.util.hashutil.randomsha1 [Failed SQL: CREATE TABLE ....]


text:
Q: How can multiple python servers on the same machine be made to interact with each other? I need to implement "serial look-up" and "parallel look-up" across a set of local servers. My servers are simple HTTP python server instances. The local servers must be able to send updated data to other local servers. Each local server knows about all the remaining local servers and the ports they are bound to. I need to know if this kind of communication is possible. If yes how? . Searching on the web results in mostly single server - multiple client architectures.
I am implementing a research paper and I need to compare the latency in serial and parallel look up in such a scenario.
edit 1: It does not need to be a HTTP server. It was easy to set up initially, thus it was chosen. Other alternatives are welcome


text:
Q: Advice to write/extend JQuery drag and drop where so DIVs can also be drop zones I'm a JQuery newbie and moderately competent JS programmer. I want to write a JQuery plug-in so I can drag and drop a DIV onto another DIV. If the other DIV is not a dropzone, then it simply calls a function of my choice. Perhaps dropping a draggable DIV onto another draggable DIV already exists which would be perfect, but I haven't found it.
If it doesn't exist, I wanted advice on the implementation.
Do I keep track of the x,y position and dimensions of every DIV so when a DIV is dropped onto another DIV (that may or may not be a dropzone) I can determine which DIV it was dropped upon?
Should I even do this using JQuery? Any other suggestions on my approach would also be appreciated!

A: This seemed interesting so I wrote a code, which covers the basics of what you want. Didn't want to make it over-complicated, so in this example, you can drag boxes inside the container area, and you can put box1 into box2.
This should cover up the overall idea, from here on you can write functions to detach boxes, apply extra styles etc. And better use event listeners though.
Here's the fiddle: http://jsfiddle.net/6LV25/
Here's the source:
<!DOCTYPE html>

<meta charset="utf-8">
<title>BoxCeption</title>

  Container

box1

box2


text:
Q: How can I update XML files in Powershell containing ascii characters greater than 126? I'm reading in an xml file, updating a value and writing it back - all fairly easy excpet for the fact that the file I'm updating contains a right curly single quote ' character.  The first time I save the file this gets replaced with '.  The more times I run it the worse it gets and the file size starts to grow exponentially.
I have worked out this happens to any character with an ascii value over 126 and that I can prevent this by replacing the ' characer with ' however, there must be a better way!
Any advice on how to save XML files correctly - my only thought is to search through the entire xml file for any chacter with ascii value > 126 and replace it.
My current code is:
$Path = "C:\path\to\file.xml"
[xml]$xml = Get-Content $Path
$xml.Save($Path)

A: Unless your file is encoded in a way that allows Get-Content to auto-detect the encoding (like UTF-8 or UTF-16 with the proper byte order mark) you need to tell the cmdlet which encoding to use:
[xml]$xml = Get-Content 'C:\path\to\your.xml' -Encoding UTF8

or create an Xml object and use its Load() method, which will use the encoding specified in the XML preamble and throw an error if it encounters characters that don't match that encoding:
$xml = New-Object Xml
$xml.Load('C:\path\to\your.xml')

A: Try somehing like this
$Path = "C:\path\to\file.xml"
[xml]$xml = Get-Content $Path -Encoding UTF8

A: Specify encoding for Get-Content Cmdlet.
Get-Content $Path -Encoding ENCODING_HERE


text:
Q: How to use Google Analytics with Phonegap in android? I am making an app in  android and I want to get analytics from the users. I tried to use the Phonegap Plugin, but I didn't have any luck trying to implement it.
I was wondering if it was possible to get Google Analytics by treating the app like a normal webpage and putting some javascript in the head of my page.

A: I was struggeling with that GAplugin recently. So this is what I did:
1: if you're using phonegap build just place this in your config.xml:
<gap:plugin name="com.adobe.plugins.gaplugin" />

2: on the google analytics page create a new mobile app.
3: place the plugin in your index.html
 <script src="GAPlugin.js"></script>

4: place the following code in your onDeviceReady function.
gaPlugin = window.plugins.gaPlugin;
gaPlugin.init(successHandler, errorHandler, "UA-12345678-1", 10);

5: track a page like this:
gaPlugin.trackPage( nativePluginResultHandler, nativePluginErrorHandler,     "some.url.com");

more information can be found here:
https://github.com/phonegap-build/GAPlugin/blob/master/README.md


text:
Q: удаление объекта в C++ Есть связной список , во время когда удаляется из списка один узел,
по идее его надо удалить , поскольку он был создан через new.
Я использую оператор delete ,но после этого оператора выводится все так же
адрес указателя. Почему???
 class LinkedList{

private:
    class Node{
    public:
        int a;
        Node* next;
        ~Node(){
            delete next;
        }
    };
    Node* head;
    int lenght;
public:
    LinkedList(){
        lenght=0;
        head=nullptr;
    }

    void add(int x) {

        Node* current = new Node;
        current->a = x;
        current->next = nullptr;
        if(head==NULL){
            head=current;
        }else{
            Node *node=head;
            while(node->next!=NULL){
                node=node->next;
            }
            node->next=current;

        }
            lenght++;
    }

    void remove(int index){
        Node *temp=head;
        int count=0;
        while(count<index-1){
            temp=temp->next;
            count++;
            }

        Node *rem=temp->next;
        Node *next=rem->next;
        temp->next=next;
        lenght--;
        delete rem;
        cout<<rem<<endl;
    }

    bool isEmpty(){
        return lenght==0;
    }

    int get(const  int index){
        Node *temp=head;
        int i=0;
        while(i<index){
            temp=temp->next;
            i++;
        }
        return temp->a;
    }

    int *toArray(){
        int arr[lenght];
        Node *temp=head;
        for(int i=0;i<lenght;i++){
            arr[i]=temp->a;
            temp=temp->next;
        }
        return arr;
    }
  int size(){
        return lenght;
    }
};

int main(){
    setlocale(LC_ALL,"rus");

 LinkedList obj;

        obj.add(1);
        obj.add(2);
        obj.add(3);
        obj.add(4);
        obj.add(5);

        obj.remove(2);
for(int i=0;i<obj.size();i++)
     cout<<obj.get(i)<<endl;

    return 0;

}

A: оператор delete rem;  освобождает память, выделенной для обьекта, на который указывает rem.   Но в rem,  как и раньше, записан этот адрес, только с той разницей, что этот адрес  может использоваться  для других обьектов. Так как этот указатель создан в функции, он уничтожается сам после выхода из функции, и его значение вы не возвращаете из функции, поэтому несанкцианированный доступ к освобожденной части памяти(уничтоженного обьекта) вы не сможете иметь. Если есть ситуация, что вы где то должны хранить этот указатель, то его перед хранением нужно обнулять, т.е. присвоить ноль(nullptr)


text:
Q: Java - .jar unexpected issue with Netbeans First of all, I am aware of Stack Overflow (and any competent forum-like website) policy of "search first, ask last", and, doing my homework, I searched various sources to find a solution to my issue. That said, I, failing to find any suitable answers, was left no choice but to ask this problem personally.
I have somewhat moderate programming skills, especially regarding the Java language. I am working on this 2D game with the default Java SE JDK. More specifically JDK 7u4. In this project, we have a class that manages most I/O operations. One of its methods returns the path to a file:
public static URL load(String resource) {
    return ZM.class.getResource(resource);
}

Now, this method works fine when running the project on Netbeans (version 7.1). However, when building and cleaning the project, the resulting .jar file does not seem to agree with its creator. When running the .jar on command line, the JVM caught a NullPointerException. It seemed that the file was not being able to be read inside the .jar. Following my programmers instinct, I started debugging the project. My first attempt was to check whether the load method was the faulty member. I ran some tests and obtained a couple of interesting results:
When running the application on Netbeans and with "ZM.class" as the methods argument, it returned:
/D:/Projects/GeometryZombiesMayhem/build/classes/geometryzombiesmayhem/ZM.class

But when running it from the .jar file, it returned:
file:/D:/Projects/GeometryZombiesMayhem/dist/GeometryZombiesMayhem.jar!/geometryzombiesmayhem/ZM.class

Naturally, I tried removing the initial file: string from it. No effect. Then I tried taking the exclamation mark from [...].jar![...]. Again, nothing. I tried removing all the possible permutations from the path. No luck.
Testing the method against the very own .jar file worked okay. Now, when I try to access the inside of the file, it doesn't let me. On earlier versions of this project it worked just fine. I am not really sure of what is going on. Any help is welcome.
Thank you in advance,
Renato

A: When loading resources from a jar file, I've always used a classLoader. Everything seems to work the same whether you run from within the IDE, launch the executable jar file or run the program from a web site using JNLP.
Try loading the resource this way instead:
 try {
      ClassLoader cl = ZM.getClass().getClassLoader();
      ImageIcon img  = new ImageIcon(cl.getResource("images/programIcon.jpg"));
      // do stuff with img.
 }
 catch(Exception failed) {
     System.out.println(failed);
 }

One more suggestion - you should create a separate folder for resources.  In my example above, images is a folder inside of my src folder.  This way it will automatically become part of the jar when I build it, but I am keeping resources separate from source code.

A: I suppose your problem is in loading an image from your jar file.
Here is how i do it
URL imageurl = Myclassanme.class.getResource("/test/Ergophobia.jpg");
Image myPicture = Toolkit.getDefaultToolkit().getImage(imageurl);
JLabel piclabel = new JLabel(new ImageIcon( myPicture ));
piclabel.setBounds(0,0,myPicture.getWidth(null),myPicture.getHeight(null));

This way I can get the Ergophobia.jpg file inside 'test' package.


text:
Q: Is the spherical growth function of a finite group always a unimodular sequence? Let $G$ be a finite group with symmetric generating set $S$, and let the spherical growth function of $G$ (with respect to those generators) be $a_S(n) = |\{g \in G \mid \ell_S(g) = n \}|$, where $\ell_s(g)$ is word length of $g$ with respect to $S$.
For a typical choice of generators (say, transposistions in $S_n$) one expects the sequence $a_S(n)$ to increase early on and then later decrease. But is it possible for the sequence to exhibit more complicated behavior, such as increasing, then decreasing, then increasing again (that is, for the sequence to not be unimodular)?
It is known that there are infinite finitely generated groups without monotonic growth function, and this seems a natural question to ask in the finite case.

A: I just calculated the growth series for $A_5$ with generators $(1,2)(3,4)$ and $(2,3,5)$, and it is
$$1,\,3,\,4,\,6,\,8,\,10,\,8,\,10,\,6,\,3,\,1,$$
so it has a little dip in the middle.


text:
Q: when you extend a private class. are the public and protected members of class become private when you extend a private class. Are the public and protected members of class become private. if not any explanation.

A: if you extend a nested private class, it wont change public/protected modifiers of the members. Here is an example :
public class Clazz {

    private static class NestedClazz {
        public int value = 123;
    }

    public static class NestedClazzExt extends NestedClazz {
    }
}

you can now access the inherited member: value from outside
public static void main(String[] args) {
    NestedClazzExt nestedClazz = new Clazz.NestedClazzExt();
    System.out.println(nestedClazz.value);
}

A: you can create private class in side a class . We call it as Nested classe. Means a class inside a class. The Concept itself is saying that you can create private class in side another class. The private class will act like as data member to the outer class.
So, You can't extend the private class.

A: Based on your query I tried to prepare a simple class.

public class pvtClass {

    private class As {
        public String abc = "private attribute";

        public void print(){
            System.out.println("privateClass");
        }
    }

    class Ab extends As{
        public String ab = "extended attribute";

        public void printAb(){
            System.out.println("extended class");
            print();
            System.out.println(abc);
        }
    }

    public static void main(String as[]){
        Ab ab1 = (new pvtClass()).new Ab();
        As as1 = (new pvtClass()).new As();

        ab1.printAb();
        as1.print();
        System.out.println(as1.abc);
    }
}

If you have a look at this class, I have a private class named "As" which has public attribute and public methods. I have another class named "Ab" which extends "As". I have written a main method to invoke the private attribute and methods.

below is the output for the code snippet:
extended class
privateClass
private attribute
privateClass
private attribute

A: There is a difference between the access of the members of a class and the access to the type itself.
public class C {
    private class InnerP1 {
        public void m() {
            System.out.println("InnerP1.m()");
        }
    }

    private class InnerP2 extends InnerP1 {
        public void p() {
            this.m();
            System.out.println("InnerP2.p()");
        }
    }

    public InnerP1 strange() {
        return new InnerP2();
    }
}

In this example, the interface I is visible from outside class C. The classes InnerP1 and InnerP2 are not visible from outside C. Jave itself makes not restrictions to the visibility of types you use in your public interface. The method strange() of class C returns a result of class InnerP1. Since outside of C we do not know anything about the class InnerP1 other than it is subtype of Object, the only thing we can do is use the result of strange() as an Object.
public class D {
    public static void main(String[] args) {
        C c = new C();
        Object o = c.strange();
        if(o.equals(c.strange())) {
            System.out.println("Strange things are going on here!");
        }
    }
}

As @KnusperPudding pointed out already, the visiblity of public members is not changed, we might just not have enough knowledge of the type itself to access them.

A: Access to members cannot be restricted by sub-classing.  When you mark a class as private then access via the class name is restricted i.e. to the same .java file, however once you have an instance of this class it can be accessed at least as easily as the super class.


text:
Q: Get output of document.write in scrapy I am scraping a website that has the following structure:

        91.240.61.217

When you see it on the page, this looks like this:
91.240.61.217:6660

But when I try to scrape it, I find myself unable to get the ":6660" part as that's generated by the JS script above.
How do I get that part of the HTML? Here is my current code:
val = Selector(response)
ip = val.xpath('//tr[@class="spy1xx"]/td[1]/font').extract_first()

The JS code may seem nonsensical but the page also has this script in it:
eval(function(p,r,o,x,y,s){y=function(c){return(c<r?'':y(parseInt(c/r)))+((c=c%r)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(o--){s[y(o)]=x[o]||y(o)}x=[function(y){return s[y]}];y=function(){return'\\w+'};o=1};while(o--){if(x[o]){p=p.replace(new RegExp('\\b'+y(o)+'\\b','g'),x[o])}}return p}('p=B^C;m=G^I;h=F^E;r=H^J;f=2;l=K^u;e=5;c=4;n=8;t=v^w;j=A^z;g=y^x;k=1;d=D^O;b=T^V;s=6;a=3;o=7;i=0;q=9;L=i^j;Q=k^g;P=f^b;M=a^m;N=c^d;R=e^l;S=s^r;X=o^p;W=n^t;U=q^h;',60,60,'^^^^^^^^^^Four^Seven4Seven^Five^Nine3Three^One^Zero^OneTwoZero^Seven9Four^Two^Nine6Six^Three^TwoOneNine^Eight5One^Seven^Eight^NineThreeTwo^Nine^Four3Eight^Six^Seven0Five^8090^5462^88^808^12035^3129^11286^10218^8909^6038^8888^7449^6689^3320^80^443^2546^Zero9EightSeven^Nine1SixNine^SixThreeFiveFive^8000^Nine7OneZero^Seven0FourOne^ZeroSixTwoEight^One2NineSix^9273^Six2ZeroFour^8118^Eight9SevenThree^FiveFourThreeTwo'.split('\u005e'),0,{}))

So it does actually print out ":6660". This I tested.
Is there a way to either
a) get the output of their script as displayed on the page by document.write
or
b) scrape the JS code and run it locally through Python, somehow

A: An alternative to Guillaume's answer would be using js2py inside your spider to execute the JS code:
>>> import js2py
>>> js = r"eval(function(p,r,o,x,y,s){y=function(c){return(c<r?'':y(parseInt(c/r)))+((c=c%r)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(o--){s[y(o)]=x[o]||y(o)}x=[function(y){return s[y]}];y=function(){return'\\w+'};o=1};while(o--){if(x[o]){p=p.replace(new RegExp('\\b'+y(o)+'\\b','g'),x[o])}}return p}('p=B^C;m=G^I;h=F^E;r=H^J;f=2;l=K^u;e=5;c=4;n=8;t=v^w;j=A^z;g=y^x;k=1;d=D^O;b=T^V;s=6;a=3;o=7;i=0;q=9;L=i^j;Q=k^g;P=f^b;M=a^m;N=c^d;R=e^l;S=s^r;X=o^p;W=n^t;U=q^h;',60,60,'^^^^^^^^^^Four^Seven4Seven^Five^Nine3Three^One^Zero^OneTwoZero^Seven9Four^Two^Nine6Six^Three^TwoOneNine^Eight5One^Seven^Eight^NineThreeTwo^Nine^Four3Eight^Six^Seven0Five^8090^5462^88^808^12035^3129^11286^10218^8909^6038^8888^7449^6689^3320^80^443^2546^Zero9EightSeven^Nine1SixNine^SixThreeFiveFive^8000^Nine7OneZero^Seven0FourOne^ZeroSixTwoEight^One2NineSix^9273^Six2ZeroFour^8118^Eight9SevenThree^FiveFourThreeTwo'.split('\u005e'),0,{}))"
>>> js2py.eval_js(js)
16296

Js2Py: https://github.com/PiotrDabkowski/Js2Py
As for extracting the JS code from the page, I'm afraid you need to share more details about the page itself so that we can help you figure out how to do it.

A: You can install a Javascript interpreter such as NodeJS and call it from Python.
from subprocess import Popen, PIPE

js = r"eval(function(p,r,o,x,y,s){y=function(c){return(c<r?'':y(parseInt(c/r)))+((c=c%r)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(o--){s[y(o)]=x[o]||y(o)}x=[function(y){return s[y]}];y=function(){return'\\w+'};o=1};while(o--){if(x[o]){p=p.replace(new RegExp('\\b'+y(o)+'\\b','g'),x[o])}}return p}('p=B^C;m=G^I;h=F^E;r=H^J;f=2;l=K^u;e=5;c=4;n=8;t=v^w;j=A^z;g=y^x;k=1;d=D^O;b=T^V;s=6;a=3;o=7;i=0;q=9;L=i^j;Q=k^g;P=f^b;M=a^m;N=c^d;R=e^l;S=s^r;X=o^p;W=n^t;U=q^h;',60,60,'^^^^^^^^^^Four^Seven4Seven^Five^Nine3Three^One^Zero^OneTwoZero^Seven9Four^Two^Nine6Six^Three^TwoOneNine^Eight5One^Seven^Eight^NineThreeTwo^Nine^Four3Eight^Six^Seven0Five^8090^5462^88^808^12035^3129^11286^10218^8909^6038^8888^7449^6689^3320^80^443^2546^Zero9EightSeven^Nine1SixNine^SixThreeFiveFive^8000^Nine7OneZero^Seven0FourOne^ZeroSixTwoEight^One2NineSix^9273^Six2ZeroFour^8118^Eight9SevenThree^FiveFourThreeTwo'.split('\u005e'),0,{}))"

p = Popen(['node', '-p', js], stdout=PIPE)
output, _ = p.communicate()
print(output)

This prints:
b'16296\n'


text:
Q: Is an irreducible ideal in $R$ also irreducible in $R[x]$? Let $R$ be a commutative Noetherian ring and $I\subset R$ an ideal that is irreducible in the sense that if $I = J_1 \cap J_2$, then $I=J_1$ or $I=J_2$. Is (the ideal generated by) $I$ irreducible in the polynomial ring $R[x]$?
The answer to the question is "yes" since the number of irreducible components has a homological characterization which can be found in Computational methods in commutative algebra and algebraic geometry by W. V. Vasconcelos.
Proposition 3.1.7. Let $(R,\mathfrak{m})$ be a local commutative Noetherian ring. Let $\mathfrak{p}$ be an associated prime of an $R$-module $M$ and denote $\Delta_\mathfrak{p}(M)$ the submodule of $M$ whose elements are annihilated by $\mathfrak{p}$. The number of irreducible $\mathfrak{p}$-primary components in an irredundant irreducible decomposition of $0\subset M$ is $\dim_{k(\mathfrak{p})}(\Delta_\mathfrak{p}(M))_\mathfrak{p}$.
The minimal number of irreducible intersectands of $I$ equals the $R_{P}/P_P$-vector space dimension of the socle of $R[x]_{P}/I_{P}$. Now when adjoining indeterminates the field $R[x]_P/PR[x]_P$ grows, but the socle dimension is the same.
Now the real question is: Is there a simpler proof (without localization(?)) or do we have to use homological invariants of ideal decompositions?
Background: This comes from Exercise 3.6 in Eisenbud's book on commutative algebra which asks for a characterization of irreducible monomial ideals.  I'm wondering if a reader who has only read Chapters 1,2,3 would be able to do that exercise.  This is a repost of my math.se question which can't be migrated because it is too old.

A: I prove your question for (not necessarily Noetherian) commutative ring. Irreducible ideals in non-Noetherian ring are complicate (see this question). For Noetherian ring, see our paper for a study of the index of reducibility. The proof is elementary but quite long.
Edit: I realise that the proof also work for another question. If$(0)$ is an irreducible ideal of $R$ then it is a graded irreducible ideal of the graded ring $R[X]$.
We can assume that $I = 0$. Suppose $ 0 \in R[X]$ is reducible as the intersection of two proper ideals. We can assume these two ideals are principal, so $0 = (f) \cap (g)$ with
$$f = X^r (a_0 + a_1X + \cdots + a_nX^n), a_0 \neq 0,$$
$$g = X^s (b_0 + b_1X + \cdots + b_mX^m), b_0 \neq 0.$$
Choose $f$ and $g$ so that $m+n$ is minimal.
Fact: Let $f = X^rf'$ and $g = X^sg'$. Then $(f) \cap (g) = 0$ if and only if $(f') \cap (g') = 0$.
Proof. The "if part" is clear since $(f) \subseteq (f')$ and $(g) \subseteq (g')$.
For the "only if" part, suppose $(f') \cap (g') \neq 0$. We have $(X^{r+s} f') \cap (X^{r+s}g') = X^{r+s}((f') \cap (g')) \neq 0$. Thus $(f)\cap (g) \neq 0$ since $(X^{r+s}f') \subseteq (f)$ and $(X^{r+s}g') \subseteq (g)$.
Using the above fact we can assume
$$f = a_0 + a_1X + \cdots + a_nX^n, a_0 \neq 0$$
$$g = b_0 + b_1X + \cdots + b_mX^m, b_0 \neq 0.$$
If $m+n = 0$ then $f, g \in R$ and this contradicts the assumption that $(0)$ is irreducible there.
So $m+n> 0$.  Without loss of generality we assume that $m \ge n$ and thus $m>0$. Choose $0 \neq c \in (a_0) \cap (b_0)$ in $R$.  Then $c = da_0 = eb_0$ for some $d, e \in R$. Replacing $f$ and $g$ by $df$ and $eg$, respectively, we can assume henceforth that $a_0 = b_0$.
By the minimality of $m+n$ we have the following.
Claim 1: Let $r$ be an element of $R$ such that $ra_0 = 0$. Then $rf = 0$ and $rg = 0$.
Proof. Assume $ra_0 = 0$ and $rf \neq 0$. Since $(f) \cap (g) = 0$ also $(rf) \cap (g) = 0$. However, since $ra_0 = 0$, $rf = X^tf'$ with $\mathrm{deg}(f')<n$. By the Fact, $(f') \cap (g) = 0$ in contradiction to  minimality of $m+n$.  The same argument applies to $g$.
Applying Claim 1 inductively one can prove:
Claim 2: If a polynomial $h = c_0 + c_1X + \cdots + c_k X^k$ satisfies $hf = 0$ (resp. $hg = 0$), then each coefficient $c_i$ satisfies $c_if = 0$ (resp. $c_ig = 0$).
Combining Claims 1 and 2 we have
Claim 3: $hf = 0$ if and only if $hg = 0$.
We continue the proof. Let $g' = g-f$. Since $a_0 = b_0$, we get $g' = X^{m-m'}g' '$ for some $m' < m$ and polynomial $g' '$ of degree $m'$.
By minimality of $m+n$ and the Fact, we have $(f) \cap (g' ') \neq 0$. Thus there are polynomials $u,v,w$ such that $0 \neq w = uf = vg' '$, and thus $X^{m-m'}uf = vg' = v(g-f)$.  Now, if $vg \neq 0$ then $vg = (u+v)f \in (f) \cap (g)$, a contradiction. Therefore $vg = 0$. By Claim 3 we have $vf = 0$ so $w = 0$. This is also a contradiction. The proof is complete.


text:
Q: How does landscape calculate memory usage? I'm trying to debug an OOM situation in an Ubuntu 12.04 server, and looking at the Memory graphs in Landscape, I noticed that there wasn't any serious memory usage spike. Then I looked at the output of the free command and I wasn't quite sure how both memory usage results relate to each other.
Here's landscape's output on the server:
$ landscape-sysinfo
  System load:  0.0               Processes:           93
  Usage of /:   5.6% of 19.48GB   Users logged in:     1
  Memory usage: 26%               IP address for eth0: -
  Swap usage:   2%

Then I ran the free command and I get:
$ free -m
             total       used       free     shared    buffers     cached
Mem:           486        381        105          0          4        165
-/+ buffers/cache:        212        274
Swap:          255          7        248

I can understand the 2% swap usage, but where does the 26% memory usage come from?

A: In Landscape
landscape-sysinfo actually gets its data directly from /proc/meminfo:
dpb@helo:~$ cat /proc/meminfo |egrep 'MemTotal:|Active:'
MemTotal:       12286760 kB
Active:          3794832 kB
dpb@helo:~$

The calculation of "Memory Usage" in this case would be:
((MemTotal - Active) / MemTotal) * 100

You can see these calculations in:
/usr/share/pyshared/landscape/sysinfo/memory.py
/usr/share/pyshared/landscape/lib/sysstats.py

gets its data directly from /proc/meminfo:
In free
The free utility also gets its data directly from /proc/meminfo:
Mem

*

*total: MemTotal

*used: MemTotal - MemFree

*free: MemFree

*buffers: Buffers

*cached: Cached
Buffers/cache

*

*used: MemTotal - MemFree - Buffers - Cached

*free: MemFree + Buffers + Cached
Swap

*

*total: SwapTotal

*used: SwapTotal - SwapFree

*free: SwapFree
Total

*

*total: MemTotal + SwapTotal

*used: MemTotal - MemFree + SwapTotal - SwapFree

*free: MemFree + SwapFree
Corrected cached -- lzap

A: Those graphs don't reflect every single memory allocation/freeing event, but samples from /proc/meminfo (exactly as dpb described) at given intervals.  A slightly speculative explanation for why it's not showing in the graph would be that it simply occurred between to points when memory usage was sampled.
I suspect that what has happened here is that some process acquired lots of memory in a hurry and OOM killer disposed of it before a sample could be made.  That would be a fairly extreme circumstance, and also one that would mean the whole machine was running slowly as it was swapping heavily. This loading on the machine would reduce the likelihood of the system having available time to sample memory usage during that window and report it back to the Landscape server.

A: To add to dpb's correct answer, we need to define the difference between memory types.  Going by redhat's documentation on /proc/meminfo:
The main definitions to use:

*

*Active memory is memory has been used recently and shouldn't be replaced by the OS when new pages are brought in.

*MemTotal is how much usable memory your system has (physical memory minus a tiny amount of memory used for the kernel code).

*MemFree is memory currently unused memory.  Memory used as disk cache is not free.

*MemUsed is memory being used = MemTotal - MemFree.

*Cached is memory used as a cache for files on disk - if you recently read a file from disk maybe you'll look at it again in the near future so let's keep it in memory when its available (as essentially free and could dramatically speed up your computer as reads from disk take several milliseconds while reads from memory take microseconds or less).

*Buffers is a buffer for the IO devices located -- e.g., when you change values of a file, it first gets saved to the buffers (in your main memory) and then the changes get written to the disk as writing to the disk is slow.  This buffered memory is short lived and tiny on modern kernels.  (Granted the distinction between cached/buffers is less clear on modern linux kernel see [1]).

*MemUsed - Buffers/Cached (first number in second line of free) is how much memory is used by your processes.  This is how much memory is in use ignoring the disk cache (which your system is free to over write)..

You could easily have more active memory than MemUsed - Buffers/Cached.  This scenario would occur when you are frequently accessing parts of disk that have been cached in memory.  Similarly, you could have processes that have allocated memory but haven't used that allocated memory recently -- maybe its ideal to move this allocated memory to swap if you need more memory.


text:
Q: how to create sliding menu for all Activities Here Is Slide Menu Image That I want
like
https://www.dropbox.com/s/t51hnf1768xifsj/Screenshot_2014-07-02-13-47-32.png
Hello Guyes
i want to make Sliding Menu Like this Image .Top Of Sliding Menu Show User Logged Image .I m using Json
Sliding Should Work For All Activity .Guyes i m very New On Android .I dont How To make Sliding Menu Like This
please Help Me To create Sliding Menu
thanks In Advance

A: You can achieve this by implementing Navigation Drawer.
Here is the example which will help you understand it better
Navigation Drawer - android  and Android Sliding Menu using Navigation Drawer
Hope this will help you.


text:
Q: How to remove unknown characters using T-SQL? I try to do a script to eliminate the Chinese characters in a string and between the Chinese characters I want to remove. Please see the example below. Thank you.
select LTRIM(SUBSTRING('Tower 6A 第6A座', PATINDEX('%[a-zA-Z0-9]%', 'Tower 6A 第6A座'), LEN('Tower 6A 第6A座')))
select LTRIM(REPLACE(SUBSTRING('Tower 6A 第6A座', CHARINDEX(N'樓', 'Tower 6A 第6A座') + 1, LEN('Tower 6A 第6A座')), ' ', ''))

Sample string:
Tower 6A 第6A座
Tower 3 第3座

Bad Result:
Tower 6A ?6A?
Tower6A?6A?
Tower 3 ?3?
Tower3?3?

Good result, I want to achieve:
Tower 6A
Tower 6A
Tower 3
Tower 3

A: Try this
   SELECT Replace(Replace('Tower 6A 第6A座','[^a-zA-Z0-9]+', ''),'?','')

A: Looks weird but does the job. However I wouldn't count on great performance:
;WITH string AS (
    SELECT N'Tower 6A 第6A座' s
),
split AS (
    select LEFT(s, 1) s_item,
       STUFF(s, 1, 1, N'') s
    from string
    union all
    select LEFT(s, 1),
       STUFF(s, 1, 1, N'')
    from split
    where s > ''
)
,
remove_non_ascii AS (
    SELECT s_item, UNICODE(s_item) s_unicode
    FROM split WHERE UNICODE(s_item)<256
)
SELECT STUFF((SELECT s_item FROM remove_non_ascii
FOR XML PATH, TYPE).value('.[1]', 'NVARCHAR(MAX)'), 1,0, '');

What it does:

*

*Splits strings into rows

*Eliminates UNICODE characters bigger than 256 (you can fiddle with condition)

*Puts the string together
It uses recursive query so in case of strings longer than 100 characters you need to expand amount of recursive loops by adding: OPTION (MAXRECURSION n) (where n is new amount of recursive loops)

A: Try This
;With cte(Data)
AS
(
SELECT 'Tower 6A 第6A座' UNION ALL
SELECT 'Tower 3 第3座'
)
SELECT
CASE WHEN CHARINDEX('Tower', DATA)= 0 THEN 'Tower ' + DATA ELSE DATA END AS DATA
FROM
(
SELECT
Split.a.value('.', 'VARCHAR(1000)') AS Data
FROM
(
SELECT  CAST('<S>' + REPLACE(REPLACE(Data, '?', '</S><S>'),'','</S><S>') + '</S>' AS XML) AS Data
FROM cte
) AS
    A CROSS APPLY Data.nodes('/S') AS Split(a)
) DT
Where
DT.Data <> ''

Result
DATA
----------
Tower 6A
Tower 6A
Tower 3
Tower 3

A: Using delimitedSplit8k you can do this:
-- Sample data
DECLARE @table TABLE (someid int identity, string nvarchar(100));
INSERT @table VALUES (N'Tower 6A 第6A座'), (N'Tower 3 第3座');

-- Solution
WITH base AS
(
  SELECT someid, ItemNumber, itemClean = replace(item,'?','')
  FROM @table t
  CROSS APPLY dbo.delimitedSplit8K(t.string, ' ')
)
SELECT someid, newstring = b1.itemClean + ' ' +  b2.itemClean
FROM base b1
CROSS APPLY
(
  SELECT itemClean
  FROM base b2 WHERE ItemNumber = 1 AND b1.someid = b2.someid
) b2
WHERE b1.ItemNumber > 1;

Results:
someid      newstring
----------- ---------
1           6A Tower
1           6A Tower
2           3 Tower
2           3 Tower

A: One approach for this problem is to make use of SQL Server 2016 ability to execute R Script. For this method to work you will have to ensure that the R Services has been installed on your SQL Server, you will also have to enable the 'sp_execute_external_script' stored procedure.
Enable external scripts as follow:
EXECUTE sp_configure;
GO
-- enable execution of external script add an argument:
EXECUTE sp_configure 'external scripts enabled', 1;
GO

RECONFIGURE;
GO

Also ensure that the 'SQL Server Launchpad' service is running.  You may also have to restart SQL Server.
If we convert our input data containing the Chinese characters from a Unicode to ASCII (VARCHAR) then SQL Server will automatically convert the Chinese characters to question marks '?'.
Next, we can use the R languages pattern matching capabilities to remove all the text between the question marks (formally our Chinese characters) as per following example:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ExampleData]') AND type in (N'U'))
BEGIN

    CREATE TABLE [dbo].[ExampleData](
        [RawData] [nvarchar](100) NULL
    ) ON [PRIMARY]

    INSERT INTO ExampleData
    (
        [RawData]
    )
    VALUES ( N'Tower 6A 第6A座');

    INSERT INTO ExampleData
    (
        [RawData]
    )
    VALUES ( N'Tower 3 第3座');

END

DECLARE @inputQuery NVARCHAR(MAX) = N'SELECT CAST([RawData] AS VARCHAR(100)) as a FROM ExampleData'

DECLARE @RScript NVARCHAR(MAX) = N'
pattern <-"\\?.*\\?";
inData$a <- sub(pattern, "\\1", inData$a, perl = T );
outData <- inData;';

EXEC sp_execute_external_script @language = N'R'
, @script = @RScript
, @input_data_1 = @inputQuery
, @input_data_1_name = N'inData'
, @output_data_1_name=N'outData'
with result sets ( (a varchar(300)));


text:
Q: In BibDesk, change the cite key before importing from the web When I use BibDesk, suppose I import a citation from a webpage. The cite key comes up automatically as cite-key. How can I change it before I actually add it to the bibliography?
I can always add it and then go back and change the cite key, but that's a pain.
To be clear, the image below shows the stage I'm at. If I click import, the reference is imported as is, with cite-key as the cite key. But I can't seem to change the cite key before I click import.

A: There is an automated way to fix your citation keys after importation and for the entire bib file, using bibtool and entering one of the following commands in terminal, after you have install bibtool:
bibtool -k BibFileIn.bib -o BibFileOut.bib
bibtool -K BibFileIn.bib -o BibFileOut.bib
or
bibtool -f "%n(author)%d(year)" BibFileIn.bib -o BibFileOut.bib
These commands will take all the entries of your initial bib file BibFileIn.bib in my example and generate the new keys in a new bib file called BibFileOut.bib. For instance, the last command generates keys with the format AuthorYear
If you use the option -f you can tune the citation key generated to what you are used to.
Hope that helps.
Romain


text:
Q: How to play .wav files on IE? I am developing a html5 - angularjs application.
Where I need to play .wav files being fetched from server on UI.
This functionality needs to be supported on all browsers.
It is working fine with Chrome, firefox, safari.
But on IE, I am receiving error.

*

*If I try
<audio controls>
   <source src="example.wav">
</audio>

Error - in audio tag it displays Invalid source. But no console error.

*If I try
<audio controls src="example.wav"></audio>

Error - in audio tag it displays

Invalid source

Also in browser console, it displays

MEDIA12899: AUDIO/VIDEO: Unknown MIME type.

A: I ran into this same problem and it's caused by IE not supporting .wav files in HTML5 (which makes no sense, but, oh well).
I came up with a Javascript function that handles this; I included a call to the function in the <a> that was triggering the audio to play; this way, the function fires, but does nothing in non-IE browsers, but in IE, it plays it and fails pretty gracefully in the HTML5 audio player.
function playWavFileInIE(src){
    if(/msie/i.test(navigator.userAgent) || /trident/i.test(navigator.userAgent)){
        var origPlayer = document.getElementById('currentWavPlayer');
        if(origPlayer){
            origPlayer.src = '';
            origPlayer.outerHtml = '';
            document.body.removeChild(origPlayer);
            delete origPlayer;
        }
        var newPlayer = document.createElement('bgsound');
        newPlayer.setAttribute('id', 'currentWavPlayer');
        newPlayer.setAttribute('src', src);
        document.body.appendChild(newPlayer);
        return false;
    }
}

All of the lines in the if(origPlayer){...} block appear to be needed; without any one of those, I ended up with the .wav remaining on the page and it steadily became an echo with every click. I'm sure there's a logical explanation, but...I was in a hurry.

A: If it is a possibility for you, convert the .wav files on the server to .mp3.
This worked for me in audio elements of a site that I was working on.
.MP3 file format seems to be more widely supported than .WAV (see links below):

*

*https://caniuse.com/#search=wav

*https://caniuse.com/#search=mp3


text:
Q: Re-setting learning rate while training in Pytorch I am training a model using Learning Rate Scheduler in Pytorch to decrease the value of learning rate. By using learning rate scheduler, I reduced learning rate from 0.0001 to 1e-5, and save all the weights, parameters, learning rate values, etc at a particular checkpoint. Now, I want to resume training the model, but with different value of learning rate, while remaining all other values. How can I do this?
This is the code for saving checkpoint. I used Adam optimizer
checkpoint = {
        'epoch': epoch + 1,
        'val_loss_min': val_loss['total'].avg,
        'state_dict': model.state_dict(),
        'optimizer': optimizer.state_dict(),
        'scheduler': scheduler.state_dict(),
    }

When loading checkpoint, I used this code:
checkpoint = torch.load(args.SAVED_MODEL)
        # Load current epoch from checkpoint
        epochs = checkpoint['epoch']
        # Load state_dict from checkpoint to model
        model.load_state_dict(checkpoint['state_dict'])
        # Load optimizer from checkpoint to optimizer
        optimizer.load_state_dict(checkpoint['optimizer'])
        # Load valid_loss_min from checkpoint to valid_loss_min
        val_loss_min = checkpoint['val_loss_min']
        # Load scheduler from checkpoint to scheduler
        scheduler.load_state_dict(checkpoint['scheduler'])

A: You can change the learning rate of your optimizer by accessing its param_groups attribute. Depending on whether you have multiple groups or not, you can do the following (after having loaded the checkpoint onto it):
for g in optimizer.param_groups:
    g['lr'] = new_lr


text:
Q: SQL multiple table query, join syntax I have following:
Tables(field names)

*

*Active( activeID, activeName)

*ActiveCategories(activeID, categoryID)

*Categories(categoryID,categoryName)
I wish to query such that the result fetches Left Join of Active on ActiveCategories but instead of CategoryID [from ActiveCategories] Integer it should display corresponding categoryName [ from Categories].
Till now I have managed to display integer but not the corresponding name.

A: Try:
select a.activeID, a.activeName, d.categoryName
from Active a
    left join (select b.activeID activeID, c.categoryName CategoryName
            from ActiveCategories b
                left join Categories c on b.categoryID = c.categoryID) d
        on a.activeID = d.activeID

A: select a.activeID, a.activeName, c.categoryName
from Active a
left outer join ActiveCategories b on a.activeID = b.activeID
left outer join Categories c on b.categoryID = c.categoryID


text:
Q: How can i check if file exist and create if not and then append text to the file in some places? using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;

namespace Youtube_Player
{
    public partial class Authentication : Form
    {
        public static string AuthenticationApplicationDirectory;
        public static string AuthenticationFileName = "Authentication.txt";
        StreamWriter w;
        public static bool formclosed = false;

        static Authentication()
        {
            AuthenticationApplicationDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "Authentication";
            if (!Directory.Exists(AuthenticationApplicationDirectory))
            {
                Directory.CreateDirectory(AuthenticationApplicationDirectory);
            }
            AuthenticationFileName = Path.Combine(AuthenticationApplicationDirectory, AuthenticationFileName);

            if (!File.Exists(AuthenticationFileName))
                File.Create(AuthenticationFileName);
        }

        public Authentication()
        {
            InitializeComponent();

            cTextBox1.Text = Form1.AuthenticationValues.ApiKey;
            cTextBox2.Text = Form1.AuthenticationValues.UserId;
            cTextBox3.Text = Form1.AuthenticationValues.JsonFileDirectory;

            label1.Visible = false;
            button1.Enabled = false;
            button4.Enabled = false;

            cTextBox2.WaterMarkForeColor = Color.Blue;
            cTextBox3.WaterMarkForeColor = Color.Green;
            cTextBox2.WaterMarkActiveForeColor = Color.Blue;
            cTextBox3.WaterMarkActiveForeColor = Color.Green;
            cTextBox1.ForeColor = Color.Red;
            cTextBox2.ForeColor = Color.Blue;
            cTextBox3.ForeColor = Color.Green;
            cTextBox1.WaterMark = "Enter Api Key";
            cTextBox2.WaterMark = "Enter Email Account";
            cTextBox3.WaterMark = "Browse To The Json File Location";
        }

        private void Authentication_Load(object sender, EventArgs e)
        {

        }

        private void cTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (cTextBox1.Text != "Enter Api Key" && cTextBox1.Text != "")
            {
                button1.Enabled = true;
            }
            else
            {
                button1.Enabled = false;
            }
        }

        private void cTextBox2_TextChanged(object sender, EventArgs e)
        {
            if (cTextBox2.Text != "Enter Email Account" && cTextBox2.Text != "")
            {
                button4.Enabled = true;
            }
            else
            {
                button4.Enabled = false;
            }
        }

        private void cTextBox3_TextChanged(object sender, EventArgs e)
        {
            if (cTextBox3.Text != "Browse To The Json File Location" && cTextBox3.Text != "")
                button6.Enabled = false;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = "Confirmed";
            button1.Enabled = false;
            label1.Text = "Updating Settings File";
            label1.Visible = true;
            if (label1.Visible == true)
            {
                button6.Enabled = false;
                button4.Enabled = false;
                button1.Enabled = false;
            }
            FileInfo fi = new FileInfo(AuthenticationFileName);
            if (fi.Length == 0)
            {
                w = new StreamWriter(AuthenticationFileName, true);
                w.WriteLine("Api" + "=" + cTextBox1.Text);
                w.Close();
            }
            else
            {
                w = new StreamWriter(AuthenticationFileName);
                w.WriteLine("Api" + "=" + cTextBox1.Text);
                w.Close();
            }
            timer1.Start();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            label1.Text = "Updating Settings File";
            label1.Visible = true;
            if (label1.Visible == true)
            {
                button6.Enabled = false;
                button4.Enabled = false;
                button1.Enabled = false;
            }
            w = new StreamWriter(AuthenticationFileName, true);
            w.WriteLine("UserId" + "=" + cTextBox2.Text);
            w.Close();

            timer1.Start();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "Json Files (*.json)|*.json";
            openFileDialog1.FilterIndex = 0;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                cTextBox3.BackColor = Color.White;
                cTextBox3.ForeColor = Color.Green;
                cTextBox3.Text = openFileDialog1.FileName;
                label1.Text = "Updating Settings File";
                label1.Visible = true;
                if (label1.Visible == true)
                {
                    button6.Enabled = false;
                    button4.Enabled = false;
                    button1.Enabled = false;
                }
                w = new StreamWriter(AuthenticationFileName, true);
                w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
                w.Close();

                timer1.Start();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ResetValues(true);
        }

        int count = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            count += 1;
            if (count == 2)
            {
                label1.Visible = false;
                timer1.Stop();
                count = 0;
            }
        }

        private void Authentication_FormClosing(object sender, FormClosingEventArgs e)
        {
            ResetValues(false);
        }

        private void ResetValues(bool DeleteFile)
        {
            cTextBox1.Text = "";
            cTextBox2.Text = "";
            cTextBox3.Text = "";
            button1.Text = "Confirm";
            button4.Text = "Confirm";
            button6.Enabled = true;
            timer1.Stop();
            count = 0;
            if (DeleteFile == true)
            {
                if (File.Exists(AuthenticationFileName))
                    File.Delete(AuthenticationFileName);
            }
            Form1.AuthenticationValues.ApiKey = "";
            Form1.AuthenticationValues.JsonFileDirectory = "";
            Form1.AuthenticationValues.UserId = "";
            if (Form1.AuthenticationValues.AuthenticationMenu.Enabled
                == false && (Form1.lines.Length < 3 && Form1.lines.Length > 0))
                Form1.AuthenticationValues.AuthenticationMenu.Enabled = true;
            formclosed = true;
        }
    }
}

The first problem is in the constructor when checking for the file existing:
if (!File.Exists(AuthenticationFileName))
                File.Create(AuthenticationFileName);

This make the file to be busy in use. When later in my code i'm trying to use the file again to write to it i'm getting exception that the file is in use by another process.
The second problem is in the 3 places i'm trying to write to the file.
The first place:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();

Then under it in another place in the code i'm writing again to the file:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("UserId" + "=" + cTextBox2.Text);
w.Close();

And last:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
w.Close();

The problems are first the file is busy in use since the checking if exist i'm doing in the constructor.
The second problem is that i want to make that if in the file there is no line that start with "Api" then write the Api part:
w.WriteLine("Api" + "=" + cTextBox1.Text);

But if it does exist and the text is changed in the textBox cTextBox1.Text i want to write to the file the changed text to the place where the Api line is. And to append a new Api line.
Same for all two other places i'm writing to the file.
If i will make it all false not to appen when writing it will write one line each time and will overwrite the line.
But if i'm doing true it will append many Api lines or many UserId lines.
And i want each to time to replace the line with the textBox to overwrite only on this line but with the new text.
If in cTextBox1 there is the text: Hello World
Then i changed it to: Hello World Now
Then replace the Api line Hello World with Hello World Now

A: Alright, addressing your main concern:
File.CreateFile actually opens a filestream for you to use.  Easiest way to solve this is to do File.CreateFile().Close() to close it when you're done.
Next, you are trying to change data in a file, but you never read it to find the information.
You can look up StreamReader and use that, and parse out data and figure out what's where, but there's a much more obvious choice:  Just re-write all of the information every time.


text:
Q: How can I determine which request is periodically timing out through my ssh tunnel? I am using a ssh tunnel from OSX combined with the SwitchyOmega chrome plugin to browse via a ubuntu box like this:
ssh -D 54321 1.2.3.4

This timeout only occurs after I've started chrome. but even after killing chrome it continues to periodically time out every 30 seconds.
channel 12: open failed: connect failed: Connection timed out
channel 8: open failed: connect failed: Connection timed out
channel 9: open failed: connect failed: Connection timed out
channel 15: open failed: connect failed: Connection timed out
channel 10: open failed: connect failed: Connection timed out
channel 5: open failed: connect failed: Connection timed out
channel 7: open failed: connect failed: Connection timed out
channel 4: open failed: connect failed: Connection timed out
channel 11: open failed: connect failed: Connection timed out

I'm trying to determine what is causing the timeout and where the request is being sent. any suggestions on how to display more verbose error information for the ssh tunnel?
here is the plugin I am using:
https://github.com/FelisCatus/SwitchyOmega

A: using the -v option for ssh allowed me to home in on the offending chrome extension.


text:
Q: Error installing MAP-REDUCE plugin in eclipse When I'm trying to install MAP-REDUCE plug-in in eclipse INDIGO I am getting following kind of error
Screenshot:
I have install hadoop 1.2.1.

A: The plugin you are trying to use was compiled using Java 8 but you are running Eclipse using an earlier version of Java.
You will have to run your Eclipse using Java 8 to use this plugin.


text:
Q: Rails - A database connection per request, based on user credentials We have the following problem: our app interfaces with exchange via its exchange web services (EWS), you can think of it as being just a fancy DB.
As an example, we have an Appointment model which should be synchronized with the calendar on Exchange. Now EWS requires the users credentials for every connection. This creates 2 issues:

*

*how do we get the users credential on every request?

*how should the model interact with EWS?

What we don't want to do is ask the user for his password on every action that requires an interaction with EWS. We also don't want to sacrifice security.
Our current solution:
We store the credentials from the user (which we get during the login) in the session.
This is ugly because it means the username and password are stored in a cookie on the clients computer - I know it is encrypted, but it's still ugly.
Then in the controller, we lazily create an EWS Client and pass it to each model instance which needs to interact with EWS.
This is ugly because it means that unlike other DB operations (and you can think of EWS as just another database), it means you have to do additional steps for each operation.
Example (simplified/stripped down):
# app/models/appointments.rb
class Appointment
  attr_writer :ews

  def pull_from_exchange
    exchange_event = ews.events[exchange_id, exchange_change_key]
    # …update from exchange_event.to_hash…

    self
  end

  def push_to_exchange
    exchange_event = ews.events.new(to_hash_for_exchange)
    exchange_event.save
    update_attributes(exchange_id: exchange_event.id, exchange_change_key: exchange_event.change_key)

    self
  end

  def ews
    raise EwsClientNotProvided unless @ews
    @ews
  end

  def save_and_push!
    self.class.transaction do
      save!
      push_to_exchange
    end
  end
end

# app/controllers/appointments_controller.rb
class AppointmentsController < ApplicationController
  def create
    @appointment = Appointment.new(params[:appointment])
    @appointment.ews = ews
    @appointment.save_and_push!
  end

private
  def ews
    @ews ||= Ews.client(session.slice(:username, :password, :email).merge(endpoint: ews_endpoint))
  end

  def ews_endpoint
    Rails.application.configuration.ews_endpoint
  end
end

I'm interested in alternative and/or better designs to deal with the situation.
Any ideas/suggestions?

A: For the DB connection, I recommend Thread.current[] in a rackapp, pseudo-global variables are a necessary evil sometimes.
Storing the User credentials on the client is the optimal solution, you could spice the password field with yet another encryption to protect it against brute-forcing. This is because the cookie is hashed and therefore it might be possible to brute-force it, since it's possible to check wherever the decryption is successful locally. If you store the credentials somewhere on your server, all the passwords are compromised if the server is hacked. If you store the data on the client side, they are more secure, as you need both parts (the key on the server and the cookie).


text:
Q: How do I save every value of k in the loop? I am trying to create a code that calculates this infinite formula as many times as I want...
3 + 4/(234) - 4/(456) + 4/(678) - 4/(8910) + 4/(101112) - 4/(121314)....
static void Main(string[] args)
{
    double a = 2;
    double b = 3;
    double c = 4;

    double g = 2;
    double t = 3;
    double n = 4;
    int A = 0;

    while (A < 10)
    {
        double d = 4 / (a * b * c);
        double e = -4 / (g * t * n);
        double k = d + e;

        if (A % 2 == 0)
        {

            g += 2;
            t += 2;
            n += 2;
            A++;
        }
        else if (A % 2 == 1)
        {
            a += 2;
            b += 2;
            c += 2;
            A++;
            Console.WriteLine(k);

            //3.1415926
        }
    }
}

A: To save your values of k to a file, you can use a StreamWriter instead of Console.
static void Main(string[] args)
{
    using StreamWriter writer = File.CreateText("output.txt");

    // ...

    writer.WriteLine(k);
}


text:
Q: Find all functions $f:\mathbb R^+\to\mathbb R$ such that $f\left(\frac x y\right)=f(x)+f(y)-f(x)f(y)$
Find all functions $f:\mathbb R^+\to\mathbb R$ such that
$$f\left(\frac x y\right)=f(x)+f(y)-f(x)f(y)$$
for all $x,y\in\mathbb R^+$. Here, $\mathbb R^+$ denotes the set of all positive real numbers.

I really couldn't solve it. Any help?
This question is from IMO Competition, 2015 day 1, first problem.

A: Let $P(x,y)$ be the property that $f(\tfrac{x}{y}) = f(x)+f(y)-f(x)f(y)$.
$P(1,1)$ yields $f(1) = 2f(1)-f(1)^2$, and so, either $f(1) = 1$ or $f(1) = 0$.
If $f(1) = 1$, then $P(x,1)$ yields $f(x) = f(x)+f(1)-f(x)f(1)$, which simplifies to $f(x) = 1$ for all $x \in \mathbb{R}^+$.
Now, suppose instead $f(1) = 0$.
$P(x,x)$ yields $f(1) = 2f(x)-f(x)^2$, which gives us that $2f(x)-f(x)^2 = 0$ for all $x \in \mathbb{R}^+$.
$P(1,x)$ yields $f(\tfrac{1}{x}) = f(1)+f(x)-f(1)f(x)$, which simplifies to $f(\tfrac{1}{x}) = f(x)$ for all $x \in \mathbb{R}^+$.
Finally, $P(\sqrt{x},\tfrac{1}{\sqrt{x}})$ yields $f(x) = f(\sqrt{x})+f(\tfrac{1}{\sqrt{x}})-f(\sqrt{x})f(\tfrac{1}{\sqrt{x}}) = 2f(\sqrt{x})-f(\sqrt{x})^2 = 0$ for all $x \in \mathbb{R}^+$.
Hence, the only solutions are $f(x) = 0$ for all $x \in \mathbb{R}^+$ and $f(x) = 1$ for all $x \in \mathbb{R}^+$.

A: None of these functions are very interesting. Let $x=y$. Then $$f(1)=2f(x)-f(x)^2.$$ Solving this quadratic, we have that $$f(x)=1\pm\sqrt{1-f(1)}.$$ Thus, $f$, whatever it is, is constant. To find the constant, $$f(1)=1\pm\sqrt{1-f(1)}$$
$$f(1)^2-2f(1)+1=1-f(1)$$
$$f(1)^2-f(1)=0$$
$$f(1)=0\text{ or }f(1)=1.$$
Thus, $f(x)=0$ and $f(x)=1$ are the only two continuous solutions.

A: Small Hint :Let $y=1$. $f(x)=f(x)+f(1)-f(x)f(1)$. So if $f$ does not vanish at $1$,then $f$ is the constant function $1$. Edited later: If $f$ vanishes at $1$, then pluging in $x=y$, you can get $2f(x)=f(x)^{2}$.

A: There are two approaches to problems like this that I know. One is to recognize some $f$ that meets the requirement and then prove that is the only one.  I don't see one offhand, but maybe somebody will. The other is to try special values for the variables and see what you learn.  For example, let $y=1$, then $f(x)=f(x)+f(1)-f(x)f(1)$ or $0=f(1)(1-f(x))$