text:
Q: Minimal bounding Ellipse and Oval of a Convex Polygon I was searching for a standard equation of an egg like curve that I can tweak and transform to a ellipse and a circle. I found this link with example $x^2+\left(1.4^x 1.6y\right)^2=1$. A generic version looks like the following $$ax^{2}+(\gamma^{x} by)^{2} = c$$ If I put $\gamma=1$ I get a general equation of ellipse. If I plot the example equation given in that site I get an egg shaped curve as shown below. So my first question is, is this equation known to be a generalisation of ellipse and circle ? But this equation doesn't look like to produce convex shapes for all values, there is a relation between $a, b, c$ and $\gamma$ that produces convex shape. That is why I feel like this is even more generalisation of an ellipse.

Now coming to the second part of my question. Given a Convex Polygon I want to find out the tightest ellipse that bounds the polygon. However in sometimes The input polygon may be somewhat like a trapezium, in that case I want the tightest Oval as shown above that fits the polygon inside. I assume if I can fit an oval to a polygon that oval will look like an ellipse if my input polygon is a rectangle. If oval is defined as the equation above how can I find out the smallest such oval that fits a given convex polygon.


text:
Q: Obtaining accessToken for google sign-in (Android) I'm using Google sign-in in my application
the problem is that I want to obtain accessToken to send it to the back end server, but the GoogleSignInAccount dosen't have it
private fun handleGoogleSignInResult(task: Task<GoogleSignInAccount>) {

    task.addOnSuccessListener { googleSignInAccount ->

        // TODO: Obtaining accessToken

    }

    task.addOnFailureListener { e ->
        Timber.e(e)
        showToast(R.string.something_went_wrong_try_again_later)
    }

}

A: I suspect you might have to cast the AuthCredential to OAuthCredential to get the accessToken. Try the below. Note, I did not run this code to verify. Some additional information here: Firebase Docs
private fun firebaseAuthWithGoogle(idToken: String) {
        val credential = GoogleAuthProvider.getCredential(idToken, null)
        val auth = Firebase.auth
        auth.signInWithCredential(credential)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    val user = auth.currentUser
                    val oAuthCredential = credential as OAuthCredential
                    val token = oAuthCredential.accessToken
                } else {
                    // If sign in fails, display a message to the user.
                }
            }
    }

UPDATE
The above fails as casting fails.
Seems like the Android SDK does not provide an easy way to get the access code.
Have a look at this link for another option: GoogleAuthUtil
Beware of some of the info mentioned in the link like running this async etc.
You might be able to get the access token so:
val scope = "oauth2:" + Scopes.EMAIL + " " + Scopes.PROFILE;
                    val account = GoogleSignIn.getLastSignedInAccount(this)
                    val token = GoogleAuthUtil.getToken(this, account?.account, scope)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error while installing FFMPEG under Raspbian (Debian 8 Jessie) I am attempting to get FFMPEG installed on my Raspberry Pi 3 running Raspbian (based on Debian 8 Jessie)
When I run the install command I get:
sudo apt-get install ffmpeg
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
ffmpeg : Depends: libavcodec54 (>= 8:1.0.0) but it is not going to be         installed
          Depends: libavdevice54 (>= 8:1.0.0) but it is not going to be installed
          Depends: libavfilter3 (>= 8:1.0.0) but it is not going to be installed
          Depends: libavformat54 (>= 8:1.0.0) but it is not going to be installed
          Depends: libpostproc52 (>= 8:1.0.0) but 6:0.git20120821-4 is to be installed
E: Unable to correct problems, you have held broken packages.

Has anyone seen this error before? The Debian site states: Be careful, FFmpeg is not available on Debian 8 Jessie.
Is there a way to get FFMPEG installed on Debian 8 Jessie?
UPDATE: I am going through this: https://www.assetbank.co.uk/support/documentation/install/ffmpeg-debian-squeeze/ffmpeg-debian-jessie/
Hopefully this works.
UPDATE:
This got ffmpeg built from source and installed but the script I am running that needs ffmpeg seems to think it should be in user/bin/ffmpeg while its actually installed in user/local/bin/ffmpeg


text:
Q: How does IE8 and below handle media queries I am wondering how IE8 and below react to media queries in CSS.
I'm not looking for a solution for IE8 to render them. I'm just wondering if IE will just ignore them, or if IE will try to parse them.
Background story: we are building a responsive site, but since IE8 and below is rarely to be used on a smaller screen device, we hope IE just ignores media queries. This way IE8 (and below) users always see the "regular sized" version of the site, which is fine.

A: In short, you're exactly right.
IE8 does not support media queries, and will not parse any CSS contained within them.
Therefore, if you want to support IE8 in a responsive site, you should make sure that your default CSS which you want IE8 to use is outside of any media queries.
So the short answer is that what you said in the question is pretty much exactly right.
There are other considerations of course: IE8 isn't the only browser not to know about media queries; some older Android devices and other old phones may also not support them. If you need to support those devices, you may need to consider how to handle it. Fortunately there really aren't that many people browsing the web using those devices, so you can generally ignore them unless you have a specific need.
You also have the option of using a polyfill script like Respond.js, which adds support for media queries to older browsers like IE8. Note that this is a javascript library, so it will only run after the page has loaded, so there may be some delay and screen redrawing involved, which isn't pretty, but it is being used by a lot of sites and with good results, so you may want to consider it.

