text:
Q: How to export a Vagrant virtual machine to transfer it I have a vagrant box up and running (configured with a LAMP stack). I need to transfer it to another PC. How can I export it?
I guess that I can get a file (or files) that can be copied to another PC, so there I can run some command to import the vagrant box.

A: The easiest way would be to package the Vagrant box and then copy (e.g. scp or rsync) it over to the other PC, add it and vagrant up ;-)
For detailed steps, check this out => Is there any way to clone a vagrant box that is already installed

A: My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:

*

*I'm vagrant w/ virtualbox on a Mac

*I'm using git

This is what worked for me:
1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine.
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines.
5.) `git clone my_project`
6.) `vagrant up`

I had a few problems with VB Guest additions.

I fixed them with this solution.

A: This is actually pretty simple

*

*Install virtual box and vagrant on the remote machine

*Wrap up your vagrant machine
vagrant package --base [machine name as it shows in virtual box] --output /Users/myuser/Documents/Workspace/my.box

*copy the box to your remote

*init the box on your remote machine by running
vagrant init [machine name as it shows in virtual box] /Users/myuser/Documents/Workspace/my.box

*Run vagrant up

A: None of the above answers worked for me. I have been 2 days working out the way to migrate a Vagrant + VirtualBox Machine from a computer to another... It's possible!
First, you need to understand that the virtual machine is separated from your sync / shared folder. So when you pack your machine you're packing it without your files, but with the databases.
What you need to do:
1- Open the CMD of your computer 1 host machine (Command line. Open it as Adminitrator with the right button -> "Run as administrator") and go to your vagrant installed files. On my case: C:/VVV
You will see your Vagrantfile an also these folders:
/config/
/database/
/log/
/provision/
/www/
Vagrantfile
...

The /www/ folder is where I have my Sync Folder with my development domains. You may have your sync folder in other place, just be sure to understand what you are doing. Also /config and /database are sync folders.
2- run this command: vagrant package --vagrantfile Vagrantfile
(This command does a package of your virtual machine using you Vagrantfile configuration.)
Here's what you can read on the Vagrant documentation about the command:

A common misconception is that the --vagrantfile option will package a
  Vagrantfile that is used when vagrant init is used with this box. This
  is not the case. Instead, a Vagrantfile is loaded and read as part of
  the Vagrant load process when the box is used. For more information,
  read about the Vagrantfile load order.

https://www.vagrantup.com/docs/cli/package.html
When finnished, you will have a package.box file.
3- Copy all these files (/config, /database, Vagrantfile, package.box, etc.) and paste them on your Computer 2 just where you want to install your virtual machine (on my case D:/VVV).
Now you have a copy of everything you need on your computer 2 host.
4- run this: vagrant box add package.box --name VVV
(The --name is used to name your virtual machine. On my case it's named VVV)
(You can use --force if you already have a virtual machine with this name and want to overwrite it. (Use carefully !))
This will unpack your new vagrant Virtual machine.
5- When finnished, run:
vagrant up
The machine will install and you should see it on the "Oracle virtual machine box manager". If you cannot see the virtual machine, try running the Oracle VM box as administrator (right click -> Run as administrator)
You now may have everything ok but remember to see if your hosts are as you expected:
c:/windows/system32/hosts

6- Maybe it's a good idea to copy your host file from your Computer 1 to your Computer 2. Or copy the lines you need.
In my case these are the hosts I need:
192.168.50.4 test.dev
192.168.50.4 vvv.dev
...

Where the 192.168.50.4 is the IP of my Virtual machine and test.dev and vvv.dev are developing hosts.
I hope this can help you :) I'll be happy if you feedback your go.
Some particularities of my case that you may find:
When I ran vagrant up, there was a problem with mysql, it wasn't working. I had to run on the Virtual server (right click on the oracle virtual machine -> Show console): apt-get install mysql-server
After this, I ran again vagrant up and everything was working but without data on the databases. So I did a mysqldump all-tables from the Computer 1 and upload them to Computer 2.
OTHER NOTES:
My virtual machine is not exactly on Computer 1 and Computer 2. For example, I made some time ago internal configuration to use NFS (to speed up the server sync folders) and I needed to run again this command on the Computer 2 host: vagrant plugin install vagrant-winnfsd

A: You have two ways to do this, I'll call it dirty way and clean way:
1. The dirty way
Create a box from your current virtual environment, using vagrant package command:
http://docs.vagrantup.com/v2/cli/package.html
Then copy the box to the other pc, add it using vagrant box add and run it using vagrant up as usual.
Keep in mind that files in your working directory (the one with the Vagrantfile) are shared when the virtual machine boots, so you need to copy it to the other pc as well.
2. The clean way
Theoretically it should never be necessary to do export/import with Vagrant. If you have the foresight to use provisioning for configuring the virtual environment (chef, puppet, ansible), and a version control system like git for your working directory, copying an environment would be at this point simple as running:
git clone <your_repo>
vagrant up

A: As stated in
How can I change where Vagrant looks for its virtual hard drive?
the virtual-machine state is stored in a predefined VirtualBox folder. Copying the corresponding machine (folder) besides your vagrant-project to your other host should preserve your virtual machine state.

