text:
Q: Configuration file with untrackable parts I've got a configuration file containing some configuration important for the whole project (ie: anybody who clones the repository should have this same conf), and some local configuration (anybody who clones the repository could need to  customize something in this file, and I don't want to track local customization).
This file is unique: I cannot configure the software to use multiple files, and it doesn't support any kind of include directive.
Is there any way to handle this scenario with Git?

I could use git-add -p or -i to only stage part of this file, but it's not a good solution: it's too error prone, requires quite some work and git-status will always display this configuration file as locally modified.
Maybe I could use some git hooks?

A: Have a "config.global" and a "config.local" file for your checked in global config and the local user-specific parts. Make a wrapper script for the application (how, exactly, will depend on the OS of course). Have the script first check for modification time of the global, local and "real" config file. If either partial file is newer, concatenate them into the real config. Then start the application proper.

A: There really is no way to track part of a file in git that I know of.
You could modify the code to load the main file, and then one customized for the environment that overrides the defaults. Developers can keep their own custom version, and you might also use the custom one for differences in test/dev/prod etc...


text:
Q: Python using cusom Class into Main i have developed a custom python script. I'm using main to run all script funtion. This is an example of strucure:
import ssl
import itertools
import decimal

def main():

if __name__ == '__main__':
main()

Now i have a specific class with different def that i need to use into main.
This example of Class that i have see on internet:
class GeoJSON:
"""GeoJSON class which allows to calculate bbox"""
def __init__(self, geojson):
    if geojson['type'] == 'FeatureCollection':
        self.coords = list(self._flatten([f['geometry']['coordinates']
                       for f in geojson['features']]))
        self.features_count = len(geojson['features'])
    elif geojson['type'] == 'Feature':
        self.coords = list(self._flatten([
                    geojson['geometry']['coordinates']]))
        self.features_count = 1
    else:
        self.coords = list(self._flatten([geojson['coordinates']]))
        self.features_count = 1

def _flatten(self, l):
    for val in l:
        if isinstance(val, list):
            for subval in self._flatten(val):
                yield subval
        else:
            yield val

def bbox(self):
    return [min(self.coords[::2]), min(self.coords[1::2]),
            max(self.coords[::2]), max(self.coords[1::2])]

Now i can use the GeoJson class and def into my main?
Thanks

A: Your main function is not magical, you instantiate classes here in the same way as anywhere else.
class A():
    pass

def main():
    a = A()  # a is now an instance of A, you can create multiple instances
    b = A()
    a_third_instance = A()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using sed to replace text with curly braces I am trying to find the following text