A: i.e 8 does not support media queries, but these poly fills which makes media queries support to i.e 8 and i.e 7. In fact its a good option to use else you need to show  "regular sized" version of the site? its possible through some hacks i.e conditional comments of css link file and the way you write css code for i.e older browsers, try to override the styles with high css specificity.
note: if you are using html5 add another polyfill Html5shiv hosted by google.
use html5 and media queries like this:
<!--[if lt IE 9><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">            </script>
<script src="js/respond.min.js"></script>
<![endif]-->

Check for polyfills respondjs --- http://responsejs.com/  and css3 media queries --
https://code.google.com/p/css3-mediaqueries-js/
In order to use "regular sized" version.
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="ie8.css" />
<![endif]-->

learn some specs and tips,tricks log on http://www.pointmycode.com/


text:
Q: Determine the primary index of a table in Teradata Is there a command in teradata that returns which column in a table has been defined as the primary index? I didn't make some of the tables im working off of and trying to optimize my joins against those tables. Thanks!

A: There's dbc.IndicesV, where IndexNumber=1 indicates the PI and dbc.PartitioningConstraintsV for partitioning information.
For a single table Iprefer SHOW TABLE tab; because you get the full DDL including indexes & datatypes.
If you DBA's allow it you might also try SHOW SELECT .... to get the DDL od all obects used by that select.

A: You can query DBC table to get this info..
SELECT
databasename, tablename, columnname, indextype, indexnumber, indexname
FROM
dbc.indices


text:
Q: Getting data from the database before form submitting I have a database with users. I can get the users email from the drop-down list to the modal window. using ajax.
The question is how to receive born_date and phone_number of this user via his email in the same modal window, and then send the form for processing. Something doesn't work. What could be the mistake?
DB strcture:

python:
description = ['mymail@gmail','mymail@gmail','uuser@mail.ru','mymail2222@gmail','my1212mail@gmail','11mymail@gmail']

@app.route('/profile', methods=['GET'])
def profile():
    if request.method == 'GET' and 'loggedin' in session:
        cur = mysql.connection.cursor()
        cur.execute("SELECT firstname, lastname, email FROM users.data WHERE description = 'description'")
        account = cur.fetchall()
        description = account
        return render_template('profile.html', id=session['id'], email=session['email'],
                                                firstname=session['firstname'], description=description)

@app.route('/profile', methods=['POST'])
def profile_post():
    data = request.json
    data_list = list(data.values())

    data_list = str(data_list)
    doc_data = data_list.split()[2][:-4]

    cur = mysql.connection.cursor()
    cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = '%s'" % doc_data.replace("'", ""))
    account = cur.fetchone()

born = account[0]
num = account[1]

    print('Got data:', data)
    return jsonify({
        'status': 'SUCCESS',
        'data': data,
    })

return render_template('profile.html', id=session['id'], born=born, num=num)

html
<select id='sel' name='sel' class="selectpicker sel" multiple data-live-search="true" onchange="optionClick(this)">
    {% for descr in description%}
        <option id="val" value="{{descr}}">{{ descr }}</option>
    {% endfor %}
</select>
<button type="button" class="btn btn-primary" onclick="process();">
    Process
</button>

Information about user

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Born date is: {{ born }}

Phone number is: {{ num }}

        <button class="btn btn-primary">
            Send Data
        </button>

A: Without your printing out what your actual argument is for the email address I can't be sure what the error is, but since you are not getting an exception I can only guess you are using a value that does not exist on the database and hence you are not separating the email address out correctly from the input using what amounts to:
email_address = data_list.split()[2][:-4].replace("'", "")

So my suggestion is to make the following changes:
In the HTML:
Change value="{{descr}}"> to value="{{descr['email']}}">:
<select id='sel' name='sel' class="selectpicker sel" multiple data-live-search="true" onchange="optionClick(this)">
    {% for descr in description%}
        <option id="val" value="{{descr['email']}}">{{ descr }}</option>
    {% endfor %}
</select>

In that way only the email address is going to be sent back up when the Ajax call is made.
Your Python code then becomes:
data = request.json
email_address = data['selectedItems'][0] # the first email address selected
cur = mysql.connection.cursor()
cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = %s", (email_address,))
account = cur.fetchone()

I believe because you have a multi select dropdown that you will be sent up a list of values even if the list only contains a single item and that's why I have specified data['selectedItems'][0]. Of course, the obvious question is if the user has selected multiple email addresses, your code does not seem to handle this, so I don't know why you have made this a multi select dropdown. Note also that I am using a prepared statement so SQL Injection attacks should no longer be a problem.


text:
Q: Image slideshow will not function properly I'm making an image slideshow/carousel where there are play, pause, and stop buttons. When you press play, the images are expected to change every 1 second. But once it gets to the last picture, it will not go back to image number one. Is there any reason for this? There are 19 photos and they will move in order. Each photo has the same URL except for the end of the link where it changes according to its sequence in the 19 orders.
    <script>
  var count = 1;
  let mainElement = document.querySelector("div.main>.imgSub");
  let URL = "https://www.takushoku-u.ac.jp/summary/images/summary_successive-chancellor_img_";
  let thumbnailsElement = document.querySelector("div.thumbnails");
  thumbnailsElement.children[count-1].classList.add('selected');
    function next() {
        if (count < 19) {
          count++;
            if (count < 10) {
               console.log("count:" + count);
                x = URL + "0" + count + ".jpg";
            } else {
                x = URL + count + ".jpg";
            }
        } else {
            count = 1;
            x = URL + "0" + count + ".jpg";
        }
        mainElement.setAttribute('src', x);
        thumbnailsElement.children[count].classList.remove('selected');
        thumbnailsElement.children[count-1].classList.add('selected');
        thumbnailsElement.children[count-2].classList.remove('selected');
    }
    function prev() {
        if (count > 1) {
            if (count < 10) {
                count--;
                x = URL + "0" + count + ".jpg";
            } else {
                count--;
                x = URL + count + ".jpg";
            }
        } else if (count == 19) {
            count = 1;
            x = URL + count + ".jpg";
        }
        mainElement.setAttribute('src', x);
        thumbnailsElement.children[count].classList.remove('selected');
        thumbnailsElement.children[count-1].classList.add('selected');
        thumbnailsElement.children[count-2].classList.remove('selected');
    }
    //play stop reset buttons
    let timer;
    let nowPlaying = false;
    function autoPlay() {
      next();
      timer = setTimeout(function() {autoPlay();}, 1000);
    }
    function play() {
      if (nowPlaying == true) {
        return;
      }
      nowPlaying = true;
      autoPlay();
    }
    function stop() {
      clearTimeout(timer);
      nowPlaying = false;
    }
    function reset() {
      stop();
      thumbnailsElement.children[count].classList.remove('selected');
      thumbnailsElement.children[count-1].classList.remove('selected');
      count = 1;
      thumbnailsElement.children[count-1].classList.add('selected');
      URL = URL + "01.jpg";
      mainElement.setAttribute('src', URL);
    }
</script>

A:

thumbnailsElement.children[count-2].classList.remove('selected');

This line will give an error when the value of count is 1. So, considering your code, move 'count++' at the end of if-else statement i.e

  if (count < 19) {
      if (count < 10) {
         console.log("count:" + count);
          x = URL + "0" + count + ".jpg";
      } else {
          x = URL + count + ".jpg";
      }
  } else {
      count = 1;
      x = URL + "0" + count + ".jpg";
  }
    count++;    //changed statement
    mainElement.setAttribute('src', x);
    thumbnailsElement.children[count].classList.remove('selected');
    ...

Also i think there is an error in prev() function, in else if statement. It should be,

 else if (count == 2) {
    count = 19;
    x = URL + count + ".jpg";
}

there is 2 instead of 1, since count never becomes 1 in next() function


text:
Q: How to compare the case of two strings in Clojure? I have a Clojure function autocomplete that takes in a prefix and returns the possible autocompletion of that string. For example, if the input is abs, I get absolute as the possible complete word.
The problem is that the function does a case-insentitive match for the prefix so if I have Abs as the prefix input, I still get absolute instead of Absolute.
What would be the correct way to get the final string completion that matches the case of the original prefix entered?
So, a function case-match that could work like
(case-match "Abs" "absolute")  => "Absolute"

A: You can use the prefix string as the prefix to the case-insensitive search result. Just use subs to drop the length of the prefix from the search result:
(defn case-match [prefix s]
  (str prefix (subs s (count prefix))))

(case-match "Abs" "absolute")
=> "Absolute"

This assumes your autocomplete function stays separate, and case-match would be applied to its result.

A: also, you can go with startsWith
(defn case-match
  [prefix s]
  (when (.startsWith (clojure.string/lower-case s)
                     (clojure.string/lower-case prefix))
       s))

(case-match "Abs" "absolute")
#=> "absolute"
(case-match "Absence" "absolute")
#=> nil


text:
Q: Change Zlib version in android project Recently I found that archive-patcher library isn't working in android 12, and then I found that android 12 used the new version of Zlib that is changed a little and the problem is for that.
Is it possible to explicitly link my own zip version in my project?


text:
Q: Is there an RXJS standard for creating/handling HTTP streams? Simply put, I constantly hit roadblocks with RXJS because almost every example relies on a constant stream of data whereas I'm making HTTP requests that are singular in nature.
My common scenario is as such: I have a service that makes API calls and updates the necessary consumers. In my head, it's like simple event emitting. The subscribers connect and wait for the event - once they get it, they go off and do their own thing separately.
The problem, as I'm sure you're aware, is that HTTP subscriptions terminate immediately upon completion and to "connect" triggers it immediately. It's a concept of RXJS that I still struggle to wrap my head around.
So when you throw in concurrent calls to the method, consumers relying on other consumers, forkjoins and asynchronous hell - I've tried all sorts of abominations involving Subjects, replays, shared maps. I've ultimately settled on something like so:
myBehaviorSubject = new BehaviorSubject<Result>(null);
myBehaviorSubject$ = myBehaviorSubject.asObservable()
...
getData(params): Observable<Result[]> {
      const http$ = this.httpClient
        .get('blah', {params})
        .pipe(map(response => response as Result[]));

      http$.subscribe(result: Result => {
         myBehaviorSubject.next(result);
      });

      return myBehaviorSubject$;
    }

It feels...wrong. I know things like mergeMap handle internal subscriptions similarly and higher order observables aren't anti-pattern, but I can't help but think I'm just doing it wrong.
Is internal subscriptions really the way to do this? Are there ways too keep consumers waiting for HTTP requests without making redundant calls to the server?
Can anyone shed some light on this matter?

A: I go against the norm with http requests.  They aren't streams to me.
async getData(params): Promise<Result[]> {
    return this.httpClient
        .get('blah', {params})
        .toPromise();
}

Or:
async loadComplexViewModelData(params): Promise<{[dataA, dataB, dataC]}> {
  [dataA, dataB, dataC] = await Promise.all([
    this.httpClient
      .get('blahA', {params})
      .toPromise();
    this.httpClient
      .get('blahB', {params})
       .toPromise();
    this.httpClient
      .get('blahC', {params})
      .toPromise();
  ]);
}

Above doesn't include error handling or nesting..  Maybe request blahB returns keys you then need to fetch.  Append a then() statement to toPromise().
This is an alternative that is contrary to popular pattern and does't specifically answer stated question.
This is how I solved the "It feels...wrong" delima I had as well. I don't think rxjs is the right tool for the job, and I am in the minority :)


text:
Q: Feature selection based on information gain papers I want to apply feature selection based on information gain: I have many features many of which are redundant. I am planning on selecting a feature and then iteratively add features that 'add the more information'. Is there any relevant paper I should read to get familiar with such methods?

A: If many of your features are redundant I would propose performing PCA. This will eliminate the redundancies while retaining the variance in the data. You can find numerous example/explanations of this with a google search. Also, consider reading this post (Basic question on PCA: can it be used to divide original features into groups?)
Here is an excellent text that covers the area of feature selection (and many others): http://www.stanford.edu/~hastie/local.ftp/Springer/OLD/ESLII_print4.pdf
A quick google search also shows numerous papers, for example http://www.ijitee.org/attachments/File/v2i2/B0352012213.pdf


text:
Q: Wordpress Ajax Custom Query - High CPU LOAD I'm developing a fully AJAX community WP theme that comes with a lot of custom queries.
Everything is fine, there is no bug but recently but I had a few client that have a huge database and my theme started to kill CPU. I wonder how can I make it more faster.
What this code is doing?
This code is  trying to get posts that contains only have "comment" type comments (comment_type="comment") AND approved ones.
database information: Mysql - mariaDB
table name I'm trying to get result - wp_comments
how many data that table have - 380.000 (380K) comments
query's raw output time on phpmyadmin (w/o php) - 0.23 seconds
time to get this data on front end - 0.85-90 seconds
JS Code that calls function
    function lfload(page) {
  $("#sol-load").css("opacity","0.75");
  document.cookie = "lf= popular;  expires = Fri, 31 Dec 9999 23:59:59 GMT; path=/";
  document.cookie = "popular_page = " + page + ";  expires = Fri, 31 Dec 9999 23:59:59 GMT; path=/";
  var xhr = new XMLHttpRequest();
  xhr.open("POST", bilgi.tema_url + '/admin-ajax.php', true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
      document.getElementById("sol-load").innerHTML = this.response;
      $("#sol-load").css("opacity","1");
  }
  }
  xhr.send("action=popular_ajax");
}