A: I had to migrate my Vagrant boxes to a new machine and found this dirty but simple method to work well (it's for VirtualBox-based machines, I assume it can be adapted to other providers):

*

*copy over the VirtualBox box, e.g. by using the "Export/Import Appliance" functionality in the VirtualBox GUI

*copy over the Vagrant directory

*edit .vagrant/machines/default/virtualbox/id in the Vagrant directory to the new VirtualBox ID (which you get via VBoxManage list vms).

A: I also had to copy the private_key file from .vagrant/machines/default/virtualbox folder in order for vagrant ssh to work

A: As of 2019 there is a subcommand: vagrant box repackage
vagrant box repackage --help
Usage: vagrant box repackage <name> <provider> <version>
    -h, --help                       Print this help

You can find name provider and version by running vagrant box list
vagrant box list
macinbox (virtualbox, 10.14.5)

The ouput of vagrant box repackage is a file called package.box which is basically a tgz file which the content can be listed as below:
tar tzf package.box
./metadata.json
./box.ovf
./Vagrantfile
./box-disk001.vmdk


text:
Q: Add static ARP entries on boot [systemd] I wanted to add a number of static ARP entries that will persist across system reboots. For that I tried using a systemd service which would simply populate the ARP table via the /etc/ethers file:
[Unit]
Description=startup-test
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
Group=root
ExecStart=arp -f
Restart=on-failure

[Install]
WantedBy=multi-user.target

This method does not work and the ARP entries are not added on boot, but the systemd service appears to run the arp -f command (though unsuccessfully because the "network is unreachable"):
Output of systemctl status:
● startup.service - startup-test
     Loaded: loaded (/etc/systemd/system/startup.service; enabled; vendor preset: enabled)
     Active: inactive (dead) since Sun 2023-01-29 15:10:53 EET; 1min 7s ago
    Process: 562 ExecStart=arp -f (code=exited, status=0/SUCCESS)
   Main PID: 562 (code=exited, status=0/SUCCESS)
        CPU: 14ms

Jan 29 15:10:52 raspberrypi systemd[1]: Started startup-test.
Jan 29 15:10:53 raspberrypi arp[562]: SIOCSARP: Network is unreachable
Jan 29 15:10:53 raspberrypi arp[562]: arp: cannot set entry on line 1 of etherfile /etc/ethers !
Jan 29 15:10:53 raspberrypi arp[562]: SIOCSARP: Network is unreachable
Jan 29 15:10:53 raspberrypi arp[562]: arp: cannot set entry on line 2 of etherfile /etc/ethers !
Jan 29 15:10:53 raspberrypi systemd[1]: startup.service: Succeeded.

If however I manually start the service with systemctl start, no errors are thrown (and the ARP table is populated as expected).
Output of systemctl status after starting it manually:
● startup.service - startup-test
     Loaded: loaded (/etc/systemd/system/startup.service; enabled; vendor preset: enabled)
     Active: inactive (dead) since Sun 2023-01-29 15:11:55 EET; 5s ago
    Process: 1664 ExecStart=arp -f (code=exited, status=0/SUCCESS)
   Main PID: 1664 (code=exited, status=0/SUCCESS)
        CPU: 13ms

Jan 29 15:11:55 raspberrypi systemd[1]: Started startup-test.
Jan 29 15:11:55 raspberrypi systemd[1]: startup.service: Succeeded.

What is wrong here?
PS. I've managed to do what I want by using dhcpcd hooks. So I'm not looking for an alternative method, I just would like to know what is wrong with the systemd approach.
(Raspbian Bullseye)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Heatmap axis labeling in python I am trying to generate a heatmap of a random matrix with the following code:
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt

data = np.random.rand(7, 7)
ax = sns.heatmap(data)
plt.show()

Which gives me:

However I would like for the axis numberings to start at 1 not at 0, how could I achieve this?

A: You can use ax.set_xticklabels and ax.set_yticklabels to re-label the axes from 1 to 7:
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt

data = np.random.rand(7, 7)
ax = sns.heatmap(data)
ax.set_xticklabels(range(1, 8))
ax.set_yticklabels(range(1, 8))
plt.show()


text:
Q: Multiple Checkbox value in Array I have got a form with a table where various student names and other information will be displayed with a checkbox (status) showing in an array.

*

*The checkbox value is set to 1 or 0 in the table. 1 being active.

*A user will view the info, and if required, disable the entire record by un-checking the checkbox, or re-activate a record by checking the box or do nothing and simply Submit the Form (please see screenshot attached)

All I am trying here is to get the 0 and 1 value so that I can later update the table.
I am getting:

Undefined offset: 2 in C:\xampp\htdocs\SH - Test\test22.php on line 116
  Line 116: echo  $status[$i].'';

I understand, that if the checkboxes are not checked it will not be considered.
I have also tried to use a hidden checkbox with a different id, but couldn't achieve what I want.
Is there any way I can also accept the value of the unchecked boxes?
<?php for ($i=0; $i<=$rowcount-1; $i++){ ?>

    <?php echo $nominee[$i]; ?>
    <textarea name="updated_comment[]" rows="4"><?php echo $comment[$i] ?> </textarea>
    <?php echo $nominator_name[$i]; ?>
    <input type="checkbox" name="status[]" value="1" <?php if ($nomstatus[$i] == 1) echo 'checked'; ?> />

<?php }
if(isset($_POST['submit'])) {
    $status = (isset($_POST['status']) ? $_POST['status'] : '');
    for ($i=0; $i<=$rowcount-1; $i++){
        if (empty($status[$i])){$status[$i] = $nomstatus[$i];}
        elseif ($status[$i] == "1"){$status[$i] = 1;}
        else {$status[$i] = 0;}
        echo  $status[$i].'
';
    }

A: The Undefined offset error means that you are trying to access an invalid array position, for example:
$myArray[0] = "foo";
$myArray[1] = "bar";

echo $myArray[2]; // This should trigger an undefined offset error,
                  // as your array has only two positions

I would guess that the problem would be related to a wrong reusage of the variable $rowcount. I would suggest you to try the following code, where you modify it in order to evaluate the number of elements of $status inside the for loop.
    if(isset($_POST['submit'])) {
        $status = (isset($_POST['status']) ? $_POST['status'] : '');
        for ($i=0; $i < count($status); $i++){
            if (empty($status[$i])){
                $status[$i] = $nomstatus[$i];
            } elseif ($status[$i] == "1"){
                $status[$i] = 1;
            } else {
                $status[$i] = 0;
            }
            echo  $status[$i].'
';
        }
    }


text:
Q: I need a noun in American English that represents the idiom 'to look on the bright side' We're developing an application where we have categories users may progress towards, and one of them is 'to look on the bright side; to live without worry, etc.'. However, categories are titled with a single word, and I have failed to think of a word that perfectly suits that meaning.
Can anyone assist?

A: An optimist is a person who looks on the bright side. Optimism is the word for the perspective itself.
Sanguinity is another option.
Added: Based on your criteria, I would go with either carefreeness or lightheartedness. I personally prefer the second and think it's used more often. Both words are commonly known, if that's what you mean by "popular."

A: How about positivism or brightness or carefree?

A: Cheerful, "noticeably happy and optimistic; bright and pleasant" may suit.
Also consider blithe.  In one sense it means "happy, cheerful" (although Wiktionary claims this usage is dated or literary), and in another sense, "indifferent, careless, showing a lack of concern".  Synonyms of it include
animated, buoyant, cheerful, gay, happy, jovial,  lighthearted, lively, merry, sprightly.
While these are mostly adjectives rather than nouns, as category headings that might not matter.

A: The common British name Felicity means "happiness" and would make a great category name.


text:
Q: Kotlin property initialization I've created the following snippet, not anything that I would actually write in production, but just to help me understand how properties are initialized:
class C {
    val a: String = run {
        println("init a")
        f()
    }
    val b: String = run {
        println("init b: a=$a")
        a
    }

    private fun f(): String {
        println("f(): a=$a, b=$b")
        return b
    }
}

fun main() {
    println(C().a)
    println(C().b)
}

Note that all properties are val and String, so immutable and non-nullable. Yet the output shows that they are null.
Is the result of this code well-defined? Is there somewhere in the language spec that says that a non-nullable property can in fact be null when you access it from the wrong place?

A: According to the Kotlin/Core spec, the order of the execution is specified,

When a classifier type is initialized using a particular secondary constructor ctor delegated to primary constructor pctor which, in turn, is delegated to the corresponding superclass constructor sctor , the following happens, in this initialization order:

*

*[...]

*Each property initialization code as well as the initialization blocks in the class body are invoked in the order of appearance in the
class body;

*[...]

but the values of the uninitialised properties are not.

If any of the properties are accessed before they are initialized w.r.t initialization order (e.g., if a method called in an initialization block accesses a property declared after the initialization block), the value of the property is unspecified. It stays unspecified even after the "proper" initialization is performed.

In other words, you will see the messages printed in the order of
init a
f(): a=null, b=null
init b: a=null
null

but the values are not guaranteed to be null.
There might be stronger guarantees in Kotlin/JVM, but there is no spec for that right now.

A: This is explicitly not an answer, just two small remarks/questions:
First, doesn't one of the three members a, b, or f() need to be set to a or return a value? The way it is in the OPs code, everything is null by definition as there is no non-null value anywhere. The 'call chain' is a –> f() –> b, so if we set b to a value like "start", it would look like this:
class C {
  val a: String = run { f() }
  val b: String = run { "start" }
  private fun f(): String = b
}

fun main() {
  val c = C()
  println(c.a)   // Output: null
  println(c.b)   // Output: "start"
}

Secondly, if the order is changed so that b is appearing in the code before the other two members we get a different result:
class C {
  val b: String = run { "start" }
  val a: String = run { f() }
  private fun f(): String = b
}

fun main() {
  val c = C()
  println(c.a)   // Output: "start"
  println(c.b)   // Output: "start"
}


text:
Q: How to divide beamer into different parts?
I want to divide the beamer into A, B, C, three parts, and A is divided into a and b.
I tried
\minipage{0.3\linewidth} %for A
\minipage{0.5\linewidth} %for a
\minipage{0.5\linewidth} %for b

\minipage{0.3\linewidth} %for B

\minipage{0.3\linewidth} %for C

while it doesn't work.
I also tried \minipage with \subfloat, but the error message with subfloat outside float.
So how to divide the beamer page properly?

A: Try the columns environment from beamer.
\documentclass{beamer}
\newcommand\dummy{Nam dui ligula, fringilla a, euismod sodales, sollicitudin vel, wisi.}

\begin{document}
\begin{frame}{Title}
  \begin{columns}[t]
    \begin{column}{.333\textwidth}
      \begin{minipage}[t][.5\textheight]{\textwidth}
        \dummy
      \end{minipage}\par
      \begin{minipage}[t][.5\textheight]{\textwidth}
        \dummy
      \end{minipage}
    \end{column}
    \begin{column}{.333\textwidth}
      \dummy
    \end{column}
    \begin{column}{.333\textwidth}
      \dummy
    \end{column}
  \end{columns}
\end{frame}
\end{document}


text:
Q: How to prevent menu bar from wrapping? Using Tkinter 8.6 in Python 3.6 on Windows 10, at the moment my root form is rather narrow causing the menu bar to wrap. Is there a way to prevent wrapping? In this particular case, increasing the form width to accommodate the menu is acceptable behavior.
The problem with wrapping is the geometry manager does not compensate - the grid, for instance, will have controls partially out of view since the window is not automatically resized to account for the extra menu height.
Actual:

Expected:

A: No, there is no way to prevent wrapping. The menubar is not under the control of tkinter.
Grid will compensate just fine as long as you don't explicitly set the window size to something smaller than will fit the wrapped menu and your contents. If you aren't setting the window size, and grid isn't compensating, then you need to show an example that illustrates that.


text:
Q: List of reserved words a username can't be?
Possible Duplicate:
Is there a list of common usernames to reserve in a new system?

I'm working on a site where users will have a custom URL e.g.: http://domain.com/username
I want to avoid the situation where a user registers and creates a username that I later need, e.g. if I want a page at domain.com/about and someone's already named themselves 'about'.
Does anyone have a list of generic words that could be added to a blacklist for this?

A: What about using a prefix for site pages, like domain.com/site/about? And just make sure usernames can't include the '/' character.

A: There's some great answers on this StackOverflow question:
https://stackoverflow.com/questions/5316876/is-there-a-list-of-common-usernames-to-reserve-in-a-new-system
Here's the best list I've found:
http://blog.postbit.com/reserved-username-list.html

A: I would  have your users page as a sub section. Ie http://domain.com/users/username
There is no way we or even you could guess what pages you might want to create in future

A: You can always encode any http reserved characters in the username.
You should do this anyway in case someone decides to register the user name /../../etc/passwd


text:
Q: My Karma won't start Or, more accurately, it starts but it doesn't produce results a lot of the time. It just comes back with a command prompt. This only happens some of the time--I can run it one time and it works, then use up arrow in the command window and it fails. It's wasting a lot of time when the tests only report back some of the time. Anyone ever see this?
Edit
Starting it with karma start
Karma.config:

// Karma configuration
// Generated on Thu Sep 18 2014 07:48:58 GMT-0700 (Pacific Daylight Time)

module.exports = function (config) {
    var rootDir = 'TestSplitContent';
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        browserNoActivityTimeout: 30000,

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        //TODO: make more generic, while still keeping correct load order so Karma can pick up new files
        files: [
            rootDir + '/scripts/jquery-2.0.3.js',
            rootDir + '/scripts/angular.js',
            rootDir + '/scripts/angular-mocks.js',
            rootDir + '/scripts/angular-animate.js',
            rootDir + '/scripts/angular-route.js',
            rootDir + '/scripts/angular-sanitize.js',
            rootDir + '/scripts/angular-resource.js',
            rootDir + '/scripts/angular-touch.js',
            rootDir + '/scripts/bootstrap.js',
            rootDir + '/scripts/toastr.js',
            rootDir + '/scripts/moment.js',
            rootDir + '/scripts/angular-ui/ui-bootstrap.js',
            rootDir + '/scripts/angular-ui/ui-bootstrap-tpls.js',
            rootDir + '/scripts/spin.js',
            rootDir + '/scripts/bootstrap-collapse.js',
            rootDir + '/app/app.js',
            rootDir + '/app/config.js',
            rootDir + '/app/config.exceptionHandler.js',
            rootDir + '/app/common/common.js',
            rootDir + '/app/common/commonFilters.js',
            rootDir + '/app/common/xmlParseWrapper.js',
            rootDir + '/app/common/mediaAssetService.js',
            rootDir + '/app/common/logger.js',
            rootDir + '/app/common/spinner.js',
            rootDir + '/app/common/angular-local-storage.js',
            rootDir + '/app/common/imagePreloader.js',
            rootDir + '/app/common/bootstrap/bootstrap.dialog.js',
            rootDir + '/scripts/Types/BrowserInfo.js',
            rootDir + '/scripts/Types/ConnectionSpeed.js',
            rootDir + '/scripts/Utilities/DeviceCaps.js',
            rootDir + '/scripts/Utilities/GeneralUtilities.js',
            rootDir + '/scripts/Utilities/string.js',
            rootDir + '/scripts/WebServiceUtils/AjaxAsyncAPI.js',
            rootDir + '/scripts/WebServiceUtils/AjaxSyncAPI.js',
            rootDir + '/scripts/WebServiceUtils/BoolDataMessage.js',
            rootDir + '/scripts/WebServiceUtils/BoolMessage.js',
            rootDir + '/scripts/WebServiceUtils/Utils.js',
            rootDir + '/scripts/assessment/custom.module.js',
            rootDir + '/app/layout/shell.js',
            rootDir + '/app/controllers/NotFound.js',
            rootDir + '/app/services/*.js',
            /*modules*/
            rootDir + '/app/signon/bypass/bypass.module.js',
            rootDir + '/app/culturefit/cultureFit.module.js',
            rootDir + '/app/dataverification/dataVerification.module.js',
            rootDir + '/app/feedback/feedback.module.js',
            rootDir + '/app/signon/nonIntegrated/nonIntegrated.module.js',
            rootDir + '/app/signon/orderFiller/orderFiller.module.js',
            rootDir + '/app/signon/signon.module.js',
            rootDir + '/app/signon/selfSignOn/selfSignOn.module.js',
            rootDir + '/app/sitjudge/sitJudge.module.js',
            rootDir + '/app/startup/startup.module.js',
            rootDir + '/app/thankYou/thankYou.module.js',
            rootDir + '/app/workhistory/wh.module.js',
            rootDir + '/app/workstyle/ws.module.js',
            rootDir + '/app/mth/mth.module.js',

            rootDir + '/app/assessmentState/*.*',
            rootDir + '/app/assessmentState/*/*.*',
            rootDir + '/app/composite/*.*',
            rootDir + '/app/dataverification/*.*',
            rootDir + '/app/dataverification/instructions and example/*.*',
            rootDir + '/app/dragAndDrop/*.*',
            rootDir + '/app/error/*.*',
            rootDir + '/app/factory/*.js',
            rootDir + '/app/formFactor/*.*',
            rootDir + '/app/forms/*.*',
            rootDir + '/app/forms/**/*.*',
            rootDir + '/app/directives/*.js',
            rootDir + '/app/discovery/*.js',
            rootDir + '/app/views/directives/*.html',
            rootDir + '/app/feedback/*.*',
            rootDir + '/app/mth/*.*',
            rootDir + '/app/multiTasking/*.*',
            rootDir + '/app/multiTasking/*/*.*',
            rootDir + '/app/orderFiller/*.*',
            rootDir + '/app/rb/*.*',
            rootDir + '/app/signon/*.*',
            rootDir + '/app/signon/**/*.*',
            rootDir + '/app/sitjudge/*.*',
            rootDir + '/app/sitjudge/**/*.*',
            rootDir + '/app/startup/*.*',
            rootDir + '/app/strategyRichness/*.*',
            rootDir + '/app/strategyRichness/**/*.*',
            rootDir + '/app/prio/**/*.*',
            rootDir + '/app/problemSolving/**/*.*',
            rootDir + '/app/textBox/*.*',
            rootDir + '/app/thankYou/*.*',
            rootDir + '/app/workstyle/*.*',
            rootDir + '/app/workhistory/*.*',
            rootDir + '/app/culturefit/**/*.*',
            rootDir + '/app/exercise/*.*',
            rootDir + '/app/rjp/*.js',
            rootDir + '/app/rjp/**/*.js',
            rootDir + '/app/app.core.js',

            //pallet stacking
            'PalletStackingLevelEditor/app/*/*.js',

            /*  To replace a real implementation with a mock implementation,
                put a mock in the mocks folder and it will overwrite the real mapping
            */
            'VJTNext.Tests/Jasmine_Tests/**/*.js',
            'VJTNext.Tests/Jasmine_Tests/*.js',

            // fixtures
            { pattern: 'VJTNext.Tests/Jasmine_Tests/mocks/*.json', watched: true, served: true, included: false }
        ],

        // list of files to exclude
        exclude: [
            rootDir + '/app/run.js'
        ],

        plugins: ['karma-ng-html2js-preprocessor', 'karma-jasmine', 'karma-xml-reporter', 'karma-chrome-launcher'],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '**/*.html': 'html2js'
        },

        ngHtml2JsPreprocessor: {
            stripPrefix: rootDir + '/'
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'xml'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_ERROR,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'/*', Firefox', 'IE'*/],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true
    });
};


