text:
Q: Using PHP within JS for $redirectlocation and .$_POST I've looked and my tweaks won't work (noob) but I've tried!
I have a custom login for cPanel Webmail at a secured port and would like the error message to populate at the custom login page rather than redirecting to the default ports generic login page.
Here's the code I found which should work perfectly except I'm using Wordpress and experiencing the headers already sent error.  I tried to include the pluggable.php as this has worked with plugins I've written in the past for Wordpress admin area, but I cannot get the error resolved public frontend.
Username: <input type="text" name="user" value="" size="20" />

Password: <input type="password" name="pass" value="" size="20" />

<input type="text" name="domain" value="emajenweb.webserversystems.com"/>
<select name="port">
  <option selected="selected" value="2096"></option>
</select>

<?php
        if($_POST['domain'] && $_POST['user'] && $_POST['pass'] && !($_GET['failed'] == "1")) {
            $port = $_POST['port']; // sets the port number to login to
            // Get the protocol to use for this connection
            switch($port) {
              case '2096': // Secure Webmail
                $protocol = 'https://';
                break;
            }
          // Build the URL
          $redirectlocation = $protocol.$_POST['domain'].':'.$port.'/login/?user='.$_POST['username'].'&pass='.$_POST['pass'].'&failurl='.$_POST['failurl'];
          header ("Location: ".$redirectlocation); // Send URL
        } else {
          $error = 1;
          header ("Location: ".$_POST['failurl']); // Send URL if all neede information is not provided
        }
        ?>