PHP Code to get data
function popular_ajax()
  {
          global $wpdb;
           // getting latest page from cookie
          if (isset($_COOKIE["popular_page"]) AND
          $_COOKIE["popular_page"] != 0) {
              $latest_sent_page_no = intval($_COOKIE["popular_page"]);
          } elseif (!isset($_COOKIE["popular_page"]) OR
           $_COOKIE["popular_page"] == 0) {
              $latest_sent_page_no = 1;
          }
          $page = $latest_sent_page_no;
          $cur_page = $page;
          $page -= 1;
          $per_page = 20;
          $start = $page * $per_page;
          $count_limiti = $per_page*50;
          // tried to limit count
          //query to make it more faster but did'nt work
          // count how many page exists to use it for pagination
          $count = $wpdb->get_var("SELECT COUNT(DISTINCT comment_post_ID)
           FROM ".$wpdb->prefix."comments
           USE INDEX (left_frame_index)
           WHERE comment_approved = 1
           AND comment_type = 'comment'
           LIMIT $count_limiti");
          $sorgu = $wpdb->get_results("SELECT DISTINCT comment_post_ID
            FROM ".$wpdb->prefix."comments
          USE INDEX (left_frame_index)
          WHERE comment_approved = 1
           AND comment_type = 'comment'
           GROUP BY comment_post_ID
           ORDER BY MAX(comment_date)
           DESC LIMIT $start, $per_page");
          // GET DATA FROM SQL
          foreach($sorgu as $goflying2){
              // Çıktı bölgesi
              $msg .= "
comment_post_ID) ."'
                title='".get_the_title($goflying2->comment_post_ID)."'>
                ".get_the_title($goflying2->comment_post_ID)."
                " .clean_comment_count_wo_newbies($goflying2->comment_post_ID).
                "
";
          }
          wp_reset_postdata();
          // SAY THERE IS NO DATA IF ITS EMPTY
          if ($count == 0) {
            echo '

            '.__("gündemimiz boş...", 'hype-community').'
';
              exit;
          }
          // PAGINATOIN STARTING HERE
          $no_of_paginations = ceil($count / $per_page);
          $start_loop = 1;
          $end_loop = $no_of_paginations;
          //conditional pagination
          if ($cur_page > 1) {
              $pre = $cur_page - 1;
              $pag_container .= "
              <button onclick='gundemNav(this)' value='$pre' class='button is-small'>

              </button>
              ";
          }

          $pag_container .= "

        <button class='button is-small ml-3 mr-3 dropdown-trigger
        has-fullwidth' aria-haspopup='true' aria-controls='dropdown-menu5'>
           $cur_page

            </button>
              ".'

';
      // tried to limit for loop
          if ($end_loop > 50) {
              $end_loop = 50;
          }
          for ($i = $start_loop; $i <= $end_loop; $i++) {
            // loop to print all page numbers
              if ($cur_page == $i) {
                  $pag_container .= "$i";
              } else {
                  $pag_container .= "$i";
              }
          }
          $pag_container = $pag_container . "

";
          if ($cur_page < $no_of_paginations) {
            //conditional pagination output
              $nex = $cur_page + 1;
              $pag_container .= "
              <button onclick='gundemNav(this)' value='$nex' class='button is-small'>

              </button>
              ";
          }
          if ($no_of_paginations == 1) {
            //conditional pagination output
              print     '
' . $msg .
              '
';
          } elseif ($cur_page == 1 and $no_of_paginations >= 2) {
            //conditional pagination output
              print     '
' . $msg .
              '
';
              echo  '
              <button onclick="gundemNav(this)" value="'. $nex .'"
              class="button is-small is-bg-blue has-text-white is-fullwidth mt-3">

                '.__("fazlasını yükle", 'hype-community').'
              </button>
              ';
          } elseif ($cur_page != 1 and $no_of_paginations > 1) {
              //conditional pagination output
              echo
           '
'.$pag_container .
            '
'. // pagination
          '
' . $msg .
          '
'; // content that called from wpdb get results
          }
          // kill ajax
          exit;
  }

INDEX I used in this query
left_frame_index -> commenst_post_ID, comment_date, comment_approved, comment_type

How can I make it more faster, more stable. Is there something wrong with my SQL code or PHP code? This code is really killing the CPU...
Without this index, query is around 0.5 seconds (phpymyadmin exec. time. 1.5 seconds when calling with AJAX).
Thank you and sorry for my bad English! ^_^


text:
Q: Can Ghostscript print pages in different order than input with -sPageList I want to print with Ghostscript pages in different order than input with the handle -sPageList. Though gs prints the pages in consecutive order. For e.g. gs -o output.pdf -sPageList 1,13-14,3-7 input.pdf the ouptut is in the concecutive order 1,3-7,13-14. Is it a mistake? How can this be solved?

A: No. PagesList cannot execute pages out of order.
You can use Ghostscript to produce pages in a different order, but it requires some PostScript programming to alter the behaviour of the PDF interpreter and is not a supported usage (ie we might change the way the PDF interpreter works, and since its not supported we wouldn't feel the need to tell anyone)


text:
Q: Disconnect from Openstack? I am writing python code on top of the openstack shade library.
Connecting to a stack is pretty straight forward:
return shade.openstack_cloud(cloud='mycloud', **auth_data)

Now I am simply wondering: is there a canonical way to disconnect when I am done?
Or is the assumption that my script ending will do a "graceful" shutdown of that connection; not leaving anything behind?

A: OpenStack works on a RESTful api model. This means the connections are stateless, i.e. it makes a HTTP connection when you do your request, and closes that connection when the request is finished.
The above code simply initialises things by reading your config, authentication data, etc. A connection is not made until you do something with that object, e.g. create an image:

image = cloud.create_image(   'ubuntu-trusty',
  filename='ubuntu-trusty.qcow2', wait=True)

In summary, no, you don't need to disconnect, shade's underlying code will take care of closing connections.


text:
Q: Marker size unit proportionnal to the axis values I have an X Y Z dataset.
X and Y are the 2D coordinates and Z is the intensity.
I plot the data using the scatter function:
markerSize=100;
scatter(x,y,markerSize,z,'s','fill');

I use the options 's' and 'fill' to get filled squares.
My problem is the markerSize value corresponds to the area of the marker, and its unit is points (1/72 of one inch).
The marker size is constant, even if I resize the figure plot. So that the gap between the data points increases when I increase the figure size.
What I would like is a constant marker size which is a constant of the axis unit. For instance, the marker size should be 5x5 (5 in X axis and 5 in Y axis).
Thanks for your help.

A: You want to make the size of markers proportional to the figure size.
The size of markers is controlled by SizeData parameter of the scattergroup object. The size of figure is stored in Position parameter of the figure object. The difficult part is to interactively resize the marker when the figure size is changed. So you need to use ResizeFcn callback and call setmarkersize function that you define.
function [ ] = setmarkersize( src, evnt )

    % # get position of the figure (pos = [x, y, width, height])
    pos = get(src, 'Position');
    % # get the scattergroup object
    h = get(get(src,'children'),'children');
    % # resize the marker
    relativesize = 0.5;
    set(h,'SizeData', pos(3)*relativesize);

end
================================================
% # attach the callback to figure
f = figure('ResizeFcn', @setmarkersize);
h = scatter(x,y,markerSize,z,'s','fill');

A: You will have to set the marker size manually according to the actual figure size on screen. Using axes property Position you can convert data units to relative figure units. In the next step this size can be converted to the absolute size in points on screen. With that information you can set the marker size accordingly. In the following code snippet I've set the x/y axis limits and width/height of the axis to identical values, because the square marker area can only be calculated reasonably if the marker width is equal to the marker height.
Set marker size relative to data units
% test data
x = [25*rand(1,10) 2.5];
y = [25*rand(1,10) 2.5];
z = [rand(1,10) 0.5];

% relative marker size in squared normalized figure units
marker_rel = 5;

%% Set relative marker size (approximately)
scatter(x,y,100,z,'s','fill');

% Set identical x/y limits and set axes height=widht, so that markers
% really represent squares in data units
xlim([0 25]);
ylim([0 25]);
set(gca, 'Units', 'Points');
axpos_pt = get(gca, 'Position');
axpos_pt = [axpos_pt(1) axpos_pt(2) min(axpos(3:4)) min(axpos(3:4))];
set(gca, 'Position', axpos_pt);

grid on;
grid minor;

% Set marker size relative to data units
markerSize = (marker_rel * axpos_pt(3) / diff(xlim))^2;
set(get(gca, 'children'), 'sizedata', markerSize);

As it turns out, the displayed marker size is slightly smaller than expected. Obviously, there's some bounding box of unknown (at least to me) size, see here.
An alternative approach is to plot rectangles "manually" as shown in the following code snippet (same test data is used). When the figure is resized, the rectangles are resized as well without any special callback function being needed.
Draw rectangles manually
%% Use rectangles (exact)
figure;
axes;
cmp = colormap;
z_range = max(z) - min(z);
line_style = 'none'; % set to '-' to make the edges visible
for k = 1:length(x)
    x_pos = x(k) - marker_rel/2;
    y_pos = y(k) - marker_rel/2;
    w = marker_rel;
    h = marker_rel;
    color = cmp( round(((z(k) - min(z))/z_range)*(length(cmp) - 1)) + 1, : );
        rectangle('Position', [x_pos y_pos w h], 'FaceColor', color,...
          'LineStyle', line_style);
end
grid on;
grid minor;

The above code produces the desired marker size:

In general, these are no squares. They can (and will) only be squares if xlim = ylim and absolute height of axis = absolute width of axis. I have shown in my first code snippet how to achieve this.

A: I found an answer on the Matlab central forum which does not use the useful dsxy2figxy function. Here is the link to it (link)
The code is the following:
x = rand(1,50);
y = rand(1,50);
s = 5; %Marker width in units of X
h = scatter(x,y); % Create a scatter plot and return a handle to the 'hggroup' object
%Obtain the axes size (in axpos) in Points
currentunits = get(gca,'Units');
set(gca, 'Units', 'Points');
axpos = get(gca,'Position');
set(gca, 'Units', currentunits);
markerWidth = s/diff(xlim)*axpos(3); % Calculate Marker width in points
set(h, 'SizeData', markerWidth^2)

A: The answer by ysakamoto doesn't work in Matlab 2014, where Mathworks changed figure handles from double to object. The following modification makes it work again:
function [ ] = setmarkersize( src, ~ )
% get position of the figure (pos = [x, y, width, height])
pos = get(src, 'Position');
% marker size
relativesize = 0.01;
% axes is not necessarily the only child of figure (e.g. colorbar may be first)
for i = 1:numel(src.Children)
    if strcmpi(src.Children(i).Type, 'axes')
        % make marker size depend on figure width
        src.Children(i).Children.SizeData = pos(3) * relativesize;
        break
    end
end
end

Also, when creating the figure it will not set the marker size to the correct value until resized. So call setmarkersize explicitly:
f = figure('ResizeFcn', @setmarkersize);
...
setmarkersize(f)

A: Consider abandoning 'markers' and drawing directly on the axis using rectangles or circles. The 'rectangle' command with 'curvature' set to [1 1] is essentially an open circle. Units are in plot units, so each rectangle can be scaled:
rectangle('position', [rectCentX rectCentY widthInPlotUnits, heightInPlotUnits],'curvature',[1 1])


text:
Q: How to find if a large Number is even or odd? I was asked an interview question.How to find if a  very large number(more than the range of double) is odd or even?
I replied : Store the number in the array and find if the last digit is divisible by two.
public static boolean isEven(int[] verLargeNum)
{
    int size=verLargeNum.length;
    if(verLargeNum[size-1]%2!=0)
        return true;
    else
        return false;
}

My question is: Is there a better approach ?

A: if your number doesn't have a decimal part, you can simply do a bit operation
If(MyBigNumber & 0x1) {
     odd
} else {
    even
}

A: Your answer looks correct, alternative way:
Since they are not specifying if the very large number has a primitive type or not, you can assume that the number acts as int, double, long etc...
String largeNumber = VERY_LARGE_NUMBER + "";
boolean isEven(String input){
    return Integer.parseInt(input.charAt(input.length()-1)+"")%2 == 0;
}


text:
Q: Refused to load the image '' I am trying to load images in my index.ejs as bellow

      <img src="<%=imageBaseUrl+movie.poster_path %>" alt="">

imageBaseUrl set as:

imageBaseUrl="http://image.tmdb.org/t/p/w300";

But I am getting error as Refused to load the image '' because it violates the following Content Security Policy directive: "img-src 'self' data:".
console error image
What should I do to resolve this error ?


text:
Q: Weighted Adjacency matrix igraph and R I would kindly ask you for your help. I have a data structure similar than the one bellow:
  ID    Name
  1      A
  2      B
  1      C
  1      B
  2      C
  2      D
  3      A
  3      B

The "ID" column, is a unique identifier for a paper, and the "Name" column stands for the name of an author that has a collaboration in a paper. I need to produce an undirected, weighted Adjacency Matrix. The nodes(or vertex) in the matrix will be pairs of authors (ij) in the "Name" column. The weighted values in the matrix (ij, i≠j) will be given by the sum of a collaboration ratio, using an algorithm that I can describe with an example:
For instance, pair A-B, in the data above, has two collaborations together in paper "1" and "3". Further, paper 1 has 3 collaborators (A,B,C); and paper 3 has 2 collaborators (A,B). The weight for the node AB will be the sum of the inverted number of collaborators minus 1 for each paper in column ID from which A and B has participated together. i.e.,
                                    Paper 1          Paper 3
                   Collaborators   A, B, C = 3      A, B = 2
                   Weight          1 / (3 - 1)     1 / (2 - 1)

Sum of the Weight(AB) = (1/2)+(1) = (3/2)
Note that if if A and B has collaborated in a paper the numerator will be one, otherwise 0.The key of the algorithm would be to compute this sum for each pair of authors in column "Name" and produce a weighed adjacency matrix.
Thank for your help and suggestions
Mario.

A: What you have is a bipartite graph, and you need the unipartite projection of it. This is easy:
## Sample data
data <- "  ID    Name
  1      A
  2      B
  1      C
  1      B
  2      C
  2      D
  3      A
  3      B
"

## Read it in an edge list
el <- read.table(textConnection(data), header = TRUE)

## Create the bipartite graph from it
G <- graph.data.frame(el, directed = FALSE)
V(G)$type <- grepl("[0-9]+", V(G)$name)
G
#> IGRAPH UN-B 7 8 --
#> + attr: name (v/c), type (v/l)
#> + edges (vertex names):
#> [1] 1--A 2--B 1--C 1--B 2--C 2--D 3--A 3--B

## Project it to authors (and papers)
G_one <- bipartite.projection(G)

## You only need the authors
GA <- G_one[[1]]

## Create an adjacency matrix form it
GA[]
#> 4 x 4 sparse Matrix of class "dgCMatrix"
#>   A B C D
#> A . 2 1 .
#> B 2 . 2 1
#> C 1 2 . 1
#> D . 1 1 .


text:
Q: How do I expand factors in a column into multiple columns - essentially shortening the dataset by half? How do I break/split the "strike" column into two columns, "kick_type" and "punch_type", and the "damage" column to "kick damage" and "punch damage"?
I have been at this for 3 hours now and I can't figure out how to split this. Note that I've used pivot_longer to come to this stage from untidy format where the strikes were all columns, so I've done other steps before but can't figure this out.
Reproducible code:
trial <- data.frame(fighter=c("Saenchai","Saenchai","Saenchai","Saenchai","Buakaw","Buakaw","Buakaw","Buakaw"),
strike=rep(c("roundhouse_kick","side_kick","lefthook_punch","uppercut_punch")),
damage=c(0.7,0.8,0.6,0.3,0.9,0.5,0.7,0.1))

It should look like this, but I don't know how to get there:
fighter   kick_type         kick_damage   punch_type      punch_damage
Saenchai  roundhouse_kick   0.7           lefthook_punch  0.6
Saenchai  side_kick         0.8           uppercut_punch  0.3

A: I'm sure there are better ways, but here's a non-regex friendly way:
library(tidyverse)

trial %>%
  pivot_wider(names_from = "strike", values_from = "damage") %>%
  pivot_longer(ends_with('kick'), names_pattern = '(.*)_kick', names_to = "kick_type", values_to = "kick_damage") %>%
  pivot_longer(ends_with('punch'), names_pattern = '(.*)_punch', names_to = "punch_type", values_to = "punch_damage") %>%
  group_by(fighter) %>%
  filter(row_number() == 1 | row_number() == n())

# A tibble: 4 x 5
# Groups:   fighter [2]
  fighter  kick_type  kick_damage punch_type punch_damage
  <chr>    <chr>            <dbl> <chr>             <dbl>
1 Saenchai roundhouse         0.7 lefthook            0.6
2 Saenchai side               0.8 uppercut            0.3
3 Buakaw   roundhouse         0.9 lefthook            0.7
4 Buakaw   side               0.5 uppercut            0.1

Another simpler way is to use separate:
trial %>%
  separate(strike, into = c("type", "move")) %>%
  group_by(fighter, move) %>%
  mutate(n = row_number()) %>%
  pivot_wider(c(fighter, n), names_from = move, values_from = c(type, damage))

# A tibble: 4 x 6
# Groups:   fighter [2]
  fighter      n type_kick  type_punch damage_kick damage_punch
  <chr>    <int> <chr>      <chr>            <dbl>        <dbl>
1 Saenchai     1 roundhouse lefthook           0.7          0.6
2 Saenchai     2 side       uppercut           0.8          0.3
3 Buakaw       1 roundhouse lefthook           0.9          0.7
4 Buakaw       2 side       uppercut           0.5          0.1

A: Solution with data.table (inspired by @Maël answer)
library(data.table)

# data.table
trial <- data.table::data.table(fighter=c("Saenchai","Saenchai","Saenchai","Saenchai","Buakaw","Buakaw","Buakaw","Buakaw"),
                                strike=rep(c("roundhouse_kick","side_kick","lefthook_punch","uppercut_punch")),
                                damage=c(0.7,0.8,0.6,0.3,0.9,0.5,0.7,0.1))

# pivot_wider() equivalent
trial <-  dcast(trial, fighter~strike, value.var="damage")

# pivot_longer() equivalent, punch
trial <- data.table::melt(data          = trial,
                            id.vars       = c("fighter",
                                              "roundhouse_kick","side_kick"),
                            measure.vars  = c("lefthook_punch",
                                              "uppercut_punch"),
                            value.name    = "punch_damage",
                            variable.name = "punch_type")

# pivot_longer() equivalent, kick
trial <- data.table::melt(data          = trial,
                            id.vars       = c("fighter", "punch_damage","punch_type"),
                            measure.vars  = c("roundhouse_kick","side_kick"),
                            value.name    = "kick_damage",
                            variable.name = "kick_type")

# Select first and last row by fighter
trial <- trial[
  j = .SD[unique(c(1,.N))],
  by = c("fighter")
]

A: Another tidyverse approach here.
library(tidyverse)

trial %>%
  separate(strike, sep = "_", into = c("type", "attack")) %>%
  pivot_wider(everything(), names_from = attack, names_glue = "{attack}_{.value}",
              values_from = c("type", "damage"), values_fn = list) %>%
  unnest(cols = !fighter) %>%
  select(fighter, kick_type, kick_damage, punch_type, punch_damage)

# A tibble: 4 × 5
  fighter  kick_type  kick_damage punch_type punch_damage
  <chr>    <chr>            <dbl> <chr>             <dbl>
1 Saenchai roundhouse         0.7 lefthook            0.6
2 Saenchai side               0.8 uppercut            0.3
3 Buakaw   roundhouse         0.9 lefthook            0.7
4 Buakaw   side               0.5 uppercut            0.1


text:
Q: Custom Excel VBA Function with return type as Date I have a workbook with multiple sheets. Except for the Summary Sheet, all other sheets have a dynamic range of consecutive cells (within a column) that stores some Date formatted values. I need to select that range dynamically and choose the Largest Date Value. The Function should return that value.
Here's what I was trying:
Function GetMSDate(Counter As Integer, DesignCtrs() As String, NumOfVendors() As Long,
          MSDesc() As String, PlanOrActual As String) As Date
    GetMSDate = Application.Max(ThisWorkbook.Worksheets(Counter + 1).Range("A:A")
            .Find(PlanOrActual, SearchOrder:=xlByColumns, searchDirection:=xlNext)
            .EntireRow
            .Find(MSDesc(1), SearchOrder:=xlByColumns, searchDirection:=xlNext)
            .Offset(1, 0).Address & ":" & _
            ThisWorkbook.Worksheets(Counter + 1).Range("A:A")
            .Find(PlanOrActual, SearchOrder:=xlByColumns, searchDirection:=xlNext)
            .EntireRow
            .Find(MSDesc(1), SearchOrder:=xlByColumns, searchDirection:=xlNext)
            .Offset(NumOfVendors(Counter) + 1, 0).Address)
    MsgBox GetMSDate
End Function

My intent was that I would define the dynamically constructed Range for the Application.Max() argument. In doing so, finding the range anchor, I choose the correct sheet (Counter+1 allows that correctly); then find a specific "predefined" string in the first column; select the entire row of the found cell and find within that range another predefined string; the range is then defined from the cell below that anchor cell to an offset defined by: NumOfVendors(Counter)+1
In running the above, it gives me:

Type Mismatch error at the "GetMSDate = " statement.

A: To debug, assign your value to a variant variable and then output the typename() of that variable after the assignment.   It should tell you why it is not accepting date.
Function GetMSDate(Counter As Integer, DesignCtrs() As String, NumOfVendors() As Long, MSDesc() As String, PlanOrActual As String) As Date
    Dim v as Variant

    v = Application.Max(ThisWorkbook.Worksheets(Counter +
        1).Range("A:A").Find(PlanOrActual, SearchOrder:=xlByColumns,
        searchDirection:=xlNext).EntireRow.Find(MSDesc(1), SearchOrder:=xlByColumns,
        searchDirection:=xlNext).Offset(1, 0).Address & ":" & _
    ThisWorkbook.Worksheets(Counter + 1).Range("A:A").Find(PlanOrActual,
        SearchOrder:=xlByColumns, searchDirection:=xlNext).EntireRow.Find(MSDesc(1),
        SearchOrder:=xlByColumns, searchDirection:=xlNext).Offset(NumOfVendors(Counter)
        + 1, 0).Address)
    debug.print v
    debug.print TypeName(v)
    stop
    MsgBox GetMSDate
End Function


text:
Q: Unicode characters in string Python I have Pandas Series with list of games names, for example:

*

*\u3010\u6226\u8266\u3011Warship Saga \u30a6

*\u22c6Spider Solitaire+

*\u25bbCHESS

I want to remove all Unicode characters that are "unprintable" (so desirable outcome supposed to look like this - Warship Saga, Spider Solitare+, CHESS)
I tried to do his
 data['Name'] = data['Name'].str.encode('ascii').str.decode('ascii')
but it didn't help
Also just decoding didn't help.
data['Name'] = data['Name'].str.decode('ascii')
Thank you in advance!

A: This works for me, in python 3, by adding 'ignore' as a parameter
string = '\u3010\u6226\u8266\u3011Warship Saga \u30a6'
string = string.encode('ascii', 'ignore').decode('ascii')
print(string)

Out:
Warship Saga

For the whole column:
data['Name'] = data['Name'].str.encode('ascii', 'ignore').str.decode('ascii')

A: I tried this, let me know if it helps ;)
s= "\u3010\u6226\u8266\u3011Warship Saga \u30a6"
my_string = [chr(i) for i in ([(ord(c)) for c in s])]
for i in my_string:
    if type(i) == str:
        try:
            print(i.encode('utf-8').decode('ascii'))
        except:
            pass


text:
Q: Sourcecode syntax highlighting with Code Folding I know there are many syntax highlighting scripts in Javascript for adding syntax highlighting to source code, I am looking to see if such a thing exist with the addition of having Code Folding like many IDE's have.
Do you know if anything exist like that?

A: Thanks to Wikipedia, I found CodeMirror, which is not only a syntax highlighter, but also a code editor. However, according to the following code folding demo, you can use it just as a viewer.
It's written in Javascript and it supports a lot of languages (full list here).


text:
Q: Java :: Parsing a multiline text with regular expressions I want to parse a multiline text, so I wrote something like this:
String text = "[timestamp1] INFO - Message1 \r\n"
            + "[timestamp2] ERROR - Message2 \r\n"
            + "[timestamp3] INFO - Message3 \r\n"
            + "Message3_details1......... \r\n"
            + "Message3_details2 ......... \r\n";
String regex = "\\[(.*)\\] (.*) - (.*)";
Pattern p = Pattern.compile(regex, Pattern.DOTALL);
Matcher m = p.matcher(text);
while (m.find()) {
    System.out.println("G1: " + m.group(1));
    System.out.println("G2: " + m.group(2));
    System.out.println("G3: " + m.group(3));
    System.out.println();
}

What I want to get is this:
G1: timestamp1
G2: INFO
G3: message1

G1: timestamp2
G2: ERROR
G3: message2

G1: timestamp3
G2: INFO
G3: message3
    message_details1....
    message_details2...

But what I get is like this:
G1: timestamp1] INFO - Message1
    [timestamp2] ERROR - Message2
    [timestamp3
G2: INFO
G3: Message3
    Message3_details1........
    Message3_details2........

I'm not able to solve that even with Google's help.

A: You have used greedy quantifier in your regex. So, .* in [(.*)] will consume everything till the last found ]. You need to use reluctant quantifier. Add a ? after .*.
Also, for the last .*, you need to use a look-ahead, to make it stop before the next [.
The following code would work:
String text = "[timestamp1] INFO - Message1 \r\n"
            + "[timestamp2] ERROR - Message2 \r\n"
            + "[timestamp3] INFO - Message3 \r\n"
            + "Message3_details1......... \r\n"
            + "Message3_details2 ......... \r\n";

String regex = "\\[(.*?)\\] (.*?) - (.*?)(?=\\[|$)";

Pattern p = Pattern.compile(regex, Pattern.DOTALL);
Matcher m = p.matcher(text);
while (m.find()) {
    System.out.println("G1: " + m.group(1));
    System.out.println("G2: " + m.group(2));
    System.out.println("G3: " + m.group(3));
    System.out.println();
}

The last part of the regex - (.*?)(?=\\[|$) matches everything till the [ in the next line, or till the end ($). $ is required for the last two lines to be captured in group 3 of the last match.
Output:
G1: timestamp1
G2: INFO
G3: Message1

G1: timestamp2
G2: ERROR
G3: Message2

G1: timestamp3
G2: INFO
G3: Message3
Message3_details1.........
Message3_details2 .........

A: try "\\[(.*?)\\] (.*?) - (.*?) \\r\\n"


text:
Q: Increasing the server configured values for client timeouts I am using log4j to maintain logs. so generally insert query gets executed to store logs details. i get the below exception only if the table contains more than 800 records. if i truncate table, insert query runs but fail to run if there are 800 + records
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet success
fully received from the server was 176,705,355 milliseconds ago.  The last packet sent successfully to the server was 176,705,366 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.


text:
Q: Is there an image service from GOES available for ArcGIS? I have an arcmap project using an arcims service from NOAA ENC (http://ocs-spatial.ncd.noaa.gov) but maybe the service is unavailable right now and I can't access to imagery...
Is there an image service from GOES available for ArcGIS?

A: Check out a new attempt by NOAA to display all ENC data.
http://ocs-gis.ncd.noaa.gov/encdirect/viewer.html
This was introduced recently (Early Sept 2012) and looks a lot better than the old one! There is also talk on exposing most of these as WMS and Rest services. This will go prime-time and replace the old site sometime in Jan next year. Uptime for ENC direct has been an issue and I am not sure if the new site will alleviate this.
Your best best is to build a local solution using the freely downloadable S-57 data from NOAA and apply the rendition rules defined in S-52. This is analogous to HTML and CSS, where any map server that you host (MapServer, GeoServer, ArcGIS) can render layers you are interested in by you defining Style Layers.
Depending on what specific layers you are looking in GOES server you may be able to find them in other places or map catalogs.


text:
Q: TimesTen: Cannot connect to TimesTen daemon I'm trying to create a prototype application using TimesTen insted of home written IMDB. When I install TimesTen, TimesTen Data Manager service is hosted and also few subdaemons and server. Everything seems fine, but ttDaemonAdmin refuse to connect to main daemon. When I kill the process from Task Manager I can run it with ttDaemonAdmin, but after that none command isn't working. Every time I get a "Unable to connect to daemon. Check daemon status", but it indicates that there is a daemon proces ("Daemon pid 3576 port 53396 instance tt1122_64").
Same thing happens when I try to run ttStatus and ttModInstall command, so I can't change port number or any other option.
What could be a problem? Is it possible that port is blocked or something? I'm logged as user with admin privileges, but timestend proces owner is SYSTEM.
I tried every imaginable solution I could find in oracle documentation, but nothing seems to work. Please help!
Thanx in advance,
Nikola

A: try use you timesten install user.
ttisql "dsn= tt1122_64"

if you use network connect way.
use
ttisqlcs "dsn= tt1122_64"

try check
1. TNS_ADMIN
2.ORACLE and timesten lib
3.sys.odbc.ini
4.tnsnames.ora


text:
Q: How to avoid issues with Maven builds on Travis CI which don't occur locally? I'm regularily using Travis CI and noticed multiple issues with forked projects the last weeks when building on Travis which do not occur locally or on the Travis instance of the forked project. I made sure that I used the the same Maven version which imo is all that can be different from the Travis CI environment since both Maven and Java are portable across platforms. Travis runs Ubuntu 12.04 or 14.04 which I do as well (17.04).
In detail I experienced:

*

*The failure to retrieve a SNAPSHOT version which I could retrieve with the same Maven version locally after deleting ~/.m2/repository and moving ~/.m2/settings.xml aside (see Why fails Travis CI to retrieve a SNAPSHOT artifact when retrieval works locally? for details)

*[ERROR] Failed to execute goal org.jacoco:jacoco-maven-plugin:0.7.5.201505241946:check (default-check) on project commons-numbers-complex: Coverage checks have not been met. repeatedly which doesn't happen on their master branch (which I added to the aggregator of my project)

I'm not looking for solutions to the issues here, but to any explanation how this could make any sense in order to broaden my understanding of Travis and Maven in a cross-platform environment.

A: Have you pinned all plugins you use in Maven? You should first fix your build issues like : [WARNING] 'parent.relativePath' of POM org.apache.commons:commons-numbers-parent:1.0-SNAPSHOT (/home/travis/build/document-scanner/document-scanner-aggregator/commons-numbers/pom.xml) points at richtercloud:document-scanner-aggregator instead of org.apache.commons:commons-parent, please verify your project structure @ org.apache.commons:commons-numbers-parent:1.0-SNAPSHOT, /home/travis/build/document-scanner/document-scanner-aggregator/commons-numbers/pom.xml, line 19, column 11?
Is there a good reason why you rebuild apache-commons-numbers and not using the released versions of them?


text:
Q: How to override the thread pool in Spring Boot app I am writing below code to override the thread pool. But it is not working properly. What is the correct way to set override the thread pool in spring boot app startup. Note that i don't have a control in my code over the Server instance, so instantiating a Server is not a solution for my need.
        @Bean
        public EmbeddedServletContainerCustomizer getContainerCustomizer() {
            return (configurableEmbeddedServletContainer) -> {
                if (configurableEmbeddedServletContainer instanceof JettyEmbeddedServletContainerFactory) {
                    ((JettyEmbeddedServletContainerFactory)configurableEmbeddedServletContainer).addServerCustomizers((server) -> {
                        QueuedThreadPool newPool = new QueuedThreadPool(10);
                        QueuedThreadPool oldPool = server.getBean(QueuedThreadPool.class);
                        server.updateBean(oldPool, newPool);
                    });
                }
            };
        }

When i execute the code, it was throwing below error
Exception in thread "main"
java.util.concurrent.RejectedExecutionException: org.eclipse.jetty.io.ManagedSelector@1ee0005 id=0 keys=0 selected=0
    at org.eclipse.jetty.util.thread.QueuedThreadPool.execute(QueuedThreadPool.java:377)
    at org.eclipse.jetty.io.SelectorManager.execute(SelectorManager.java:125)
    at org.eclipse.jetty.io.SelectorManager.doStart(SelectorManager.java:255)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:106)
    at org.eclipse.jetty.server.AbstractConnector.doStart(AbstractConnector.java:260)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:81)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:244)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:384)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)