text:
Q: How to set (global) variables under scheduled repeating task? I am testing a simple python script to collect images. Set a fixed timing to run the script every day, but I want to keep a count continuously increasing.
schedule.every().day.at(time1).do(job)

I realized that if I do not do that, new images will overwrite the old images. I want to find a way to properly count/name the newly downloaded images in the next day. Can anyone help?


text:
Q: Use of optional parameter for execute in try block? I observed a dubious design pattern in some C# code today used in several methods:
public void DoSomething(bool safe=true)
{
   if (!safe) DoSomethingDangerous();
   else
   {
       try
       {
           DoSomethingDangerous();
       }
       catch
       {
           // Log error & carry on
       }
   }
}

I am wondering if this design pattern should be discouraged, and if so for what specific reasons. My own intuition tells me that these are possible concerns:

*

*Masking errors without taking meaningful action

*Encouraging the use of error handling for control flow (an antipattern)

However, I could potentially also see the utility in such a pattern. Perhaps it is useful to execute the logic in two different contexts one in which the error needs to be meaningfully dealt with, and another where it does not need to be worried about. This design pattern would help by creating a general method for both cases where you simply change the safe argument. Are there any legitimate reasons to use this design pattern?

A: The aspect of this that I'd say is the pattern to avoid, is the use of a flag argument.
The bool completely changes what the method does, so make it two methods:
public void DoSomethingSafely()
{
    try
    {
        DoSomethingDangerous();
    }
    catch
    {
        // Log error & carry on
    }
}

public void DoSomethingDangerous()
{
    // whatever it does
}

A: First, is there a risk of

Masking errors without taking meaningful action  ?

Probably not, since either the exception is passed to the caller (so the caller is responsible for a meaningful action), or the exception is logged, which is probably the intended action here.
Is there a sign of

use of error handling for control flow  ?

The answer is IMHO also no, this would only be the case if DoSomethingDangerous throws an exception for a non-exceptional situation, but there is no indication for this in the code presented in the question.
So, if these two points are not the problem, is there another issue?
I guess the intention of the author was to make the code reusable in two different contexts:

*

*one where exceptions are allowed to pop-up to the caller, which for example could result in displaying a message box in the UI, which disrupts any outer processing

*one where exceptions shall not disrupt the outer control of flow (for example, in an asynchronous batch processing)
So far this could be a reasonable requirement. But is it possible to improve something? Of course, the obvious thing here is to avoid the code duplication (already suggested by @ErikLippert in a comment). If you need to keep the semantics, it should look like this:
public void DoSomething(bool safe=true)
{
   try
   {
       DoSomethingDangerous();
   }
   catch(Exception ex)
   {
       if(!safe)
          throw ex;

       // Log error & carry on
   }
}

The other maintainability problem I see here is that the exception handling now happens at two different levels of abstraction, that is something I would avoid whenever possible, since it can become easily error prone. Solving this, however, requires to refactor the code first the way suggested by @DavidArno, and then refactor to outer code to call DoSomethingSafely only in the batch processing context and DoSomethingDangerous only in "UI mode".
This however, can result in a lot of refactoring. If there are several intermediate layers between the outer "batch controller" or "UI controller" and the shown method, it can become really hard to avoid additional code duplication inside the calling layer. The reason for this is, you will probably be forced to implement two different versions of the calling code, one for each context. One of these versions will use  DoSomethingSafely in a specific way, and one using DoSomethingDangerous in a similar way, but with some differences in regards to error handling and maybe the other context. So to make a decision if that is the right approach, you need to look careful at the calling code.
Finally, here is another approach using Dependency Injection. The "Logger" itself could be an injected object (maybe it should not called "Logger" then, but something like "ExceptionProcessor"):
class MyClass
{
    IExceptionProcesser exProc;  // gets injected through the constructor

    public void DoSomething()
    {
      try
      {
         DoSomethingDangerous();
      }
      catch(Exception ex)
      {
         // Log error, or rethrow
         exProc.Process(ex);
      }
   }
}

That way, the parametrization of the exception behaviour is not done by a boolean parameter to the function any more, but by passing a different logger into the class. That fits typically better to the requirement of making the function behave differently in different contexts, and it avoids the usage of a flag argument as a function parameter as well.

A: I've used this sort of thing in a few places. Usually I frame it the opposite way (something is allowed to fail, the default is to throw); in particular it comes up doing some resolution operations when an app is starting up and it's unclear if the target is ready or not. Once everything is setup, it becomes a hard and fast error if the dependency is unavailable.
The other thing to consider with this pattern is refactoring. If I saw this code, I'd assume that it was originally
try
{
  DoSomethingDangerous();
}
catch
{
  // log and continue
}
and that was causing problems (or was otherwise undesirable). But changing that behavior would be a semantic change, and disruptive to consumers. By having the default safe flag it allows for testing the change with consumers to make sure it won't be very disruptive to change it fully. I've seen this sort of thing also done with feature flags or a similar configuration value rather than the function parameter.
Still, I'd consider this thing sort of smelly, and to be usually avoided.

A: My option is close to David Arno's, but I would consider the use of decorators. So it could go like
    interface A
    {
        void doSomething();
    }

    class UnsafeA : A
    {
        public void doSomething()
        {
            throw new Exception();
        }
    }

    class SafeA : A
    {
        private A origin;

        public SafeA(A a)
        {
            origin = a;
        }

        public void doSomething()
        {
            try {
                origin.doSomething();
            } catch (Exception e) {
                // handle
            }
        }
    }

So you could move the if logic closer to the program entry point (which is always a good thing, imho) and instantiate a class based on safe value. Besides that, I think this approach is more SRP-ish.