The code I have problems with is:
header ("Location: ".$redirectlocation); // Send URL
        } else {
          $error = 1;
          header ("Location: ".$_POST['failurl']); // Send URL if all neede information is not provided

Given the header already sent error, I am hoping to change the header location values to javascript but I fail...
I have the form working but not as desired with failure messages propagating at the custom login page.
Webmail Login

A: Error header already sent is a pretty common error. This is caused by... well... header already sent. Header is sent when you send response to server. In your case, it is the:
Username: <input type="text" name="user" value="" size="20" />

Password: <input type="password" name="pass" value="" size="20" />

<input type="text" name="domain" value="emajenweb.webserversystems.com"/>
<select name="port">
  <option selected="selected" value="2096"></option>
</select>

So... how to fix this? Very simple. Just move your processing script BEFORE you send response:
<?php
        if($_POST['domain'] && $_POST['user'] && $_POST['pass'] && !($_GET['failed'] == "1")) {
            $port = $_POST['port']; // sets the port number to login to
            // Get the protocol to use for this connection
            switch($port) {
              case '2096': // Secure Webmail
                $protocol = 'https://';
                break;
            }
          // Build the URL
          $redirectlocation = $protocol.$_POST['domain'].':'.$port.'/login/?user='.$_POST['username'].'&pass='.$_POST['pass'].'&failurl='.$_POST['failurl'];
          header ("Location: ".$redirectlocation); // Send URL
        } else {
          $error = 1;
          header ("Location: ".$_POST['failurl']); // Send URL if all neede information is not provided
        }
?>
Username: <input type="text" name="user" value="" size="20" />

Password: <input type="password" name="pass" value="" size="20" />

<input type="text" name="domain" value="emajenweb.webserversystems.com"/>
<select name="port">
  <option selected="selected" value="2096"></option>
</select>

You should refer to this SO thread for more information: How to fix "Headers already sent" error in PHP


text:
Q: shell_exec empty response for nslookup query I am using Ubuntu and xampp, I am trying to execute the command nslookup gmail.com via. PHP, but I am getting an empty response. The same thing worked while I tried on a windows machine as well as in a Linux server running CentOS.
FYI nslookup gmail gives proper response when I run the command directly on my terminal, the problem is only when I try to do it via. php.
I even tried doing a which nslookup and then
$nslookup = shell_exec("/usr/bin/nslookup $server"); with no help, but the same blank response.
Although Note that the command whoami when executed from PHP(which I have commented in the following code) does give a proper response of daemon
I am very new to Ubuntu, so a little help would be great.
<?php
$email = $_GET['email'];
$server = explode("@", $email)[1];
echo $server;

$nslookup = shell_exec("nslookup $server");
// $nslookup = shell_exec("whoami");
print_r($nslookup);
?>

A: The php script executes as less privileged www user (daemon in your case) when you execute via web browser. It doesn't have enough privilege to execute command nslookup. I won't recommend increasing privilege of www user, which is a security risk. As an alternative try gethostbyname php function. It returns IPv4 address corresponding to a given Internet host name.
<?php
 $email = $_GET['email'];
 $server = explode("@", $email)[1];
 echo $server;
 $ip = gethostbyname($server);
 echo $ip;
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace the last octet of a valid network address with the number 2 Lets say I have a string that can be any possible/valid network address like so:
STR="192.168.1.0/24"

What I want to do is replace the last octet (in this case it's 0/24, however it can be anyting) with the number 2, however I don't know what the last octet could (do not will be print the new value, so change:
192.168.1.0/24

to:
192.168.1.2

Whatever the network address is, I want to replace the last octet with "2"
Note: it is not important to check if the string is a valid network address as all strings being tested are assumed to be valid network addresses.

A: In terminal this worked:
echo "192.168.1.0/24" | sed  -n 's/0.24/2/p'

In script this works:
str="192.168.1.0/24"
newstr=$(sed  -n 's/0.24/2/p' <<<$str)

To replace last digit of any IP address:
str="192.111.12.20"
newstr=$(awk -F"." '{print $1"."$2"."$3".2"}'<<<$str)
echo $newstr


text:
Q: How to dispose FormattedText / make WPF let go of .TTF file? In my WPF application I have a custom Canvas implementation, in which I draw some text using a specified .ttf file. The ttf file resides in a temporary location that can be deleted at some later point in time. My problem is that once my text has been rendered on the canvas, the ttf file seems to be kept open, and can't be deleted until the application has been closed down. Is seems to be the FormattedText instance that keeps the font file open. Does anybody know a way to "Dispose" the FormattedText, or in any other way make sure that the font file is closed after rendering?
My text drawing code:
public class MyCanvas : System.Windows.Controls.Canvas
{
    protected override void OnRender(DrawingContext dc)
    {
        base.OnRender(dc);

        // Some other drawing stuff...

        FontFamily fontFamily = new FontFamily(fontUri);
        Typeface typeFace = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
        FormattedText formattedText = new FormattedText(chars, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeFace, text.FontHeight, new SolidColorBrush(color));
        dc.DrawText(formattedText, new Point(text.X + offsetX, text.Y + offsetY));
        int textWidth = (int) formattedText.Width;
        int textHeight = (int)formattedText.Height;

        // Drawing continues...
    }
}

Note: It seems I don't even have to call DrawText to lock the font file (tried commenting that line out). Using the formattedText instance to assign the textWidth and textHeight variables is enough for WPF to keep the file open.
Update:
I've not been able to solve this problem, so currently I'm using a workaround that creates a new temporary font directory if overwriting the existing one fails. It works, but I'm not very happy with having to do it like this, so I'm still interested in any suggestions how to fix this.

A: Perhaps it's related in some way to the Presentation Font Cache, a service that runs to cache font data structures so that WPF apps perform better....maybe it is keeping the file locked.
Try to change the Presentation Font Cache service so that it is Stopped and Disabled. Run your application, then try and see if you can delete the font file.
Disabling the Presentation Font Cache isn't a long term solution if it is in fact the cause. You might get away with programmatically stopping and restarting it...not sure how that would affect other running WPF applications.
There is a more definitive way to see who has the file locked, by using a tool e.g.

*

*http://windowsxp.mvps.org/processlock.htm
A possible solution (to get around whoever is locking the file) is to put the .TTF file as a Resource in your application, then you can let WPF worry about how to manage and clean it up.
Links:

*

*http://msdn.microsoft.com/en-us/library/ms753303.aspx

*WPF PresentationFontCache. What is this?

*http://blog.tune-up.com/myth-buster/the-case-of-the-mysterious-presentation-font-cache-cpu-hog/
UPDATE:
You could create a wrapper class whose job is to delete a file when the object is disposed or if it can't delete the file at dispose time because the file is still locked, then it will get deleted when the Garbage Collector calls the Finalizer.

*

*http://www.codeproject.com/Articles/84831/A-simple-technique-to-take-care-of-temporary-files
Another possiblity is to use FileOptions.DeleteOnClose - you'd have to see if it was possible to use FontFamily on a font file that you opened/created and are currently maintaining an open file handle on.

*

*FileStream with DeleteOnClose File option
You say "The ttf file resides in a temporary location that can be deleted at some later point in time."...when you say at some later point in time...I'm presuming it's when you exit the program/process....or is that not the case?
or try TempFileCollection:

*

*http://msdn.microsoft.com/en-us/library/system.codedom.compiler.tempfilecollection.aspx


text:
Q: Adding secondary X-axis to a Powerbi document connected to SSAS? Our powerbi document is connected to an SSAS cube (Connect Live option).
In our case, we have a Fact table, a DimDate table, and a DimHour table.
I need to show the trend, per day and hour, of all the sales. In my powerbi, I filtered from 5/1-5/5. When I only add HourKey to my X-Axis, it shows me the total by hour (no date slicing). It's technically correct because I'm only showing hours, so it's grouping both days by hours:

When I add Full Date Alternate Key so that the X-axis groups by Date and hour, this is what the chart looks like:

My question: how can I have a secondary X-axis so that I can see the days and the hours?

A: Under "Data/Drill" menu, click on "Expand next level". In my case, this will show a secondary x-axis of hours:
Goes from this:

To this:


text:
Q: CasperJS/PhantomJS doesn't load https page I know there are certain web pages PhantomJS/CasperJS can't open, and I was wondering if this one was one of them: https://maizepages.umich.edu. CasperJS gives an error: PhantomJS failed to open page status=fail.
I tried ignoring-ssl-errors and changing my user agent but I'm not sure how to determine which ones to use.
All I'm doing right now is the basic casper setup with casper.start(url, function () { ... }) where url=https://maizepages.umich.edu;

A: The problem may be related to the recent discovery of a SSLv3 vulnerability (POODLE). Website owners were forced to remove SSLv3 support from their websites. Since PhantomJS < v1.9.8 uses SSLv3 by default, you should use TLSv1:
casperjs --ssl-protocol=tlsv1 yourScript.js

The catchall solution would be to use any for when newer PhantomJS versions come along with other SSL protocols. But this would make the POODLE vulnerability exploitable on sites which haven't yet disabled SSLv3.
casperjs --ssl-protocol=any yourScript.js

Alternative method: Update to PhantomJS 1.9.8 or higher. Note that updating to PhantomJS 1.9.8 leads to a new bug, which is especially annoying for CasperJS.
How to verify: Add a resource.error event handler like this at the beginning of your script:
casper.on("resource.error", function(resourceError){
    console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
    console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
});

If it is indeed a problem with SSLv3 the error will be something like:

Error code: 6. Description: SSL handshake failed

As an aside, you also might want to run with the --ignore-ssl-errors=true commandline option, when there is something wrong with the certificate.


text:
Q: @entangle initial state is always set to true on view side inside  I was wondering what could be the reason that @entangle value is always true on view side when the page is loaded. The behavior is normal when we change the value. The divs are inside the . If I extract them out @entangle normal from the initialization. To compensate for that i used x-init="show = @this.dshow"
Test.php

...
class Test extends Component
{
     public $dshow = false;
     ....
}

view.blade.php

<x-jet-dialog-modal>
    ...
   <x-slot name="content">

                         <input type="checkbox" value="1" wire:model="dshow" />
                         Check me

                         This will be shown after you check abve

   </x-slot>
</x-jet-dialog-modal>

The above will not hide the div on load, but after we check and then uncheck the div is toggled as I wanted. I used x-init to force initial state. What could possibly be the reason? Is it a bug?


text:
Q: How to login to a website using python and upload a file to s3? I have a script that uploads a file from a public URL to S3 which is working fine. i have a need to use this script to upload some files which are not Public, i need to log in to the site to get the file. i need help implementing this in my script; where the script would log in to the site and get the file. site i am trying to login to https://catalog.ldc.upenn.edu/login
Here is my Script
import threading
import requests
import boto3
from boto3.s3.transfer import TransferConfig

def multi_part_upload_with_s3():
    config = TransferConfig(multipart_threshold=1024 * 25, max_concurrency=30,
                            multipart_chunksize=1024 * 25, use_threads=True)
    url = "www.example-url.com"
    r = requests.get(url, stream=True)
    session = boto3.Session()
    s3 = session.resource('s3')
    key = 'examplePath/file'
    bucket = s3.Bucket(bucket_name)
    bucket.upload_fileobj(r.raw, key, Config=config, Callback=None)

Here is the html from the site i need to log in to
<form class="new_spree_user" id="new_spree_user" action="/login" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="xjxGqf8OYqJd6Ynt1GcK1Ms0XM6YcPz3kS69TFKCCRQwOgwh1kEMlpJSTKAoblXLtLpSLCIiwPWT+LLab0Altw==">

      E-mail

      <input class="title" tabindex="1" type="text" name="spree_user[login]" id="spree_user_login">

      Password

      <input class="title" tabindex="2" type="password" name="spree_user[password]" id="spree_user_password">

      <input name="spree_user[remember_me]" type="hidden" value="0"><input type="checkbox" value="1" name="spree_user[remember_me]" id="spree_user_remember_me">
      Remember me

<input type="submit" name="commit" value="Login" class="button primary" tabindex="3" id="submit_form" data-disable-with="Login">

</form>
    or
    Create a new account |
    Forgot password?


text:
Q: Restore PostgreSQL data into existing database Of course, the situation is such that I need a solution as soon as possible.
I have database in production in which I accidentally ran a script that deleted records that I did not want deleted.  Thankfully, I have a backup of the data before doing so as an *.sql file.  As such, I can manipulate it on my development environment to obtain only the data or even a dump file from pg_dump.
Whenever I try to use pg_restore or psql to import the file, it does not seem to import the missing rows.  It throws many errors, which I expect since it has duplicate data.  But I don't care about the duplicate data; I want the non-duplicated data back into the database.
Does anyone have any idea how to about doing this?

A: pg_dump with --inserts. This will get you a script with individual inserts for the rows instead of single COPY statements.
Run the script with AUTOCOMMIT on (the default).


text:
Q: Why this method currying can run in such a way I have confused about the code below. Why this can run? And what is the meaning of the .isEmpty. In the process of calling test, and I am mysterious about the { means what? A new Function?
def test(age:Int)(name:name_class => name_class): String = {
  val str: String = name.toString()+age+""
  print(str)
  str
}
test(19){
  x =>
    name_class("dage1")
}.isEmpty

A: *

*def test - test is a method.

*(age:Int) - It takes an Int parameter. We'll call it age.

*(name:name_class => name_class) - It takes a 2nd parameter (curried) that is a function that takes a name_class and returns a name_class. We'll call that function name.

*: String - Method test returns a String.

...

*

*test(19) - Let's invoke the test method. The 1st argument, age, will be 19.

*{ - The 2nd argument to test starts here. It might be multiple lines of code so we'll use {...} instead of (...). (Actually not needed in this case.)

*x=> - This is a function that takes a name_class. We'll call it x. (And ignore it hereafter.)

*name_class("dage1") - Return a name_class.

*} - All done with the 2nd argument to test.

*.isEmpty - Test the String that test returns to see if it is empty.


text:
Q: how to get the index of value in drop down in javascript? I have dropdown list on my aspx page. I want to mannually set the selected value which in exist in the dropdown list. this value i am getting in var. i want to set this value as selected value when page get initialize. I want this in javascript. is there any property for dropdown as ddp.SelectedValue='40'..? here I don't know the index of 40 in the list.

A: selectedIndex is a property of HTMLSelectElement so you can do the following:
<select id="foo"><option>Zero<option>One<option>Two</select>
<script>
document.getElementById('foo').selectedIndex = 1;  // Selects option "One"
</script>

And given an OPTION element, you can get its index using the index property:
<select><option>Zero<option id="bar">One<option>Two</select>
<script>
alert(document.getElementById('bar').index);  // alerts "1"
</script>

A:
I want to manually set the selected value

Iterate the select's options list to get the option you were interested in and set selected on it:
var options= document.getElementById('ddp').options;
for (var i= 0; n= options.length; i<n; i++) {
    if (options[i].value==='40') {
        options[i].selected= true;
        break;
    }
}

this will select the first option with a matching value. If you have more than one option with the same value, or a multiple-select, you may need different logic.
This:
document.getElementById('ddp').value= '40';

is specified by HTML5 to do the same, and has worked in most modern browsers for ages, but still fails in IE, unfortunately (even IE9).

A: <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery 1.6.2.min.js" />
<script language="JavaScript">
    $(function() {
        quickSelect();
        // Handler for .ready() called.
    });
    function quickSelect() {
        var bnd = "40";
        if (bnd != "") {
            $("#ddp option[value='" + bnd + "']").attr("selected", "selected");
        }
    }
</script>


text:
Q: Reduce a UTF-8 string for binary comparison I want to quickly check if an UTF-8 word exists as an array key.
The words may have:

*

*different case

*accented characters or not

*different Unicode normalization forms

I can use mb_strtolower() to make them both lowercase, and Normalizer::normalize() to normalize the strings. This checks the first 2 bullet points, but does not handle accents:
'tést' !== 'test'

I can use Collator to compare both words:
$collator = new Collator('fr_FR');
$collator->setStrength(Collator::PRIMARY);
$collator->compare('tést', 'test'); // 0

This checks my 3 bullet points, but I now I have to loop over all my word pairs to compare them, when I want to be able to perform a binary lookup as an array key (I have many lookups to perform on a big dictionary).
What I want is:
function reduce($word) {
    // how?
}

// prepare the dictionary (once)

$dictionary = [];

foreach ($dictionaryWords as $dictionaryWord) {
    $dictionary[reduce($dictionaryWord)] = true;
}

// perform a lookup (many times)

if (isset($dictionary[reduce($lookupWord)])) {
    // it's a match!
}

Basically, I want the reduce() function (which may be poorly named) to perform a simplification like this one:

*

*'TÈST' => 'test'

*'Straße' => 'strasse'

I believe MySQL does something like this internally for its text indexes.
Is there an intl function that does this? The list of intl classes and functions is hard to digest.

A: Reading your question, it seems that you're only really interested in checking if a word exists as a unique array index.
You could do this by cryptographically hashing the word and using the hash as the index. It would go something like this:
<?php
$word = 'TÈST';
$dictionary[sha1($word)] = TRUE;

Or use an algorithm that is more resilient to collision attacks, if that is a concern to you. Please elaborate your question if you need any pointers in that area.
UPDATE
Please see the snippet below, which produces "test, strasse".
<?php

setlocale(LC_ALL, 'nl_NL.UTF-8');

$words = [ 'TÈST', 'Straße' ];

foreach ($words as $index => $word)
{
    echo ($index?', ':'') . strtolower(iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $word));
}

A: What I'm looking for is the Transliterator class. An example can be found in this answer:
$string = "Fóø Bår";
$transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;', Transliterator::FORWARD);
echo $transliterator->transliterate($string); // foo bar

Thanks to @Pete for the pointer in the comments.
This even works with non-european characters:
echo $transliterator->transliterate('Fóø Bår 学中文'); foo bar xue zhong wen

Where iconv would fail at the job:
echo iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'Fóø Bår 学中文'); // Foo Bar ???

Unless I'm missing some other iconv options, of course.


text:
Q: Why is the "harden" suite of packages not available for Debian Jessie (8.0)? These include all the harden packages listed in the Debian automatic hardening documentation (https://www.debian.org/doc/manuals/securing-debian-howto/ch-automatic-harden.en.html), including:

*

*harden

*harden-tools

*harden-servers

*harden-clients

*etc., etc.
Confusingly, it appears that the suite's documentation package will be available for Debian Stretch (9.0), but none of the harden meta-packages are currently slated for that release either.
What gives? Are there alternative replacement packages that I overlooked? If so, what are they?

It may be worth noting that I spent a great deal of time searching for the answer to this question online. There seems to be no information on this topic, and I've found nothing in the mailing lists, though I haven't search as thoroughly there.
All I have found is that the packages must have been available for Jessie at some point, but were later removed, as some Google queries still return dead links to Jessie package information pages.
The harden packages were a novice administrator's godsend, though I understand they were never the complete answer to securing a Debian server. Still, it is odd not seeing any explanation for their exclusion in Debian's newest releases.

A: So looking through the bugs for harden I found the following two bugs.

*

*https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=782978

*

*
Subject: RM: harden -- RoQA; no longer useful
  Date: Sun, 19 Apr 2015 20:12:06 -0400
  The maintainer thinks it would be best for it to be removed:

*https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=760449

*

*
Hi
  I agree with you. I think we should consider to remove the package
  altogether.
  // Ola

So the answer seems to be that the maintainer didn't think it was useful or functional anymore.
I have never used the package, so I can't provide much beyond linking you to the correct bug reports.


text:
Q: Getting the SVM example of OpenCV to run in Version 3.0.0 with c++ I tried to run the SVM example project of the official OpenCV documentation but it seemed that the code is outdated for openCV version 3.0.0.
So i adjusted the code with the help of this stackoverflow entry and came up with the following code:
// Data for visual representation
    int width = 512, height = 512;
    Mat image = Mat::zeros(height, width, CV_8UC3);

    // Set up training data
    int labels[4] = { 1.0, -1.0, -1.0, -1.0 };
    Mat labelsMat(4, 1, CV_32S, labels);

    int trainingData[4][2] = { { 501, 10 },{ 255, 10 }, { 501, 255 }, { 10, 501 } };
    Mat trainingDataMat(4, 2, CV_32F, trainingData);

    // Set up SVM's parameters
    Ptr<SVM> svm = SVM::create();
    svm->setType(SVM::C_SVC);
    svm->setKernel(SVM::LINEAR);
    svm->setTermCriteria(TermCriteria(CV_TERMCRIT_ITER, 100, 1e-6));

    Ptr<TrainData> trainData = TrainData::create(trainingDataMat, ml::ROW_SAMPLE, labelsMat);

    // Train the SVM
    //svm->trainAuto(trainData);
    svm->train(trainingDataMat, ml::ROW_SAMPLE, labelsMat);

    Vec3b green(0, 255, 0), blue(255, 0, 0), red(0, 0 ,255), yellow(0, 255, 255);
    // Show the decision regions given by the SVM
    for (int i = 0; i < image.rows; ++i)
        for (int j = 0; j < image.cols; ++j)
        {
            Mat sampleMat = (Mat_<float>(1, 2) << i, j);
            Mat result;
            svm->predict(sampleMat, result);
            float response = result.at<float>(0);
            if (response == 1)
                image.at<Vec3b>(i, j) = green;
            else if (response == -1)
                image.at<Vec3b>(i, j) = blue;
            else if (response == 2)
                image.at<Vec3b>(i, j) = red;
            else if (response == -2)
                image.at<Vec3b>(i, j) = yellow;
            //else return 0;
        }

The code is now at least running without exceptions but it is still not working.
When using the TrainingData::create method in combination with svm->trainAuto(trainData) I just get a black image ( predict always returns 0 ).
If I use svm->train(trainingDataMat, ml::ROW_SAMPLE, labelsMat) I get an image where every pixel has the same color ( predict always returns the same value ). With the labels set as above the image will be all blue.
I do not really see what I may have done wrong.


text:
Q: Can you define recursive type hints in Python? I have an alias for a type in Python:
from typing import Tuple, Dict, Union

SelectedModelArgs = Dict[
    str,
    Union[
        str,
        float,
        Tuple[float, float],
        Dict[str, Union[str, float, Tuple[float, float]]],
    ],
]

At present this allows for a dictionary with str to str, float, a tuple of floats or a nested dictionary of the same type. Is there a way to define this recursively to allow arbitrary nesting?
e.g.
SelectedModelArgs = Dict[
    str,
    Union[
        str,
        float,
        Tuple[float, float],
        SelectedModelArgs,
    ],
]

When I try this I get IDE errors:

*

*Pylance: "SelectedModelArgs" is not defined

*Mypy: Cannot resolve now "SelectedModelArgs" (possible cyclic definition)

Adding from __future__ import annotations to the top of the file does not resolve these (as it does with using a class name within a class definition).
I have also tried using the code example above but with the nested "SelectedModelArgs" as a string (as noted in this answer). This resolves the pylance error, but not the mypy error.


text:
Q: Securing HTML and JS files in SPA with .NET I'm starting to develop single page apps with .NET and Durandal JS and I'm wondering how to secure the HTML and JS files of the application. I'm talking about the files in the App folder, those files currently can be directly accessed through the URL and I would like to prevent this.
Of course, since the HTML will be displayed anyway to the user it seems to be unnecessary to do that, but I really think it's better to have this and mainly the JS logic protected from direct access. I was looking at some examples of authentication in SPA's and mostly of them expose some of the logic used in this way.
How can I do that? How can I prevent direct access to these files? I thought on doing that with a route mapping to an action in a controller to return an error, but I think that in this way my javascript would be blocked as well.

A: First and foremost, trying to prevent people from downloading and inspecting client code in an application that is running on the client is an exercise in futility. If you give someone something a computer can execute within the system a person has access to, that someone can reverse engineer it, or find someone who can. More often than not, the only person who suffers from your tricks and hacks to try and prevent them is you, the developer, both in wasting time implementing something that will fail, and trying to work around it when debugging your own work.

If you are truly interested in dissuading casual attempts to peek at your work, well, alright.
You can minify assets in a way that also obfuscates, but all that does is make it temporarily inconvenient (such an approach is still valuable in reducing page weight, however). There is a plethora of tools that make it easy to de-minify code.
You could come up with a way that the initial page and script bootstraps the rest of the app by requiring it to, say, place a certain value in the header, and have your HTTP server prevent serving resources to certain files unless they have that header. But requests can be easily inspected, recreated, and issued manually to circumvent that.
Perhaps some efforts have been made to create a shell app or browser that only executes trusted code that you package up into some sort of encrypted format and can open with a key. Or perhaps a browser plugin. I don't know. You could come up with whatever crazy thing you want, but is it worth it? Will people want to use it? If you make it hard for someone to use something, they won't.

The key, then, is to minimize what you give to clients to run on their machine that you consider invaluable and/or a trade secret. You can strategize what really isn't all that special (and let's be honest, your client side code for your app's UI isn't really all that valuable... not because you didn't create something wonderful, but the code is only the means to an end) and choose the right technological approach to provide that service but keep it out of people's hands.
So if you have some special sauce for a business model, don't implement it all on the client side. Separate the concerns into client responsibilities and server responsibilities. Restrict the client to basic UI, getting info from the user, sending to the server, and displaying the response. Keep your secret sauce on the server away where they can't see it.
You don't HAVE to make it an SPA... just make it a standard ASP.NET WebForms or MVC and be done with it. If you do go with SPA, you must buy into its inherent principles.
If that's not possible, and all logic has to be on the client, you need to make a decision. Either a) don't bother b) beat your head against the way trying to construct your perfect secure little environment (which will fail) or c) rely on legal agreements with your users.
TL;DNR: My opinion? Be proud of your work and let the value of it stand on its own. Keeping private business logic on the server end and architecting appropriately, in addition to letting go of the notion that people seeing your client code will threaten your business, is a simple and sound approach. Also, minify your JS. It doesn't secure your intellectual property, but it has other more practical benefits.

A: This is my advise:

*

*You need to use .NET Forms Authentication. This will allow you

*To set up your web.config like this:

<compilation ...>
       <buildProviders>
        <add extension=".html" type="System.Web.Compilation.PageBuildProvider"/>
        <add extension=".htm" type="System.Web.Compilation.PageBuildProvider"/>
        <add extension=".js" type="System.Web.Compilation.PageBuildProvider"/>
      </buildProviders>
    </ compilation ...>

This configuration forces your html and js to be validated against your forms authentication, without loosing the wonders of the MVVM Javascript Framework.

*Set up the roles and permissions probably folder based, again in your web.config to secure both html and js files, like this:

<location path="js/app/folder1">
    <system.web>
      <authorization>
        <deny users="?"/>
        <allow roles="role1"/>
      </authorization>
    </system.web>
  </location>
 <location path="js/app/folder2">
    <system.web>
      <authorization>
        <deny users="?"/>
        <allow roles="role2"/>
      </authorization>
    </system.web>
  </location>
  </location>


text:
Q: Async Operation vs Async Network task? Having the common scenario of needing to asynchronously call a RESTful Web Service to get a JSON content, and then parsing that JSON response to create some data model entities. This process could be cancelled/resumed. I'm not completely sure of which the best approach would be:

*

*Implementing an Operation for the network call and another Operation for the JSON parsing and setting a dependency between both operations (the JSON output from the former being the data input of the latter). Then, adding those operations to a OperationQueue.

*Using a URLSession and URLSessionDataTask to perform the network call, and the JSON parsing in its callback.

Or maybe another different and better way?
EDIT: In my scenario, I don't need to perform concurrent network calls. If I need to call the service with different params, I should be able to stop the previous network task if necessary, and start the new one.

A: In most simple cases, the answer is just an URLSession, but if it is complicated, as your seems to be, then Operation is a useful tool. This precise use case is discussed at length in Advanced NSOperations.


text:
Q: How do I use the API to get the information shown on Docusign's Envelope History screen I would like to have a page on my website that displays the information shown on the Envelope History screen (Envelope Details and Activity history).
Is that possible, and if so, how?
I'm using the REST API v2.
https://demo.docusign.net/MEMBER/ManageEnvelopes.aspx
Envelopes - Inbox
Actions - History

A: Try using the "Get Envelope Audit Events" operation, as described on pages 121-122 of the DocuSign REST API guide:  http://www.docusign.com/sites/default/files/REST_API_Guide_v2.pdf.
GET https://demo.docusign.net/restapi/v2/accounts/{accountId}/envelopes/{envelopeId}/audit_events
This operation won't return an exact 1-to-1 of everything shown in the web console's "Envelope History" view, but it's as close as you can get with the API.

A: Is this for completed (signed) envelopes, or for in-process ones?  For in-process ones you can make the API request that Kim has mentioned, the Get Envelope Audit Events call.  However for completed envelopes, you can make a call to download the envelope certificate, which has most (if not all) the info you want.
Once a given envelope is completed an Envelope Certificate is automatically created and added to the envelope.  At that point you can view it manually through the Console, or you download it separately or combined with the envelope documents.  You actually have two different ways of downloading it:
1  Download the certificate by itself.
2  Download all envelope documents including the certificate in one combined PDF

For #1, you can make the Get Envelope Certificate api call, which has the following properties:

Get Envelope Certificate
This retrieves a PDF document containing the certificate for the envelope.
URL:
/accounts/{accountId}/envelopes/{envelopeId}/documents/certificate
HTTP Method:
GET
Formats:
XML, JSON

For #2, you can make the Get Envelope Documents and Certificate api call:
Get Envelope Documents and Certificate
This retrieves a PDF containing the combined content of all documents and the certificate. If the account has the Highlight Data Changes feature enabled, there is an option to request that any changes in the envelope be highlighted.
URL:
/accounts/{accountId}/envelopes/{envelopeId}/documents/combined
Optional additions: certificate={true or false}, show_changes={true}, watermark={true or false}
HTTP Method:
GET
Formats:
XML, JSON


text:
Q: PHP dice game with classes I'm trying to develop the 'roll the dice' with classes in PHP and with two dice and several players, do you know how the structure could be better? I've started with this simple code:
class dice extends nplayer{
private $face1;
private $face2;
public function roll(){
    $die = array('1', '2', '3', '4', '5', '6');
    $randDie = array_rand($die);
    $this->face1=$randDie;
...
}
}

class nplayer{
private $name;

private function __construct($nam){
    $this->namw=$nam;
}

public function play(){
    $this->roll();
}
public function show($name){
    print "<...>";
}
}
class resuts{
}

A: Your function roll() can look like this:
$this->face1 = rand(1,6);
and that's it. You do not need array to dice some number.
You shouldn't call $this->roll(); in class nplayer because this class do not have method roll()


text:
Q: For any natural number $n$, Prove that $\prod^{n}_{r=1}\bigg(r+\frac{1}{n}\bigg)\leq 2(n!)$
For any natural number $n$, Prove that $$\displaystyle \prod^{n}_{r=1}\bigg(r+\frac{1}{n}\bigg)\leq 2(n!)$$

Trial Solution: Using $\displaystyle \frac{1}{n}\leq 1,2,3,\cdots n$
$\displaystyle \prod^{n}_{r=1}\bigg(1+\frac{2}{n}\bigg)\leq 2\cdot 4\cdot 6\cdots \cdots 2n$
$$\prod^{n}_{r=1}\bigg(1+\frac{2}{n}\bigg)\leq 2^n\cdot n!$$
Could some help me how to prove my original inequality, Thanks

A: We can verify directly for $n=1,2$. Suppose $n\geq3$. Then
$$
  \sum_{r=1}^n\log\left(1+\frac1{rn}\right)
    \leq\sum_{r=1}^n\frac1{rn}
    \leq\frac{1+1/2+(n-2)/3}{n}
    \leq\frac{11}{18}<\log 2.
$$
Now exponentiate and multiply by $n!$.

A: It is "easy" to show it at least for large values of $n$.
$$\prod^{n}_{r=1}\bigg(r+\frac{1}{n}\bigg)=\left(\frac{1}{n}+1\right)_n$$ where appears Pochammer symbol.
Using asymptotics,
$$\log \left(\left(1+\frac{1}{n}\right)_n\right)=n (\log (n)-1)+\frac{1}{2} \left(\log (2 \pi )+\log
   \left({n}\right)\right)+\frac{\log \left({n}\right)+\gamma
   +\frac{1}{12}}{n}+O\left(\frac{1}{n^{3/2}}\right)$$ while, using Stirling approximation, $$ \log(2(n!))=n (\log (n)-1)+\left(\log \left(2 \sqrt{2 \pi }\right)+\frac{1}{2} \log
   \left({n}\right)\right)+\frac{1}{12
   n}+O\left(\frac{1}{n^{3/2}}\right)$$ making
$$\log \left(\left(1+\frac{1}{n}\right)_n\right)-\log(2(n!))=-\log (2)+\frac{\gamma +\log
   \left({n}\right)}{n}+O\left(\frac{1}{n^{3/2}}\right)$$ which is negative $\,\,\forall n$.


text:
Q: How to receive zipped json data from RabbitMQ in scala Im using below scala code to receive messages from rabbitmq.
 import com.rabbitmq.client.Channel
    import com.rabbitmq.client.Connection
    import com.rabbitmq.client.ConnectionFactory
    import com.rabbitmq.client.ConsumerCancelledException
    import com.rabbitmq.client.QueueingConsumer

   val rabbitMQconnection = getRabbitMQConnection
    val channel = rabbitMQconnection.createChannel()
    val args = Map[String, AnyRef]("x-message-ttl" -> Long.box(40000))

         channel.queueDeclare("test",true,false,false,args )
          val consumer = new QueueingConsumer(channel)
             channel.basicConsume("test",true,consumer)
           var message: String = null
         val delivery = consumer.nextDelivery()
         message= new String(delivery.getBody(), StandardCharsets.UTF_8)
         println("at consumer : " +message)

My input data from RabbitMq is zipped Json data. When I use the above code, Im unable to unzip the data. Could someone please let me know how to read zipped json data.
Thank you.


text:
Q: Kubernetes Worker Node in Status NotReady after introducing a proxy in between worker node and control plane I have setup a  kubernetes cluster with kubeamd; One control-plane and a worker node.
Everything worked fine. Then
I setup a Squid proxy on the worker node and in the kubelet config I have set http_proxy=http://127.0.0.1:3128 essentially asking kubelet to use the proxy to communicate to the control-plane.
I see, using tcpdump, network packets landing on the control plane from worker node, and I am able to issue the following command from worker as well;
kubectl get no --server=https://10.128.0.63:6443
NAME        STATUS     ROLES    AGE    VERSION
k8-cp       Ready      master   6d6h   v1.17.0
k8-worker   NotReady   <none>   6d6h   v1.17.2

but the worker status always remains NotReady.
What might I be doing wrong?
I am using Flannel here for networking.
P.S. I have exported http_proxy=http://127.0.0.1:3128 as an env variable as well before issuing
kubectl get no --server=https://10.128.0.63:6443

from the worker node.
If it matters here is the node status;
kubectl  describe no k8-worker
Name:               k8-worker
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/arch=amd64
                    kubernetes.io/hostname=k8-worker
                    kubernetes.io/os=linux
Annotations:        flannel.alpha.coreos.com/backend-data: {"VtepMAC":"fe:04:d6:53:ef:cc"}
                    flannel.alpha.coreos.com/backend-type: vxlan
                    flannel.alpha.coreos.com/kube-subnet-manager: true
                    flannel.alpha.coreos.com/public-ip: 10.128.0.71
                    kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock
                    node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Wed, 29 Jan 2020 08:08:33 +0000
Taints:             node.kubernetes.io/unreachable:NoExecute
                    node.kubernetes.io/unreachable:NoSchedule
Unschedulable:      false
Lease:
  HolderIdentity:  k8-worker
  AcquireTime:     <unset>
  RenewTime:       Thu, 30 Jan 2020 11:51:24 +0000
Conditions:
  Type             Status    LastHeartbeatTime                 LastTransitionTime                Reason              Message
  ----             ------    -----------------                 ------------------                ------              -------
  MemoryPressure   Unknown   Thu, 30 Jan 2020 11:48:25 +0000   Thu, 30 Jan 2020 11:52:08 +0000   NodeStatusUnknown   Kubelet stopped posting node status.
  DiskPressure     Unknown   Thu, 30 Jan 2020 11:48:25 +0000   Thu, 30 Jan 2020 11:52:08 +0000   NodeStatusUnknown   Kubelet stopped posting node status.
  PIDPressure      Unknown   Thu, 30 Jan 2020 11:48:25 +0000   Thu, 30 Jan 2020 11:52:08 +0000   NodeStatusUnknown   Kubelet stopped posting node status.
  Ready            Unknown   Thu, 30 Jan 2020 11:48:25 +0000   Thu, 30 Jan 2020 11:52:08 +0000   NodeStatusUnknown   Kubelet stopped posting node status.
Addresses:
  InternalIP:  10.128.0.71
  Hostname:    k8-worker
Capacity:
  cpu:                2
  ephemeral-storage:  104844988Ki
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             7493036Ki
  pods:               110
Allocatable:
  cpu:                2
  ephemeral-storage:  96625140781
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             7390636Ki
  pods:               110
System Info:
  Machine ID:                 3221f625fa75d20f08bceb4cacf74e20
  System UUID:                6DD87A9F-7F72-5326-5B84-1B3CBC4D9DBE
  Boot ID:                    7412bb51-869f-40de-8b37-dcbad6bf84b4
  Kernel Version:             3.10.0-1062.9.1.el7.x86_64
  OS Image:                   CentOS Linux 7 (Core)
  Operating System:           linux
  Architecture:               amd64
  Container Runtime Version:  docker://1.13.1
  Kubelet Version:            v1.17.2
  Kube-Proxy Version:         v1.17.2
PodCIDR:                      10.244.1.0/24
PodCIDRs:                     10.244.1.0/24
Non-terminated Pods:          (3 in total)
  Namespace                   Name                           CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                   ----                           ------------  ----------  ---------------  -------------  ---
  default                     nginx-86c57db685-fvh28         0 (0%)        0 (0%)      0 (0%)           0 (0%)         6d20h
  kube-system                 kube-flannel-ds-amd64-b8vbr    100m (5%)     100m (5%)   50Mi (0%)        50Mi (0%)      6d23h
  kube-system                 kube-proxy-rsr7l               0 (0%)        0 (0%)      0 (0%)           0 (0%)         6d23h
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests   Limits
  --------           --------   ------
  cpu                100m (5%)  100m (5%)
  memory             50Mi (0%)  50Mi (0%)
  ephemeral-storage  0 (0%)     0 (0%)
Events:              <none>

Link to kubelet logs on worker:
https://pastebin.com/E90FNEXR

A: The Kube-controller-manager/node-controller is responsible for monitoring the health of the nodes monitoring the endpoint "/healthz" exposed by kubelet.
So far you have configured a one way communication over proxy (from Node to Master).
You need to do it for other components, especially Kube-controller-manager.
This way you enable two way communication over HTTP Proxy.

This is achievable by specifying HTTP_PROXY on KUBEADM INIT:
$ sudo http_proxy=192.168.1.20:3128 kubeadm init

Learn more here:  Kubadm Issue 182

*

*It creates a one-time variable which is read-in by kubeadm, and then re-created inside all components of control plane also as Env Variable.

You will see some output like this:
kubeadm@lab-1:~$ sudo http_proxy=192.168.1.20:3128 kubeadm init
[init] Using Kubernetes version: v1.17.0
[preflight] Running pre-flight checks
        [WARNING HTTPProxy]: Connection to "https://10.156.0.6" uses proxy "http://192.168.1.20:3128". If that is not intended, adjust your proxy settings
        [WARNING HTTPProxyCIDR]: connection to "10.96.0.0/12" uses proxy "http://192.168.1.20:3128". This may lead to malfunctional cluster setup. Make sure that Pod and Services IP ranges specified correctly as exceptions in proxy configuration

*

*Optionally you can do this manually through Env Variable, like you did for kubelet by adjusting kube-controller-manager's pod spec.

Learn more here: Kubeadm Issue 324.


text:
Q: Limit number of messages sent by Exchange 2007 I have a Exchange 2007, it's possible to limit the number of messages sent by a user?
When a computer is infected by virus or similar, this user sends a lot of emails (about 100.000 emails in a day). If it's possible to limit, I can delete of queue.
Now when I have a issue of emails, domain automatically appears in black lists.
I search a lot of documentation, but I think Exchange 2007 don't have this capability.
Anyone knows how enable this function?
Thank you very much.

A: Most of the virus/malware will not use your in house Exchange to send the email, most of them create a local SMTP service on the infected computer to send the mass email.
As such to limit the impact I would close the port 25 to anything except your Exchange's server IP.
I would use another public IP for the outgooing traffic on port 25, thus if a user bypass your firewall restriction somehow, your public IP, used for anything else than Exchange will be blacklisted, but not your Exchange IP.
For your actual question, you could adjust client throttling, or you could route your outgooing email to a smarthost that offer spam scanning.


text:
Q: Reload Masonry Grid after AJAX call I have a Masonry Grid that is working beautifully. It loads perfectly and readjusts. But I am using a plugin that filters results (Search & Filter plugin for Wordpress) and uses AJAX to do that. But after the AJAX call, my masonry grid is no longer working. I know it is due to the fact that I need to reload Masonry after the AJAX call, but I don't exactly know how to do that. Does anyone know how I can do that?
Here is my basic HTML structure.

Title

Content

.search-results-container is the div that repeats.
My JS looks like this:
    jQuery(window).load(function() {

      var container = document.querySelector('#masonry-container');
      var msnry = new Masonry( container, {
        itemSelector: '.search-results-card',
        columnWidth: '.search-results-card',
      });

});

That works well until the AJAX is initiated and reloads the container. Then the Masonry calculations are off and everything is out of whack. I need to figure out a way to reload Masonry after the AJAX call. Any ideas?

A: You will want to call the reloadItems() method on your Masonry instance. This will kick off the DOM recalculations:
http://masonry.desandro.com/methods.html#reloaditems


text:
Q: intellij - setting to replace the caret at the beginning of each line with correct indent I am looking for the setting that forces the caret to placed at the beginning of each line. Currently if I click anywhere, the caret gets positioned there. It is not the behavior I like, I would like it to be replaced, in order to prevent me to do it incorrectly. I think it is an option commonly used, and was standard in the intellij I became in some other company but I am bad at describing it.
Sorry for my approximative vocabulary and thanks for any hint.

A: *

*Go to File → Settings

*On the left pane, expand Editor, then select General.

*Find the Virtual Space section, and uncheck "Allow placement of caret after end of line".


text:
Q: API Endpoint Semantics Is an API endpoint the 'method', like https://api.foursquare.com/v2/venues/ or the full URL including non-query-string parameters like  https://api.foursquare.com/v2/venues/5104
In other words, are these two separate endpoints or considered the same endpoint?
http://myapi.com/somemodel/1
http://myapi.com/somemodel/2

A: According to this Wikipedia article, the endpoint is a web service, defined by a WSDL file, and

does nothing more than define the
  address or connection point to a web
  service. It is typically represented
  by a simple HTTP URL string.

Microsoft uses the term endpoint in various contexts, but they all amount to the same thing: the endpoint is the entire interface, not one particular method.
In the context of a REST endpoint, the endpoint would contain the requisite GET, PUT, POST and DELETE methods (as applicable).


text:
Q: Are Kube-state-metrics new or well formatted metrics? I am fairly new to Kubernetes and had a question concerning kube-state-metrics. When I simply monitor Kubernetes using Prometheus I obtain a set of metrics from the cAdvisor, the nodes (node exporter), the pods, etc. When I include the kube-state-metrics, I seem to obtain more "relevant" metrics. Do kube-state-metrics allow to scrape "new" information from Kubernetes or are they rather "formatted" metrics using the initial Kubernetes metrics (from the nodes, etc. I mentioned earlier).

A: The two are basically unrelated. Cadvisor is giving you low-level stats about the containers like how much RAM and CPU they are using. KSM gives you info from the Kubernetes API like the Pod object status. Both are useful for different things and you probably want both.


text:
Q: Gapless breadboards? For the most part, all solderless breadboards are alike. 5 or 6 contacts spaced 0.1" connected across, a gap (typically 0.3" wide), and 5 or 6 contacts more, and repeated x times down the other length (0.1" from each other). Some have rails on either end that are connected most of the way through.

My question is, does a breadboard without the center gap exist? I know there are ones with a wider gap (0.6"), but I have not found any without the gap. Do they have a different name?
My goal is simply being able to plug in a standard Dual In Line header without needing an adaptor, or modifying the breadboard (cutting out the middle, or cutting a contact set in half)

A: Idea: Get some stripboard, and solder rows of 0.1" spaced female headers to it to create a
facsimile of a breadboard.
You can cut across traces to disconnect adjacent headers from each other that are spaced only 0.1" apart, thereby creating the receptacle you want.

A: You may want to consider an adaptation of the idea shown here.

The idea is to split the board down the middle. (A better choice of board is the type that has an open slot down the middle with the sides connected across only in a few places). As seen above the board was split to allow it to efficiently support a wide device without covering up all the adjacent holes.
The modified idea would be to use some sandpaper laid grit side up on a nice flat surface. Then sand the inner edges of the separated board so that they become thin enough that when the two sides are slid next to each other that the rows of holes get close to the 0.1" spacing that you need for a standard dual row header. While sanding use care to hold the pieces upright in a square manner and apply even pressure so that the whole length gets sanded down in an even manner. Sometimes it can be useful to swap the piece end for end several times during the sanding process to even out the variation of pressure on how you hold the part against the sand paper.
You may find that to get the parts sanded enough to achieve the 0.1" spacing that the ends of the metal contact strips may become exposed. If this happens you can over-sand the part by the thickness of piece of plastic electrical tape and then run a strip down the middle to insulate the exposed metal from one side to the other.
That can be seen in this Instructable, requiring careful cutting (after removing the contacts), insulation, and gluing it back together, a 0.1" spacing is possible.

Here is an example of a solderless breadboard that has an open slot down the middle such that there is far less plastic to remove.

A: I may have seen a few breadboards that lack the center gap but they are VERY small boards, probably not suitable for what you are doing. For the most part all of them have a gap to allow for chips to be plugged in.

A: Hackaday noted two workarounds in their August 2015 article Literal breadboard hack forces it to accept dual pin headers:

*

*Disassemble the breadboard, remove the relevant conductive tracks, cut them in the appropriate place, and then put them back in.

*Add a long-legged header and some judicious pin-bending to extend one row of legs far enough that it can sit on the far side of the gap that runs along the middle of an ordinary solderless breadboard.
However, these workarounds are both fiddly and time-consuming. I wish manufacturers would make solderless breadboards that can accommodate 2-row 2.54mm pin headers without short-circuiting them, so that people could use such headers to prototype easily, without needing to engage in time-consuming and fiddly workarounds.
Edit: I've just learned that Adafruit makes "IDC Breakout Helper" headers that enable 2-row pin headers to be conveniently used with ordinary solderless breadboards. Hopefully this will become a standard item for electronics manufacturers to make!


text:
Q: Sets of positive measure intersected with intervals I am reading Real Analysis by Yeh and have a question about the following result

(I cut off the case where $\mu_L(E)= \infty$ since I have no question about it).
Here are Yeh's notations: $\mathfrak{M}_L$ is the $\sigma$-algebra of Lebesgue measurable subsets of $\mathbb{R}$, $\mu_L$ denotes Lebesgue measure.  If we're not sure $E \in \mathfrak{M}_L$, then $\mu_L^*(E)$ denotes the Lebesgue outer measure of E.
Question: Where is the fact that $E \in \mathfrak{M}_L$ used?  In other words, does the above result hold for arbitrary $E \subseteq \mathbb{R}$ (and using outer measure $\mu_L^*$ instead of $\mu_L$ where appropriate, of course)?  Here are my observations:

*

* Note equation (1) holds for arbitrary $E \subseteq \mathbb{R}$ (Lemma 3.21 found earlier in the book does not assume $E \in \mathfrak{M}_L$)

* $E \in \mathfrak{M}_L$ is seemingly used to show $\mu_L(E)= \sum_{n \in \mathbb{N}} \mu_L(E \cap I_n)$ right before equation (2), but even if $E$ were not measurable, the fact that outer measure is still countably subadditive gives us $\mu_L^*(E) \leq \sum_{n \in \mathbb{N}} \mu_L^*(E \cap I_n)$, and this is actually all that is needed to derive equation (2) (again, replacing $\mu_L$ with $\mu_L^*$).

Thanks a lot for your consideration

A: You are correct. However, if we no longer assume $E$ is measurable then we have to use the outer measure (as you pointed out) and in general we much prefer to deal with measures. The outer measure is a useful tool for constructing measures, but once we have succeeded in doing that we tend to discard it.


text:
Q: Eliminate redundant Left in Either Given the code below that uses Either in two methods, is there a way to eliminate case Left(error) => Left(error) in the duplicate method as it simply passes through the error variable?
object HelloScala extends App{

   def duplicateAgain(a:Int): Future[Either[String,Int]] = Future {
       if (a>0)
          Right(a*2)
       else
          Left("Error")
   }

   def duplicate(a: Int): Future[Either[String,Int]] = {
       val future = duplicateAgain(a)
       future.map { either =>
         either match {
             case Right(response) => Right(response * 2)
             case Left(error) => Left(error)  // <-- this seems redundant
           }
       }
   }

    val future2 = duplicate(-1)
    future2.map { either =>
      either match {
        case Right(response) => println(response)
        case Left(error) => println(error)
      }
    }

    Thread.sleep(10000)
}

A: Use map - replace
either match {
    case Right(response) => Right(response * 2)
    case Left(error) => Left(error)  // <-- this seems redundant
}

with
either.map(response => response * 2)

As the documentation for Either says

Either is right-biased, which means that Right is assumed to be the default case to operate on. If it is Left, operations like map and flatMap return the Left value unchanged


text:
Q: Is there a "synchronous" module definition framework for JavaScript Apps? I am looking for a "module definition" framework to run on the server when deploying my JavaScript App.
I am aware of require.js and other AMD frameworks. However, the necessity to implement define() and require() in my production code is non-satisfying for my purposes and since the App will be deployed in one file, I do not need the ability to inject scripts asynchronously.
Is there a build tool that can merge scripts without adding infrastructure code?
For clarification: The HTML page embedding the scripts is not relevant to my problem. The merging process should be done on script level.
main.js:
function a() {
    import("b");
    b();
}

b.js:
var b = function() {
    alert("b!");
};

Should simply become something like:
function a() {
    var b = function() {
        alert("b!");
    };
    b();
}

A: So you want a tool to find and replace
<script src="SOURCE_URI" type="text/javascript"></script>

in your HTML file With
<script type="text/javascript">
CONTENT_OF_SOURCE_URI
</script>

Or maybe you want to collect all of the SOURCE_URI's and then combine them into one concatenated file and then run that file into a JavaScript compiler/optimizer/obfuscater like Closure and then output the inline script?
Most of the tools that exist will probably use require() and take a JS file as the input, so I suggest you write your own. A simple regex to parse the SRC= out of the script tags in your HTML will probably suffice.
edit https://developers.google.com/closure/compiler/docs/api-tutorial3

With the default compilation level of SIMPLE_OPTIMIZATIONS, the Closure Compiler makes JavaScript smaller by renaming local variables.
  There are symbols other than local variables that can be shortened,
  however, and there are ways to shrink code other than renaming
  symbols. Compilation with ADVANCED_OPTIMIZATIONS exploits the full
  range of code-shrinking possibilities.
Compare the outputs for SIMPLE_OPTIMIZATIONS and
  ADVANCED_OPTIMIZATIONS for the following code:

function unusedFunction(note) {
  alert(note['text']);
}

function displayNoteTitle(note) {
  alert(note['title']);
}

var flowerNote = {};
flowerNote['title'] = "Flowers";
displayNoteTitle(flowerNote);

Compilation with SIMPLE_OPTIMIZATIONS shortens the code to this:

function unusedFunction(a){alert(a.text)}function displayNoteTitle(a){alert(a.title)}var flowerNote={};flowerNote.title="Flowers";displayNoteTitle(flowerNote);

Compilation with ADVANCED_OPTIMIZATIONS shortens the code even further
  to this:

var a={};a.title="Flowers";alert(a.title);

Both of these scripts produce an alert reading "Flowers", but the
  second script is much smaller.


text:
Q: Let $a,b,c$ positive integers such that $\left(1+\frac{1}{a}\right)\left(1+\frac{1}{b}\right)\left(1+\frac{1}{c}\right) = 3$. Find those triples. Full question: Let $a$,$b$,$c$ be three positive integers such that $\left(1+\frac{1}{a}\right)\left(1+\frac{1}{b}\right)\left(1+\frac{1}{c}\right) = 3$. Find those triples.
This is actually a national competition question in Vietnam (Violympic), which I have attended (and did poorly, but had a lot of fun).
I have understood almost every questions asked that day, but this one really makes my head pop, because I haven't learn much about integer solution equation and how to solve hard cases (like that one)
I have solved that a,b,c can't be all the same, because:
$$a = b = c$$
$$\implies(1+\frac{1}{a})(1+\frac{1}{b})(1+\frac{1}{c})=(1+\frac{1}{a})^3=3$$
$$⟺1+ \frac{1}{a}=\sqrt[3]{3}$$
$$⟺\frac{1}{a}=\sqrt[3]{3}-1$$
$$⟺a=b=c= \frac{1}{(\sqrt[3]{3}-1)}$$
And using wolframalpha.com, I found out that $(a,b,c) \in \{(1,3,8),(1,4,5),(2,2,3)\}$, but stuck at how to solve it.
Thank you in advance for checking out. I really appreciate your effort.

A: Suppose $a\geq 3$, then
$$\left(1+\frac{1}{a}\right)\left(1+\frac{1}{b}\right)\left(1+\frac{1}{c}\right)\leq\left(1+\frac{1}{3}\right)^3=\frac{64}{27}<3$$
(note that $a\leq b\leq c$), a contradiction. Hence $a=1,2$.
If $a=1$, it comes to solve $(1+1/b)(1+1/c)=3/2$. The same trick shows $b<5$. Now one may simply list all possible values of $b$.
The case $a=2$ can be solved similarly.


text:
Q: Substitute invalid UTF-8 characters in text file I have a large text file that comes from a SQLite dump. Somehow some invalid characters got into the database and appear in the dump as �
Now I need to use some tool (grep, sed, tr) to remove (or replace) the � characters and keep all the rest (punctuation, accented characters etc).
My difficulty is finding how to represent non-printable characters in grep. The image bellow shows how I see the text in Atom

And how gedit opens it:

I placed an example file in the following link.
https://drive.google.com/open?id=1vA6uogwGwGB14aJN3LT6Ju0LhadUMyEX
Any idea how to fix this mess?

A: Could no do this using grep / sed / tr. So I ended up writing a simple Python script to ignore those characters.
The code is in:
https://gist.github.com/dvictori/c277aa12d0f7f1bcc5b0c061227f1442


text:
Q: material-ui button active style I am trying to workout how I would have appbar buttons that link to components show a different style when active.
I should also note: this is a my first material-ui app and the docs are not so clear.
Basically I want an underline on the button that is active.
<Button color="inherit" component={Link} to={"/"}>Home</Button>
<Button color="inherit" component={Link} to={"/About"}>About</Button>

My full code.
import React, {useState } from 'react';
import { Link as Links } from 'react-router-dom';
import ReactDOM from 'react-dom';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Fab from '@material-ui/core/Fab';
//import Icon from '@material-ui/core/Icon';
import Toolbar from '@material-ui/core/Toolbar';
import Link from '@material-ui/core/Link';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';

const useStyles = makeStyles(theme => ({
    root: {
      flexGrow: 1,
    },
    menuButton: {
      marginRight: theme.spacing(2),
    },
    fab: {
      position: 'absolute',
      background:'red',
      bottom: theme.spacing(2),
      right: theme.spacing(2),
      "&:hover, &:focus":{
        background:'black',
      }
    },
    title: {
      flexGrow: 1,
      align:'center',
    },
  }));

  function Nav() {

    const classes = useStyles();
    const [icon,setIcon] = useState(false)

    const fabIcon = {
      color: 'white',
      fontSize: 40,
    };

    const handleClick = e => {
      setIcon(!icon)
      { icon ? document.getElementById("player").play() : document.getElementById("player").pause() }
    }

    return (

        <AppBar position="static">
          <Toolbar>
            <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="Menu">
              <MenuIcon />
            </IconButton>
            <Typography variant="h6" align="center" className={classes.title}>
              News
            </Typography>
            <Button color="inherit">Login</Button>
            <Button color="inherit" component={Links} to={"/"} linkButton={true}>Home</Button>
            <Button color="inherit" component={Links} to={"/about"}>About</Button>
          </Toolbar>
        </AppBar>
        <AppBar position="static">
      </AppBar>
        <audio id="player">
                <source
                    src="https://samcloud.spacial.com/api/listen?sid=106487&m=sc&rid=184639"
                    type="audio/mpeg"
                />
            </audio>
            <Fab aria-label='test' className={classes.fab}>

            { icon ? 'play_circle_outline' : 'pause_circle_outline'}
          </Fab>

    );
  }

  export default class GrandChild extends React.Component {

    componentDidMount() {
      setTimeout(function(){ document.getElementById("player").play() }, 3000);
    }

    value() {
      return ReactDOM.findDOMNode(this.refs.input).value;
    }

    render() {
      return (

      );
    }
  }

A: I recently had the same issue, and I solved it by using NavLink instead of Link from react-router-dom!
Example:
<Button
  className={classes.button}
  component={NavLink}
  to="/page-link"
>

This will add the class ".active" to active buttons.
Using material's makeStyles hook, you can then style the buttons with this class:
const useStyles = makeStyles({
  button: {
    "&.active": {
      background:'black',
    },
  },
});

A: If you're not using any third-party library like Gatsby, React-router then you should consider about this Tabs

Code:
import React from 'react';
import { makeStyles, Theme } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';

interface TabPanelProps {
  children?: React.ReactNode;
  index: any;
  value: any;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box p={3}>
          <Typography>{children}</Typography>
        </Box>
      )}

  );
}