I tried by sample main code also, and it is also giving same error.
public class FileServer
{
    public static void main(String[] args) throws Exception
    {
         Server server = new Server(9090);

        QueuedThreadPool newPool = new QueuedThreadPool(10);
        QueuedThreadPool oldPool = server.getBean(QueuedThreadPool.class);
        server.updateBean(oldPool, newPool);

        ResourceHandler resource_handler = new ResourceHandler();

        resource_handler.setDirectoriesListed(true);
        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
        resource_handler.setResourceBase(".");

         HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
        server.setHandler(handlers);

         server.start();
        server.join();
    }
}

A: Here is an example of configuring a thread pool in Jetty with properties and a different type of thread pool. The thread pool in my case is InstrumentedQueuedThreadPool.
@Configuration
public class CustomJettyConfiguration {

    @Bean
    public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(
            @Value("${server.port:8080}") final String port,
            @Value("${jetty.threadPool.maxThreads:600}") final String maxThreads,
            @Value("${jetty.threadPool.minThreads:10}") final String minThreads,
            @Value("${jetty.threadPool.idleTimeout:5000}") final String idleTimeout) {
        final JettyEmbeddedServletContainerFactory factory =
                new JettyEmbeddedServletContainerFactory(Integer.valueOf(port));

        // Tweak the connection pool used by Jetty to handle incoming HTTP connections
        InstrumentedQueuedThreadPool instThreadPool =
                new InstrumentedQueuedThreadPool(registry);
        instThreadPool.setPrefix("jetty");
        instThreadPool.setMaxThreads(Integer.valueOf(maxThreads));
        instThreadPool.setMinThreads(Integer.valueOf(minThreads));
        instThreadPool.setIdleTimeout(Integer.valueOf(idleTimeout));
        factory.setThreadPool(instThreadPool);

        ...
        return factory;
    }
}