A: Improving OP's approach
My chief complaint is the use of the word "safe" (the call can still fail, you just won't know about it) and that it is too easy for the caller to make a mistake, because the default (safe=true) is to do something that is not really recommended.
The way I would have written it would have been:
public bool DoSomething(bool swallowExceptions = false)
{
   try
   {
       DoSomethingDangerous();
       return true;
   }
   catch(System.Exception exception)
   {
       LogTheError(exception);
       if (!swallowExceptions) throw;
       return false;
   }
}

..thereby avoiding the duplicate code and ensuring that any exceptions that are swallowed are at least logged. Returning a boolean to indicate success is also helpful, and keeping with the pattern demonstrated by methods such as TryParse.  The caller doesn't have to use it, of course.
Also, most importantly, the caller is forced to set swallowExceptions to true if they want it. That way we can be reasonably sure that it is on purpose.
Also, as I mentioned, the call isn't "safe" and that name doesn't tell the caller much, but calling it "swallowExceptions" is pretty clear, IMO.
Another way to do it is to split it into two methods, using the Try convention to make it clear to the caller what is going on:
public void DoSomething()
{
    //Do something
}

public bool TryDoSomething()
{
   try
   {
       DoSomething();  //Calls the other function
       return true;
   }
   catch(System.Exception exception)
   {
       LogTheError(exception);
       return false;
   }
}

This way you don't need a separate, private DoSomethingDangerous method. You just have DoSomething and a call that wraps it.
A generalizable approach
On the other hand, it seems wasteful to write all this stuff for each and every method you want to make "safe." It could be done more generically like this:
class Try
{
    static public bool Run(Action action)
    {
        try
        {
            action();
            return true;
        }
        catch
        {
            return false;
        }
    }
}

Then you'd call DoSomethingDangerous either of these two ways:
Normal:
DoSomethingDangerous();

"Safe":
bool ok = Try.Run(DoSomethingDangerous);

or (if you need to pass arguments)
bool ok = Try.Run(() => DoSomethingDangerous("Hello"));

If you use this method, you won't have to monkey with the prototypes for any methods that you want to be "safe." You just wrap the call in Try.Run(). And it's pretty unlikely a programmer would do it by accident.

A: One reason why I'd avoid this is because it exposes internal method details through the interface. The caller needs to know what the method does, not whether or not it's going to eat exceptions. If the caller wants to handle exceptions or ignore them, it can determine that or let the exception bubble up to some point where that determination is made.
Using such a flag violates SRP in a sense. The class should only responsible for whatever it does, not for knowing what the caller wants to do with its exceptions. This is especially true since it's trivially easy for the caller to manage what - if anything - it does with an exception raised from the method.
And it's only a matter of time before someone realizes that the method contains multiple operations that could throw exceptions and takes it to the next level:
public void DoSomethingDangerous(
    bool safe = true,
    bool throwNullReference = false,
    bool handeIoException = true)


text:
Q: Segmentation fault when I change directory in C I want to make a program that imitates the use of cd in UNIX. Obviously the best option is chdir. However when the user types cd /home I get Segmentation fault. When I use gdb, it prints:
Program received signal SIGSEGV, Segmentation fault. __rawmemchr_avx2 () at ../sysdeps/x86_64/multiarch/memchr-avx2.S:61
61  ../sysdeps/x86_64/multiarch/memchr-avx2.S: The file of directory does not exist.

The code looks like this:
void cd(char buff[]){
     if(chdir(buff)==-1){
          printf("Problem with directory\n");
     }
}

int main(int argc, char *argv[]){
    char* token;
    char buffer[256];

    printf("Welcome user\n");
    sscanf("%s",buffer);
    token=strtok(buff," ");
    if(strcmp(token,"cd")==0||strcmp(token,"cd\n")==0){
        cd(strtok(NULL," ");
    }

    return 0;
}

Than you for your time.

A: You have made a few syntactic and logical mistakes inside the provided code, like for example buff instead of buffer in main()and sscanf instead of scanf for giving the input string.
Also, you wrote cd(strtok(NULL," "); but a closing brace is missing for this statement to compile: cd(strtok(NULL," "));.
I've corrected the code and the output file runs fine on my platform - with GCC on Ubuntu GNU/Linux.
Here is the corrected code:
#include <stdio.h>
#include <string.h>
#include <unistd.h>

void cd(char buff[]){
     if(chdir(buff)==-1){
          printf("Problem with directory\n");
     }
}

int main(int argc, char *argv[]){
    char* token;
    char buffer[256];

    printf("Welcome user\n");
    scanf("%s",buffer);
    token=strtok(buffer," ");
    if(strcmp(token,"cd")==0||strcmp(token,"cd\n")==0){
        cd(strtok(NULL," "));
    }

    return 0;
}

Try it with this.

A: This code has several problems:
1) even if sscanf is swapped for scanf, it does not do what you probably expect it to (read the whole line inserted by the user). scanf with %s will read up to the first whitespace. So, your buffer will actually contain cd\0 instead of cd /home\0 like you expect it to. Use fgets instead.
2) You must check that strtok does not return a NULL pointer. This is what is currently causing your segfault.
Something like this:
void cd(char buff[]) {
     if(chdir(buff) == -1) {
          printf("Problem with directory\n");
     }
}

int main(int argc, char *argv[]){
    char* token;
    char buffer[256];

    printf("Welcome user\n");
    // reads the whole line into buffer
    fgets(buffer, 256, stdin);
    token = strtok(buffer, " ");

    if (strcmp(token, "cd") == 0){
        token = strtok(NULL," ");
        // we must check if there are any tokens left
        if (token != NULL) {
            // we must remove the trailing newline character that is included by fgets
            cd(strtok(token, "\n"));
        }
    }

    return 0;
}


text:
Q: Implementing Parse.Op.Increment() error hello I'm very new to javascript. I have only been programming iOS for a year. I am stuck on trying to increment a number in cloud code. I know I need to use Parse.Op.Increment() and amount(). but I must be doing something wrong I have gotten an error since I uploaded this line.
It DID look like this.(and worked)
var sum = Record.get("totalPunches");
Sum += request.params.punches;
Record.save("totalPunches", sum);

The line I am putting on cloud code looks like this.
 Parse.Op.Increment("totalPunches", amount(request.params.punches));

any help on what I am doing wrong?
thank you


text:
Q: Flutter - Update sibling Widget after calling setState() in one I have a Dialog Widget, there are a Button and Text field there. On pressing the button there is a function which setState() and variable change. I do not see these changes instantly on a screen in the text field, I need to close and open Dialog again. Why and how can I make it happen (so the whole class/parent will be rebuilt? (It is about "Get location" button and next field)
class MyDialog extends StatefulWidget {
  MyDialogState createState() => MyDialogState();
}

class MyDialogState extends State<MyDialog> {
  String userLocation;
  double sleepLength;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        showDialog(
            context: context,
            builder: (context) {
              return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30)
                  ),
                  elevation: 20,
                  child: ListView(
                    children: <Widget>[
                      FlatButton(
                        child: Text("Get location $userLocation"),
                        onPressed: () {
                          final Geolocator geolocator = Geolocator();
                          geolocator
                            .getCurrentPosition()
                            .then((Position position) async {
                              List<Placemark> place = await geolocator
                                .placemarkFromCoordinates(position.latitude, position.longitude);
                              Placemark p = place[0];

                              setState(() {
                                //userLocation = "${p.locality}, ${p.country}";
                                userLocation = Random().nextInt(10).toString();
                                print("A");

                              });

                          }).catchError((e) {
                            print("------------");
                            print(e);
                            print("------------");
                          });
                        },
                      ),
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Center(child: Text("$userLocation"))
                      ),
                      Divider(),
                      FlatButton(
                        child: Text("Set sleep length"),
                        onPressed: () {
                          //TODO
                        },
                      ),
                      Padding(
                          padding: EdgeInsets.all(10),
                          child: Center(child: Text("$sleepLength"))
                      ),
                      Divider(),
                    ],
                  )
              );
            }
        );
      },
      child: Icon(
          Icons.settings
      ),
      backgroundColor: Colors.black12,
    );
  }
}

A: In my case StatefulBuilder works.
StatefulBuilder is best used in situations where you have a medium/large widget tree and state needs to be introduced for a small subsection of that tree.
wrap you child with StatefulBuilder hope it helps..

A: You have to wrap Dialog with return StatefulBuilder builder: ...
and carefully about } and ); because in this case it is a long string
code snippet
 builder: (BuildContext context) {
      return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {

          return Dialog(
              ...
          );

        },
      );

your code with StatefulBuilder
class MyDialog extends StatefulWidget {
  MyDialogState createState() => MyDialogState();
}

class MyDialogState extends State<MyDialog> {
  String userLocation;
  double sleepLength;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        showDialog(
            context: context,
            builder: (context) {
              return StatefulBuilder(
                  builder: (BuildContext context, StateSetter setState) {
                return Dialog(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30)),
                    elevation: 20,
                    child: ListView(
                      children: <Widget>[
                        FlatButton(
                          child: Text("Get location $userLocation"),
                          onPressed: () {
                            final Geolocator geolocator = Geolocator();
                            geolocator
                                .getCurrentPosition()
                                .then((Position position) async {
                              List<Placemark> place =
                                  await geolocator.placemarkFromCoordinates(
                                      position.latitude, position.longitude);
                              Placemark p = place[0];

                              setState(() {
                                //userLocation = "${p.locality}, ${p.country}";
                                userLocation = Random().nextInt(10).toString();
                                print("A");
                              });
                            }).catchError((e) {
                              print("------------");
                              print(e);
                              print("------------");
                            });
                          },
                        ),
                        Padding(
                            padding: EdgeInsets.all(10),
                            child: Center(child: Text("$userLocation"))),
                        Divider(),
                        FlatButton(
                          child: Text("Set sleep length"),
                          onPressed: () {
                            //TODO
                          },
                        ),
                        Padding(
                            padding: EdgeInsets.all(10),
                            child: Center(child: Text("$sleepLength"))),
                        Divider(),
                      ],
                    ));
              });
            });
      },
      child: Icon(Icons.settings),
      backgroundColor: Colors.black12,
    );
  }
}

A: Using StatefulBuilder you can solve this problem
Replace your MyDialogState with:
class MyDialogState extends State<MyDialog> {
  String userLocation;
  double sleepLength;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        showDialog(
            context: context,
            builder: (context) {
              return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30)
                  ),
                  elevation: 20,
                  child: StatefulBuilder(
                    builder: (BuildContext context, StateSetter setState) {
                      return ListView(
                      children: <Widget>[
                        FlatButton(
                          child: Text("Get location $userLocation"),
                          onPressed: () {
                            final Geolocator geolocator = Geolocator();
                            geolocator
                              .getCurrentPosition()
                              .then((Position position) async {
                                List<Placemark> place = await geolocator
                                  .placemarkFromCoordinates(position.latitude, position.longitude);
                                Placemark p = place[0];

                                setState(() {
                                  //userLocation = "${p.locality}, ${p.country}";
                                  userLocation = Random().nextInt(10).toString();
                                  print("A");

                                });

                            }).catchError((e) {
                              print("------------");
                              print(e);
                              print("------------");
                            });
                          },
                        ),
                        Padding(
                          padding: EdgeInsets.all(10),
                          child: Center(child: Text("$userLocation"))
                        ),
                        Divider(),
                        FlatButton(
                          child: Text("Set sleep length"),
                          onPressed: () {
                            //TODO
                          },
                        ),
                        Padding(
                            padding: EdgeInsets.all(10),
                            child: Center(child: Text("$sleepLength"))
                        ),
                        Divider(),
                      ],
                    );
                    },
                  )
              );
            }
        );
      },
      child: Icon(
          Icons.settings
      ),
      backgroundColor: Colors.black12,
    );
  }
}