function a11yProps(index: any) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper,
  },
}));

export default function SimpleTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
    setValue(newValue);
  };

  return (

      <AppBar position="static">
        <Tabs value={value} onChange={handleChange} aria-label="simple tabs example">
          <Tab label="Item One" {...a11yProps(0)} />
          <Tab label="Item Two" {...a11yProps(1)} />
          <Tab label="Item Three" {...a11yProps(2)} />
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        Item One
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>

  );
}

To master in Material UI Tabs


text:
Q: Puppet Master install I am using below release of redhat
cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.4 (Santiago)

I am trying to install puppet master on this server.
Here is what I did:
rpm --quiet -ivh http://yum.puppetlabs.com/el/6/products/x86_64//puppetlabs-release-6-10.noarch.rpm
 yum install puppet-master
Setting up Install Process
No package puppet-master available.
Error: Nothing to do

I guess I need different package than what I have, Could someone point me to right direction here.
Thanks for your help.

A: Looks like you might have a typo in the URL you used.
rpm -ivh http://yum.puppetlabs.com/el/6/products/x86_64/puppetlabs-release-6-10.noarch.rpm
yum install -y puppet-server puppet facter

A: The package is puppet-server not puppet-master
sudo yum install puppet-server


text:
Q: Add missing values to grouped data This is a follow up to my question. I get my grouped value by date from the array of objects. When I group the values can I fill in the metric as 0 when grouped by date for missing types per day.
This is my array:
arr = [
        {
           "date": "2020-01-01",
           "metric": 32,
           "type": "Google"
        },
        {
           "date": "2020-01-01",
           "metric": 24,
           "type": "Bing"
        },
        {
           "date": "2020-01-02",
           "metric": 1,
           "type": "Google"
        },
        {
           "date": "2020-01-02",
           "metric": 32,
           "type": "Jeeves"
        },
        {
           "date": "2020-01-03",
           "metric": 24,
           "type": "Bing"
        },
        {
           "date": "2020-01-03",
           "metric": 30,
           "type": "Google"
        }
    ]