A: In spring boot 2.x, the JettyEmbeddedServletContainerFactory has been replaced by org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory.

A: You need to customize JettyServletWebServerFactory and set your own thread pool.
@Component
public class JettyConfiguration implements WebServerFactoryCustomizer<JettyServletWebServerFactory> {

    @Override
    public void customize(JettyServletWebServerFactory factory) {
        // customize your thread pool here
        QueuedThreadPool qtp = new QueuedThreadPool(80, 500);
        qtp.setName("jettyThreadPool");
        factory.setThreadPool(qtp);
    }
}


text:
Q: Load GeoJSON file into redshift using copy command I have a file containing spatial data that I would like to load into Tableau using AWS. I found documentation that Amazon Redshift supports GeoJSON data through the GEOMETRY data type. I managed to upload the data into an S3 bucket and to create a table in my Redshift cluster through the following query:

CREATE TABLE public.data (
  PC6 VARCHAR(100),
  Aantal_adr INTEGER,
  geometry GEOMETRY,
  Gemeente2019 INTEGER,
  Wijk2019 INTEGER,
  Buurt2019 INTEGER
);

However, when I want to load the GeoJSON file from S3 into the table, the table remains empty and I don't even get an error. How do I get it to work?
I used the following command:
COPY public.data
FROM 's3://path/folder/data.json'
CREDENTIALS 'aws_access_key_id=x;aws_secret_access_key=y'
json 'auto'
region 'eu-west-1';
And this is a sample of my data:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "PC6": "1011AB", "Aantal_adr": 32, "Gemeente2019": 363, "Wijk2019": 36304, "Buurt2019": 3630400 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 4.905027952000069, 52.378425486000026 ], [ 4.905076113000064, 52.37841046300008 ], [ 4.905191411000033, 52.378376782000032 ], [ 4.905214767000075, 52.378369010000029 ], [ 4.905234707000034, 52.378360745000066 ], [ 4.905242522000037, 52.37835616600006 ], [ 4.905248247000031, 52.37835098000005 ], [ 4.905251343000032, 52.378345312000079 ], [ 4.905252578000045, 52.378339070000038 ], [ 4.905252531000031, 52.378332431000047 ], [ 4.905249474000072, 52.378312360000052 ], [ 4.905248898000025, 52.378300391000039 ], [ 4.905250074000037, 52.378294856000082 ], [ 4.905252799000039, 52.378289789000064 ], [ 4.905257110000036, 52.37828554400005 ], [ 4.905262918000062, 52.378281792000053 ], [ 4.905272242000024, 52.378277568000044 ], [ 4.905295016000025, 52.378270656000041 ], [ 4.905320961000029, 52.378264933000082 ], [ 4.90534841300007, 52.378259781000054 ], [ 4.905615848000025, 52.378213457000072 ], [ 4.905672094000067, 52.378204254000082 ], [ 4.905713623000054, 52.378198448000035 ], [ 4.905755373000034, 52.378193294000027 ], [ 4.905797334000056, 52.378188918000035 ], [ 4.905854017000024, 52.378184793000059 ], [ 4.906010385000059, 52.378175414000054 ], [ 4.906049546000077, 52.378171835000046 ], [ 4.906099170000061, 52.378165687000035 ], [ 4.906138697000074, 52.378159097000037 ], [ 4.906179196000039, 52.378151124000055 ], [ 4.906393302000026, 52.378105836000032 ], [ 4.906379850000064, 52.378077200000064 ], [ 4.906376915000067, 52.37806777000003 ], [ 4.906375354000033, 52.37805852300005 ], [ 4.906375845000071, 52.37805008600003 ], [ 4.906379084000037, 52.378043095000066 ], [ 4.906385125000043, 52.378038245000027 ], [ 4.906393308000077, 52.378034955000032 ], [ 4.906413366000038, 52.378029843000036 ], [ 4.906448001000058, 52.378023854000048 ], [ 4.906689757000038, 52.377990125000053 ], [ 4.906724868000026, 52.37798340900008 ], [ 4.906734994000033, 52.377980573000059 ], [ 4.90674369200002, 52.377977198000053 ], [ 4.906750343000056, 52.377973046000079 ], [ 4.906754179000075, 52.377967886000079 ], [ 4.90675559500005, 52.37796090900008 ], [ 4.906755038000028, 52.377952553000057 ], [ 4.906749900000023, 52.377933764000034 ], [ 4.906733622000047, 52.377896754000062 ], [ 4.906462646000023, 52.377214200000026 ], [ 4.906126387000029, 52.377292057000034 ], [ 4.905688946000055, 52.377410774000055 ], [ 4.905016945000057, 52.377587847000029 ], [ 4.90462009700002, 52.377724772000079 ], [ 4.904597594000052, 52.377732947000027 ], [ 4.904546418000052, 52.377751543000045 ], [ 4.904483645000028, 52.377774349000049 ], [ 4.904388632000064, 52.377808869000035 ], [ 4.904220272000032, 52.377870038000026 ], [ 4.904280897000035, 52.377932213000065 ], [ 4.904695869000022, 52.378344313000071 ], [ 4.904749813000024, 52.378331915000047 ], [ 4.904708505000031, 52.378356860000054 ], [ 4.904782821000026, 52.378430663000074 ], [ 4.904842127000052, 52.378489556000034 ], [ 4.905027952000069, 52.378425486000026 ] ] ] } } ] }