text:
Q: morphia: can I index on a referenced field? I'm pretty the answer to this is no, but figured I would check.
If I have a record which references another record, like this:
  public class Account{
      @id
      ObjectId id;
      long balance;
      @Reference
      Customer customer;
  }

  public class Customer{
      @id
      ObjectId id;
      String name;
      Address address
      @indexed
      long social;
 }

can I create an index based off of the referenced value?  for instance if I wish to be able to index my accounts by social, so I can look up all accounts for a given social quickly, can I do that?

A: If u wanted to do that u could use Compund Index
http://docs.mongodb.org/manual/tutorial/create-a-compound-index/#index-create-compound-index
in your case db.Account.ensureIndex( { customer.id: 1, customer.name: 1, .... } )


text:
Q: Rabbitmq - how to listen to messages on an exchange I have a program in Java that sends messages to RabbitMQ. All I know is the exchange name. No queues, bindings, and so on.
My question is this: how can I see if the program sends these successfully, knowing only the exchange name?
Thanks.
Regards,
Serban

A: You can enable publisher confirmation with RabbitMQ. It's like having a send-transaction, where RabbitMQ will tell you whether or not the message was sent successfully.

A: Please look here: https://www.rabbitmq.com/tutorials/tutorial-three-java.html
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, "EXCHANGE_NAME", "");

System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
  @Override
  public void handleDelivery(String consumerTag,
                             Envelope envelope,
                             AMQP.BasicProperties properties,
                             byte[] body) throws IOException
{
    String message = new String(body, "UTF-8");
    System.out.println(" [x] Received '" + message + "'");
  }
};
channel.basicConsume(queueName, true, consumer);

In a few words, you have to:

*

*create a queue, in this case anonymous queue

*bind the queue to your exchange

It is important to know what kind of the exchange you have since the binding can change, between fanout or topic or direct
In this example is fanout

A: Assume that we have RabbitMQ Exchange we need to create an queue to push the message to the exchange and consume it from the queue as following

    private static final String EXCHANGE_NAME = "2022";
    private static final String QUEUE_NAME = "2022";
    private final static boolean durable = true;

// now we need to create a connection to rabbitmq server //

        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        Connection conn = factory.newConnection();
       // create rabbitmq connection chaneel
       Channel channel = conn.createChannel();
      //Declare Exchange //
      channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);
     // push message to rabbitmq exchange

channel.basicPublish(EXCHANGE_NAME, "routingkey", null, yourmessage.getBytes());

the above work as producer now we need to create queue consumer

    private static final String EXCHANGE_NAME = "2022";
    private static final String QUEUE_NAME = "2022";
    private final static boolean durable = true;

// now we need to create a connection to rabbitmq server //

        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        Connection conn = factory.newConnection();
        // create rabbitmq connection chaneel
        Channel channel = conn.createChannel();

          channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);

          //Queue Declare //
          channel.queueDeclare(QUEUE_NAME, true, false, false, null);
         //Queue bind //
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "routingkey");
        // Queue Consume //
        QueueingConsumer consumer = new QueueingConsumer(channel);

  while (true)
        {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());

            System.out.println(" [x] Received '" + message + "'");

        }


text:
Q: What options in python to define your primary unix group for file/folder/links to be created? EDITED on Dec.13th 3:00PM PST:
I have a python3 program that I used pyinstaller to packaged into an executable before deploying.  This program will allow an admin-group of users to setup/package an environment based on data that is in a restricted environment.
I have the followings:

*

*Because it is access to a restricted area, the executable is owned
by "app-admin" and will be run as "app-admin".  This was achieved
via setuid.

*The script should only be allowed to run by group:
"app-administrators"; so I have the group ownership of this script
as app-administrators.

So, I have the below when I do a ls -l:
-rwsr-s--- 1 app-admin app-administrators 10926616 Nov  1 11:38 myscript

Part of the operation of the myscript will be creating file, symlinks and folders; I like the group owner for those objects to be group "app-users".
The app-admin belongs to many groups including "app-administrators", "app-users" and other at the moment.
What are my options to do that programmatically?  Maybe what I did so far is incorrect?
I am currently looking at the 2 approaches:
Approach 1: run os.chown right after the creation, but I don't like the overhead.
Approach 2: Use subprocess.call() and execute the unix command usermode to change the primary group in the beginning of my python script.
Thanks.

A: You just need to set the setgid bit on the executable file so that it runs as the correct group. When you create directories you should set the setgid bit on them too (chmod g+s).


text:
Q: Unable to update chrome: updates disabled by administrator When I go chrome://help/    it is showing up:
Version 34.0.1847.116 m

Updates are disabled by the administrato

Why this option is displayed?

*

*How to remove this option?

*How to update the chrome? which is exactly wanna achieve.

A: I will assume you are an Administrator and you have the permissions to do this.  If you don't then this has to be done by somebody that does.

*

*Go to Registry Editor

*Go to : HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\

*Double-click at the UpdateDefault or DefaultUpdate

*And type 0 to 1

*Exit Registry Editor

*Reboot

Source
After the reboot this problem should be fixed.

A: Websites kept giving me messages that my Chrome was out-of-date.  But when I tried to update or uninstall and re-install the newest version of Chrome, the operation repeatedly failed.  Chrome would neither update nor uninstall (so that I could re-install it) in Windows 7.  What to do?
I saw many fixes online in connection with the registry, but when I went to regedit.exe, as suggested, my registry showed nothing for Google at all (most of the good advice online says to change the Default Update DWord value at **HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google** from 0 to 1).
But what to do if there is no "Google" subfolder listed under Policies?  My "HKEY_LOCAL_MACHINE\SOFTWARE\POLICES" directory only contained one file, "ab [something]".  Nothing else.  What to do?
When I went to "About Chrome", in the upper right triple horizontal I-Ching-like line place to click on About Chrome, I'd get an enigmatic "Error 3. . . " message.
The swell online fixes hadn't worked.  So I searched at my Windows 7 Start button for "Chrome".  I found an old ChromeSetup.exe.  I double clicked on it and -- presto-changeo -- it updated my existing old version and now when I go to "About Chrome",  in the upper right triple horizontal I-Ching-like line place, it says "Google Chrome is up to date" and displays the current version number.
  Perfect!
I hope that this helps!


text:
Q: null is not an object evaluating this.state.touppercase() in react native? I am trying to change value in textfiled to uppercase. While doing this, I am getting the following error :
null is not an object evaluating this.state.touppercase()

Please help me with this issue, I am not sure what i am doing wrong.
<Text style={_fs.row_container_module_value}>{this.state.bayNum.toUpperCase()}</Text>

Please find error image below ..if image is not visible plz clicl on link
enter image description here


text:
Q: Unrecognized Selector [MKPointAnnotation index] I am trying to add an annotation by touch onto a mapview and after I release the press I get this error:

[MKPointAnnotation index] : unrecognized selector sent to instance

Can anyone give me an idea of what the cause is?
Code:
- (void)handleLongPress:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
    {
        return;
    }
    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
    CLLocationCoordinate2D touchMapCoordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
    MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
    point.coordinate = touchMapCoordinate;
    point.title = @"Test";
    point.subtitle = @"Test2";
    for (id annotation in self.mapView.annotations) {
        [self.mapView removeAnnotation:annotation];
    }

    [self.mapView addAnnotation:point];
}

Here is what I have in my ViewDidLoad method:
if (_isSelectLocation)
{
    UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPressGestureRecognizer.minimumPressDuration = 0.5;
    [self.mapView addGestureRecognizer:longPressGestureRecognizer];
}

Added Stack trace:
Stack trace : (
0   Lookcounter                         0x0000000100145680 -[MapViewController handleLongPress:] + 1016
1   UIKit                               0x000000018a2ceec4 <redacted> + 276
2   UIKit                               0x000000018a168508 <redacted> + 580
3   UIKit                               0x000000018a5d9214 <redacted> + 60
4   UIKit                               0x000000018a12c26c <redacted> + 292
5   UIKit                               0x000000018a12a618 <redacted> + 2504
6   CoreFoundation                      0x0000000185673ff0 <redacted> + 32
7   CoreFoundation                      0x0000000185670f7c <redacted> + 360
8   CoreFoundation                      0x000000018567135c <redacted> + 836
9   CoreFoundation                      0x000000018559cf74 CFRunLoopRunSpecific + 396
10  GraphicsServices                    0x000000018eff76fc GSEventRunModal + 168
11  UIKit                               0x000000018a19ed94 UIApplicationMain + 1488
12  Lookcounter                         0x00000001001418d0 main + 124
13  libdyld.dylib                       0x0000000197a32a08 <redacted> + 4
)

A: I am not sure what is the problem. I have copied all your code, and works well. And I post it as a project in github.
https://github.com/zhangjianxing/trySelectorApp
I believe there is other thing cause compiler did not recognized selector (in swift if you set "handleLongPress" to be private, the same error will arise ).
I suggest you comment other method/properties, and try again.