This is how I group the data:
const groupBy = (array, key) => {
    return array.reduce((result, currentValue) => {
      (result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
      return result;
    }, {});
};

const personGroupedByColor = groupBy(arr, 'date');

My result is:
2020-01-01:
0: {date: "2020-01-01", metric: 32, type: "Google"}
1: {date: "2020-01-01", metric: 24, type: "Bing"}
2020-01-02:
0: {date: "2020-01-02", metric: 1, type: "Google"}
1: {date: "2020-01-02", metric: 32, type: "Jeeves"}
2020-01-03:
0: {date: "2020-01-03", metric: 24, type: "Bing"}
1: {date: "2020-01-03", metric: 30, type: "Google"}

Is there any way I can get:
2020-01-01:
0: {date: "2020-01-01", metric: 32, type: "Google"}
1: {date: "2020-01-01", metric: 24, type: "Bing"}
2: {date: "2020-01-01", metric: 0, type: "Jeeves"}
2020-01-02:
0: {date: "2020-01-02", metric: 1, type: "Google"}
1: {date: "2020-01-02", metric: 0, type: "Bing"}
2: {date: "2020-01-02", metric: 32, type: "Jeeves"}
2020-01-03:
0: {date: "2020-01-03", metric: 30, type: "Google"}
1: {date: "2020-01-03", metric: 24, type: "Bing"}
2: {date: "2020-01-03", metric: 0, type: "Jeeves"}

Can I replace the missing values with the metric of 0?

A: You can create a Set of all the different type values, then iterate over each value in personGroupedByColor, checking to see that they have all of the different type values, and if not, pushing a new object with that type and a metric of 0:

arr = [{
    "date": "2020-01-01",
    "metric": 32,
    "type": "Google"
  },
  {
    "date": "2020-01-01",
    "metric": 24,
    "type": "Bing"
  },
  {
    "date": "2020-01-02",
    "metric": 1,
    "type": "Google"
  },
  {
    "date": "2020-01-02",
    "metric": 32,
    "type": "Jeeves"
  },
  {
    "date": "2020-01-03",
    "metric": 24,
    "type": "Bing"
  },
  {
    "date": "2020-01-03",
    "metric": 30,
    "type": "Google"
  }
]

const groupBy = (array, key) => {
  return array.reduce((result, currentValue) => {
    (result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
    return result;
  }, {});
};

let personGroupedByColor = groupBy(arr, 'date');

const types = new Set(arr.map(a => a.type));

for (a in personGroupedByColor) {
  types.forEach(t => {
    if (!personGroupedByColor[a].some(v => v.type == t)) {
      personGroupedByColor[a].push({
        "date": personGroupedByColor[a][0].date,
        "metric": 0,
        "type": t
      });
    }
  })
}
console.log(personGroupedByColor);


text:
Q: PDF reader with option to search multiple words at the time/match any of the words Are there any PDF readers with advanced search options -  searching several words at a time to be exact? Adobe has it by the name match any of the words as explained here.
Regular (standard) search would acquire searching dog, viewing result, then cat, view result, then monkey... - which would mean I would go through entire file 3 times.
I wish to input a list of words (strings) cat, dog, monkey, baby lion, and as I go through results, one by one, have all of the matching strings displayed, requiring going trough entire file only once.
Another great option would be to search (in a described way)  in multiple files. I've read  grep can do that but, I wish my results were displayed in (pdf reader) GUI.
Linux Mint 18.1 Serena

A: Okular has this feature, under Thumbnails Search (which made it a bit hard to find since it is not in standard search). It highlights each word in a different color so you can see them scrolling through a file.

DISCLAMER:  Doesn't work in case of "baby lion"

A: If you are talking about several words that appear one after another, then every pdf reader should do. Evince is one example.
If you need something more exotic, then you must specify what do you want to do.


text:
Q: How to get the data from 3 tables with one to many relation I have table named SCORES, then inside has foreign key named subject_id which relationship is one to many from table named SUBJECTS then inside table SUBJECTS has foreign key also named user_id which relationship is one to many from table named USERS, now I was able to show the list of subject from SCORES table now how to get the username who's subject_id is equal to user_id.
Controller:
$scores = Score::with('lead','subject')->where('lead_id','=',$id)->get();

$subjects=Subject::with('user')->get();

View

  @foreach($scores as $score)

  @endforeach

  @foreach($scores as $score)

   {{$score->subject->subject_name}}
  @endforeach

A: From chat discussion it found that you have belongsTo relation between Subject and User model. You are using the subject_id in your scores table and your Score model has belongsTo relation to Subject Model. So, yes you can fetch the user details like this
{{$score->subject->user->name}}

A: You need to use belongTo relationship in score model.
public function user(){
   return $this->belongsTo(User::class,'subject_id ');
}

Now you can get user name something like this.
$scores = Score::with('lead','subject')->with('user')->where('lead_id','=',$id)->get();

A: Index.php
      $posts = Posts::read_all();

      foreach ( $posts as $post )
 {
         echo $post->post_name ."
";
          echo $post->post_text ."
";

$categories_array = Posts::get_cats_by_post_id($post->id);

foreach ($categories_array as $category)
{
    echo "•". $category->category_name ."
";
}

}
Post Class
public static function get_cats_by_post_id($id)
{
    $db = new Database();
$sql = "SELECT  cats_to_posts.cats_id
        FROM    cats_to_posts
        WHERE   cats_to_posts.post_id = {$id}";

$result = $db->exe_query($sql);

$cat_id_array = array(); // stores array of category ids that match post ids

while ( $record = $result->fetch_object() )
{
    $cat_id_array[] = $record;
}

$cat_name_array = array(); // stores array of category names that match category ids
foreach($cat_id_array as $cat_id)
{
    $new_sql = "SELECT  category_name
                FROM    categories
                WHERE   id = ". $cat_id->cats_id;

    $new_result = $db->exe_query($new_sql);

    while ( $new_record = $new_result->fetch_object() )
    {
        $cat_name_array[] = $new_record;
    }

}

return $cat_name_array;

}
Try this
Hope  so this will work.


text:
Q: axios producing strange URL I am working in a Vue.js & Laravel project. Here I configure axios in main.js file like this axios.defaults.baseURL = 'http://127.0.0.1:8000/api';.
I am using axios in one of my component method like below.
methods: {
            get_words () {
                console.log(this.word_id);
                axios.get('/words/'+ this.word_id)
                .then(response => {
                    this.words = response.data;
                })
                .catch();
            },
        },

I am getting below URL in error in console.
http://127.0.0.1:8000/api/words/%E0%A6%86%E0%A6%B2-%E0%A6%86'%E0%A6%B0%E0%A6%BE%E0%A6%AB

A: const id = this.word_id;
axios.get(`/words/${id}`)

this would work for you.
Notice that it is not single quotes. It's backticks (``)


text:
Q: Assembly CPU frequency measuring algorithm What are the common algorithms being used to measure the processor frequency?

A: I'm gonna date myself with various details in this answer, but what the heck...
I had to tackle this problem years ago on Windows-based PCs, so I was dealing with Intel x86 series processors like 486, Pentium and so on.  The standard algorithm in that situation was to do a long series of DIVide instructions, because those are typically the most CPU-bound single instructions in the Intel set.  So memory prefetch and other architectural issues do not materially affect the instruction execution time -- the prefetch queue is always full and the instruction itself does not touch any other memory.
You would time it using the highest resolution clock you could get access to in the environment you are running in.  (In my case I was running near boot time on a PC compatible, so I was directly programming the timer chips on the motherboard.  Not recommended in a real OS, usually there's some appropriate API to call these days).
The main problem you have to deal with is different CPU types.  At that time there was Intel, AMD and some smaller vendors like Cyrix making x86 processors.  Each model had its own performance characteristics vis-a-vis that DIV instruction.  My assembly timing function would just return a number of clock cycles taken by a certain fixed number of DIV instructions done in a tight loop.
So what I did was to gather some timings (raw return values from that function) from actual PCs running each processor model I wanted to time, and record those in a spreadsheet against the known processor speed and processor type.  I actually had a command-line tool that was just a thin shell around my timing function, and I would take a disk into computer stores and get the timings off of display models!  (I worked for a very small company at the time).
Using those raw timings, I could plot a theoretical graph of what timings I should get for any known speed of that particular CPU.
Here was the trick:  I always hated when you would run a utility and it would announce that your CPU was 99.8 Mhz or whatever.  Clearly it was 100 Mhz and there was just a small round-off error in the measurement.  In my spreadsheet I recorded the actual speeds that were sold by each processor vendor.  Then I would use the plot of actual timings to estimate projected timings for any known speed.  But I would build a table of points along the line where the timings should round to the next speed.
In other words, if 100 ticks to do all that repeating dividing meant 500 Mhz, and 200 ticks meant 250 Mhz, then I would build a table that said that anything below 150 was 500 Mhz, and anything above that was 250 Mhz.  (Assuming those were the only two speeds available from that chip vendor).  It was nice because even if some odd piece of software on the PC was throwing off my timings, the end result would often still be dead on.
Of course now, in these days of overclocking, dynamic clock speeds for power management, and other such trickery, such a scheme would be much less practical.  At the very least you'd need to do something to make sure the CPU was in its highest dynamically chosen speed first before running your timing function.
OK, I'll go back to shooing kids off my lawn now.

A: One way on x86 Intel CPU's since Pentium would be to use two samplings of the RDTSC instruction with a delay loop of known wall time, eg:
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

uint64_t rdtsc(void) {
    uint64_t result;
    __asm__ __volatile__ ("rdtsc" : "=A" (result));
    return result;
}

int main(void) {
    uint64_t ts0, ts1;
    ts0 = rdtsc();
    sleep(1);
    ts1 = rdtsc();
    printf("clock frequency = %llu\n", ts1 - ts0);
    return 0;
}

(on 32-bit platforms with GCC)
RDTSC is available in ring 3 if the TSC flag in CR4 is set, which is common but not guaranteed.  One shortcoming of this method is that it is vulnerable to frequency scaling changes affecting the result if they happen inside the delay.  To mitigate that you could execute code that keeps the CPU busy and constantly poll the system time to see if your delay period has expired, to keep the CPU in the highest frequency state available.

A: I use the following (pseudo)algorithm:
basetime=time();    /* time returns seconds */

while (time()==basetime);
stclk=rdtsc();    /* rdtsc is an assembly instruction */

basetime=time();
while (time()==basetime
endclk=rdtsc();

nclks=encdclk-stclk;

At this point you might assume that you've determined the clock frequency but even though it appears correct it can be improved.
All PCs contain a PIT (Programmable Interval Timer) device which contains counters which are (used to be) used for serial ports and the system clock. It was fed with a frequency of 1193182 Hz. The system clock counter was set to the highest countdown value (65536) resulting in a system clock tick frequency of 1193182/65536 => 18.2065 Hz or once every 54.925 milliseconds.
The number of ticks necessary for the clock to increment to the next second will therefore depend. Usually 18 ticks are required and sometimes 19. This can be handled by performing the algorithm (above) twice and storing the results. The two results will either be equivalent to two 18 tick sequences or one 18 and one 19. Two 19s in a row won't occur. So by taking the smaller of the two results you will have an 18 tick second. Adjust this result by multiplying with 18.2065 and dividing by 18.0 or, using integer arithmetic, multiply by 182065, add 90000 and divide by 180000. 90000 is one half of 180000 and is there for rounding. If you choose the calculation with integer route make sure you are using 64-bit multiplication and division.
You will now have a CPU clock speed x in Hz which can be converted to kHz ((x+500)/1000) or MHz ((x+5000000)/1000000). The 500 and 500000 are one half of 1000 and 1000000 respectively and are there for rounding. To calculate MHz do not go via the kHz value because rounding issues may arise. Use the Hz value and the second algorithm.

A: Intel CPUs after Core Duo support two Model-Specific registers called IA32_MPERF and IA32_APERF.
MPERF counts at the maximum frequency the CPU supports, while APERF counts at the actual current frequency.
The actual frequency is given by:

You can read them with this flow
; read MPERF
mov ecx, 0xe7
rdmsr
mov mperf_var_lo, eax
mov mperf_var_hi, edx

; read APERF
mov ecx, 0xe8
rdmsr
mov aperf_var_lo, eax
mov aperf_var_hi, edx

but note that rdmsr is a privileged instruction and can run only in ring 0.
I don't know if the OS provides an interface to read these, though their main usage is for power management, so it might not provide such an interface.

A: That was the intention of things like BogoMIPS, but CPUs are a lot more complicated nowadays. Superscalar CPUs can issue multiple instructions per clock, making any measurement based on counting clock cycles to execute a block of instructions highly inaccurate.
CPU frequencies are also variable based on offered load and/or temperature. The fact that the CPU is currently running at 800 MHz does not mean it will always be running at 800 MHz, it might throttle up or down as needed.
If you really need to know the clock frequency, it should be passed in as a parameter. An EEPROM on the board would supply the base frequency, and if the clock can vary you'd need to be able to read the CPUs power state registers (or make an OS call) to find out the frequency at that instant.
With all that said, there may be other ways to accomplish what you're trying to do. For example if you want to make high-precision measurements of how long a particular codepath takes, the CPU likely has performance counters running at a fixed frequency which are a better measure of wall-clock time than reading a tick count register.

A: "lmbench" provides a cpu frequency algorithm portable for different architecture.
It runs some different loops and  the processor's clock speed is the greatest common divisor of the execution frequencies of the various loops.
this method should always work when we are able to get loops with cycle counts that are relatively prime.
http://www.bitmover.com/lmbench/

A: One option is to sense the CPU frequency, by running code with known instructions per loop
This functionality is contained in 7zip, since about v9.20 I think.
> 7z b
7-Zip 9.38 beta  Copyright (c) 1999-2014 Igor Pavlov  2015-01-03

CPU Freq:  4266  4000  4266  4000  2723  4129  3261  3644  3362

The final number is meant to be correct (and on my PC and many others, I have found it to be quite correct - the test runs very quick so turbo may not kick in, and servers set in Balanced/Power Save modes most likely give readings of around 1ghz)
The source code is at GitHub (Official source is a download from 7-zip.org)
With the most significant portion being:
#define YY1 sum += val; sum ^= val;
#define YY3 YY1 YY1 YY1 YY1
#define YY5 YY3 YY3 YY3 YY3
#define YY7 YY5 YY5 YY5 YY5
static const UInt32 kNumFreqCommands = 128;

EXTERN_C_BEGIN

static UInt32 CountCpuFreq(UInt32 sum, UInt32 num, UInt32 val)
{
  for (UInt32 i = 0; i < num; i++)
  {
    YY7
  }
  return sum;
}

EXTERN_C_END

A: On Intel CPUs, a common method to get the current (average) CPU frequency is to calculate it from a few CPU counters:
CPU_freq = tsc_freq * (aperf_t1 - aperf_t0) / (mperf_t1 - mperf_t0)

The TSC (Time Stamp Counter) can be read from userspace with dedicated x86 instructions, but its frequency has to be determined by calibration against a clock. The best approach is to get the TSC frequency from the kernel (which already has done the calibration).
The aperf and mperf counters are model specific registers MSRs that require root privileges for access. Again, there are dedicated x86 instructions for accessing the MSRs.
Since the mperf counter rate is directly proportional to the TSC rate and the aperf rate is directly proportional to the CPU frequency you get the CPU frequency with the above equation.
Of course, if the CPU frequency changes in your t0 - t1 time delta (e.g. due due frequency scaling) you get the average CPU frequency with this method.
I wrote a small utility cpufreq which can be used to test this method.
See also:

*

*[PATCH] x86: Calculate MHz using APERF/MPERF for cpuinfo and scaling_cur_freq. 2016-04-01, LKML

*Frequency-invariant utilization tracking for x86. 2020-04-02, LWN.net

A: I'm not sure why you need assembly for this.  If you're on a machine that has the /proc filesystem, then running:
> cat /proc/cpuinfo

might give you what you need.

A: A quick google on AMD and Intel shows that CPUID should give you access to the CPU`s max frequency.


text:
Q: EventListener work only once I have this HTML code,
<input type='button' id='addQuestion' class='btn' value='Add Question'/>

and a JavaScript Code,
var question;
document.addEventListener('DOMContentLoaded', function(){
    var aQ = document.getElementById("addQuestion");
    aQ.addEventListener("click",addQ);
});

function addQ(){
question = question + 1;
document.getElementById("content").innerHTML += "
question
";
}

It supposed to be able to create more than one div.
I tried to use onclick instead of EventListener,
<input type='button' id='addQuestion' class='btn' onclick="addQ()" value='Add Question'/>

and it is working.

A: Some minor changes (demo):
    var question = 0; // init as typeof Number

    window.addEventListener('DOMContentLoaded', function(){
        var aQ = document.getElementById("addQuestion");
        aQ.addEventListener("click",addQ);
    });

    function addQ(){
        question = question + 1;
        document.getElementById("content").innerHTML += "
"+question+"
";
        //                                    Use the variable--^^^^^^^^
    }


text:
Q: How to reduce the file size/rendering performance of PDFs embedding large EPS? If one has a PDF with EPS-like graphics embedded.
The EPS-like is something like finite-element method plot or browian motion which takes quite a long time for the machine to render.
That makes the rendering of PDF slow/freezed.
Any suggestion to improve rendering performance(more scrolling/print efficient) on a Mac using some quartz filers or Adobe Acrobat?
Thanks a lot !


text:
Q: Modulus 11 Counter I'm trying to build a modulus 11 counter that will count from 0 to 10 and reset at state 11 in Multisim using a 4516 counter and a D-FF based off the following figure:

Because the D-FF inserts a delay of one clock cycle before the RESET signal is sent to the 4516 and the AND gate, I've place the 1 at 12 instead of 11.

Based on this I've set up my circuit in Multisim as follows:

However, It's not working correctly and counts up to 13 before resetting instead of from 0 to 10.

A: As ErikR observed, you haven't defined P0 through P3.  However, assertions of PL on pin 1 of U1 are intended to copy the inputs from those pins to the counter's output.
In truth, you don't mean to use this feature at all.  I can see this because you are using a decoder to recognize the pattern 11xx and through some additional logic you use that pattern to assert MR on pin 9 of U1.  This forces the counter to take on the value 0000.
To avoid the conflict, tie pin 1 of U1 low and don't use the preset feature.  I make a practice of not letting the inputs of CMOS integrated circuits float, so if you wish to follow the same practice, you could tie P0 through P3 low.  With PL (pin 1) low, these will have no effect.
But there is another mistake.  Consider the moment when the counter contains the value 1011 (11 in decimal) and the clock input CP on pin 15 of U1 goes high.  This causes the counter to increment to 1100 (12 in decimal).  The same clock pulse also is used to update the flip-flop in U2A.  It will load a 0 because when the clock goes high, the 10xx pattern produces a zero input at D1 (pin 5) of U2A.  I'm sure you were expecting it to recognize the pattern 11xx at this moment, but you must reckon with the delay of the signal through the counter.  Effectively, the flip-flop is one cycle behind the counter.  But even if you changed the decoding to recognize 1x11, you still would have an error because the output of U5A wouldn't go high for another half cycle, since U4A makes U5A run on negative-going clock edges.  This would cause a reset halfway through the display of 1100.  But since you're not decoding 1x11, but 11xx, the counter outputs 1100, then after one cycle the D flip-flop recognizes this, but at this moment the counter outputs 1101.  After half a cycle, the D flip-flop's output causes a reset of the counter halfway through the pattern 1101.  That's why your counter goes to 13 no matter what you do with the preset pins.
Because the counter does not have a synchronous-load feature, you can't make it hold the pattern 1011 for a full clock cycle, and then output 0000 except by asserting the reset at the MR input (pin 9).  It's an asynchronous input, so takes effect at once, but the counter will have fleetingly counted up to 1100 before the decoding logic can take effect and cause the MR pin to go high.  If you don't mind the brief appearance of 1100, just change the decoder to look for 1x11 and get rid of U4A.  This will cause the counter to go very briefly to 1100 and then reset to 0000 when the clock goes high.  You will never see it on the lights, but if you're using the counter's output to do something, other circuitry might observer and act on that brief 1100 showing up.
If you use a different counter, one that allows synchronous loading of a desired pattern, then you can avoid the brief appearance of the objectionable 1100 output altogether.