A: Loading GeoJSON directly into a GEOMETRY column is not currently supported. However, we will consider adding to our roadmap. When new features are released they are noted in our regular maintenance announcements at the top of the forum.

You can only COPY to GEOMETRY columns from data in text or CSV format. The data must be in the hexadecimal form of the extended well-known binary (EWKB) format …
  https://docs.aws.amazon.com/redshift/latest/dg/copy-usage_notes-spatial-data.html


text:
Q: Compiling with Xamarin Studio for Linux or Mac Good morning. I just switched from Visual Studio to Xamarin Studio. I really like the interface and the multiplatform support but I have a question.
I already published an application but these are the files:
OpenTK.dll
AppTest.exe
OpenTK.xml

https://i.stack.imgur.com/mcMIL.png (image)
I was expecting multiplatform compiling in this .NET Console Application but I just got windows executables.
I want to compile my game to Windows, Linux, and Mac (without needing java) but do I need a Linux partition or Virtual box to compile for Linux and the same for Mac (at least I have one of those)
Thanks.


text:
Q: Can I install grub2 on a flash drive to boot both BIOS and UEFI Well, obviously I can, because all of the Linux distros are delivered as hybrid ISOs that can boot both BIOS and UEFI.
The question is how? I had thought I could run grub-install twice:
grub-install --target=i386-pc --recheck --boot-directory=/mnt/boot /dev/sdX
grub-install --target x86_64-efi --efi-directory /mnt --boot-directory=/mnt/boot --removable

and that it would install both. However, doesn't one clobber the other?
When it comes down to it, I don't understand enough of what grub installs in the MBR (BIOS or UEFI mode) to know. In theory, UEFI shouldn't care about the MBR itself, but just unsure.
FYI, running grub-install off of an Ubuntu LiveCD in VirtualBox because, well, because it was there.

A: You can try this tuto_by_sysmatck_ubuntuforums.org
First Step: Format USB drive
To create a EFI firmware compatible boot drive, you need a GPT partition table and at least one FAT32 partition. Do as follows...
sudo apt-get install gdisk
sudo sgdisk --zap-all /dev/sdb

You probably need to remove and insert the USB drive again at this point for the kernel to update information about it...
sudo sgdisk --new=1:0:0 --typecode=1:ef00 /dev/sdb
sudo mkfs.vfat -F32 -n GRUB2EFI /dev/sdb1

Second Step: Copy files and Set directory structure
Let's mount the usb drive
sudo mount -t vfat /dev/sdb1 /mnt -o uid=1000,gid=1000,umask=022

To make life easier, I created a pack with all necessary files for you to modify as you need usb-pack_efi. If you don't trust my files, create yours using  this page as reference.
Extract the zip file and paste those inner files using Command Line Interface or a file manager you like.
cd ~/Downloads/
unzip usb-pack_efi.zip
rsync -auv usb-pack_efi/ /mnt

The most important files are bootia32.efi to boot on 32bit machines, bootx64.efi to boot on 64bit machines and grub.cfg to setup grub to load ISOs or chainload to other paths.
In the end, you might get a directory tree like this:

Third Step: Install GRUB2 on the drive
sudo grub-install --removable --boot-directory=/mnt/boot --efi-directory=/mnt/EFI/BOOT /dev/sdb

Fourth Step: Setup ISOs to be loaded
Put (copy) the .iso files you want to load in /mnt/iso/ and setup grub.cfg like the existing examples...
Note that the most important variable to set is isofile. There is lots of examples on the web about how to configure grub2 menu. Use # to comment those lines you don't want to use, e.g. to hide a configuration of absent .iso at /iso.
Last Step: Configure firmware and Test
First and most important, deactivate secure boot on your computer's firmware. Search on the web if you don't know how.
To boot the USB drive you can set your machine firmware to search first for the USB device (boot order). Or you can choose what drive to boot as soon as you turn on your computer. Each manufacturer has its own keys to do it. Search for your machine's manual if needed.
thank you sysmatck

A: Yes, you can just install Grub2 EFI and Legacy side by side. They don't clobber each other and the ordering doesn't matter.
The precondition for this to work is that you use GPT partitioning and that you have an BIOS boot partition (1 MiB is enough).
Otherwise, the legacy MBR Grub2 install will fail since there isn't enough space for its intermediate stage.
The Grub2 install commands look like this - to install into the MBR:
grub2-install --target=i386-pc /dev/sdb

And to install into the EFI system partition (ESP) it's either (after the ESP is mounted under /boot/efi)
grub2-install --target x86_64-efi

or, on Fedora-like distributions it's instead:
dnf reinstall grub2-efi-x64 shim-x64

(grub2-install works there too, but needs an additional package and breaks secure boot)


text:
Q: Multiple variables in a message box I'm looking to present multiple variables into a messagebox: ID, Customer Name, Date Added, Venue and Status. At the moment, I can only get the ID to display, the other variables present a Runtime 13 Error. My code is below.
Sub LookupTicket()
Dim ibox, tid As Range
Dim dad, sta, ven, cna As Variant

Set Sheet = Worksheets("ControlSheet")

dad = Range("DateAdded_CS").Value
sta = Range("Status_CS").Value
ven = Range("Venue_CS").Value
cna = Range("CustName_CS").Value

ibox = InputBox("Enter Ticket ID:", "Redeem Ticket")
If ibox <> "" Then
Set tid = Sheet.Range("A:A").Find(ibox)
If tid Is Nothing Then
    MsgBox "Ticket ID not found!", vbCritical, "Redeem Ticket"
Else
'MsgBox "Ticket details for ID: " & tid & vbNewLine & "Date Added: " & dad & vbNewLine & "Customer Name: " & cna & vbNewLine & "Venue: " & ven & vbNewLine & "Status: " & sta, vbInformation, "Lookup Ticket Details"
MsgBox "ID: " & sta, "Lookup Ticket"
End If
End If

Thanks guys for any input.

A: The variable tid is a Range. You should change that to tid.Value if its going to have a single cell.
edit: Check if tid.count = 1 I get a type mismatch (13) error when trying to value out of a group of cells in a range. Your Range.Find(ibox) might be returning more than one value.


text:
Q: When undoing a downvote on Area 51, reputation is not re-calculated Somebody downvoted my post (on Area 51) and then they changed their mind. They "un-downvoted" it, and the count went back to 0. I had lost two reputation when they downvoted me, but when they "un-downvoted" my post, I didn't get my reputation back. Is this meant to be like this, or is this a glitch? How do I get my reputation back?
Edit:
I tried triggering the reputation recalc, and nothing happened.

A: Area 51 is running on  a very old codebase of Stack Exchange.
Back when it was built, reputation was not calculated when votes were removed, only added.
The only way to synchronize the reputation on Area 51 is to visit the reputation audit page,  scroll to the bottom and click the "Trigger Reputation Recalc" button:

Note: this will also remove all reputation gained on proposals that have been deleted, even years after it happened. You might lose thousands of reputation by doing that.


text:
Q: How to display a button for each row in a table I have a MySQL database of booking records and I am displaying this in an HTML table. I was wondering how to add a button in every row of the table that will allow me to delete that row from the database.

<!DOCTYPE html>

 All bookings

              ID
              First name
              Surname
              Date
              Time
              Action

            <?php
                if($result->num_rows>0){
                    while($row = $result->fetch_assoc()){
                        echo
                        "
".
                        "". $row['id'] . "	" .
                        "". $row['firstName'] . "	" .
                        "". $row['surName'] . "	" .
                        "". $row['date'] . "	" .
                        "". $row['timeSlot'] . "	" .
                        "
";
                    }
                } else{
                    echo 'no bookings';
                }
            ?>

A: You'll need to add a cell with a URL that has code configured to run a DELETE command in your database. This is typically what atomic ID's are used for. Lets assume the above table is in a file called table.php. Given this, we can adjust your first table cell to the following:
...
"". $row['id'] . "
Delete Row	" .
...

Now when you click this link you'll have a GET variable assigned in the $_GET superglobal array called "deleteId" that you can use to delete the row.
You'll want to place this above your table so that any deletions reflect in the table each time you reload the page.
if (isset($_GET['deleteId'])) {
  // Sanitize input for SQL injection risk
  $deleteId = $mysqli->real_escape_string($_GET['deleteId'])

  if (!is_null($deleteId)) {
    // Just an example, you will need to correct this query and optionally use parameters vs. directly putting the variable in the SQL string
    $mysqli->query("DELETE FROM ... WHERE id = '$deleteId'");
  }
}

A: Bedlams suggestions seems like a good solution.
However I would recommend to NOT delete anything from your database. I would add a column to my table 'Removed' with an integer 0 or 1.
1 = deleted
0 = not deleted (default)
When clicking the button in the table it updates the selected row's removed to 1.

A: I use bootstrap so this example uses that library.
If you want to add a confirmation modal, just simply replace bedlam's a href to something like:
Delete Row

Then add a button in that modal that will handle the deletion logic. You can use bedlam's a href in that modal.
<button type="button" id="delete">Delete</button>

You'll need to add some javascript to get the dynamic modal. Something like:
$("#whateveridyougiveyourmodal").on("shown.bs.modal", function(event){
    var id = $(event.relatedTarget).data('id');
    $(this).find("#id-hidden-input").val(id);
});

$("#delete").click(function(event){
    var id = document.querySelector("input[name='id']").value;
    // POST ID TO DELETE FOR EXAMPLE I'LL USE AJAX
    $.ajax({
        type: "POST",
        data:{data: id},
        url: "WHERE YOU WANT TO HANDLE DELETION LOGIC.php",
        success:function(result){
            console.log(result);
        }
    });
});

In your "WHERE YOU WANT TO HANDLE DELETION LOGIC.php" you'll want to accept the POST data with the super global "$_POST", or in this case "$_POST['data']".


text:
Q: send a broadcast from logcat how can i send broadcast from logcat result like send broadcast if activity start (it taged with activity manager)
like if browser start the logcat will display that :
09-10 09:47:04.020: I/ActivityManager(2707): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.android.browser/.BrowserActivity } from pid 2880

there are app in market do like what is ask for which called
LogCatNotifier
https://play.google.com/store/apps/details?id=RabiSoft.LogCatNotifier&hl=en

A: If what you're asking is how do you know when to send a broadcast when something specific is logged, you should have a Service monitor the device's logs, and when it encounters a log that you want to send a broadcast about, then you should send a broadcast.
You can learn about reading from logs programmatically here
EDIT: If I'm not mistaken, in JellyBean it's no longer possible to read logs from any app besides your own.


text:
Q: Apex Trigger Optimization? enter code hereI have a trigger which sends out an email to a Responsibility Lead (basically an user) , when an responsibility lead in planned revenue (custom object) is not the same as of logged in user.
I have written the below piece of code. However wanted to see if it needs any further optimization.
trigger SendEmail on Revenue__c (after insert,after update) {
    List<String> emailIds = new List<String>();
    Set<Id> plnId = new Set<Id>();
    User usr = [select id from User where id = :UserInfo.getUserId()];
    List<Id> empIds = new List<Id>();
    if(Trigger.isInsert){
        for(Revenue__c p: [SELECT Id,Employee__c,Employee__r.T1C_Base__User__c, FROM Revenue__c WHERE id IN :Trigger.new AND Employee__r.T1C_Base__User__c!=:usr.id]){
            empIds.add(p.Employee__r.User__c);

        }
    }
    else If (Trigger.isUpdate){
        for(Revenue__c plnrev :Trigger.new){
            if(trigger.oldMap.get(plnrev.Id).Employee__c != plnrev.Employee__c){
                 for(Revenue__c p: [SELECT Id,Employee__c,Employee__r.User__c FROM Revenue__c WHERE id =:plnrev.Id])
                {
                    empIds.add(p.Employee__r.User__c);

                }
            }
        }
    }
    List<Employee__c> e = [SELECT Id, __c FROM Employee__c WHERE User__c =:empIds ];
    for (Employee__c emp : e) {
        emailIds.add(emp.Email__c);
        if (emp.User__c != usr.id) {
        EmailUtils.sendEmail(emailIds,plnId);
        }
    }
}

A: You should consider using a trigger framework
To move the logic out of your trigger itself.
This has a few benefits, like making testing easier (and more independent) and letting you be able to call this code from somewhere else. When your logic is inside of a triggger, it can only be called by causing the trigger to be executed (via DML)
There are several frameworks you can explore, like Kevin O'Hara's, the Lightweight Apex Trigger Framework from Chris Aldridge, Hari Krishnan's, and likely others.
Your query on the User object does nothing
You're using Userinfo.getUserId() to get an Id to let you query for the User Id that you already have.
The query isn't doing anything for you here (except using a precious query that could be better used elsewhere).
You seem to be sending emails in a loop
for (T1C_Base__Employee__c emp : e) {
    emailIds.add(emp.T1C_Base__Email__c);
    if (emp.T1C_Base__User__c != usr.id) {
      SC_GBM_EmailUtils.sendEmailPlanRev(emailIds,plnId);
    }
}