text:
Q: Argument missing with no default My app was running before, but after I tried to add icons to the tab panels in the navbarpage, the app would not run anymore. I have checked every possible syntax problem, and I just can't pinpoint where the problem lies. Here is my code:
if(interactive()){
library(shiny)
library(shinycustomloader)
library(shinythemes)
library(SentimentAnalysis)
library(textclean)
library(reactable)
library(tm)

ui<-navbarPage(strong("Mavis Analytic"),theme=shinytheme("cerulean"),
               windowTitle="Mavis Analytic",fluid=TRUE,inverse=FALSE,
               tabPanel(strong("Opinion Miner"),icon=icon("table"),
                          sidebarLayout(
                          sidebarPanel(width=3,
                          img(src="logo.jpg",height=130,width=150),
                          h4(strong("Enter your texts in these fields")),
                          actionButton("clear","Clear Fields"),br(),br(),
                          textAreaInput("text","Text Field 1",value="It is a beautiful day"),
                          textAreaInput("texts","Text Field 2",value="I am happy to be here"),
                          textAreaInput("word","Text Field 3",value="Let's have some fun"),
                          textAreaInput("words","Text Field 4",value="It has been a bad outing"),
                          textAreaInput("wordy","Text Field 5",value="I dislike clowns"),
                          actionButton("run","Run Analysis"),br(),br(),h5(strong("The number of words entered into each text field:")),tableOutput("count"),tableOutput("freq")),
                          mainPanel(h4("The Opinion Miner is a tool for conducting sentiment analysis. It is useful for generating insights from product reviews as well as social media posts."),withLoader(reactableOutput("table"),loader="dnaspin"),downloadButton("download",strong("Download Table")),
                                    selectInput("choice","Select Sentiment Score to Plot",choices=c("QDAP","LoughranM","HarvardIV")),selectInput("color","Select Color",choices=c("Blue","Red","Green","Yellow","Purple")),
                                    withLoader(plotOutput("plot",height=400,width=400),loader="dnaspin"),withLoader(plotOutput("graph",height=400,width=400),loader="dnaspin")))),

               tabPanel(strong("Financial Ratios Calculator"),icon=icon("table")),
               tabPanel(strong("Send Us Your Feedback")),
               navbarMenu(strong("More"),
               tabPanel(strong("Graphs and Charts")),
               tabPanel(strong("Tables"))),

)
server<-function(input,output,session){

      observeEvent(input$clear,{
      updateTextAreaInput(session,"text",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"texts",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"word",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"words",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"wordy",value="",placeholder="Enter new text")

    })

  doc<-reactive({c(input$text,
                   input$texts,
                   input$word,
                   input$words,
                   input$wordy)})
  many<-reactive({termFreq(paste(
                          input$text,
                          input$texts,
                          input$word,
                          input$words,
                          input$wordy
  ))})
  Analyze<-reactive({
    round(analyzeSentiment(
      replace_symbol(
        replace_number(
          replace_ordinal(
            doc())))),1)})
  isolate_Analyze<-isolate(Analyze())
  QDAP<-isolate_Analyze$SentimentQDAP
  LoughranM<-isolate_Analyze$SentimentLM
  HarvardIV<-isolate_Analyze$SentimentGI

  word.count<-reactive({countWords(doc(),removeStopwords=FALSE)})

  tables<-reactive({
    data.frame(QDAP,LoughranM,HarvardIV)
  })
  isolate.tables<-isolate(tables())
  data<-reactive({switch(input$choice,
                         "QDAP"=isolate.tables$QDAP,
                         "LoughranM"=isolate.tables$LoughranM,
                         "HarvardIV"=isolate.tables$HarvardIV)})

  output$download<-downloadHandler(
    filename=function(){
      paste("table",".csv",sep="")
    },
    content=function(file){
      write.csv(tables(),file)
    }
  )
  output$table<-renderReactable({
      input$run
      isolate(reactable(tables(),searchable=TRUE,bordered=TRUE,defaultColDef=colDef(
      align="center",
      headerStyle=list(background="#5dade2"),
      style=function(value){
        if(value>0){color<-"#27ae60"}
        else if(value<0){color<-"#e74c3c"}
        else{color<-"#5dade2"}
        list(color=color,fontWeight="bold")
      }),
      highlight=TRUE,outlined=TRUE,striped=TRUE,filterable=FALSE,compact=TRUE,onClick="select")
      )
  })

  output$count<-renderTable({
        input$run
        isolate(data.frame(word.count()))
       })

  output$freq<-renderTable({
        input$run
        isolate(as.matrix(many()))
      })

  output$plot<-renderPlot({

    color<-switch(input$color,
                  "Blue"="#5dade2",
                  "Red"="#e74c3c",
                  "Green"="#1abc9c",
                  "Yellow"="#f7dc6f",
                  "Purple"="#a569bd")

    barplot(data(),col=color,border="white",xlab="Texts",ylab="Sentiment Scores",main="Bar Plot of Sentiment Scores")

  })
  output$graph<-renderPlot({

            plotSentiment(data())
      })

}
}

shinyApp(ui=ui,server=server)

Whenever I run the app, I get the error message: "Error in navbarPage: argument is missing, with no default".


text:
Q: Synchronizing application state while joining a Phoenix Channel (or other pubsub) I am building a collaborative drawing board (eg r/place): there is a grid of pixels which users can change at any time and the pixel updates get propagated to all other users online. I want to use Phoenix Channels to broadcast the pixel changes.
My question is about how to correctly send the current application state when the user connects to the service.
Currently I have an ETS table holding the drawing board state. I can update this table in MyChannel.handle_in/3 before broadcasting any pixel writes.
My fear is that in between reading the current state in MyChannel.join, and the user being subscribed to the Channel by Phoenix, a different process updates the state.
The user would get a stale version of the application state, and they wouldn't be subscribed yet, so they wouldn't get the update through the Channel either.
To solve this, I think I need a way to atomically read the current state and then subscribe to the pubsub, ensuring that no messages get written to the ETS table or the Channel for that time period. I guess a lock? Is that Elixirey, or is there another way?

A: While writing this question I had a look at Chris McCoord's ElixirConf 2015 training materials. I thought there was that same race condition in that example, but it turns out there isn't! That channel holds the solution.
In that example,in the Channel.join function process sends itself an :after_join message, which later on (after being subscribed) will
trigger handle_info({:after_join...}) to read the application state and sends that to the user.
The key is to query the application state after being subscribed.
And also always change the state before publishing.
I say always because I went through every of the 24 possible orderings of:

*

*reading the state,

*mutating the state,

*subscribing to the channel

*publishing to the channel

and confirmed reading the state after subscribing, combined with
updating the state before publishing, was guaranteed not to have data loss.
 Here my work in a gist.
It does lead to 4 possible conditions where a state change is seen twice, but that is a lot easier to deal with than data loss.


text:
Q: new created pipenv environment is not empty I created a new env with pipenv shell however doing pip freeze (yes inside the environment)
does return many installed packages.
I tried pipenv clean and pipenv uninstall --all  but same result. The packages (rekated to ROS apparently) but how can I create a new environment without them. Some of the packages:
    rqt-robot-dashboard==0.5.7
    rqt-robot-monitor==0.5.13
    rqt-robot-steering==0.5.10
    rqt-runtime-monitor==0.5.7
    rqt-rviz==0.6.0
    rqt-service-caller==0.4.8
    rqt-shell==0.4.9
    rqt-srv==0.4.8
    rqt-tf-tree==0.6.0
    rqt-top==0.4.8
    rqt-topic==0.4.11
    rqt-web==0.4.8
    rviz==1.13.13
    sensor-msgs==1.12.7
    smach==2.0.1
    smach-ros==2.0.1
    smclib==1.8.5
    tf==1.12.1
    tf-conversions==1.12.1
    rosbag==1.14.9
    rosboost-cfg==1.14.9
    rosclean==1.14.9
    roscreate==1.14.9
    rosgraph==1.14.9
    roslaunch==1.14.9
    roslib==1.14.9
    roslint==0.11.2
    roslz4==1.14.9

To Summarize:
Doing pip freeze in the global environment shows all packages ROS + others.
Doing pip freeze in the created environment, does not show the "other" packages only the ROS one.How can I create an empty one?

A: I have a bunch of packages installed on my system, but I don't experience the same problem. I think this is because I typically create a Pipfile before doing pipenv install.
To test this, I made an empty Pipfile like this:
[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"

[dev-packages]

[scripts]

[requires]
python_version="3"

[packages]

I then did pipenv install, then pipenv run pip freeze. This gave no output. I then added one package manually to the Pipfile, did the same again, and this time got the expected output.
This may be replicable by you as follows:

*

*delete the virtual environment you already created

*make the blank Pipfile in your project as outlined

*do pipenv install

*do pipenv run pip freeze
(if it doesn't work, maybe add some details about your OS, pipenv version etc.)


text:
Q: Jump ComboBox on Arrow key pressed When i press UP/DOWN arrows on every control which have tabstop property set to true then PREVOIUS/NEXT tabindex is selected. It works fine but when ComboBox is focused it changes it's value cause it trapped arrow too.
How can i achieve tabindex jump without sending the keystroke to ComboBox?
Code which handles tabindex jumping:
private void ParentForm_KeyDown(object sender, KeyEventArgs e)
    {
    Control ctl;
    ctl = (Control)sender;
    if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Enter)
    {
        ctl.SelectNextControl(ActiveControl, true, true, true, true);

    }
    else if (e.KeyCode == Keys.Up)
    {
        ctl.SelectNextControl(ActiveControl, false, true, true, true);

    }

}

A: You cannot do this with KeyPreview or the form's KeyDown event.  That's VB6 legacy, navigation keys were intercepted before they fired KeyDown.  You must override the form's ProcessCmdKey() method instead.
It is in general quite ugly to solve a problem this way, it is a global solution to a localized problem.  You'll break other controls when you do this, like RichTextBox or a multi-line TextBox for example, leaving your user utterly stumped why they misbehave.  The much cleaner approach is to just create your own ComboBox control that doesn't swallow the cursor keys.  Add a new class to your project and paste the code shown below.  Compile.  Drop your new control from the top of the toolbox, replacing the existing combo.
using System;
using System.Windows.Forms;

class MyComboBox : ComboBox {
    protected override bool IsInputKey(Keys keyData) {
        if ((keyData == Keys.Up) || (keyData == Keys.Down)) return false;
        return base.IsInputKey(keyData);
    }
}

A: you must set your form KeyPreview property to true
so your form determine whether keyboard events for controls on it are registered with the form


text:
Q: How can the same bash-function be known under multiple names? We have several sizeable functions, which differ very little -- by one line.
I'd like to replace them all with a single function -- with that one line determined by FUNCNAME:
function single () {
    ....
    case $FUNCNAME in
    variant1)
        foo=meow
        ;;
    variant2)
        foo=woof
        ;;
    esac
    ....
}

The in-function code handling the different names is easy (see above). My problem is registering the same code (function body) under different names...
How can I make the same function known under different aliases? Simply using alias variant1=single is not working. For example, after the below code runs:
shopt -s expand_aliases
for v in variant1 variant2 ... variantN
do
     alias $v=single
done

the new variants remains unknown somehow -- even if type -t variant1 correctly prints alias.

A: I don't (personally) know of a way to give a function multiple names other than via an alias.
One (relatively) easy approach using an alias would be to pass in the name of the 'variant' as the first arg to the function call.  Then the first thing you do in the function is test the first argument as being one of the 'variant' names.
Consider:
func1 () {
case "$1" in
    func2) currFUNCNAME="func2"; shift      ;;  # shift remaining args into positions $1, $2 ... $n
    func3) currFUNCNAME="func3"; shift      ;;  # shift remaining args into positions $1, $2 ... $n
        *) currFUNCNAME="${FUNCNAME}"       ;;  # func1 called directly so $1 is not a known variant
esac
echo "currFUNCNAME = ${currFUNCNAME}"
}

Define a few variants:
alias func2='func1 func2'
alias func3='func1 func3'