get_pins {

and replace it with
get_pins -hierarchical {proc_top_*/

I've tried using sed but I'm not sure what I'm doing wrong. I know that you need # in front of curly braces but I still can't get the command to work properly.
The closest I've come is to this:
sed 's/get_pins #{#/get_pins -hierarchical #{#proc_top_*\//g' filename.txt > output

but it doesn't do the replacement I wanted above.

A: The problem is not in the curly braces, it's in the /.
This is exactly why sed lets you do alternate delimiters.
The line below uses ! as a delimiter instead, and works correctly for a simple file with get_pins { in it.
sed 's!get_pins {!get_pins -hierarchical {proc_top_*/!g' Input.txt

Output:
get_pins -hierarchical {proc_top_*/

Update: Based mklement0's comment, and testing with the csh shell, the following should work in csh.
sed 's@get_pins {@get_pins -hierarchical {proc_top_*/@g' Input.txt

A: @merlin2011's answer shows you how to do it with alternative delimiters, but as for why your command didn't work:
It's actually perfectly fine, if you just remove all # chars. from your statement:
sed 's/get_pins {/get_pins -hierarchical {proc_top_*\//'g filename.txt > output

There are two distinct escaping requirements involved here:

*

*Escaping literal use of the regex delimiter: this is what you did correctly, by escaping the / as \/.

*Escaping characters with special meaning inside a regex in general: this escaping is always done with \-prefixing, but in your case there is NO need for such escaping: since you're NOT using -E or -r to indicate use of extended regexes - and are therefore using a basic regex -  { is actually NOT a special character, so you need NOT escape it. If, by contrast, you had used -E (-r), then you should have escaped { as \{.

A: This awk should do the replace:
awk '{sub(/get_pins {/,"get_pins -hierarchical {proc_top_*/")}1'


text:
Q: How atomic update is implemented in Coroutines Here's update function from Coroutines StateFlow. I have two questions:

*

*How is it atomic? We have multiple operations inside, how can atomicity be guaranteed without mutual exclusion?

*Why is it in while(true) loop? At what condition the loop is necessary?

*Can the loop be endless?

/**
 * Updates the [MutableStateFlow.value] atomically using the specified [function] of its value.
 *
 * [function] may be evaluated multiple times, if [value] is being concurrently updated.
 */
public inline fun <T> MutableStateFlow<T>.update(function: (T) -> T) {
    while (true) {
        val prevValue = value
        val nextValue = function(prevValue)
        if (compareAndSet(prevValue, nextValue)) {
            return
        }
    }
}


text:
Q: DRAM monitoring tool Is there any tool that can shows how much memory is used in each DRAM? Like 40% is used in DRAM1, 20% is used in DRAM2.
The concept is similar to PageFileUsageMonitor. Thanks.

A: It doesn't work like that.  To the OS, RAM is RAM.  2x2GB chips is no different than 4x1GB chips.  Plus, why does it matter to know which physical chip is storing a certain amount of data?  I'm not sure how that information would even be useful.
If you're curious about RAM usage, the Windows 7 task manager really provides a good overview of how much RAM you have, how much is allocated, how much is cache, and how much is available vs. actually free.


text:
Q: Upper bound on the size of the maximum independent set In this assignment under chapter 3.7 the following formula is mentioned as an upper bound for the size of an maximum independent set in any given graph:
$$ |I_{max}| \leq \frac{1}{2}\left(1+\sqrt{1-8m-4n+4n^2}\right) $$
Where $n$ is the number of vertices and $m$ is the number of edges.
However the formula is not proven in any way in said text, which is why I ask how one would prove this?

A: Let there be an independent set $I$ of cardinality $k$. Then there are at most  $\binom{n - k}{2}$ edges between vertices not from $I$ and at most $k(n - k)$ edges between vertex from $I$ and vertex not from $I$. But there is no edge between two vertices from $I$. Therefore
$$m \le \binom{n - k}{2} + k(n - k),\\
2m \le (n^2 - 2nk + k^2 - n + k) + 2(kn - k^2),\\
k^2 - k - (n^2 - n - 2m) \le 0,\\
D = 1 + 4n^2 - 4n - 8m,\\
\left(k - \frac{1 + \sqrt{1 + 4n^2 - 4n - 8m}}2\right)\left(k - \frac{1 - \sqrt{1 + 4n^2 - 4n - 8m}}2\right)\le 0,\\
k \ge 0 \ge \frac{1 - \sqrt{1 + 4n^2 - 4n - 8m}}2 \land k \le \frac{1 + \sqrt{1 + 4n^2 - 4n - 8m}}2.
$$


text:
Q: org.json.JSONException: End of input at character 0 of with volley and php yesterday I came across the error mentioned below, so I started looking for similar questions on stackoverflow...but none of them seemed to help:(
My guess is that im getting no response from the server but I cant come up with an idea how to fix that. Im using like the same code in some other activities (of course with other functions) but al of them are working perfectly fine.
The only thing that changed is that I used Update table for the first time but I cant see how that would result in the following error.
I hope you can help me.
The strange thing is if the
$anzahlrows == 1

is true and there is no more error in the php file with the query (like usual) than I get in android:
Register Response: {"success":true,"error_msg":"Sie wurden erfolgreich angelegt!"}
I/jsonResponse: {"success":true,"error_msg":"Sie wurden erfolgreich angelegt!"}

and everything works fine....
This is the error im getting:
org.json.JSONException: End of input at character 0 of

in the line of
JSONObject jsonResponse = new JSONObject(response);

This is the code in android studio:
Response.Listener<String> responseListener = new Response.Listener<String>() {

                    //  this gets called on response
                    @Override
                    public void onResponse(String response) {

                        Log.d("Response:", "Register Response: " + response);
                        //  check for boolean success from php
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            Log.i("jsonResponse", jsonResponse.toString());
                            boolean success = jsonResponse.getBoolean("success");

                            //  if true from php start LoginActivity
                            if (success){
                                Toast.makeText(RegisterActivity.this, jsonResponse.getString("error_msg"), Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                RegisterActivity.this.startActivity(intent);
                            }

                            //  if false build an AlertDialog
                            else {
                                Toast.makeText(RegisterActivity.this, jsonResponse.getString("error_msg"), Toast.LENGTH_LONG).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                //  call register request and transfer string username and password
                RegisterRequest registerRequest = new RegisterRequest(email, password, matrikelnummer, firstName, surname, responseListener);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(registerRequest);

This is my PHP File:
if (isset($_POST["email"]) or isset($_POST["password"]) or isset($_POST["matrikelnummer"]) or isset($_POST["firstName"]) or isset($_POST["surname"])) {

$email = $_POST["email"];
$password = $_POST["password"];
$matrikelnummer = $_POST["matrikelnummer"];
$firstName = $_POST["firstName"];
$surname = $_POST["surname"];

$query = "SELECT * FROM Users WHERE Matrikelnummer ='$matrikelnummer'";
if ($result=mysqli_query($con,$query)) {

    $anzahlrows = mysqli_num_rows($result);

    if($anzahlrows == 1) {

        $query = "UPDATE Users SET email = '$email' ,password = '$password',firstName = '$firstName', surname = '$surname' WHERE Matrikelnummer = '$matrikelnummer'";
        if ($result=mysqli_query($con,$query)) {

            $response["success"] = TRUE;
            $response["error_msg"] = "Sie wurden erfolgreich angelegt!";
            echo json_encode($response);
            exit;

        } else {
            $response["success"] = FALSE;
            $response["error_msg"] = "Fehler bei der INSERT SQL Abfrage";
            echo json_encode($response);
            exit;
        }

    }
    else {
        $response["success"] = FALSE;
        $response["error_msg"] = "Die angegebene Matrikelnummer ist nicht verfügbar";
        echo json_encode($response);
        exit;

    }
}
else {
    $response["success"] = FALSE;
    $response["error_msg"] = "Fehler bei der SQL Abfrage";
    echo json_encode($response);
    exit;
}

}
else {
$response["success"] = FALSE;
$response["error_msg"] = "Required parameters missing!";
echo json_encode($response);
exit;
}

The Log shows following:
D/Response:: Register Response:
W/System.err: org.json.JSONException: End of input at character 0 of
W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
.
.
.

A: I usually create a response in my PHP code before my code enters the if (isset($_POST["email"]) code starts. Then at each if/else statement I create an appropriate response-- just as you have, with the exception that I do not echo the response and exit. My final statement is where I use the echo response such that it will echo my response regardless of what happens between.
<?php

// array for JSON response
$response = array();
$response["success"] = 0;
$response["message"] = "Error before Parameters";

// check for post data
if (isset($_POST["id"])) {

    $id = $_POST['id'];

    // include db connect class
    require_once __DIR__ . '/db_config.php';
    // set vars
    $host = DB_SERVER;
    $db   = DB_DATABASE;
    $user = DB_USER;
    $pass = DB_PASSWORD;
    $charset = 'utf8';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $opt = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    // connecting to db
    $pdo = new PDO($dsn, $user, $pass, $opt);
    $sql = 'SELECT * FROM tblConnectionData WHERE ID = :id;';
    $stmt = $pdo->prepare($sql);
    $res = $stmt->execute(['id' => $id]);

    /* Check the number of rows that match the SELECT statement */
    if ($res) {
        // success
        $response["success"] = 1;
        $response["data"] = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $data = array();
            $data["id"] = $row["ID"];
            $data["state"] = $row["State"];
            $data["state_abbrev"] = $row["StateAbbrev"];
            $data["city"] = $row["City"];

            array_push($response["data"], $data);
        }
    }
    else {
        /* No rows matched -- do something else */
        // required field is missing
        $response["success"] = 0;
        $response["message"] = "No data returned!!";
    }
}
else {
    $response["success"] = 0;
    $response["message"] = "Parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>

This way I always get a response. I also use int responses for my "success"  Tag. That way I can differentiate in my client code what went wrong in by checking the intvalue instead of trying to decipher the string response.
Notice that I am also using PDO with Prepared Statements. I highly recommend that you also use Prepared Statements to prevent SQL Injection.

A: I fixed it with initializing the array at the start of the php file. It normallt works without in my other php files and I dont know why it fixed my problem but it did.
Thanks for the answers anyway!
Do you see any reasons why it worked this way?


text:
Q: Raise error if launched output and uses result I want to raise an error if the user uses return launch and result().
def launch(returnOutput=False):
    # Function
    if returnOutput:
       return "value"
    else:
       value = "value"

def result():
    return value

I want it to say like:
Console > print(launch(True), result())
Error: "Can't get result if launched output."

Is there a way to do this?

A: I am dumb so i didn't think of this:
def result():
    if value == None:
       # Throw error
    else:
       return value


text:
Q: How to implement individual options (like video and audio) of twilio in php I am going to integrate twilio api in my project.
Here I want to give some options like listen only to audio instead of watching the video. How can I implement this option, i.e. how can I make the video to be invisible?
Any suggestion?
Thank you.

A: Twilio developer evangelist here.
When a participant joins a room the easiest way to show both their Video and Audio is to use attach() to slot them into the DOM as a <video> element.
However, if you want independent control of the audio and video then you probably want to inspect and attach the participant's media.audioTracks and media.videoTracks separately. Each property is a map of a Track.ID and an AudioTrack or VideoTrack. You can then attach and detach the individual tracks as you like over the course of the call.
Let me know if that helps at all.


text:
Q: Separation and access times in SQL server In SQL Server if I have a column that is large, it's going to reduce the number of rows I can pull in a page (and presumably increase the access time).
If I remove that column from the table and put that data in a more isolated table it will increase the number of rows I can pull in a page of data.
Suppose I remove that column from the database entirely and put it in a separate database entirely. Will that decrease the seek times for everything in the database?
More generally: when does it make sense to move a column to a separate table and when should it go in a separate database?

A: If the column actually needs to be accessed frequently, placing it in a separate table (or database) creates a need to join to the other table.  Nothing is saved.  In fact, performance will get worse if this specific performance consideration is the only reason for moving the column.
If you have situations where a subset of a table is frequently accessed, but you still sometimes need to access all columns, consider a covering index for such queries.

A: micahhoover your question reads like a Kobayashi Maru scenario.  If the long data is mostly null and mostly not needed to be displayed then you could put it in another table so you can pack more in your pages. But if your dual table data is in SQL cache then it is occuping the same amount of space as placing it in the same table and loading the table into cache.
Placing the data into another table works well when there is an infrequent need for the data and it will be retrieved via a seperate query NOT a join during every access of the main table which will lead to the performance impace Eric J. mentioned.
Placing the data into another DB would be a disaster due to the need to syncronize the backups, log file backups etc.
There is but one way to be sure you have the best design. The only is to benchmark several designs with REAL world data and queries.

A:
In SQL Server if I have a column that is large, it's going to reduce
  the number of rows I can pull in a page (and presumably increase the
  access time).

Theoretically yes.  It depends on certain factors.  It depends on the data type, and how often that column has data in it and how much.

If I remove that column from the table and put that data in a more
  isolated table it will increase the number of rows I can pull in a
  page of data.

Technically yes, but again it depends on several factors.

Suppose I remove that column from the database entirely and put it in
  a separate database entirely. Will that decrease the seek times for
  everything in the database?

It depends on what you are doing with the database as far as sql server managing memory etc., but for the most part no.  I would not do this.  Joining data across databases when you don't need to is always more trouble than it's worth.  There are a lot of things to consider such has back up plans, managing database growth etc.  99% of the time, it's not worth it.
It really sounds like you are trying to do vertical partitioning for speed performance on queries.  Now in theory this could help, but I would guess that the amount of data you are looking at isn't going to really make this advantageous.  If you want your look ups to go faster, I would start by looking at the query execution plans, and the indexing to make sure that is all in order.
Moving fields for speed should be a last resort as it makes maintenance etc. more tedious.  This approach will also have to be explained to anyone who takes over, but the first thing they are going to question is why do all these 1x1 relationships exist, and unless they know it's been done to be a performance hack they will probably try and start logically organizing the data back to being together.


text:
Q: Values aren't Grouping from Regular Expression I am trying to build a regular expression that evaluates the value enter to determine the blocks within the text. I have grouped the blocks. This Regular Expression will evaluate the Account ID entered in Various pattern.

The AccountID is composed in the following way: [Prefix] + [Account
Number] + [Account Type] + [Joint Account Number]

*

*[Prefix] = [A-Za-z]  but not mandatory

*[Account Number] = All numbers \d; Can range from 2-9 in length; Mandatory

*[Account Type] = [A-Za-z];can be 1-2 length but not mandatory

*[Joint Number] = \d; can be 1-2 in length but not mandatory

My Reg Ex:
(?<prefix>JKB)*\w*\s*(?<number>\d+)*\w*\s*(?<suffix>\W*)*\w*\s*(?<joint>\d*)

So I compiled some values for A/c JKB999LI00 in how users can write it:
9999LI
JKB9999LI00
JKB/999-LI/0
9999 LI
JKB 999 LI 00
9999LI 0
9999LI1
JKB000009999LI01
JKB-999-LI-00
I noticed that not all are placing in the group. What am I doing wrong here?
My Working
NB: Sorry I am unable to share my work done from http://regexstorm.net/ as I couldn't find a share button.

A: You can use
^(?:(?<prefix>[A-Z]+)[\s/-]*)?(?<number>\d{2,9})(?:[\s/-]*(?<suffix>[A-Za-z]+))?(?:[\s/-]*(?<joint>\d{1,2}))?$

See the .NET regex demo and the PCRE regex demo.
Details:

*

*^ - start of string

*(?:(?<prefix>[A-Z]+)[\s/-]*)? - an optional sequence of one or more capital letters (captured into Group "prefix") and then zero or more whitespaces, / or -

*(?<number>\d{2,9}) - Group "number": two to nine digits

*(?:[\s/-]*(?<suffix>[A-Za-z]+))? - an optional sequence matching zero or more whitespaces, / or - and then Group "suffix" capturing one or more letters

*(?:[\s/-]*(?<joint>\d{1,2}))? - an optional sequence matching zero or more whitespaces, / or - and then Group "joint" capturing one or two digits

*$ - end of string.


text:
Q: Checkbox will never check - even when value is true I have a checkbox with a condition that checks whether an id is within the Set. If so, it should check, if not it should remain unchecked. However, even if it is true, the checkbox will not check for some reason and I can't figure out why.
  const [ checkedAccounts, setCheckedAccounts ] = React.useState(new Set());

  const toggleChecked = (id) => {
    if (checkedAccounts.has(id)) {
      checkedAccounts.delete(id);
    } else {
      checkedAccounts.add(id);
    }
  };

  const toggleAllChecked = (ids) => {
    if (!checkedAccounts.size) {
      setCheckedAccounts(new Set(ids));
    } else {
      setCheckedAccounts(new Set());
    }
  };

return (
...

Select All

   <Checkbox onChange={() => toggleAllChecked(allIds)}/>

 {data?.map((delta, idx) => (

         <Checkbox onChange={() => toggleChecked(delta.accountId)}
                   checked={checkedAccounts.has(delta.accountId)}/>

...

When I use the toggleAllChecked function, it will check all of the checkboxes. However, when I use toggleChecked function, the id will be added/removed from the set as the checkbox is clicked but the checkbox will remain unchecked and I have no idea why.


text:
Q: How to obtain authentication token using urllib2 in python? I want to obtain authentication token using urllib2 in python.
My program is (I changed credentials):
import urllib2
import urllib

USER_NAME = 'me'
USER_PASSWORD = 'mypass'

url = "http://myurl.org/oauth/token"

query_args = { "grant_type":"password",
               "username":USER_NAME,
               "password":USER_PASSWORD,
               "client_secret":'123',
                'client_id':'456'}

encoded_args = urllib.urlencode(query_args)
print urllib2.urlopen(url, data=encoded_args).read()

The result of running is 403 Error: Forbidden.
However I can obtain the authentication token using curl in terminal:
curl -X POST "url" -d "credentials"

I used "url" and "credentials" from the python code (to obtain "credentials" string I prinded out encoded_args).
How to get authentication token using urllib2?

A: First off, you shouldn't mix urllib and urllib2 in the same application. urllib2 is the successor to urllib, and will do the same things.
The real answer here is to use an OAuth capable library to like python-oauth2 to do the heavy lifting for you. Or better, switch from urllib2 to a slightly higher level package like requests, and use one of their brilliant oauth plugins for a single solution which kicks some ass!


text:
Q: class 'MongoDB\Cient' not found I am using the following code to create a connection to a MongoDB server, so as to create databases and stuff but I keep getting class 'MongoDB\Cient' not found. I really need help.
<?php
    $client = new MongoDB\Client('mongodb://localhost:27017');
    $db = $client->reach;
    $collection = $db->messages;
    $collection->insertOne($record);
?>

where $record is some record.
Also, $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); connects and I can use it to communicated with any already created db (using the command line). So, I want to ask if MongoDB\Driver\Manager can substitute MongoDB\Client?

A: After all the struggle, this solved the issue...
installing using composer:
$ composer require "mongodb/mongodb=^1.0.0"
OUTPUT:
    ./composer.json has been created
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Installing mongodb/mongodb (1.0.0)
    Downloading: 100%

Writing lock file
Generating autoload files

Usage:
<?php
require 'vendor/autoload.php'; // include Composer goodies

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

echo "Inserted with Object ID '{$result->getInsertedId()}'";
?>

That fixed the issue for me. follow the link:
http://docs.php.net/manual/en/mongodb.tutorial.library.php


text:
Q: Mysql IN Condition Limiting I have two tables, one for Strains, and one for StoreStrains. Stores sell strains so there can be multiple entries in "StoreStrains" for a certain strain_id.
I'm making a one call to grab all Strains from Strain table. Then I'm mapping those strain_ids like so "1,2,3,4,5". Then I'm doing another SQL call to find what stores have those strains.
SELECT * FROM StoreStrains
WHERE strain_id IN (strain_ids)
LIMIT 5

As you could expect, this will return all StoreStrains with a strain_id of 1-5. But if 3 of those stores carry the same strain, I it would return 8 results, but I'm limiting to 5.
On a larger scale (in a DB with 500,000+ StoreStrains), just increasing the limit to "get all the results" isn't a good option at all. So I'm wondering if there is a way limit
WHERE strain_id IN (strain_ids)

To 1 result per?
I know I could just do 5 separate SQL calls like this:
SELECT * FROM StoreStrains Where strain_id = ? LIMIT 1

But I would much prefer this all happens in one sql call if possible. Thank you.

A: If you want to arbitrarily pick a store, then do this
Select strain_id,
       (Select StrainStore.id
        from StrainStore
        Where StrainStore.strain_id = Strains.strain.id
        Limit 1)
From Strains

But it's probably better to do this
Select Strains.strain_id, GROUP_CONCAT(StrainStore.id)
From Strains
Join StrainStore
    On (Strains.strain_id = StrainStore.strain_id)
Group by Strains.strain_id


text:
Q: Missing Access Rights for OpenOffice Applications I'm very new to Linux and Ubuntu.
I recently installed Ubuntu LTS 18.04 and I've replaced LibreOffice with OpenOffice, but I'm not sure how to allow myself to access OpenOffice without relying on the sudo command.
Is there a way to make it open like any other program?
My computer gives me an error when I try to run it from the console without sudo.
It says, "OpenOffice user installation cannot be processed due to missing access rights. Please make sure that you have sufficient access rights for the following location and restart OpenOffice: /home/userName/.openoffice/4".
Here is what the command "namei -lx ~/.openoffice/4" brings up. I have replaced my username (which is my real name) with "userName".

f: /home/userName/.openoffice/4
  Drwxr-xr-x root   root   /
  drwxr-xr-x root   root   home
  drwxr-xr-x userName userName userName
  drwxr-xr-x root   root   .openoffice
  drwxr-xr-x root   root   4


text:
Q: C# Httpwebrequest with proxy Okay so currently my program uses IP:PORT list of proxies from a .txt file, example -
proxy = new List<string>(System.IO.File.ReadAllText("proxy.txt").Split(new char[] { '\n' })).Distinct<string>().ToList<string>();

But rather than use proxies from a .txt file, I was wondering if it was possible to use them from a URL, I have a custom link that automatically downloads a .txt file with IP:PORT list, I wish to integrate this into my program & refresh/redownload the list once the list has finished or every 10-15 minutes.


text:
Q: Ubuntu taking way too long time to start So, I have a Dell laptop. Core i5 4th Generation and 8GB RAM. I recently installed Kali alongside Ubuntu and Windows 10 and then when I booted from Ubuntu (15.10 with Gnome) again it took a VERY LONG TIME to show up the log in interface, comparing to before I installed Kali, which'd take 20-30 tops(Before GRUB the speed was fine, it just takes to long with that little Gnome circle rolling). As a silly newbie I removed kali thinking it'd get better because I thought that the partition sequence was making the trouble (it was like sda1, sda2, sda3, sda4, sda5, sda8,sda6,sda7) but it didn't work. I looked it up but didn't find anything. Please  Help.
EDIT:
boot.log gave me this:
[K[    [31m*[1;31m*[0m] A start job is running for dev-disk-by\x2duuid-e39e44ff\x2dbf9e\x2d4c0e\x2dbc35\x2dba255ac475e6.device (1min 29s / 1min 30s)
[K[     [31m*[0m] A start job is running for dev-disk-by\x2duuid-e39e44ff\x2dbf9e\x2d4c0e\x2dbc35\x2dba255ac475e6.device (1min 30s / 1min 30s)
[K[[1;31m TIME [0m] Timed out waiting for device dev-disk-by\x2duuid-e39e44ff\x2dbf9e\x2d4c0e\x2dbc35\x2dba255ac475e6.device.
[[1;33mDEPEND[0m] Dependency failed for /dev/disk/by-uuid/e39e44ff-bf9e-4c0e-bc35-ba255ac475e6.
[[1;33mDEPEND[0m] Dependency failed for Swap.

Many  of the "A start job...", actually. Like fifty.
And my fstab looks like this:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda5 during installation
UUID=3504ff47-dec1-407c-ad0a-a82b74007d24 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/sda1 during installation
#UUID=7ADE-45D6  /boot/efi       vfat    umask=0077      0       1
# /home was on /dev/sda7 during installation
UUID=ab6e808f-2570-44d6-9552-5b90a55723a5 /home           ext4    defaults        0       2
# swap was on /dev/sda6 during installation
UUID=e39e44ff-bf9e-4c0e-bc35-ba255ac475e6 none            swap    sw              0       0
UUID=7ADE-45D6  /boot/efi   vfat    defaults    0   1

A: SOLVED!!! The problem was that the UUID of swap on fstab was different from the actual UUID that is shown using: sudo blkid. I just had to replace it and boot is like a bullet again. :D


text:
Q: Linq: Adding extra condition along with GroupBy and SelectMany Continuing from my previous post:
SQL Query: Display only latest Id from each set
I have the following SQL Table:
Name       Description   Id   UserId   CreatedDate

UserSet1   Desc1         0    Abc      06/01/2018
UserSet1   Desc2         1    Abc      06/01/2018
UserSet1   Desc4         2    Def      06/02/2018
UserSet2   Desc for 2    5    NewUser  06/04/2018
UserSet2   Desc for 2    7    NewUser  06/19/2018

What I want to extract from the above table is just the latest Id for each Name so that I could get the following output
Name      Description    Id    UserId    CreatedDate

UserSet1  Desc1          0     Def       06/01/2018
UserSet1  Desc2          2     Def       06/01/2018
UserSet2  Desc for 2     7     NewUser   06/19/2018

Since Id 2 & 7 are the latest entries in the table for UserSet1 & UserSet2, I would like to display that instead of all the entries in the table. Now this was solved with the below LINQ code. Now I have another requirement to also show all rows which have ID's zero as well (see above expected result).
var results = response
  .GroupBy(row => row.Name)
  .SelectMany(g => g
     .OrderByDescending(row => row.Id)
     .Take(1));

How can I modify my above Linq so that it shows all highest no IDs of the name together with any ID's which are zero as well.
Thanks

A:   var results = response.GroupBy(row => row.Name)
                        .SelectMany(g => g
                        .OrderByDescending(row => row.Id)
                        .Take(1))
                      .Union(response.Where(x=>x.Id== 0));


text:
Q: Drawing $D=\{(x,y)| |x-1|+|y-1|\leq \frac{1}{2}\}$ in $\mathbb R^2$ $$D=\{(x,y)| |x-1|+|y-1|\leq \frac{1}{2}\}$$
I know how $y=|x-1|$ looks, and $|y-1|$ but how do I find this? The problem I have is to find $$\iint_{D}|\ln(xy)|dxdy$$. I think I can do this, just need to find how this set looks. And how this is generaly done.

A: You have
 $$|y-1|+|x-1|\le \frac{1}{2}\Rightarrow  |y-1|\le -|x-1|+\frac{1}{2}$$
This means that
$$y-1\le -|x-1|+\frac{1}{2}\Rightarrow y\le-|x-1|+\frac{3}{2}$$
and
$$y-1\ge |x-1|-\frac{1}{2}\Rightarrow y\ge |x-1|+\frac{1}{2}$$
The bound will just be the equalities
$$y=-|x-1|+\frac{3}{2}, y= |x-1|+\frac{1}{2}$$
The first equality you will shade below because your original inequality symbol was 'less than or equal to'.  The second equality you will shade above because your second inequality was 'greater than or equal to'.  The solution set is the intersection of the two graphs.  See my original comment for a graph from Wolfram Alpha.
If you are not sure how to graph this, just recall that the general form of the absolute value equation is
$$y=a|x-h|+k$$
where the ordered pair $(h,k)$ is the vertex.


text:
Q: How scroll led in dot matrix without using microcontroller? I can turn ON my desired led in dot matrix. And given that i know about the trick of persistence of vision, help me.

A: Whether you use a microcontroller, FPGA or wired logic the principle is the same.
You scan through the LEDs (typically with a 5x7 characters say 20 across you might have 100 sink drivers, one for each column and 5 source row drivers. You scan the display by turning on the desired sink drivers for each row and turn on the appropriate row driver. The cycle has 5 phases in this example and you repeat this many times a second so all the LEDs in the matrix that are supposed to be on appear to be on continuously (preferably at a few hundred Hz to 1kHz).
Scrolling characters across is accomplished by changing the data fed to the column drivers. Usually there's a lookup table or ROM for character generation so you can deal with character codes rather than bitmaps of characters. You can store the character codes in a shift register (eg. 20 bytes), look up the column driver code for each character in each position and for each row (0..4). You could do that once per phase just before turning the column driver on. Then shifting the character codes in the shift register would scroll the display.
Simple enough once you think about it a bit. One interesting artifact of the multiplexing is that you will typically perceive the characters slanting slightly to the left or right as they scroll across the display.


text:
Q: Confusion related to firebase realtime database pricing model I am planning to use firebase for a project. The use case scenario is such that there might be situations (sometimes - may be 5 to 6 times in a month) that the simultaneous connections to 'Realtime Database' exceed 100 - the limit for the free plan.
Quoting from their pricing faq -

What happens if I exceed Spark or Flame plan storage or download
  limits for Realtime Database?
To provide you with a predictable price, the resources available to
  you in the Spark and Flame plans are capped. This means that when you
  exceed any plan limit in any month, your app will be turned off to
  prevent any further resource usage and additional charges.

What happens if I exceed Spark plan simultaneous connection limits for
  Realtime Database?
Usage is measured monthly, and if your app is disabled in a given
  month because of usage, it is automatically re-enabled at the
  beginning of the next month.

So my question is - say at a time 'T' my app exceeds 100 simultaneous connections to the Realtime Database by 'n' users. Will this mean that -
1) My application will be shut down for the rest of the month and no further connections to the real-time database will be possible for that entire month?
OR
2) The first 100 active connections will work and the 'n' users trying to connect after the 100-mark will not be able to connect until some one from the first 100 disconnects?

A: Your application will not get suspended or shut down if you exceed the limit.
When you have 100 users connected to your real time database, the database stops accepting new connections. But as soon as one of the existing user disconnects, the database will accept the new connection again in this process the number of simultaneous connections will never exceed 100.
When you upgrade your project to a paid plan, the connection limit is immediately raised.


text:
Q: How to save List to Room database? I'm trying to save a List of Double to Room database using this Converter class:
public class Converters {

    @TypeConverter
    public static String fromDoubleList(List<Double> doubleList){

        Gson gson = new Gson();
        String json = gson.toJson(doubleList);
        return json;
    }

    public static List<Double> fromString(String value){

        Type listType = new TypeToken<List<Double>>(){}.getType();
        return new Gson().fromJson(value, listType);
    }
}

but I keep getting this message:
error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

Why isn't the converter class working?
Edit - This is my database:
@Database(entities = {MarketUnit.class}, version = 1)
@TypeConverters({Converters.class})
public abstract class MarketDatabase extends RoomDatabase {

    public static final String DATABASE_NAME = "market_db";

    private static MarketDatabase instance;

    public static MarketDatabase getInstance(final Context context){
        if(instance == null){
            instance = Room.databaseBuilder(
                    context.getApplicationContext(),
                    MarketDatabase.class,
                    DATABASE_NAME
            ).build();
        }
        return instance;
    }

    public abstract MarketDao getMarketDao();

}

I've tried the suggestion from the duplicate question, but it's not working!

A: In short you cannot have an Array/List directly as a column.
What you can do is have a POJO as a holder class and then have the column use that type.
e.g.
class Holder() {
   List<Double> doubleList;
}

and in the Entity class have something like
Holder theColumn;

Noting that the Type Converter would then be from/to Holder
e.g. :-
class Converters {

    @TypeConverter
    public String fromHolder(Holder h) {
        Gson gson = new Gson();
        String json = gson.toJson(h);
        return json;
    }
    @TypeConverter
    public Holder toHolder(String s) {
        return new Gson().fromJson(s, Holder.class);
    }
}

Working Example:
Holder :-
class Holder {
    public List<Double> doubles;
}

MarketUnit :-
@Entity
class MarketUnit {
    @PrimaryKey
    Long id = null;
    Holder doubleList;
}

Converters :-
class Converters {

    @TypeConverter
    public static String fromHolder(Holder h) {
        Gson gson = new Gson();
        String json = gson.toJson(h);
        return json;
    }
    @TypeConverter
    public static Holder toHolder(String s) {
        return new Gson().fromJson(s, Holder.class);
    }
}

*

*made static so can be called

MarketDao :-
@Dao
abstract class MarketDao {

    @Insert
    abstract long insert(MarketUnit marketUnit);
    @Query("SELECT * FROM marketunit")
    abstract List<MarketUnit> getAllMarketUnits();

}

MarketDatabase :-
@Database(entities = {MarketUnit.class}, version = 1)
@TypeConverters({Converters.class})
public abstract class MarketDatabase extends RoomDatabase {

    public static final String DATABASE_NAME = "market_db";

    private static MarketDatabase instance;

    public static MarketDatabase getInstance(final Context context){
        if(instance == null){
            instance = Room.databaseBuilder(
                    context.getApplicationContext(),
                    MarketDatabase.class,
                    DATABASE_NAME
            ).allowMainThreadQueries().build();
        }
        return instance;
    }

    public abstract MarketDao getMarketDao();

}

*

*.allowMainThreadQueries added for brevity and convenience

Finally an Activity MainActivity for test:-
public class MainActivity extends AppCompatActivity {

    MarketDatabase db;
    MarketDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        db = MarketDatabase.getInstance(this);
        dao = db.getMarketDao();

        MarketUnit mu1 = new MarketUnit();
        Holder h = new Holder();
        ArrayList<Double> dbls = new ArrayList<>();
        dbls.add(200.01);
        dbls.add(111.111);
        h.doubles = dbls;
        mu1.doubleList = h;
        dao.insert(mu1);

        for(MarketUnit mu: dao.getAllMarketUnits()) {
            Log.d("DBINFO","MarketUnit ID = " + mu.id);
            Log.d("DBINFO","Converted Holder :-\n\t" + Converters.fromHolder(mu.doubleList));
            for(Double d: mu.doubleList.doubles) {
                Log.d("DBINFO","\tDouble is " + d);
            }
        }
    }
}

Result from the Log :-
2021-11-12 16:34:37.776  D/DBINFO: MarketUnit ID = 1
2021-11-12 16:34:37.777  D/DBINFO: Converted Holder :-
        {"doubles":[200.01,111.111]}
2021-11-12 16:34:37.777  D/DBINFO:  Double is 200.01
2021-11-12 16:34:37.777  D/DBINFO:  Double is 111.111

The MarketUnit table using App Inspection :-


text:
Q: What DNS Changes should I make? I'm moving a website to a new server. But I only want to change where the website is pointing to. So basically example.com and www.example.com. I'm afraid if I change the A record for @, mail will stop working for this website.
Right now everything is pointing to 13.119.XX.XX. I want to point just the website to the 67.91.XX.XX ip-address that the staging A record is pointing at.

A: Your email (POP3/IMAP/SMTP) works with MX records, not A records. So if you change the A records, the only thing of concern would be making sure the A record for 'mail' points to the correct email web interface.

A: *

*change www cname "@" to example.com

*make and A record for
example.com that points to the new IP

A     example.com. 167.99.XX.XX
cname www         example.com.


text:
Q: Cardinal Orderings: What is he even asking for? Consider the following exercise.

Show that for any set $S$ we have $S \preccurlyeq {}^S2$, but $S \not\approx {}^S2$. (This should be done directly, without use of
$\mathscr{P}S$ or cardinal numbers. If $F: S \rightarrow {}^S2$, then
define $g(x) = 1 - F(x)(x)$.)

I'm confused. What type of proof is he even asking for? Does he just want me to create an explicit injection from S into ${}^S2$ (the word "directly" confuses me)? If so, how do I generate such a function? I was thinking maybe something like $F(a) = \langle a, 0 \rangle \cup f[\![S - a]\!]$ for any function $f \in {}^S2$? But is this even a valid way of defining a function? Also, why does he mention $g(x) = 1 - F(x)(x)$? Why does it matter and where did $g$ even come from? This is Exercise 6.16 from Enderton's Elements of Set Theory by the way, in case any of you want to look for yourself which exercise I'm referencing. I'm probably missing something.
Note: $f[\![x]\!]$ is the image of $x$ under $f$

A: You have the right ideas.
Yes, you have to construct an injection from $S$ into ${}^S 2$. Of course, one approach would be to take the obvious injection from $S$ into $\mathcal{P}(S)$ by sending $x \in S$ to $\{x\} \in \mathcal{P}(S)$. Then compose this with the bijection $\mathcal{P}(S) \approx {}^S 2$. However, the exercise asks to do it "directly", so that means that they want you to give an explicit description of the injection from $S$ into ${}^S 2$.
Hint: can you use the injection I described before (so $x \mapsto \{x\}$, composed with $\mathcal{P}(S) \approx {}^S 2$) to construct an explicit injection from $S$ into ${}^S 2$?
There is a second part to the exercise. Namely to show that $S \not \approx {}^S 2$. This is where the hint is useful. Suppose for a contradiction that $S \approx {}^S 2$. Then let $F: 2 \to {}^S 2$ be a bijection and use the hint to define $g(x) = 1 - F(x)(x)$. So $g$ is a function from $S$ to $2$, that is $g \in {}^S 2$. Can you use this to find the contradiction?


text:
Q: Is the set of functions from $\mathbb{N}$ to $\mathbb{N}$ countable? My first thought was that there should exist a list of all functions from $\mathbb{N}$ to $\mathbb{N}$. Namely because, given a finite sequence, we can find all possible orderings of the sequence. However, $\mathbb{N}$ is not finite, leading me to believe that I can't list all functions from $\mathbb{N}$ to $\mathbb{N}$ .

A: The set  $\{0,1\}^{\mathbb{N}}$ of functions from $\mathbb{N}$ to $\{0,1\}$ is the set of subsets of $\mathbb{N}$ and is not countable. $\{0,1\}^{\mathbb{N}}$ is a subset of the set of functions from $\mathbb{N}\rightarrow \mathbb{N}$.

A: Hint: You can easily adopt Cantor's diagonal argument to this question:
Each $f: \mathbb{N} \to \mathbb{N}$ can be written as a series $f(1), f(2),...$.
If the set of such functions was countable you can order it, and draw up a chart to include all such series. Try using Cantor's diagonal argument now to construct a function $\mathbb{N} \to \mathbb{N}$ to arrive at a contradiction.

A: Note that the set of functions from $\mathbb N\to \{0,1\}$ has the same cardinality as the powerset of $\mathbb N$, since we can create a bijection as follows:
$$\phi: \{\mathbb N\to \{0,1\}\} \to \mathcal{P}(\mathbb N)$$$$f\mapsto \{x\in\mathbb N\;|\;f(x)=1\}$$
The powerset has larger cardinality than the naturals by Cantor's Diagonal Argument.


text:
Q: In Angular JS - how to use ng-include to make my code generic and reusable? Using the AngularJS,
I want to use ng-include to make my code generic.
So here is my problem:
I want to have my 'ang-attribute.html' file used in the ng-include to be as generic as possible, and for that I want to get the attribute name outside of the html.
With something like this:

In my html file I would like to use the data-field-name, and then use it again with a different value.
I tried to get it via DOM... and couldn't find a way to do that.
So in my ng-include html file I have the following line:

{{displayAttribute}}:

....

Maybe there is a way to pass a constructor to the controller and then I could pass my data-field-name into it?
Or any other solution?
Thanks!

A: I believe you want to be looking at directives, this has an attributes object easily accessible after the dom has rendered to re-use.
Html
<my-directive field-name="display_name"></my-directive>

Directive
angular
.module("myApp", [])
.directive("myDirective", function() {
    return {
        restrict: "E",
        template: "
{{exposeAttribute}}
",
        //templateUrl: "mytemplate.html",
        link: function(scope, element, attr) {
            scope.exposeAttribute = attr.fieldName;
        }
    };
});

http://jsfiddle.net/mhCaD/


text:
Q: Presentation of the monoid of self-maps of a finite set Is there a common presentation of the semigroup of functions from a given (finite) set to itself?

A: There are several well known presentations. One has to first choose your favorite presentation of the symmetric group. Then one usually adds in a rank n-1 idempotent but some people add all of them or other elements. Then one figures out the extra relations. See page 161 of Classical Finite Semigroups by Ganyushkin and Mazorchuk. You should know the monoid of all self-maps of a set is usually called the full transformation monoid or $T_n$ when googling.
Pages 42-43 of http://research-repository.st-andrews.ac.uk/bitstream/10023/2821/3/NikolaRuskucPhDThesis.pdf give two presentations.


text:
Q: Amazon Web Services - RDS Configuration I am using AWS tools for deploy a simple application.
I have a RDS instance (Oracle) and it is working.  (I can access to it from SQL Developer in my local computer)
By other side, I built in Eclipse a simple application in jsp that loops over a table in my Oracle instance (above metioned) and shows the values in the screen.
Test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="dbconnection.DataSource"%>
<%@page import="java.sql.*"%>
<%@page import="oracle.jdbc.pool.OracleDataSource"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Tercera Prueba</title>
</head>
<body>
<%
DataSource ods = new DataSource();
Connection conn=ods.connect();
out.println (ods.getUserName(conn));
// Close the connection
conn.close();
conn = null;
%>

</body>
</html>

DataSource.java
import oracle.jdbc.pool.OracleDataSource;

public class DataSource
{

  public String getUserName(Connection conn)
       throws SQLException
  {
    // Create a Statement
    Statement stmt = conn.createStatement ();
    String str="";
    // Select the ENAME column from the EMP table
    ResultSet rset = stmt.executeQuery ("select USER from dual");

    // Iterate through the result and print the employee names
    while (rset.next ())
      str= "User name is " + rset.getString (1);

    // Close the RseultSet
    rset.close();
    rset =  null;

    // Close the Statement
    stmt.close();
    stmt = null;

    return (str);
  }

  public Connection connect() throws SQLException{
        // Create a OracleDataSource instance explicitly
        OracleDataSource ods = new OracleDataSource();

        // Set the user name, password, driver type and network protocol
        ods.setDriverType("thin");
        ods.setServerName("xxxxxx");
        ods.setDatabaseName("oracledb");
        ods.setPortNumber(1521);
        ods.setUser("xxxxxx");
        ods.setPassword("xxxxxxx");

        Connection conn = ods.getConnection();

        return (conn);

  }
}

Once this app is deployed in Apache Tomcat server (localhost), everything Works ok and the value is shown in the screen.

However, once this app is deployed over Elastic BeanStalk service (using AWS toolkit for Eclipse), the web page takes too long for loading, and finally nothing appear (page in blank). In fact, it does not shows errors either.

I was debugging line by line, and everything goes well untill the line :
Connection conn=ods.connect();

I think is something related to the configuration of my RDS Oracle instance. but Im not sure. it is how it is configured.

Do you have any idea?
Many Thanks

A: Have you ensured that the RDS Instance and the Elastic Beanstalk have the appropriate security groups?
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.managing.ec2.html#using-features.managing.ec2.securitygroups

A: Solved!.
Need to configure Security Groups.
My RDS Instace had only one inbound ip (it was my local computer, thats why it worked from Apache Tomcat Server). For allowing all ip's you must specify 0.0.0.0/0 as ip.
:)


text:
Q: Will key in the index be removed after deletion in B Plus tree? I'm a little confused with the deletion in B+ tree. I searched a lot in Google and find that there are two implementation when the key you want to delete appears in the index:

*

*Delete the key in the index

*Keep the key in the index

Algorithm from https://www.javatpoint.com/b-plus-tree-deletion uses the first way.

Algorithm from https://www.cs.princeton.edu/courses/archive/fall08/cos597A/Notes/BplusInsertDelete.pdf uses the second way.

So I really want to know which one is right.
But I'm more inclined to take that as an undefined behavior. At this point, could someone help me figure out the advantage and disadvantage between them? And how to choose between them?
Thanks in advance.

A: Both methods are correct.
The difference that you highlight is not so much in deleting/not-deleting internal keys, but in updating/not-updating them.
Obviously, when you delete a value (i.e. a key in a leaf node), the b-plus-tree property is not violated: all child values are still within the range dictated by the parent information. You can never break this range-rule by merely removing a value from a leaf. This rule is also still valid when you update the internal key(s) in the path to that leaf (according to method 1), which is only necessary when the deleted value was the left-most one in its leaf.
Note that the two methods may produce quite different trees after a long sequence of the same operations (insert, delete).
But on average the second method will have slightly less work to do. This difference is not significant though.


text:
Q: Could you tell me what exactly happens when we edit the Web.config (at runtime) on a IIS server? Could you tell me what exactly happens when we edit the Web.config (at runtime) on a IIS server.
Is the application that depend of the web.config automatically restarted? If yes is it possible to cancel the automatic restart (or reload of the web.config)?

A: The application that uses the web.config will restart when you change it, there's more info here:
http://msdn.microsoft.com/en-us/library/ms178473.aspx
I don't know of any way to prevent this from happening (and I'm not sure why you'd want to - perhaps you can provide some more details of what you're trying to achieve).

A: FYI - In ASP.NET 2.0 you can use the built in Health Monitoring Events to log application restarts along with the reason for the restart.  This will enable you to clearly document when and how often it occurs.  This is accomplished by editing the master web.config for the machine.
For more information:
http://blogs.msdn.com/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx

A: [JUST A NOTE]
I know this is an old one but this still deserves to noted.
Scott Forsyth - MVP answer is incorrect.

The ASP.NET AppDomain is restarted whenever you 'touch' web.config.

This is wrong.

Whisk answer is the most technically correct & complete answer as it includes a link to the MSDN that includes one important detail:

When an application restart is required, ASP.NET will serve all
  pending requests from the existing application domain and the old
  assemblies before restarting the application domain and loading the
  new assemblies.

This is particular important when we are talking web services. This indicates that it may be ok do a mid-day restart safely.

A: The ASP.NET AppDomain is restarted whenever you 'touch' web.config.  It's possible to turn off the File Change Notification (FCN) for a folder, but it's usually not the best bet if you can help it.  If you do turn it off, it just means that you need to manually recycle the app pool for changes to take effect.
Prior to IIS7, only ASP.NET changes would cause the AppDomain recycle, but with IIS7 and many of the settings living in web.config, this is a more common issue.  i.e. changing a default doc in IIS 7 Manager will cause that AppDomain recycle now.
Ideally you just need to keep your change rate down, or sometimes apply the change to applicationHost.config (which doesn't cause the AppDomain recycle) rather than web.config.


text:
Q: Unable to Start daemon process & Gradle syncing is too slow I Updated my Android Studio and as well I keep getting this error when I launch any project ...
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/6.7.1/userguide/gradle_daemon.html
Process command line: C:\Program Files\Android\Android Studio\jre\bin\java.exe --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.invoke=ALL-UNNAMED --add-opens java.prefs/java.util.prefs=ALL-UNNAMED -Xmx2048m -Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en -Duser.variant -cp C:\Users\Nerd\.gradle\wrapper\dists\gradle-6.7.1-bin\bwlcbys1h7rz3272sye1xwiv6\gradle-6.7.1\lib\gradle-launcher-6.7.1.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 6.7.1
Please read the following process output to find out more:
-----------------------
OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x0000000080000000, 268435456, 0) failed; error='The paging file is too small for this operation to complete' (DOS error/errno=1455)
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 268435456 bytes for Failed to commit area from 0x0000000080000000 to 0x0000000090000000 of length 268435456.
# An error report file with more information is saved as:
# C:\Users\Nerd\.gradle\daemon\6.7.1\hs_err_pid21920.log

-----------------------
Check the JVM arguments defined for the gradle process in:
 - gradle.properties in project root directory

I thought maybe my C: drive has insufficient space but I cleaned lost of unuseful files.
and I can't figure out why my C: drive had 32 GB Space and while Gradle is Building it's just becomes Low space and when the Gradle synch finish unsuccessfully it has 7.2 GB space!

I just recently install Unity game engine and used the Android Studio SDK directory as well. I don't know if it doesn't have any relation with the problem, but that's whole the contemporary changes to my computer.

Any Idea other than uninstalling and reinstalling Android Studio will be appreciated.

A: Your error states that the daemon exited because there was insufficient memory. Here, it is referring to the RAM, and not the hard disk. Add this to gradle.properties file, create one if it's not present,
org.gradle.jvmargs=-Xms512M -Xmx5G


text:
Q: BigQuery Crashlytics - Crash free users / sessions I've linked my firebase crashlytics data to bigquery and setup the data studio templates provided by google. A lot of great data in there except the most important metrics required for my dashboard: crash free users and crash free sessions as a percentage.
Nothing stands out in the schema which I could be used to calculate this.
Any ideas how I might get this value? It's displayed in the firebase dashboard so it must be available..

A: I looked into the documentation and found event_name='app_exception'. With that you can write a query like
WITH userCrashes AS (
  SELECT user_pseudo_id, MAX(event_name = 'app_exception') hasCrash
  FROM `firebase-public-project.analytics_153293282.events_20181003`
  GROUP BY 1
)

SELECT
  IF(hasCrash,'crashed','crash-free') crashState,
  COUNT(DISTINCT user_pseudo_id) AS users,
  ROUND(COUNT(DISTINCT user_pseudo_id) / SUM(COUNT(DISTINCT user_pseudo_id)) OVER (),2) AS userShare
FROM userCrashes
GROUP BY 1

But there is also a flag 'fatal' in the event parameters. In the example data, it's always true, but in case you wanted to take it into respect, you could do something like
WITH userCrashes AS (
  SELECT
    user_pseudo_id,
    MAX(event_name = 'app_exception') hasCrash,
    MAX(event_name = 'app_exception'
      AND (select value.int_value=1 from unnest(event_params) where key='fatal')
    ) hasFatalCrash
  FROM `firebase-public-project.analytics_153293282.events_20181003`
  GROUP BY 1
)

SELECT
  IF(hasCrash,'crashed','crash-free') crashState,
  IF(hasFatalCrash,'crashed fatal','crash-free') fatalCrashState,
  COUNT(DISTINCT user_pseudo_id) AS users,
  ROUND(COUNT(DISTINCT user_pseudo_id) / SUM(COUNT(DISTINCT user_pseudo_id)) OVER (),2) AS userShare
FROM userCrashes
GROUP BY 1,2

Disclaimer: I never worked with firebase, so this is all just based on documentation and example data. Hope it helps, though.


text:
Q: remove row with condition and duplicate value on multi column i need to remove line with condition, column 2 only "eating" and combination values on column 3 and column 4 already occurred in a previous line
my sample data csv like this:
a,eating,apple,2
b,throwing,banana,1
c,eating,apple,3
d,eating,apple,1
e,eating,banana,2
f,throwing,apple,2
g,throwing,banana,2
h,throwing,banana,3
i,eating,apple,2
j,eating,apple,3
k,eating,banana,1
l,throwing,banana,2
m,throwing,banana,1
n,throwing,apple,1
o,eating,apple,3
p,eating,banana,2
q,throwing,apple,1
r,throwing,apple,2
s,eating,apple,1

the output should be like this
a,eating,apple,2
b,throwing,banana,1
c,eating,apple,3
d,eating,apple,1
e,eating,banana,2
f,throwing,apple,2
g,throwing,banana,2
h,throwing,banana,3
k,eating,banana,1
l,throwing,banana,2
m,throwing,banana,1
n,throwing,apple,1
q,throwing,apple,1
r,throwing,apple,2

A: Assuming that the input data is "simple CSV", i.e. that there are no embedded commas or newlines in any fields, then we may use awk like so:
$ awk -F, '$2 != "eating" || !seen[$3,$4]++' file
a,eating,apple,2
b,throwing,banana,1
c,eating,apple,3
d,eating,apple,1
e,eating,banana,2
f,throwing,apple,2
g,throwing,banana,2
h,throwing,banana,3
k,eating,banana,1
l,throwing,banana,2
m,throwing,banana,1
n,throwing,apple,1
q,throwing,apple,1
r,throwing,apple,2

This prints the current line if the 2nd comma-delimited field is not precisely the string eating or (if the 2nd field is eating) if the combination of the 3rd and 4th fields has not been seen before.
The logical expression
$2 != "eating" || !seen[$3,$4]++

may be rewritten as
!($2 == "eating" && seen[$3,$4]++)

(which is the way the conditions were specified in the question) depending on which way is easiest to understand.  The two expressions are equivalent.
This is a simple variation of the common idiomatic way to remove duplicated lines while preserving the original record order using awk:
awk '!seen[$0]++' file

A: Using GNU sed with extended regex mode (-E)  we can solve this problem, by maintaining the tuple  (3rd,4th fields) belonging to eating in the 2nd field lines.
Then we compare with the pattern space
and take the appropriate action.
sed -E '
  /\n/{
    s///;s/\n+/\n/g
  h;d;}
  /^[^,]+,eating,/{
    s/[^,]+/&\n/4;T
    s/[^,]+/\n&/3;G
    /(\n.+\n).*\1/d
    h;s/\n//;s///;P
  x;D;}
' file


text:
Q: Invalid conversion from 'char' to 'const char*' I have a program that generates a single random character, using the randomCharacter function, and random strings, using the randomString function. The latter utilises the former, and breedWithMutation uses randomCharacter to probabilistically mutate a representation of a gene sequence.
#include <ctime>
#include <boost/random.hpp>

typedef boost::mt19937 randAlgorithm;

int mutationsPerGeneration = 100;
double probabilityOfMutation = 0.05;
string potentialAlleles = "abcdefghijklmnopqrstuvwxyz ";
size_t numberOfAlleles = potentialAlleles.size();

double random01(randAlgorithm & engine)
{
  boost::uniform_real<double> u01;
  return u01(engine);
}

int randomInteger(randAlgorithm & engine, size_t min, size_t max) {
  boost::uniform_int<> minmax(min, max);
  return minmax(engine);
}

string randomCharacter(randAlgorithm & engine, string charSet, size_t charSetSize) {
  return charSet[randomInteger(engine, 0, charSetSize)];
}

string randomString(randAlgorithm & engine, size_t length, string charSet, size_t charSetSize) {
  string s;
  s.reserve(length);
  for (int i = 0; i < length; i++) {
    s.append(randomCharacter(engine, charSet, charSetSize));
  }
  return s;
}

string breedWithMutation(randAlgorithm & engine, string originalGenome, size_t genomeSize) {
  string mutatedGenome;
  mutatedGenome.reserve(genomeSize);
  double mutationDraw;
  for (size_t i = 0; i < genomeSize; i++) {
    mutationDraw = random01(engine);
    if (mutationDraw < probabilityOfMutation) { //The allele undergoes mutation
      mutatedGenome.append(randomCharacter(engine, potentialAlleles, numberOfAlleles));
    }
    else {
      mutatedGenome.append(originalGenome[i]);
    }
  }
  return mutatedGenome;
}

However, when I build the application, I get these errors:
    main.cpp: In function 'std::string randomCharacter(randAlgorithm&, std::string, size_t)':
main.cpp:31:55: error: invalid conversion from 'char' to 'const char*'
main.cpp:31:55: error:   initializing argument 1 of 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]'
main.cpp: In function 'std::string breedWithMutation(randAlgorithm&, std::string, size_t)':
main.cpp:53:45: error: invalid conversion from 'char' to 'const char*'
main.cpp:53:45: error:   initializing argument 1 of 'std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::append(const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>]'

The line numbers in the errors don't line up perfectly, I realise, but the first two errors refer to the only line in randomCharacter, and the third and fourth errors refer to this line: mutatedGenome.append(originalGenome[i]); in breedWithMutation. What is causing this error?

A: In C++, char and string are distinctly different types. One cannot implicitly convert a char value to a string (as you are trying to do in randomCharacter).
You could change the return type of randomCharacter to be char instead of string, though that may require changes elsewhere too (I haven't reviewed your code in detail).

A: Change the return type of randomCharacter() to char.

A: It's not an invalid conversion to const char, it's an invalid conversion to const char*.  Strings in plain C are just arrays of characters, or const char*s.  So, you're using a single character where you should be using a string.
To examine one instance: You've set up randomCharacter() to return a C++ string, but in actuality, you're trying to return a single character from charSet.  It makes more sense to me for you to make the function return a char, but that's your decision to make.


text:
Q: Conflicting module names when using multiple gems (in my case: social_stream and rails3_acts_as_paranoid) I am using those two gems: social_stream (rails engine) and rails3_acts_as_paranoid (lib).
When I try to see the homepage, I get the following error:
NameError in Home#index

Showing /home/pinouchon/code/sharewizz/webapp/app/views/home/index.html.erb where line #25 raised:
uninitialized constant ActsAsParanoid::Relation::Public
Extracted source (around line #25):
22:
23: <%=
24:     render :partial => "activities/index",
25:          :locals => { :activities => current_subject.wall(:home).page(params[:page]),
26:                             :owner => current_subject }
27:  %>
28:

Full trace:
social_stream-base (0.21.0) app/models/relation.rb:159:in `ids_shared_with'
app/models/activity.rb:70:in `block in <class:Activity>'
activerecord (3.2.2) lib/active_record/scoping/named.rb:180:in `call'
activerecord (3.2.2) lib/active_record/scoping/named.rb:180:in `block (2 levels) in scope'
# ...

I think it is because 2 modules defined by those gems share the same name: Relation.
In /home/pinouchon/.rvm/gems/ruby-1.9.3-p392@project/gems/rails3_acts_as_paranoid-0.2.5/lib/acts_as_paranoid/relation.rb:
module ActsAsParanoid
  module Relation
  # ...

In /home/pinouchon/.rvm/gems/ruby-1.9.3-p392@project/gems/social_stream-base-0.21.0/app/models/relation.rb:
class Relation < ActiveRecord::Base
  #...
  def ids_shared_with(subject)
      # line 159:
      ids = [Relation::Public.instance.id]
      # ...

In /home/pinouchon/.rvm/gems/ruby-1.9.3-p392@project/gems/social_stream-base-0.21.0/app/models/relation/public.rb:
class Relation::Public < Relation::Single
  # ...

Before, I was using only social stream, no there were no conflicting modules names. Now, it is as if ActsAsParanoid::Relation is replacing Relation, hence the problem in .../social_stream/.../relation.rb line 159.
But what's surprising is that the Relation module of rails3_acts_as_paranoid is nicely namespaced in module ActsAsParanoid. So it shouldn't interfere with the Relation of social_stream defined in global scope, yet it is. I am probably missing something.
Am I right about what's causing the error ?
Is there any way I can fix that ?

A: By overwriting the model relation defined by social_stream (copying the file to app/models), and changing the line 159:
ids = [Relation::Public.instance.id]

to
ids = [::Relation::Public.instance.id]

Everything works fine. I have no idea why I have to explicitly specify to use the global scope here. I am still open to an explanation or a better answer.


text:
Q: Jetpack Sharing label how to customize it from functions Hello Everyone,
               I am trying to edit the Sharing label text of Jetpack plugin but having a problem to target specific text for example
in jetpack sharing settings there is an option with input field called
Sharing label

to add text before sharing icons. I have written there
Love it? Share it

here i want to add css style of italic and bold to
 Share it

text but cannot do from text field as it not allow html tag. Is there any way i can target this specific share it text using css or function?
Here is piece of code btw with class assigned to that text

Love it? Share it

A: you can replace text by using java script and set css.
add below function in function.php
function myscript() {
?>

<?php
}
add_action( 'wp_footer', 'myscript' );


text:
Q: Spring Boot + Thymeleaf - form validation i have problem with Thymeleaf when validating form. I'm trying to create simple user register form to learn Spring and i'm unfortunately stuck.
Here is my UserForm class
public class UserForm {
    @NotEmpty
    private String username;
    @NotEmpty
    private String password;
    @NotEmpty
    private String passwordConfirm;

    \\ Getters and Setters
}

First problem is  when I add my custom validator class in initBinder
@Autowired
private UserFormValidator formValidator;

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.setValidator(formValidator);
}

"Default" annotated by @NotEmpty validation stops working. This is exptected behavior?
Second problem is how can I show global reject messages in thymeleaf?
My validator class is like below
public class UserFormValidator implements Validator {
    @Autowired
    UserService userService;

    @Override
    public boolean supports(Class<?> clazz) {
        return UserForm.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        UserForm userForm = (UserForm) target;
        if(!userForm.getPassword().equals(userForm.getPasswordConfirm())) {
            errors.reject("passwords.no.match", "Passwords not match");
        }

        if(userService.findOneByUsername(userForm.getUsername()).isPresent()) {
            errors.reject("user.exist", "User already exists (default)");
        }
    }
}

and post mapping from controller
@PostMapping("/create")
public String registerUser(@ModelAttribute("form") @Valid final UserForm form, BindingResult bindingResult) {
    if(bindingResult.hasErrors()) {
        return "newuser";
    }
    userService.saveUser(form);
    return "redirect:/";
}

As "default" validation errors i can show by using exth:if="${#fields.hasErrors('passwordConfirm')}" i have no idea how can i show message for error passwords.no.match or check if this error occured?

A: By default spring boot uses bean validation to validated form object annotated with @Valid. If you want to use your custom validator and register it through @InitBinder, then bean validation will not take place, this is expected behavior. If you want to bean validation also works with your custom validation you need to do it manually inside your validator class or even in controller.
Here comes your second problem to show password not match error message. Inside your custom validator UserFormValidator.class while rejecting any value you need to use rejectValue() method like below:
    @Override
    public void validate(Object target, Errors errors) {
        UserForm userForm = (UserForm) target;
        if(!userForm.getPassword().equals(userForm.getPasswordConfirm())) {
            errors.rejectValue("passwordConfirm", "passwords.no.match", "Passwords not match");
        }

        if(userService.findOneByUsername(userForm.getUsername()).isPresent()) {
            errors.rejectValue("username", "user.exist", "User already exists (default)");
        }
    }

The rejectValue() method is used to add a validation error to the Errors object.
The first parameter identifies which field the error is associated with. The second parameter is an error code which acts a message key for the messages.properties file (or messages_en.properties or messages_fr.properties etc, if these are being used). The third parameter of rejectValue() represents the fallback default message, which is displayed if no matching error code is found in the resource bundle.
Now you can show error messages using th:if="${#fields.hasErrors('passwordConfirm')} inside your form.


text:
Q: MySQL SQL Select Query with Multiple Sub-Selects OK, so this one has had me ripping my hair out for hours.  I feel like there is something obvious I am overlooking.
I have 2 tables,  service and brand
service
-------
id
brand

brand
-----
id
brandName

So service.brand can be any of these:
Blank
"Other"
Integer (matches brand.id)
String (matches brand.brandName)
String (Not Blank, Not Other, Not brand.brandName)

I'm trying to write a query that will pull up the correct brandname from the brand table, and if the value of service.brand is not in brand.id or brand.brandName,  then display whatever is there.
So far I got everything working except it wouldn't pull up the record if service.brand was Not Blank, Not Other, Not in brand.id, Not in brand.brandName. (which I'm calling OtherThanOther from here on out).
Now my latest attempt pulls up mostly correct, but the OtherThanOther field gets pulled up many times,  like if total records is 40,  OtherThanOther is the same record almost 20 times.  HELP!
My latest attempt..
select
    s.*, b.brandName as bname
from
    service s, brand b
where
    s.brand = b.brandName
or
    s.brand = b.id
or
    s.brand = 'Other'
or
    s.brand = ''
or
    (
        s.brand not in (select brandName from brand)
        and
        s.brand not in (select id from brand)
        and
        s.brand != 'Other'
        and
        s.brand != ''
    )

Sample Table Data
service
-------
1 5
2 Dell
3 SomeRandom
4
5 Other

brand
-----

1 HP
2 Gateway
3 Dell
4 Compaq
5 Toshiba

my query results..
(service.id, service.brand, brand.id, brand.brandName, bname)
-------------------------------------------------------------
1 5 5 Toshiba Toshiba
2 Dell 3 Dell Dell
3 SomeRandom, brand.id, brand.brandName, brand.brandName
3 SomeRandom, brand.id, brand.brandName, brand.brandName
3 SomeRandom, brand.id, brand.brandName, brand.brandName
3 SomeRandom, brand.id, brand.brandName, brand.brandName
3 SomeRandom, brand.id, brand.brandName, brand.brandName
4 '', null, null, null
5 Other, null, null, null

I need it to just pull SomeRandom once, group by won't work because there may be multiple fields with the same value as SomeRandom.
Any help is much appreciated.
Thanks!

A: select
    s.*,
    CASE
      WHEN b_id.brandName IS NOT NULL THEN b_id.brandName
      WHEN b.brandName IS NOT NULL THEN b.brandName
      ELSE s.brand
    END as bname
from
    service s
LEFT JOIN brand b_id
ON  CAST(s.brand AS UNSIGNED) = b_id.id
LEFT JOIN brand b
ON  s.brand = b.brandName

A: You are using an old style inner join:
from service s, brand b
where s.brand = b.brandName or ...

More clearly written like:
from service s
inner join brand b on s.brand = b.brandName or ...

In the newer form, the problem immediately stands out.  An inner join filters out unmatched rows.  Use a left join instead:
from service s
left join brand b on s.brand = b.brandName or ...

Now you'll get all services, even if no matching row was found in the brand table.

A: You should JOIN 2 tables with multiple conditions. Something like this:
SELECT s.*, b.brandName AS bname
FROM service AS s
INNER JOIN brand AS b
ON s.brand = b.brandName OR
   s.brand = b.id OR
   s.brand = 'Other' OR
   s.brand = '' OR
   (s.brand NOT IN (SELECT brandName FROM brand) AND
   s.brand NOT IN (SELECT id FROM brand) AND
   s.brand != 'Other' AND
   s.brand != '')

A: First thing - use JOIN!
select s.*, b.brandName as bname
from service s
    LEFT JOIN brand b ON s.brand = b.brandName or s.brand = b.id

Then you can add your sensemaking conditions - for example WHERE NOT s.brand IS NULL
These condotions of you are leading to the result in which your table rows are multiplied with each other:
s.brand = 'Other'
or
    s.brand = ''
or
     (
        s.brand not in (select brandName from brand)
        and
        s.brand not in (select id from brand)
        and
        s.brand != 'Other'
        and
        s.brand != ''
    )


text:
Q: java.lang.ClassNotFoundException: javax.mail.MessagingException I want to send a email from my gmail account to the another mail account using eclipse.I used apache tomcat 7.0.34 as my web server and use port 8080 for apache server(HTTP/1.1) and use JRE 7 as system library and also include mail.jar and activation.jar in Libraries under Java Resources.
In the below my jsp page is given,where the recipient address is entered and submit to the server.
SendMail.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>

        <form action="ControllerMail">
            Recipient Address : <input type="email" name="to" >

            <input type="submit" value="Submit"/>
            <input type="hidden" name="pageType" value="sendmail"/>
        </form>

Now, My servlet class is given below.
ControllerMail.java
package com.sendmail.controller;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ControllerMail extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ControllerMail() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doProcess(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doProcess(request,response);
    }

    protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String pageType = request.getParameter("pageType");
        if(pageType.equals("SendMail"))
        {
            String to = request.getParameter("to");

            //Get the session object
              Properties props = new Properties();
              props.put("mail.smtp.host", "localhost");
              props.put("mail.smtp.socketFactory.port", "465");
              props.put("mail.smtp.socketFactory.class",
                        "javax.net.ssl.SSLSocketFactory");
              props.put("mail.smtp.auth", "true");
              props.put("mail.smtp.port", "465");

              Session session = Session.getDefaultInstance(props,
               new javax.mail.Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication("********@gmail.com","********");//change accordingly
               }
              });

            //compose message
              try {
               MimeMessage message = new MimeMessage(session);
               message.setFrom(new InternetAddress("********@gmail.com"));//change accordingly
               message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
               message.setSubject("Greetings");
               message.setContent("Hi,what's up","text/html");

               //send message
               Transport.send(message);

               System.out.println("message sent successfully");

              } catch (MessagingException e) {throw new RuntimeException(e);}
        }
    }

}

But when I run my project on server that mean when I right click on my SendMail.jsp page and click on "run on server",the following errors are occured.
Mar 17, 2015 7:41:38 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:\Program Files\PC Connectivity Solution\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.7.0_75\bin;F:\Software\JavaMailAPI\activation-jaf1.1.1.jar;F:\Software\JavaMailAPI\java-mail-1.4.4.jar;F:\Software\eclipse-jee-luna-SR1a-win32\eclipse;;.
Mar 17, 2015 7:41:39 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:SendEmail' did not find a matching property.
Mar 17, 2015 7:41:39 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8081"]
Mar 17, 2015 7:41:39 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 17, 2015 7:41:39 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 539 ms
Mar 17, 2015 7:41:39 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 17, 2015 7:41:39 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.34
Mar 17, 2015 7:41:39 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/SendEmail]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/SendEmail]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.NoClassDefFoundError: javax/mail/MessagingException
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Unknown Source)
    at java.lang.Class.getDeclaredFields(Unknown Source)
    at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:87)
    at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:261)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:140)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:67)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:405)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:881)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5173)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.lang.ClassNotFoundException: javax.mail.MessagingException
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    ... 20 more

Mar 17, 2015 7:41:39 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:684)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:451)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

Mar 17, 2015 7:41:39 PM org.apache.catalina.startup.Catalina start
SEVERE: Catalina.start:
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:684)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:451)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more

Mar 17, 2015 7:41:39 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 249 ms

After 45 seconds,there will show a dialog box and it displays "Starting Tomcatv7.0 Server at localhost" encountered a problem.

A: You miss javax.mail-<version>.jar in your classpath. Download it and add it to your classpath. It is possible that you miss also the dependencies of this jar.

A:
java.lang.NoClassDefFoundError: javax/mail/MessagingException

Add the mail.jar for example in your tomcat lib (/catalina_home/commons/libs/) or your web application file (see web-inf/lib).
Also you might need the activation jar.
For latest javax.mail.jar see https://java.net/projects/javamail/pages/Home


text:
Q: How to split a large xml file into several small ones using Mule First, and sorry, Im a mule newb.  Im trying to take a large XML file and split it into multiple files.  I keep running into out of memory exceptions.  I understand that I need to stream so Im not loading everything into memory, but from there my google-fu is letting me down.  So I have the following questions:

*

*Is there a way that I can make this happen without writing code (simply via a mule flow)?

*What are the basic steps?  Not asking for a complete solution, just a push in the right direction please.  Here are the ones that I have tried and failed with:

File (streaming) -> DataMapper (streaming) -> Dom-to-Xml-transformer -> File
File (streaming) -> Splitter (using xpath) -> aggegator -> foreach (Dom-to-Xml-transformer -> File)
Thanks in advance.

A: The current implementation of streaming in DataMapper works only for the output.
If you are receiving an InputStream that you'd like to stream you would need a previous step before DataMapper, which is to use a component or transformer and process that InputStream using SAX. You would actually need to write code.

A: It looks like Mule provides its own implementation of StAX
http://www.mulesoft.org/documentation/display/current/XmlToXMLStreamReader+Transformer
I'm not sure if it works well, but it could definitely be of help for your problem


text:
Q: SQL db2 remove specific item from the query Can you please help me out with the below query?
What I am looking for is a code to exclude items with wording '90003' from column COR_ID.
So far I have a code that extracts data with date older than today from column VAL_DT, excluding items with wordings MAN, NOSTRO, SCREV and SCRIN for which query shows also dates newer than today.
All I need is for the below code is to remove '90003' from column COR_ID
WHERE
    VAL_DT < CURRENT DATE AND COR_ID <> '90003'
    OR (
       MVT_DS = 'NOSTRO'
       OR MVT_DS = 'SCREV'
       OR MVT_DS = 'SCRIN'
       OR MVT_DS = 'MAN'
       )

A: Following WHERE clause shold do the job
WHERE COR_ID <> '90003'
  AND (VAL_DT < CURRENT DATE  OR MVT_DS in ('NOSTRO', 'SCREV', 'SCRIN', 'MAN')  )


text:
Q: How to call make in subdirectories in a certain order? So my project directory structure looks like this:
root/
--logger/
--protos/
--backend/

Directory has a Makefile and the top-level Makefile in root calls all make in each subdirectory:
TOPTARGETS := all clean

SUBDIRS := $(wildcard */.)

$(TOPTARGETS): $(SUBDIRS)
$(SUBDIRS):
    $(MAKE) -C $@ $(MAKECMDGOALS)

.PHONY: $(TOPTARGETS) $(SUBDIRS)

The executable will be in the backend folder and my issue right now is that I want to make the object files in logger and protos before calling make in backend.
How do I enforce an order like this?


text:
Q: Chart js display empty plot I am using chart.js .Bar() charts.
However, on some conditions there may be no data in the system. Short of creating empty (dummy) datasets, can I somehow make chartjs draw an empty plot?

A: Edit: I edited the post to show horizontal lines of an empty graph as @zazu asked for it
In this sample, I set up a Chart.js line graph, providing a first dataset with data (in order to scale the grid vertical axis and make the horizontal lines visible), and a second one with empty data. This results in an empty graph, but with the full grid visible:

var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    // invisible dataset
    {
        label: "",
        fillColor: "rgba(220,220,220,0.0)",
        strokeColor: "rgba(220,220,220,0)",
        pointColor: "rgba(220,220,220,0)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        // change this data values according to the vertical scale
        // you are looking for
        data: [65, 59, 80, 81, 56, 55, 40]
    },
    // your real chart here
    {
        label: "My dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: []
    }
]
};

var options = {
    animation: false,
    ///Boolean - Whether grid lines are shown across the chart
    scaleShowGridLines : true,
    //Boolean - Whether to show vertical lines (except Y axis)
    scaleShowVerticalLines: true,
    showTooltips: false
};

var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, options);
<script src="http://www.chartjs.org/assets/Chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

JSFiddle here.


text:
Q: Example to prove that $ C^1[0,1] $ is not a Banach space for the uniform norm? The space $ C^1[0,1] $- the space of all continuously differentiable functions on $ [0,1]$ is not a Banach space with respect to the sup norm,$ \|.\|_{\infty} $ since the uniform limit of a continuously differentiable function need not be differentiable.
How can I illustate this statement using a counter example? Can I use $ f_{n}=\frac1 n \sin nx $ as a counter example?
Also, is $ C^1[0,1] $ is same as the space given by $ X=\{f\in C^1[0,1]:f(0)=0 \}$. Can I use the same example to show that this is not a Banach space?
More help is appreciated!
Thanks!

A: The example you gave converges uniformly to the zero function, which is continuously differentiable.
Every continuous function on $[0,1]$ is a uniform limit of polynomial functions (by the Weierstrass approximation theorem), and polynomial functions are continuously differentiable.
For an explicit example, you could also consider the sequence $f_n(x)=\left|x-\frac12\right|^{(n+1)/n}$.

I might not fully understand the last question.  Those are not the same, because elements of $C^1[0,1]$ do not generally have to vanish at $0$.  But you can use similar examples.  E.g., you could still think about the Weierstrass approximation theorem for dramatic counterexamples, or you could modify the example above by taking, say, $g_n(x)=f_n(x)-f_n(0)$.

A: The ${\cal C}^1[0,1]$ functions are a dense subset of $\cal{C}[0,1]$ in the sup norm.  However the inclusion is proper so the $\cal{C}^1$ functions are not a complete subspace of ${\cal C}[0,1]$.
The continuous functions on $[0,1]$ that vanish at 0 are a Banach space, they are the kernel of the continuous map $f\mapsto f(0)$.   They form a closed subspace.  But those in ${\cal C}^1[0,1]$ are not.


text:
Q: making vsftpd listen on a specific hostname Is there a way to restrict which hostname(s) vsftpd listens to? I know it can be limited to listening on a particular IP and it fcan be limited by remote ip/hostname, but I wonder if listening only on a specific subdomain or something like that is possible? I'm on Ubuntu.

A: As the FTP protocol does not specifically include the server hostname in requests, this is probably not possible.