Looks like you may have meant to call SC_GBM_EmailUtils.sendEmailPlanRev() outside of the loop. We're only allowed 10 sendEmail calls in a transaction, so this is really something you should get a collection for and call outside of all loops.
You have a query in a loop
else If (Trigger.isUpdate){
    for(Planned_Revenue__c plnrev :Trigger.new){
        if(trigger.oldMap.get(plnrev.Id).Employee__c != plnrev.Employee__c){
             for(Planned_Revenue__c p: [SELECT Id,Employee__c,Employee__r.T1C_Base__User__c,GBM_Client_Plan__c FROM Planned_Revenue__c WHERE id =:plnrev.Id])
            {

Use the iterate-gather-query approach to make this nested loop (with a query) into two separate loops so that you don't waste queries. This recent canonical-qa question should help.


text:
Q: Play music across pages? So currently I have a simple template I use across all pages. It goes something like this:

My website

    <audio controls>
      <source src="music.mp3" type="audio/mpeg">
    </audio>

Content

Where the
Content
 is located, is the different content I have. One page has the history of our music group, and the other page has images of our instruments, for example, between the
 tags.
The thing is, every time someone navigates between the pages on our site, the music stops. How would I link the
 to load across the site without stopping the music? I heard there is a way of using AJAX to do this sort of thing, but I cannot find a way to implement it so that the
 appear on all site and never unloads?


text:
Q: Fill with @row_number based on group field in QGIS 3 Is there a way to fill the table with a row number so that count will restart as new group (identified by a separate column) starts? As a result, "row number" column will restart the count when the new attribute value for a group is found, and will produce row number (1,2,3 etc.) record within this group.
This post on stack overflow  seems to answer my question, but SQL in QGIS does not allow such statements (DENSE_RANK) (or it does but I don't know how?).

A: Do you need to use a field calculator? If not, the "Add autoincremental field" algorithm from the processing toolbox does what you want including the grouping.

References:

*

*How to Add Auto Increment Field in QGIS

A: If you know the row number of the beginning of each group, you can create a group_row_number field in the Field Calculator with a simple case when statement.
In my example, I have groups A, B, C and D. Group A is rows 1-4. Group B is rows 5-8. Group C is rows 9-12. Group D is rows 13-17.
Field Calculator expression:

Result:

The generalized formula is:
case
  when "groupfieldname" = 'first group name' then @row_number
  when "groupfieldname" = 'second group name' then @row_number - [final_row_number_of_first_group]
  when "groupfieldname" = 'third group name' then @row_number - [final_row_number_of_second_group]
  ...
end

A:
Credits to @Gabriel De Luca from his answer
https://gis.stackexchange.com/a/364575/99589

In the Field Calculator use the following expression:
array_find(array_agg($id, "group"), $id) + 1

where "group" is an attribute that will restart the count when a new group appears.

A: You can also do this with QGIS 3 field calculator more easy:
array_find(array_agg("GROUPFIELDNAME"||'_'||-$id,"GROUPFIELDNAME"),"GROUPFIELDNAME"||'_'||-$id)+1

Replace "GROUPFIELDNAME" with the name of your field you want to group by.


text:
Q: iMessage sharing and changing AppleID My husband and I recently split up. Both our phones and both our iPads were all on his Apple ID. Would I be notified on my phone if he were checking my iMessages? I have recently created my own Apple ID and changed my phone and iPad to that. Would that be enough to ensure he cannot access my messages and information? I'm asking because he had said he was able to read my messages if he wanted to but I would be notified

A: There is no feature to allow someone to sign in to a second Apple ID, so unless he guessed your new Apple ID and new password, he's not receiving your messages.
You could enable two factor authentication to ensure no one easily signs in as you. There are forensic and legal ways to read people's messages - but they are generally complicated or costly.
Most of this is explained at https://appleid.apple.com and if there is something specific you don't get - you can ask a new question more narrowly focusing on one aspect of privacy since the site works best with one question per question.
In summary, unless your husband (or ex) has installed key logging software on a computer, you should be able to prevent them from receiving any messages for you by changing your Apple ID password and making sure the phone company has a separate account for your devices.

A: Yes, if he had your AppleID and password, and tried to log into iMessage with it, your phone will pop up with a notification that says that a new device has connected to your imessage. This is what I got when I synced my new iPad with my imessage account.


text:
Q: Ejabberd installation failed to create cookie file in h: on Windows 10 In the past there was an older installation of ejabberd which worked on this machine, but after replacing it with a newer version (17.04), the installation throws an error as the post installation script fails. This is the error encountered by the post installation script -  "Kernel pid terminated (application_controller) ({application_start_failure,kernel,{{shutdown,{failed_to_start_child,net_sup,{shutdown,{failed_to_start_child,auth,{"Failed to create cookie file 'h:/."

A: Somehow, this solved my issue from Command Prompt run as administrator.
cd C:\Program Files\RabbitMQ Server\rabbitmq_server-3.5.6\sbin

C:\...\rabbitmq-server-3.5.6\sbin> SET HOMEDRIVE=C:
C:\...\rabbitmq-server-3.5.6\sbin> rabbitmq-service remove
C:\...\rabbitmq-server-3.5.6\sbin> rabbitmq-service install
C:\...\rabbitmq-server-3.5.6\sbin> rabbitmq-plugins.bat enable rabbitmq_management
C:\...\rabbitmq-server-3.5.6\sbin> net start RabbitMQ


text:
Q: How to remove .php extension from URL on server and on localhost with .htaccess file? Like the title says I need to remove the .php from a URL with a .htaccess RewriteRule.
https://example.com/about.php

should be
https://example.com/about

AND
localhost:8080/about.php

should be
localhost:8080/about

Here is my current .htaccess file:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [NC,L]
</IfModule>

A: You may use these rules in your site root .htaccess:
RewriteEngine On

# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]

## To internally rewrite /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

A: You can add this to your .htaccess file, it will remove .php extension from the URL:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]


text:
Q: WPF - Binding in XAML to an object created in the code behind Can an object created in the code (ie C#) be used for binding in the XAML?
For example:
public class MyForm
{
    private MyComplexObject complexObject;

    public MyForm()
    {
        InitializeComponent();
    }

    public OnButtonClick(object sender, RoutedEventArgs e)
    {
        complexObject = new MyComplexObject();
    }
}

complexObject is not created till a button is clicked.  But once that button is clicked I would like to have a text box that is bound to complexObject.ID start showing the Id.
I would like to do that in the XAML if that is possible.
Can this be done?  If so, how?

A: Yes, this can be done, binding to a property that you update with the desired value. I'd suggest you look into the MVVM pattern (Model-View-ViewModel), which is really useful for structuring this nicely working with WPF. Check out this video for a nice overview:
MVVM video
Using MMVM you would create a class which would be the ViewModel class. This one would typically be set to the DataContext of the View. Having done so you could add dynamic references to the other properties of the class, e.g. binding your text field to some property holding the Id og the ComplexObject. If your ViewModel class had a property ComplexObject, which again had a property ID you'd simply bind to the object like this:
<TextBlock Text="{Binding ComplexObject.ID}" />

Having this you could trigger creation of your ComplexObject from mouse click, which you should ideally set up as a command binding. Also note that the ViewModel class (or whoever is holding the ComplexObject needs to notify the View when the object has been set. This can either be done by making the ComplexObject a DependencyProperty or by making the class holding the property implement the INotifyPropertyChanged interface - giving it the PropertyChanged function to trigger the changed event. I prefer the latter.

A: One possibility would be to have your XAML bind to a property on your code behind.  The getter for that property would return complexObject.ID, if complexObject != null.  Otherwise, it returns something "default", whether that's null or 0 or default(ID's type).  Similarly, the setter for that property would assign value to complexObject.ID if complexObject is, again, not null.
public int ID
{
    get
    {
        if (complexObject != null)
            return complexObject.ID;
        return 0; // or null or some appropriate default
    }
    set
    {
        if (complexObject != null)
            complexObject.ID = value;
    }
}


text:
Q: How do I make a text that writes the selected date in my calendar? I just started learning Javascript, so I apologize in advance for my ignorance. I have copy-pasted a calendar into my website, and I'd like to make a text that writes the date that has been selected in the calendar. I don't really know where to begin or if there's a simple solution to this. I hope I'm not being too ambitious :)
Here's the code for the calendar (imported from a js file):
    return function(t) {
        function e(t, e, a) {
            t && (t.attachEvent ? t.attachEvent("on" + e, a) : t.addEventListener(e, a))
        }

        function a(t, e, a) {
            t && (t.detachEvent ? t.detachEvent("on" + e, a) : t.removeEventListener(e, a))
        }
        let n = {
            selector: null,
            datesFilter: !1,
            pastDates: !0,
            availableWeekDays: [],
            availableDates: [],
            date: new Date,
            todaysDate: new Date,
            button_prev: null,
            button_next: null,
            month: null,
            month_label: null,
            onSelect: (t, e) => {},
            months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            shortWeekday: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
        };
        for (let e in t) n.hasOwnProperty(e) && (n[e] = t[e]);
        let l = document.querySelector(n.selector);
        if (!l) return;
        const d = function(t) {
                let e = document.createElement("div"),
                    a = document.createElement("span");
                a.innerHTML = t.getDate(), e.className = "vanilla-calendar-date", e.setAttribute("data-calendar-date", t);
                let l = n.availableWeekDays.filter(e => e.day === t.getDay() || e.day === function(t) {
                        return ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"][t]
                    }(t.getDay())),
                    d = n.availableDates.filter(e => e.date === t.getFullYear() + "-" + String(t.getMonth() + 1).padStart("2", 0) + "-" + String(t.getDate()).padStart("2", 0));
                1 === t.getDate() && (e.style.marginLeft = 14.28 * t.getDay() + "%"), n.date.getTime() <= n.todaysDate.getTime() - 1 && !n.pastDates ? e.classList.add("vanilla-calendar-date--disabled") : n.datesFilter ? l.length ? (e.classList.add("vanilla-calendar-date--active"), e.setAttribute("data-calendar-data", JSON.stringify(l[0])), e.setAttribute("data-calendar-status", "active")) : d.length ? (e.classList.add("vanilla-calendar-date--active"), e.setAttribute("data-calendar-data", JSON.stringify(d[0])), e.setAttribute("data-calendar-status", "active")) : e.classList.add("vanilla-calendar-date--disabled") : (e.classList.add("vanilla-calendar-date--active"), e.setAttribute("data-calendar-status", "active")), t.toString() === n.todaysDate.toString() && e.classList.add("vanilla-calendar-date--today"), e.appendChild(a), n.month.appendChild(e)
            },
            r = function() {
                l.querySelectorAll("[data-calendar-status=active]").forEach(t => {
                    t.addEventListener("click", function() {
                        document.querySelectorAll(".vanilla-calendar-date--selected").forEach(t => {
                            t.classList.remove("vanilla-calendar-date--selected")
                        });
                        let t = this.dataset,
                            e = {};
                        t.calendarDate && (e.date = t.calendarDate), t.calendarData && (e.data = JSON.parse(t.calendarData)), n.onSelect(e, this), this.classList.add("vanilla-calendar-date--selected")
                    })
                })
            },
            s = function() {
                o();
                let t = n.date.getMonth();
                for (; n.date.getMonth() === t;) d(n.date), n.date.setDate(n.date.getDate() + 1);
                n.date.setDate(1), n.date.setMonth(n.date.getMonth() - 1), n.month_label.innerHTML = n.months[n.date.getMonth()] + " " + n.date.getFullYear(), r()
            },
            i = function() {
                n.date.setMonth(n.date.getMonth() - 1), s()
            },
            c = function() {
                n.date.setMonth(n.date.getMonth() + 1), s()
            },
            o = function() {
                n.month.innerHTML = ""
            };
        this.init = function() {
            document.querySelector(n.selector).innerHTML = '\n
\n                <button type="button" class="vanilla-calendar-btn" data-calendar-toggle="previous"><svg height="24" version="1.1" viewbox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z"></path></svg></button>\n

\n                <button type="button" class="vanilla-calendar-btn" data-calendar-toggle="next"><svg height="24" version="1.1" viewbox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z"></path></svg></button>\n
\n

\n

\n            ', n.button_prev = document.querySelector(n.selector + " [data-calendar-toggle=previous]"), n.button_next = document.querySelector(n.selector + " [data-calendar-toggle=next]"), n.month = document.querySelector(n.selector + " [data-calendar-area=month]"), n.month_label = document.querySelector(n.selector + " [data-calendar-label=month]"), n.date.setDate(1), s(), document.querySelector(`${n.selector} .vanilla-calendar-week`).innerHTML = `\n                ${n.shortWeekday[0]}\n                ${n.shortWeekday[1]}\n                ${n.shortWeekday[2]}\n                ${n.shortWeekday[3]}\n                ${n.shortWeekday[4]}\n                ${n.shortWeekday[5]}\n                ${n.shortWeekday[6]}\n            `, e(n.button_prev, "click", i), e(n.button_next, "click", c)
        }, this.destroy = function() {
            a(n.button_prev, "click", i), a(n.button_next, "click", c), o(), document.querySelector(n.selector).innerHTML = ""
        }, this.reset = function() {
            this.destroy(), this.init()
        }, this.set = function(t) {
            for (let e in t) n.hasOwnProperty(e) && (n[e] = t[e]);
            s()
        }, this.init()
    }
}();
window.VanillaCalendar = VanillaCalendar;

Here's the jscode from the html file:


text:
Q: Why does changing coordinates to characteristics always reduce the PDE? I was looking at the following example of reducing a pde

In this case we manage to reduce the order of the pde. There are a couple of more examples that employ this technique of finding the characteristics and parameterising through them toreduce the order of the pde.
My question is, does this always happen? Is this something like completing the square? I can't seem to prove that there will always be reduction in order. If anybody can help me with that I would greatly appreciate it.


text:
Q: Deleting Classic Google Sites pages via Apps Script Is there a way to delete large sections of a classic Site via Apps Script?

A: /* CHANGE THE URL BELOW TO THE PAGE THAT YOU WANT TO DELETE. THEN SELECT "Run" > "deletePage" ABOVE. */

const URL = 'https://sites.google.com/site/demositeappsscript/mylistpage';

/* DON'T MODIFY ANYTHING BELOW HERE. */

function deletePage() {
  const pageToDelete = SitesApp.getPageByUrl(URL);
  deletePageHelper_(pageToDelete);
}

function deletePageHelper_(page) {
  page.getChildren().forEach(childPage => deletePageHelper_(childPage));
  Logger.log(`DELETING PAGE: "${page.getName()}".`);
  page.deletePage();
}


text:
Q: How to encode json dump correctly in python I have a python 3 script that should get some data from a .csv-file and write it to a json file.
During my processing the encoding is correct, so that german umlauts ü, ä or degree sign ° are like they are (# coding=cp1252 at the head).
But when I write the dict via json.dump() the encoding is gone...
How can I write a dict to a json file with the correct encoding?
# -*- coding: cp1252 -*-
import json
from pandas import read_csv

x={"äö": "ü°"}
print(x, json.dumps(x, indent=4))

>>>> {'äö': 'ü°'} {"\u00e4\u00f6": "\u00fc\u00b0"}

A: This is happening because ä, ö, ü, and ° aren't ASCII characters.
json.dumps has an optional argument called ensure_ascii which escapes non-ASCII characters, and it's set to True by default. You can get your desired behavior by setting this to false.
x={"äö": "ü°"}
print(x, json.dumps(x, ensure_ascii=False, indent=4))