Now some tests:
$ func1
currFUNCNAME = func1

$ func2
currFUNCNAME = func2

$ func3
currFUNCNAME = func3

Using OPs sample shopt/for code to dynamically create the functions:
shopt -s expand_aliases

for v in func2 func3
do
     alias "$v"="func1 $v"
done

Running our test again:
$ func1
currFUNCNAME = func1

$ func2
currFUNCNAME = func2

$ func3
currFUNCNAME = func3

Though at this point if the functions are going to be used in this script then why not edit the script to call the primary function with an extra input arg ... ?

A: The effect can be simulated with :
#!/usr/bin/env bash

function single () {
    case $FUNCNAME in
    variant1)
        foo=meow
        ;;
    variant2)
        foo=woof
        ;;
    esac
    echo $foo
}

for variant in variant1 variant2; do
    eval "$(declare -f single|perl -pe 's/single/'$variant'/ if ($. == 1)')"
done

unset -f single

variant1
# meow
variant2
# woof

Although the function code is duplicated and use of eval is not recommended for security reasons.
Update 1
Second method
#!/usr/bin/env bash

single(){
    case ${FUNCNAME[1]} in
    variant1)
        foo=meow
        ;;
    variant2)
        foo=woof
        ;;
    esac
    echo $foo
}

variant1(){ single "$@"; }
variant2(){ single "$@"; }

variant1
# meow
variant2
# woof

A: Another alias based option that relies on a user-defined variable (as opposed to a command line argument) ...
Assume our user-defined variable is named $myalias:
func1 () {

currFUNCNAME="${myalias:-${FUNCNAME}}"
echo "currFUNCNAME = ${currFUNCNAME}"

}

NOTE: obviously we need to pick a variable that we're sure isn't in use; from OP's comments it doesn't sound like this should be an issue (ie, just pick a new variable name that's not currently in use in the OP's script)
Define our aliases to first assign a value to $myalias and then call the primary function:
shopt -s expand_aliases

for v in func2 func3
do
     alias "$v"="myalias='$v'; func1"
done

Now some tests:
$ func1
currFUNCNAME = func1

$ func2
currFUNCNAME = func2

$ func3
currFUNCNAME = func3

A: You can use aliases to define the new name to the same function

# attach a bash shell to a running docker container
function dexb {
    docker exec -it "$1" /bin/bash
}

# attach a sh shell to a running docker container
function dexs {
    docker exec -it "$1" /sh
}

# Now instead of creating another function say 'dex' with the same
# content as the function 'dexb'

# I'll just create an alias

alias 'dex'='dexb'


text:
Q: RAILS_ENV not working properly in command line I am using rails 5.2.3
Here is my command line
RAILS_ENV=development bundle exec rake db:drop

I was expecting only one development db got dropped. But I got these two dbs got dropped. Something I have missed?
Dropped database 'db/development.sqlite3'
Dropped database 'db/test.sqlite3'

database.yml
# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
#
default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

A: It's a known issue that when you run db tasks for development environment,they are also run for test envrionemnt.
You can check this issue on the following Rails github reop
https://github.com/rails/rails/issues/27299
As a workaround you can use this:
https://github.com/ioquatix/activerecord-migrations
it fixes some of these issues

A: Run: bin/rails db:environment:set RAILS_ENV=development
Then run bundle exec rake db:drop
It should only remove dev database ....


text:
Q: LateInitializationError: Field 'user' has not been initialized. Error in emulator even though it wrked fine before class _HomePageState extends State<HomePage> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  late User user;
  bool isloggedin = false;

  checkAuthentification() async {
    _auth.authStateChanges().listen((user) {
      if (user == null) {
        Navigator.of(context).pushReplacementNamed("start");
      }
    });
  }

This is how I have initialized the user.
  @override
  void initState() {
    super.initState();
    this.checkAuthentification();
    this.getUser();
  }

I have used initstate but I still get the error.
 Container(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    "${user.displayName}",
                      // "${user.email}",
                    style:
                    TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
                  ),
                ),
              ),

I have used containers to display information about every user.

A: By marking a variable as late you make an explicit promise to initialize that variable before you first try to read from it. The error you get is because your code fails to live up to that promise.
Specifically, the problem is that this is an asynchronous operation:
checkAuthentification() async {
  _auth.authStateChanges().listen((user) {
    if (user == null) {
      Navigator.of(context).pushReplacementNamed("start");
    }
  });
}

Calling authStateChanges takes time, so the code in the listen will only be run after a certain, undetermined amount of time. Worse: your listen then defines a user parameter, but it never sets the users field to any value.
The solution is to:

*

*Mark the user field as a nullable variable.

*Deal with the fact that the user field may be null in your build code.

*Assign user when your authStateChanges stream fires.

In code that'd look something like this:
class _HomePageState extends State<HomePage> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  User? user; //
  bool isloggedin = false;

checkAuthentification() async {
                                //
  _auth.authStateChanges().listen((fuser) {
    user = fuser; //
    if (user == null) {
      Navigator.of(context).pushReplacementNamed("start");
    }
  });
}

Container(
  child: Padding(
    padding: const EdgeInsets.all(8.0),
    child: Text(
      "${user?.displayName}", //
      style:
      TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
    ),
  ),
),


text:
Q: Random effect decomposition with glmer(lme4) I'm trying to simulate a dataset with random effects. But I'm not sure how to estimate nested variance and relation between nested effects and the sub-effects within.
My question (based on the glmer model, I know in linear model, the variance is not correctly specified may go to the residual):

*

*if there are nested effects(based on the data nature/experiment design) but my model doesn't contain nested structure. For example: class is nested within school (1 | school/class) in model 1 but model 2 is (1 | class) supposed that I didn't specify model structure correctly, will the variance(class) in model 2 be equal to variance(class) + variance(school) in model 2?

*What's the relationship between the nested random effects and the random effects within(level 1)?

Thanks in advance. Any clarification would be appreciated.


text:
Q: Extracting numbers till a certain paragraph using multi condition Regex in python I am new to regex. I am  trying to extract the data from log files and each files has text like this:
crt - 00:00:00 up 200 days, 23:35, 0 users, load average: 0.04, 0.05, 0.02
Tasks: 300 total, 2 running, 298 sleeping, 0 stopped, 0 zombie
Cpu(s): 12.0%us, 2.5%sy, 0.0%ni, 89.2%id, 0.0%hi, 0.1%si, 0.0%st
Mem: 123456K total, 1234567k used, 989991k free, 11156793k buffers
Swap: 456K total, 30897564k used, 785431k free, 23445897k cached

PID User Pr NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND

I am extracting only digit values till the word cached. For this i am buliding different patterns for each digit and then extracting values in a list using finditer. My code till now:
[x.group()for x in re.finditer(r"(\d{2}:\d{2}:\d{2})|(\d+\.\d+?)%id"), text]

This is a fragment of regex where i have to specify pattern for every digit like suffix and prefix string. Is there a more efficient way to take output?
desired_values=[00:00:00, 200, 23:35, 0, 0.04, 0.05, 0.02 ,
               300, 2, 298, 0, 0,
               12.0, 2.5, 0.0, 89.2, 0.0, 0.1, 0.0,
               123456, 1234567, 989991, 11156793,
               9234456, 30897564, 785431, 23445897]

These values then i insert in database, that's why they should be in list.

A: You may use
r'(?s)(?<!\d)(?:\d{2}:\d{2}(?::\d{2})?|\d*\.?\d+)(?!\d)(?=.*\bcached\b)'

See the regex demo
Details

*

*(?<!\d) - no digit immediately to the left is allowed

*(?:\d{2}:\d{2}(?::\d{2})?|\d*\.?\d+) - either of

*

*\d{2}:\d{2}(?::\d{2})? - 2 digits, :, 2 digits and then an optional sequence of : and 2 digits

*| - or

*\d*\.?\d+ - 0+ digits, an optional . and then 1+ digits

*(?!\d) - no digit immediately to the right is allowed

*(?=.*\bcached\b) - there must be a word cached somewhere to the right of the current location.

Python demo:
import re
text = r"""crt - 00:00:00 up 200 days, 23:35, 0 users, load average: 0.04, 0.05, 0.02
Tasks: 300 total, 2 running, 298 sleeping, 0 stopped, 0 zombie
Cpu(s): 12.0%us, 2.5%sy, 0.0%ni, 89.2%id, 0.0%hi, 0.1%si, 0.0%st
Mem: 123456K total, 1234567k used, 989991k free, 11156793k buffers
Swap: 456K total, 30897564k used, 785431k free, 23445897k cached

PID User Pr NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND"""
print( re.findall(r'(?<!\d)(?:\d{2}:\d{2}(?::\d{2})?|\d*\.?\d+)(?!\d)(?=.*\bcached\b)', text, re.S) )

Output:
['00:00:00', '200', '23:35', '0', '0.04', '0.05', '0.02', '300', '2', '298', '0', '0', '12.0', '2.5', '0.0', '89.2', '0.0', '0.1', '0.0', '123456', '1234567', '989991', '11156793', '456', '30897564', '785431', '23445897']


text:
Q: Email not going out I want to generate Email from my ruby application, So i used Action mail class for that.
I configured the Email setting on environment.rb  my configuration is as follows
ActionMailer::Base.raise_delivery_errors = false
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
    :address => "mail.authsmtp.com",
    :port => 2525,
    :user_name => "*******",
    :password => "*******",
    :authentication => :login
}

My mailer model is TestMailer,so i decided to check the mail operation so define method on TestMailer.rb.
def  test_mail(to) {
    subject "My first email!"
    recipients "#{to}"
    from 'test'
    charset "utf-8"
    content_type 'text/html'
    body "Testing one two three..."
}

I opened the ruby  Script/console and called the test_mail method by TestMailer.deliver_test_mail("example@gmail.com").
It is not generating the email. In the application server log its generates the email template.
I have no clue whats is the probs here .

A: You should check config/environments/development.rb | test.rb | production.rb
(depending on how you launched you console)
And verify if it does not overrides the smtp setting you have in environment.rb

A: If you ran this:
ruby script/console

... then you're in development mode, which probably has "perform_deliveries = false" or some other setting for delivery_method
Instead, run the console in production mode:
ruby script/console production

... or change config/environments/development.rb to "perform_deliveries = true".
Note this comment from environment.rb:
# Settings in config/environments/* take precedence over those specified here.

So, if something is defined in both places, it'll be overridden by the environment specific setting!


text:
Q: how can be parallelized this c code using openmp? This is the c code to edit with openmp instruction to improve the velocity of execution and below the stucture of the file used by the program.
I've try with:
#pragma omp parallel for reduction (+: hn_out, y_out) private (k,g) shared (y_out_avg, y_exp_avg)

but it doesn't work, the expected result is wrong, and different from the serial one.
I think that there is a logical error in the parallelization, I mean that this algorithm have to be parallelized in another way.
// FEEDFORWARD AND BACKPROPAGATION ALGORITHM
// WITH IMPLEMENTAtION OF BATCH TECHNIQUE
// compute the error in a batch of 5 input and then propagate the error, usefull for the parallelization.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <omp.h>

#define INPUTN 3        // number of neurons in the input layer
#define HN 3            // number of neurons in the hidden layer
#define OUTN 1          // number of neurons in the output layer
#define DATANUM 1000    // number of training samples
#define EPOCHS 1000
#define BATCH_SIZE 20

typedef struct DataS{
        double input[INPUTN];
        double teach;
}DataS;

int main(){

    double alpha = 0.0000001;       //learning rate
    double hn_out[HN];
    double price_M;
    double y_out = 0.0;
    double error;                   //loss function
    int k,g;
    double delta_y;
    double delta_w[HN][INPUTN];
    double delta_b[HN];
    DataS data[DATANUM];
    double w[HN][INPUTN];
    double v[HN];
    double b[HN];
    FILE *fp1;
    double relative_err = 0;
    double y_avg = 0.0;
    double y_out_avg = 0.0;
    double y_exp_avg = 0.0;

    //weights initialization
    for(int i=0; i<HN; i++){
        v[i]= 1.0;
        for(int j=0; j<INPUTN; j++)
            w[i][j]= 1.0;
        b[i]=0.0;
    }

    //get Dataset
    fp1 = fopen("Dataset_3.txt", "r");
    if(fp1 == NULL)
    {
        printf("cannot open file");
        exit(1);
    }
    for(int i=0;i<DATANUM; i++){
        fscanf(fp1, "%lf\t%lf\t%lf\t%lf", &data[i].input[0], &data[i].input[1], &data[i].input[2], &data[i].teach);
        printf("%lf\t%lf\t%lf\t%lf\n", data[i].input[0], data[i].input[1], data[i].input[2], data[i].teach);
        y_avg += data[i].teach/DATANUM;
    }
    fclose(fp1);

    //START ALGORITHM
    double ti = omp_get_wtime();    //initial time
    for (int i = 0; i < EPOCHS; i ++) {
        printf("\nepoch %d) ", i);
        relative_err=0;
        #pragma omp parallel for reduction (+: hn_out, y_out) private (k,g) shared (y_out_avg, y_exp_avg)
        for(int j=0; j<DATANUM/BATCH_SIZE; j++){
            //FEEDFORWARD
            //compute hn_out[HN]
            int base = j*BATCH_SIZE;
            printf("Avg of data:");
            for(int i_b=0; i_b<BATCH_SIZE; i_b++){
                printf(" %d", base+i_b);
                for(k=0; k<HN; k++){
                    hn_out[k]= 0.0;
                }

                for(k=0; k<HN; k++){
                    for(g=0; g<INPUTN; g++){
                        hn_out[k]+= w[k][g]*data[base+i_b].input[g];
                    }
                    hn_out[k]+= b[k];
                }

                //compute y_out[OUTN]
                y_out= 0.0;
                for(g=0; g<HN; g++){
                    y_out += hn_out[g]*v[g];
                }
                y_out = y_out/HN;
                y_out_avg += y_out/BATCH_SIZE;
                y_exp_avg += data[base+i_b].teach/BATCH_SIZE;
            }
            //LOSS FUNCTION
            error = pow((y_out_avg-y_exp_avg),2);
            printf("\nESTIM_AVG\tREAL_AVG\tRELATIVE_ERROR");
            relative_err = fabs((y_out_avg-y_exp_avg)/y_avg);   //relative_error: (prezzo calcolato - prezzo atteso)/misura attesa media
            printf("\n%lf\t%lf\t%lf\n", y_out_avg, y_exp_avg, relative_err);

            //BACKPROPAGATION
            //update bias and weight
            for(k=0;k<HN;k++){
                for(g=0; g<INPUTN; g++){
                    w[k][g] = w[k][g]-2*alpha*data[j].input[g]*(y_out_avg-y_exp_avg);
                    v[g]= v[g]-2*alpha*(y_out_avg-y_exp_avg);
                }
                b[k]= b[k]-2*alpha*(y_out_avg-y_exp_avg);
                //b[k]= 0;
            }
            y_out_avg = 0.0;
            y_exp_avg = 0.0;
        }
    }
    double tf = omp_get_wtime();    //final time
    double time = tf - ti;          //effective time for the execution
    printf ("Elapsed time: %lf\n", time);
    return 0;
}

using a file "Dataset_3.txt" which have 1000 rows of data here an example of 10 data:
u can copy and paste and create a file of 1000 rows or edit the code to run it correctly.
121.3168139 6.873759459 7   322386.5042
99.60902165 4.63043755  7   284554.0498
135.7221604 6.663354979 4   284796.0999
133.7192657 3.496973506 7   343977.1519
155.0125801 2.259712681 8   390169.2343
152.0527816 3.643403786 4   309419.1429
64.71485146 5.10618215  7   235827.262
130.6841885 5.405015338 4   280079.0986
56.36704    1.557336041 5   193401.2459
96.33489022 2.840480371 4   234694.1379

need some help for speed-up the program execution using openmp.

A: The level at witch you placed you OpenMP directive isn't the right one as there are too many things in the j loop that are not meant to be executed in parallel.
However, you can consider parallelizing the i_b loop.
For this one, a good stating point for this would be for example:
#pragma omp parallel for reduction(+:y_out_avg,y_exp_avg) private(k,g,y_out,hn_out)

If/when you're happy with the correctness of the code and if you want to go further in the parallelisation, then you can consider the "BACKPROPAGATION" loops and see what could be done there...


text:
Q: Prisma auto generates migration even if there are no changes to schema I have a simple Prisma schema (I'm only using the relevant part):
enum ApprovalStatus {
  APPROVED
  DENIED
  PENDING
}

model Attendee {
  user  User  @relation(fields: [user_id], references: [id])
  user_id BigInt
  event Event @relation(fields: [event_id], references: [id])
  event_id  BigInt
  status  ApprovalStatus @default(APPROVED)
  created_at  DateTime  @default(now())
  updated_at  DateTime?  @updatedAt
  deleted_at  DateTime?

  @@id([user_id, event_id])
  @@unique([user_id, event_id])
  @@map("attendees")
}

After saving the schema I run npx prisma migrate dev, and it creates the migration and successfully migrates. A quick peek in postgres shows that the table is created and a \dT+ shows that the new type and the 3 entries, have been added as well.
Then I noticed that subsequent runs of migration started adding some weird alter table lines for the attendees table, for no reason. I checked the migration and there was no reason for it. Here's the migration of the attendee table, and as you can see status column is quite clearly defined:
-- CreateTable
CREATE TABLE "attendees" (
    "user_id" BIGINT NOT NULL,
    "event_id" BIGINT NOT NULL,
    "status" "ApprovalStatus" NOT NULL DEFAULT 'APPROVED',
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3),
    "deleted_at" TIMESTAMP(3),

    CONSTRAINT "attendees_pkey" PRIMARY KEY ("user_id","event_id")
);

And now, even if there were no changes to anything in the schema, and all previous migrations were properly applied, running npx prisma migrate dev (with or without --create-only) will always generate a migration with following:
/*
  Warnings:

  - The `status` column on the `attendees` table would be dropped and recreated. This will lead to data loss if there is data in the column.

*/
-- AlterTable
ALTER TABLE "attendees" DROP COLUMN "status",
ADD COLUMN     "status" "ApprovalStatus" NOT NULL DEFAULT 'APPROVED';

It's acting as if the type or name of the column has changed, even though there were no changes to the model or even entire schema for that matter. If I run the generate command more times, it will create this same migration each time with the exact same content. I thought it might have something to do with migration order, but unless it's doing migrations randomly, ApprovalStatus migration comes before attendees does. I really see no reason for it to behave this way, but I'm uncertain how to proceed. Any advice would be welcome.
EDIT: Additional info
"prisma": "^4.6.0"
"express": "^4.17.2"
"typescript": "^4.8.4"
psql (15.0, server 12.13 (Debian 12.13-1.pgdg110+1))

A: There was a regression introduced in Prisma v4.6.0 where Prisma drops and recreates an enum field as can be seen in this issue. This was fixed in Prisma v4.6.1. Kindly update to the latest version and you should not experience this issue with Prisma migrate.


text:
Q: Module odoo 8 - how to call another module in mine i create a module in odoo and i would like to know how to call another module in mine. For example, I need the user module, Human Resources and others. please help

A: In the file __openerp__.py you must specify the dependency on the module or the modules you need separated by ,:
'depends': ['hr', 'other_module']

When you want to use the models of these modules in your classes you can use search and browse methods. Example:
self.pool.get('hr.employee').search(cr, uid, [('id', '=', your_id)], context)

I hope this help you!


text:
Q: Integration of partition-function over many momentum variables My integral looks like
$$Z(\beta)
= \frac{1}{h^3}\int d^3p\ \exp{\left(-\frac{\beta}{2m}\sum^{3N}_{i=1}p_i^2\right)}.$$
I'm confused about how to integrate over seemingly 3N variables in only a 3-dimensional integral.

A: It's a 3N dimensional integral, but it reduces to the N-th power of a 3-dimensional integral (and ultimately to the 3N-th power of a 1 dimensional integral), so you probably have a sloppy source.
$$ Z = \int (\prod_i d^3p_i) e^{-\beta \sum_i {p_i^2\over 2m}} = \prod_i (\int e^{-\beta {p^2\over 2m}} d^3p) = I^N $$
Where
$$ I = \int e^{-\beta {p^2\over 2m}} d^3 p$$
The integral I is really the product of three independent gaussians in $p_x$,$p_y$,$p_z$, so the answer is
$$ I = ({\sqrt{m}\over \sqrt{2\pi \beta}})^3$$
Which is the cube of the integral of each Gaussian separately. So that
$$ Z= {m^{3N\over 2} \over (2\pi \beta)^{3N\over 2}}$$
and taking the log gives the free energy of the ideal gas:
$$ \beta F = {3N\over 2}\log(T)$$
and you can read off the specific heat of the ideal gas from this formula--- ${3N\over 2}$. This works for any quadratic variables in H, and this is the equipartition theorem.