text:
Q: I'm unable to install Cocoapods on Mac OS Big Sur Even After trying sudo gem install cocoapods -n /usr/local/bin
Only single Gem is installed and after using command pod --version The output is following :
Traceback (most recent call last):
37: from /usr/local/bin/pod:23:in <main>' 36: from /usr/local/bin/pod:23:in load'
35: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/bin/pod:36:in <top (required)>' 34: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
33: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 32: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods.rb:17:in <top (required)>'
31: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods.rb:77:in <module:Pod>' 30: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
29: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 28: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/core_overrides.rb:1:in <top (required)>'
27: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 26: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
25: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/sources_manager.rb:7:in <top (required)>' 24: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/sources_manager.rb:185:in module:Pod'
23: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 22: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
21: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-core-1.10.0/lib/cocoapods-core/trunk_source.rb:1:in <top (required)>' 20: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-core-1.10.0/lib/cocoapods-core/trunk_source.rb:2:in module:Pod'
19: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 18: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
17: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-core-1.10.0/lib/cocoapods-core/cdn_source.rb:3:in <top (required)>' 16: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
15: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 14: from /Library/Ruby/Gems/2.6.0/gems/concurrent-ruby-1.1.7/lib/concurrent-ruby/concurrent.rb:7:in <top (required)>'
13: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 12: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
11: from /Library/Ruby/Gems/2.6.0/gems/concurrent-ruby-1.1.7/lib/concurrent-ruby/concurrent/executors.rb:20:in <top (required)>' 10: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
9: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 8: from /Library/Ruby/Gems/2.6.0/gems/concurrent-ruby-1.1.7/lib/concurrent-ruby/concurrent/executor/timer_set.rb:1:in <top (required)>'
7: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 6: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
5: from /Library/Ruby/Gems/2.6.0/gems/concurrent-ruby-1.1.7/lib/concurrent-ruby/concurrent/scheduled_task.rb:4:in <top (required)>' 4: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require'
3: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' 2: from /Library/Ruby/Gems/2.6.0/gems/concurrent-ruby-1.1.7/lib/concurrent-ruby/concurrent/ivar.rb:3:in <top (required)>'
1: from /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require' /Library/Ruby/Site/2.6.0/rubygems/core_ext/kernel_require.rb:92:in require': cannot load such file -- concurrent/collection/copy_on_write_observer_set (LoadError)


text:
Q: Pandas df.mode() of columns not working like df.mean(). Mode of all columns not obtained like mean seeing my problem tried to replicate it in a simple example to avoid sharing my data.
A sample pd DF:
df_sample = pd.DataFrame([[1, 2], [3, 4], [5, 6], [float('nan'), 8]], columns=["A", "B"])

Tried calculating mean for all columns using:
df_sample.mean()

Works well but
df_sample.mode()

doesn't work like mean as seen in output below:
Output:
Any ideas why and how can I get mode of all columns using something similar to df.mode()?Btw my purpose is to impute missing data in multiple variables with mode and it didn't replace NaNs with mode in my original data.
df_sample['A'].fillna(df_sample['A'].mode())

But now I realize, seems like mode itself has a problem in definition. Any ideas? Thanks in advance!

redpajama_set_name: RedPajamaStackExchange


text:
Q: "No database type set, using meta data indicating: SQLSERVER" Springbatch SQLSERVER Estoy iniciando mi aplicacion con springbatch pero me dice "No database type set, using meta data indicating: SQLSERVER he buscado en internet y uso la misma config que muchas ejemplos en mi properties que es la siguiente:
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=FacturaDB
spring.datasource.username=dbnameroot
spring.datasource.password=Testpass123
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql = true
IntegratedSecurity = true


text:
Q: How to access the Variable in inner function PHP? How to access the variable in inner function of outer function variable?
I want to access $arr variable in the inner function.
<?php

function outer() {

    $arr = array();

    function inner($val) {

        global $arr;

        if($val > 0) {
            array_push($arr,$val);
        }
    }

    inner(0);
    inner(10);
    inner(20);

    print_r($arr);

}

outer();

codepad link

A: Edited your code. You may want to refer to this
function outer() {

    $arr = array();

    function inner(&$arr,$val) { // pass array by reference
        if($val > 0) {
            array_push($arr,$val);
        }
    }

    inner($arr,0);
    inner($arr,10);
    inner($arr,20);

    print_r($arr);

}

outer();

You can pass arr by value, but you will not be able to print this
Array
(
    [0] => 10
    [1] => 20
)

A: This kind of "inner function" does not do what you probably expect. The global(!) function inner() will be defined upon calling outer(). This also means, calling outer() twice results in a "cannot redefine inner()" error.
As @hindmost pointed out, you need closures, functions that can get access to variables of the current scope. Also, while normal functions cannot have a local scope, closures can, because they are stored as variables.
Your code with Closures:

function outer() {

    $arr = array();

    $inner = function($val) use (&$arr) {
        if($val > 0) {
            array_push($arr,$val);
        }
    }

    $inner(0);
    $inner(10);
    $inner(20);

    print_r($arr);

}

outer();

A: First, do not use functions inside functions. Why? Because with this you'll get fatal error when triggering outer function second time (and that is because second run will invoke inner function declaration once again).
Second, if you need to do something with function result (as it stands from your code) - return that value. That is what is function intended to do - return some value. Another option may be using reference as a parameter (like in sort() functions family) - but in normal situation you should avoid such behavior. This is side-effect and this makes code less readable in general.
Third, do not use global variables. Because this binds your functions to your context, making your code totally unpredictable in terms of changing global context - and also impossible to scale to other contexts.

A: Functions in php are all global.
If you want to access the global $arr, then you have to make it global too in outer function.
function outer() {

    global $arr;
    $arr = array();

    function inner($val) {

        global $arr;

        if($val > 0) {
            array_push($arr,$val);
        }
    }

    inner(0);
    inner(10);
    inner(20);

    print_r($arr);

}

outer();

There is an better way of doing this.
function outer() {

    $arr = array();

    $inner = function ($val) use (&$arr) {
        if($val > 0) {
           array_push($arr, $val);
        }
    };

    $inner(0);
    $inner(10);
    $inner(20);

    print_r($arr);

}

outer();

A: Just put global to the outer function.
function outer() {

    global $arr;
    $arr = array();

    function inner($val) {

        global $arr;

        if($val > 0) {
            array_push($arr,$val);
        }
    }

    inner(0);
    inner(10);
    inner(20);

    print_r($arr);

}

Updated codepad.


text:
Q: Rails 4 / Sprockets: controller-specific JavaScripts are available everywhere? I'm running a Rails 4.2.4, and when creating a controller auth, app/assets/javascripts/auth.js is automatically created. It tells me that:

// Place all the behaviors and hooks related to the matching
  controller here. // All this logic will automatically be available in
  application.js.

That's fine, but since application.js manifest includes a //require_tree ., any file I add in the app/assets/javascripts folder will be available to any controller.
I was under the impression that those files were specific to one controller and wouldn't show up anywhere else but on pages of, say, AuthController.
Am I missing something here or is this by design and simply exists to help organize workflow, but nothing more?

A: You are right in that for the situation you described, any javascript you put in app/assets/javascripts/auth.js will be available to to any views that use your application.js manifest, not just ones rendered by your AuthController.
This is by design and is perhaps misleading.  How to organize javascript within the Rails framework is a bit of a hot-topic regularly debated and without consistent conventions.
The idea of splitting your javascript into a file/directory structure matching the rest of your application code is just a convenience measure to help you know where to look for or place "sprinkles" of javascript.  Before Rails 4, view helper modules were in a similar state - their filenames matched respective views and controllers but the methods themselves were available across the entire app (by default).
That said, just because Rails doesn't impose limitations on javascript scopes, doesn't mean you shouldn't follow a convention and manually enforce it.  Breaking your application manifest up into multiple controller manifests or putting erb logic inside of your layout can help achieve this.
Like I said, it's a hot-topic so if you do a little Googling on how to organize javascript in Rails you'll find tons of blogs with articulated suggestions.  Here's a decent example:
http://brandonhilkert.com/blog/organizing-javascript-in-rails-application-with-turbolinks/


text:
Q: failing access data from an array and convert it in pdf I am trying to fetch data from a database and converting it in a Pdf File but the pdf file is empty it doesn't display the database elements the problem is when I get to the variable $res inside the while cycle I get the array but I can't access it . I don't get what am I doing wrong, can you help me?
  <?php
  /**
   * @package     tool_report
   * @author      Marko
   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
   */

   require('../blocks/bbbreport/fpdf/fpdf.php');
   ob_start(); //
   require_once(__DIR__ . '/../config.php');
   defined('MOODLE_INTERNAL') || die();

   $PAGE->set_url(new moodle_url('/course/manage.php'));
   $PAGE->set_context(\context_system::instance());
   $PAGE->set_title(get_string('manage_reports', 'tool_report'));

   global $DB;

   echo $OUTPUT->header();

   $conn = new mysqli($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname);

   if ($conn->connect_errno) {
       echo $conn->connect_error;
       return;
   }

   $sql = " SELECT *
            FROM mdl_bigbluebuttonbn
          ";
   $result = $conn->query($sql);
   $res = [];

   $pdf = new FPDF();
   $pdf->AddPage();
   $pdf->SetFont('Courier','B',16);
   $pdf->Cell(50,10,'Course ID', '1', '0', 'C');
   $pdf->Cell(50,10,'Course TYPE', '1', '0', 'C');
   $pdf->Cell(50,10,'Course COURSE', '1', '0', 'C');
   $pdf->Cell(50,10,'Course NAME', '1', '0', 'C');
   ?><?php
    if ($result->num_rows > 0) {
      while ($row = $result->fetch_assoc()) {
      **$res[]= $row;
      var_dump($res['name]);**
     ?>

       <?php echo $res['id'] ?>
       <?php echo $res['type'] ?>
       <?php echo $res['course'] ?>
       <?php echo $res['name'] ?>

   <?php
     var_dump($res);die();

    }
   }
   ob_end_clean();
   $pdf->Output();
   $conn->close();

   echo $OUTPUT->footer();
   ?>


text:
Q: Launching Multiple Simultaneous Tasks in VS Code I have a single "project" with 3 separate codebases (loaded into a single workspace), each of which has its own long-running npm start task. I want to run all of these at the same time. This isn't too hard if you just go to Terminal -> Run Task 3 times and launch each individually, but since I do this every day and sometimes multiple times per day, it'd be nice to simplify it into running a single command that launches all 3 at once, preferrably in a split terminal (though not necessary), rather than each having their own tab. Anyone know if this is possible?

A: What you want to do is make a new separate task and list the 3 tasks you want to run as dependancies. For example, in your tasks.json:
{
"version": "2.0.0",
"tasks": [
    {
        "label": "Task1",
        // ...
    },
    {
        "label": "Task2",
        // ...
    },
    {
        "label": "Task3",
        // ...
    },
    {
        "label": "Run 3 Tasks",
        "dependsOn": ["Task1", "Task2", "Task3"]
    }
]
}

The default behavior for dependancies will be to run tasks in parellel. This can be changed with the dependsOrder tag.
https://code.visualstudio.com/Docs/editor/tasks


text:
Q: Why I'm getting "This app is incompatible with your device for all devices" on Google Play Store We have android app which is giving This app is incompatible with your device. for all devices which are trying to access the app listing on Google Play Store.
While Developing The app is working and can be installed freely on any device but from play store it is not getting installed.
Attaching gradle file where I feel the error is coming!
splits {
    abi {
        enable true
        reset()
        include 'arm64-v8a', 'armeabi-v7a' // i believe this is this the issue (before judging please read the p.s)
        universalApk true
   }
}

defaultConfig {
        applicationId ""
        minSdkVersion
        targetSdkVersion
        versionCode 1
        versionName "1"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters 'x86_64','arm64-v8a', 'armeabi-v7a' // i believe this is this the issue (before judging please read the p.s)
        }
    }

When I created the apk, I'm getting just one APK which i'm uploading to the google play console
Phones used while development Xiaomi and Samsung and all of them have Android Version 8, 9, 10
P.s I'm a fullstack developer, my company has given me responsibility of managing android app development also, now developers are developing the application under me, and i'm just responsible for releasing the application to play store. And when I asked them, they are not aware of this issue as they are freshers

A: Simple Solutions, I don't remember how I came to this conclusion
In the manifest file, inside defaultConfig object and inside ndk, I added 'x86' which fixed the issue and now app is compatible with devices
defaultConfig {
    applicationId ""
    minSdkVersion
    targetSdkVersion
    versionCode 1
    versionName "1"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    ndk {
        // ***************** check this line for the answer *****************

        abiFilters 'x86_64','arm64-v8a', 'armeabi-v7a', 'x86' // <------ Added 'x86'

        // ***************** check the above line for answer ****************
    }
}


text:
Q: Recompile R with PNG support I am running R 3.1.2 on a headless Raspberry Pi 2 with Raspbian. Packages install fine, but I can't save PNGs. After googling the error for a long time, I found this response, which says I need to "manually recompile R with explicit PNG support."
I apologize if this is a basic question, but how do I recompile R with PNG support? If it's helpful, this is how I installed in the first place. Thanks in advance!

A: What does capabilities()["png"] say?  I suspect it says TRUE as I see no reason why your Raspian package should not follow the standard configuration of both the R source defaults as well as the Debian package default.

A: Thanks to @Dirk, who correctly diagnosed this as a problem of running R headless on the pi, I found a solution by mixing answers from previous posts:

*

*I start R by calling xvfb-run --server-args="-screen 0 1024x768x24" sudo R

*I installed the Cairo package in R and save plots using code I adapted from this blog post
I also found this site helpful.


text:
Q: Stacked Area Plot in R I have some example data attached, I want to make a stacked area plot with the ASVid being the different colors, and the RepCode being the unique sample identifier or date (day.month.year) on the x axis. Then it should add up to 100% so that it is completely filled in. I am having issues getting my dates to be ordered correctly and getting the graph to look correct. So my plot ends up looking all garbled and I have tried to format the days various ways (year.month.day or different formatting in R) but it hasn't worked. Any help would be appreciated.
previously I have attempted the following code:
ggplot(d, aes(x=t,y=val,group=var,fill=var)) + geom_area(position="fill")

This image is what I want to end up with, with the various colors being my ASVid column and the y-axis being Mean (which is proportional so it should equal 100) I could either calculate that proportion in the code for the figure or before running the code...

ASVid   day.month.year  Mean
B1000072    16.01.2015  4
B1000676    16.01.2015  5
B1003168    16.01.2015  5
B1016436    16.01.2015  4
B1001873    16.01.2015  3
B1001931    16.01.2015  2
B1000161    16.01.2015  5
B1001289    16.01.2015  5
B1004651    16.01.2015  2
B1000191    16.01.2015  5
B1000278    16.01.2015  9.00E+00
B1001292    16.01.2015  8
B1002209    16.01.2015  7
B1002593    16.01.2015  6.00E+00
B1003600    16.01.2015  5.00E+00
B1003388    16.01.2015  4
B1003628    16.01.2015  3.00E+00
B1005794    16.01.2015  2.00E+00
B1006374    16.01.2015  1.00E+00
B1005605    16.01.2015  1.00E+00
B1006940    16.01.2015  1.00E+00
B1034395    16.01.2015  1.00E+00
B1001633    16.01.2015  1
B1011183    16.01.2015  1
B1002990    16.01.2015  1
B1004756    16.01.2015  1
B1003006    16.01.2015  2
B1006056    16.01.2015  3
B1011591    16.01.2015  3.00E+00
B1001310    6.06.2014   4
B1003643    6.06.2014   5
B1000408    6.06.2014   5
B1002960    6.06.2014   4
B1001336    6.06.2014   3
B1003763    6.06.2014   2
B1000006    6.06.2014   5
B1000105    6.06.2014   5
B1000843    6.06.2014   2
B1002710    6.06.2014   5
B1013163    6.06.2014   9.00E+00
B1000479    6.06.2014   8
B1001687    6.06.2014   7
B1002223    6.06.2014   6.00E+00
B1009009    6.06.2014   5.00E+00
B1010218    6.06.2014   4
B1001037    6.06.2014   3.00E+00
B1001049    6.06.2014   2.00E+00
B1002384    6.06.2014   1.00E+00
B1002556    6.06.2014   1.00E+00
B1003363    6.06.2014   1.00E+00
B1003380    6.06.2014   1.00E+00
B1004762    6.06.2014   1
B1008036    6.06.2014   1
B1008649    6.06.2014   1
B1012788    6.06.2014   1
B1013162    6.06.2014   2
B1000054    6.06.2014   3
B1003433    6.06.2014   3.00E+00
B1019886    6.06.2014   0
B1000294    6.06.2014   0
B1000471    6.06.2014   0
B1000935    6.06.2014   0
B1002742    6.06.2014   0
B1003964    6.06.2014   0
B1004377    6.06.2014   0
B1006053    6.06.2014   0
B1013830    6.06.2014   0
B1021000    6.06.2014   0
B1001893    9.01.2015   2
B1001048    9.01.2015   5
B1000100    9.01.2015   5
B1000920    9.01.2015   2
B1001049    9.01.2015   5
B1003817    9.01.2015   9.00E+00
B1001037    9.01.2015   8
B1000441    9.01.2015   7
B1001507    9.01.2015   6.00E+00
B1002556    9.01.2015   5.00E+00
B1001686    9.01.2015   4
B1001598    9.01.2015   3.00E+00
B1002552    9.01.2015   5.00E+00
B1002787    9.01.2015   7.00E+00
B1002858    9.01.2015   7.00E+00
B1002916    9.01.2015   3.50E+00
B1003926    9.01.2015   5.50E+00
B1004598    9.01.2015   2
B1004947    9.01.2015   3
B1005691    9.01.2015   3
B1004172    9.01.2015   1
B1006246    9.01.2015   2
B1000102    5.12.2014   3
B1001635    5.12.2014   2
B1000511    5.12.2014   3
B1000361    5.12.2014   3
B1002435    5.12.2014   1
B1008707    5.12.2014   2
B1000092    5.12.2014   3
B1001610    5.12.2014   2
B1002293    5.12.2014   3
B1001977    5.12.2014   3
B1002522    5.12.2014   7
B1002614    5.12.2014   8
B1002750    5.12.2014   0
B1003983    5.12.2014   9
B1004407    5.12.2014   5
B1020999    5.12.2014   7
B1001651    5.12.2014   1
B1000254    5.12.2014   7
B1008692    5.12.2014   9
B1002787    5.12.2014   4
B1017385    5.12.2014   3
B1000996    5.12.2014   3
B1001321    5.12.2014   2
B1002858    5.12.2014   2
B1005632    5.12.2014   3
B1008044    5.12.2014   2
B1029767    5.12.2014   3
B1000365    29.04.2016  8
B1000157    29.04.2016  5
B1001935    29.04.2016  2
B1000684    29.04.2016  6
B1000417    29.04.2016  8
B1000400    29.04.2016  5
B1000591    29.04.2016  6
B1001351    29.04.2016  7
B1002861    29.04.2016  2
B1001150    29.04.2016  3
B1003145    29.04.2016  2
B1004872    29.04.2016  9
B1000650    29.04.2016  6
B1003404    29.04.2016  6
B1000166    29.04.2016  10
B1000237    29.04.2016  8
B1002435    29.04.2016  4
B1006836    29.04.2016  3

A: I would suggest two approaches using ggplot2. Your data is large and has plenty of ASVid values. The area plot can be created but I think the issue would be the large legend and the lack of values. Here the code for an area plot:
library(ggplot2)
#Code for data format
df$day.month.year <- as.Date(df$day.month.year,'%d.%m.%Y')
#Plot option 1
ggplot(df, aes(x=day.month.year,y=Mean,fill=ASVid))+
  geom_area(position="fill")

This would be the output (see the not elegant legend):

A second approach would be using a stacked geom_bar() like this:
#Plot option 2
ggplot(df, aes(x=factor(day.month.year),y=Mean,fill=ASVid))+
  geom_bar(stat='identity',position = 'stack')

Despite the large legend, values can be seen better. Here the output:

You can choose any of the options.
Some data used:
#Data
df <- structure(list(ASVid = c("B1000072", "B1000676", "B1003168",
"B1016436", "B1001873", "B1001931", "B1000161", "B1001289", "B1004651",
"B1000191", "B1000278", "B1001292", "B1002209", "B1002593", "B1003600",
"B1003388", "B1003628", "B1005794", "B1006374", "B1005605", "B1006940",
"B1034395", "B1001633", "B1011183", "B1002990", "B1004756", "B1003006",
"B1006056", "B1011591", "B1001310", "B1003643", "B1000408", "B1002960",
"B1001336", "B1003763", "B1000006", "B1000105", "B1000843", "B1002710",
"B1013163", "B1000479", "B1001687", "B1002223", "B1009009", "B1010218",
"B1001037", "B1001049", "B1002384", "B1002556", "B1003363", "B1003380",
"B1004762", "B1008036", "B1008649", "B1012788", "B1013162", "B1000054",
"B1003433", "B1019886", "B1000294", "B1000471", "B1000935", "B1002742",
"B1003964", "B1004377", "B1006053", "B1013830", "B1021000", "B1001893",
"B1001048", "B1000100", "B1000920", "B1001049", "B1003817", "B1001037",
"B1000441", "B1001507", "B1002556", "B1001686", "B1001598", "B1002552",
"B1002787", "B1002858", "B1002916", "B1003926", "B1004598", "B1004947",
"B1005691", "B1004172", "B1006246", "B1000102", "B1001635", "B1000511",
"B1000361", "B1002435", "B1008707", "B1000092", "B1001610", "B1002293",
"B1001977", "B1002522", "B1002614", "B1002750", "B1003983", "B1004407",
"B1020999", "B1001651", "B1000254", "B1008692", "B1002787", "B1017385",
"B1000996", "B1001321", "B1002858", "B1005632", "B1008044", "B1029767",
"B1000365", "B1000157", "B1001935", "B1000684", "B1000417", "B1000400",
"B1000591", "B1001351", "B1002861", "B1001150", "B1003145", "B1004872",
"B1000650", "B1003404", "B1000166", "B1000237", "B1002435", "B1006836"
), day.month.year = structure(c(16451, 16451, 16451, 16451, 16451,
16451, 16451, 16451, 16451, 16451, 16451, 16451, 16451, 16451,
16451, 16451, 16451, 16451, 16451, 16451, 16451, 16451, 16451,
16451, 16451, 16451, 16451, 16451, 16451, 16227, 16227, 16227,
16227, 16227, 16227, 16227, 16227, 16227, 16227, 16227, 16227,
16227, 16227, 16227, 16227, 16227, 16227, 16227, 16227, 16227,
16227, 16227, 16227, 16227, 16227, 16227, 16227, 16227, 16227,
16227, 16227, 16227, 16227, 16227, 16227, 16227, 16227, 16227,
16444, 16444, 16444, 16444, 16444, 16444, 16444, 16444, 16444,
16444, 16444, 16444, 16444, 16444, 16444, 16444, 16444, 16444,
16444, 16444, 16444, 16444, 16409, 16409, 16409, 16409, 16409,
16409, 16409, 16409, 16409, 16409, 16409, 16409, 16409, 16409,
16409, 16409, 16409, 16409, 16409, 16409, 16409, 16409, 16409,
16409, 16409, 16409, 16409, 16920, 16920, 16920, 16920, 16920,
16920, 16920, 16920, 16920, 16920, 16920, 16920, 16920, 16920,
16920, 16920, 16920, 16920), class = "Date"), Mean = c(4, 5,
5, 4, 3, 2, 5, 5, 2, 5, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1,
1, 1, 1, 2, 3, 3, 4, 5, 5, 4, 3, 2, 5, 5, 2, 5, 9, 8, 7, 6, 5,
4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 2, 5, 5, 2, 5, 9, 8, 7, 6, 5, 4, 3, 5, 7, 7, 3.5, 5.5,
2, 3, 3, 1, 2, 3, 2, 3, 3, 1, 2, 3, 2, 3, 3, 7, 8, 0, 9, 5, 7,
1, 7, 9, 4, 3, 3, 2, 2, 3, 2, 3, 8, 5, 2, 6, 8, 5, 6, 7, 2, 3,
2, 9, 6, 6, 10, 8, 4, 3)), row.names = c(NA, -135L), class = "data.frame")


text:
Q: Что означают квадратные скобки в распределённом условном типе? Подскажите, пожалуйста, что означают квадратные скобки вокруг Type и any? Это кортеж из одного элемента, или что-то другое?
type ToArrayNonDist<Type> = [Type] extends [any] ? Type[] : never;

A: [Type] - это значит массив из одного элемента типа Type, а Type[] - означает массив из неограниченного количества элементов типа Type


text:
Q: Android app not changing volume so I am trying to make a simple app that mutes the media volume then closes itself. When I run the app I get two problems first it does not change the volume, and second it claims the app crashed on my phone witch I don't want to happen. Hers my code:
package com.example.scielencetester;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AudioManager mgr=null;
        mgr=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
        mgr.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
        finish();
    }

    }

If it helps here is a copy of the error log:
12-29 09:49:20.698: E/AndroidRuntime(23766): FATAL EXCEPTION: main
12-29 09:49:20.698: E/AndroidRuntime(23766): Process: com.example.scielencetester, PID: 23766
12-29 09:49:20.698: E/AndroidRuntime(23766): android.util.SuperNotCalledException: Activity {com.example.scielencetester/com.example.scielencetester.MainActivity} did not call through to super.onCreate()
12-29 09:49:20.698: E/AndroidRuntime(23766):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2254)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at android.os.Handler.dispatchMessage(Handler.java:102)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at android.os.Looper.loop(Looper.java:135)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at android.app.ActivityThread.main(ActivityThread.java:5221)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at java.lang.reflect.Method.invoke(Native Method)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at java.lang.reflect.Method.invoke(Method.java:372)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
12-29 09:49:20.698: E/AndroidRuntime(23766):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Thanks in advance for your help.

A: The stack trace is telling you what to do...

android.util.SuperNotCalledException: Activity {com.example.scielencetester/com.example.scielencetester.MainActivity} did not call through to super.onCreate()

In your onCreate() method, call the superclass method (super.onCreate(...))
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AudioManager mgr=null;
    mgr=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
    mgr.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
    finish();
}


text:
Q: Issue loading layer from OpenLayers plugin in QGIS I installed the OpenLayers plugin in QGIS and tried to load one of the layers. Regardless of which layer I try to load, I am getting an error message. See example:

Does anyone know how to resolve this?

A: It may be a problem with the CRS in some of the layers. I hope this post could help you:
QGIS failed with error: latitude or longitude exceeded limits


text:
Q: Как сделать кастомный sidebar для несколько страниц? Ситуация такая, есть:

*

*шаблон по умолчанию layouts/default.vue

*левый sidebar который присуствует на все страницы

*правый sidebar, который должен быть только на несколько страниц
В store/index.js храню переключатель, если state.sidebar.right === true то в layouts/default показываю кнопку для открытия правого сайдбара.
Теперь проблема в том чтобы при переходе на страницу в которой должен быть сайдбар, загрузить в нём нужные компоненты и в них данные с API.
И ещё вопрос, где нужно хранить <v-navigation-drawer> чтобы он открылся при клике на кнопку с layout/default? Объязательно в layout/default? Пробовал хранить его в компоненте страницы (pages/cat/index.vue) но не работает. Наверное нужно держать его состояние тоже в store, правильно понимаю?
<nuxt-child> тоже пробовал использовать но грузиться контент который есть и в <nuxt>
Может быть не очень чётко сформулировал проблему, я ещё начинающий.


text:
Q: jQuery on yesod haskell I'm new on functional programming. New on Haskell and Yesod.
I'm just only trying to show a 'div' with login form
(Sorry, but english is not my first language)
module Handler.Share where

import  Import
import  Text.Lucius

menu :: Widget
menu = [whamlet|

  Entrar

      Login

Usuário:

Senha:

            Esqueci minha senha

            Novo cadastro

|]

getShareR :: Handler Html
getShareR = do
    defaultLayout $ do
        addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"
        toWidgetHead [julius|
          function showlogin(){
            $("#login").show("slow");
          }
        |]
        toWidget $ $(luciusFile "templates/share.lucius")
        $(whamletFile "templates/share.hamlet")

Return: Uncaught ReferenceError: $ is not defined

A: I learned to use 'toWidget' instead 'toWidgetHead' to load the script at the end of the page.
getShareR :: Handler Html
getShareR = do
    defaultLayout $ do
        addStylesheet $ StaticR css_bootstrap_css
        addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"
        toWidget [julius|
          $(document).mouseup(function (e) {
            var div = $("#login");
            if (!div.is(e.target) && div.has(e.target).length === 0) {
                if (div.is(':visible')) {
                    div.toggle("slow");
                }
            }
          });

          function showlogin(){
            $("#login").show("slow");
          }
        |]
        toWidget $ $(luciusFile "templates/share.lucius")
        $(whamletFile "templates/share.hamlet")


text:
Q: Hiding TabPage from TabControl in Winform application I have a TabControl in Winform s application,
I have to disable the second tab,  clicking it would be enabled only after some action on my first page.
I have achieved this by disabling tab by code
tabControl1.TabPages[1].Enabled = false;

But I want that tab to be hidden or clicking the tab itself should be disabled.

A: You have asked two questions:

*

*How to hide a TabPage

*How to make it non-selectable
You can't really hide a TabPage; the closest and simplest solution is to remove it from the orginal Tab control and add it to a hidden helper Tab control:
tabPage3.Parent = helperTab;

To make it non-selectable, you code the Selecting event of the Tab control. You need to set a flag, maybe in the Tag of the page, and then you can prevent a page where the flag is set from being selected:
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
    if (e.TabPage.Tag == "X") e.Cancel = true;
}

A: Try This. It will hide and show the TabPages without a Control lost.
Hide TabPage and Remove the Header:
this.tabPage1.Hide();
this.tabPage3.Hide();
this.tabPage5.Hide();
tabControl1.TabPages.Remove(tabPage1);
tabControl1.TabPages.Remove(tabPage3);
tabControl1.TabPages.Remove(tabPage5);

Show TabPage and Visible the Header:
tabControl1.TabPages.Insert(0,tabPage1);
tabControl1.TabPages.Insert(2, tabPage3);
tabControl1.TabPages.Insert(4, tabPage5);
this.tabPage1.Show();
this.tabPage3.Show();
this.tabPage5.Show();
tabControl1.SelectedTab = tabPage1;


text:
Q: Android ExpandableListView with clickable links in child TextView won't expand properly First, I have searched for similiar questions but none that I have found have been answered (except to say that it is impossible, which I doubt).
Android ExpandableListView with clickable links in child TextView won't expand when touching TextView
ExpandableListView centains a link does not expand
I have an expandable list adapter that may or may not contain links within a textview in the item's groupview. Here is what is currently happening:

*

*when I touch one of these textviews without a link in it, it expands properly (this is what I want)

*when I touch one of these textviews with a link in it directly on the highlighted text, it opens the proper website in the external browser (this is what i want)

*when I touch one of these textviews with a link in it on non-highlighted text that is not part of the link, it does nothing (this is NOT what I want.)

how do I get it so that if I touch one of these textviews with a link in it on the non-highlighted text it expands and shows the childviews?
relevant code:
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    View v = convertView;
    if(v == null){
        LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = infalInflater.inflate(R.layout.docket_layout, null);
    }
    TextView docketTitle = (TextView) v.findViewById(R.id.docketHeader);
    docketTitle.setText(myDockets.getDocket(groupPosition).title);
    return v;
}

and the relevant XML:
<TextView
    android:id="@+id/docketHeader"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="19dp"
    android:autoLink="web"
    android:linksClickable="true"
    />

Thank you in advance for you help


text:
Q: Storing Web Session on S3 bucket I have a cluster of web servers which store web session related information in a NFS shared directory. We are trying to implement an AWS version of our product where we could use S3 bucket to store static contents.
I now need to store the web sessions on a shared location which all the ec2 webservers can share. As it has been explained here http://harish11g.blogspot.co.uk/2012/10/web-session-synchronization-aws-ec2.html, Amazon's Elasticache would be one of the best option to store we b session but it would require some code changes. This is not too much of problem. I am trying to find out what is the best option without changing too much.
Could the S3 buckets be used for storing web sessions? Would there be any issue with latency?  Applications are written in PHP4 and PHP5.


text:
Q: How to get client secret expiry date using the azure AD graph API I am trying to get the expiry date of the client secrets for our AAD application. However when I use the following graph request, the passwordCredential and keyCredential fields is blank.
https://graph.windows.net/myorganization/directoryObjects/{ServicePrincipalObjectId}/?api-version=1.6
Is there a way to get this data? I see it in the manifest if I download that, just not in the Odata object
Thank you for your help!

A: Use this AAD Graph API below:
https://graph.windows.net/{org_domain}/applications/{obj_id}/passwordCredentials

The response will show the list of keys used by your specific AAD Application.
You can derive the expiration date of your key from the endDate field.
{
  "odata.metadata": "https://graph.windows.net/{org_domain}/$metadata#Collection(Microsoft.DirectoryServices.PasswordCredential)",
  "value": [
    {
      "customKeyIdentifier": null,
      "endDate": "2018-05-07T09:12:13.2177408Z",
      "keyId": "{your_key_id}",
      "startDate": "2016-05-07T09:12:13.2177408Z",
      "value": null
    }
  ]
}

A: As an alternative to using Graph API you might also consider using Get-AzAdApplication cmdlet together with Get-AzAdAppCredential, which are part of Az PowerShell
https://learn.microsoft.com/en-us/powershell/module/az.resources/get-azadappcredential?view=azps-5.5.0


text:
Q: Can you block an ip with multiple connections? (Apache ddos attack) My server is under a Apache ddos attack right now. There's a ton of single ip addresses with 30+ connections.
When I use this SSH command:
netstat -n | grep ':80' | awk -F' ' '{print $5}' | awk -F':' '{print $1}' | sort | uniq -c | sort -n

I'm getting this:
     30 69.144.146.74
     31 190.216.242.195
     31 92.20.224.127
     34 24.127.224.73
     37 197.34.29.122
     37 85.225.133.82
     38 108.29.62.196
     38 86.95.44.115
     40 66.62.146.84
     40 94.123.91.147
     46 24.117.238.91
     48 70.112.112.127
     48 71.58.158.150
     48 75.65.172.192
     51 99.127.238.167
     52 99.98.74.66
     53 107.7.34.66
     54 95.238.27.3

I've black listed over 100 ip's already, but within 5 min. there's all new ip's with 50+ connections.
I have no idea what to do right now. Is there a way to only allow a ip address to have 1 connection at a time? Or, is there a firewall that can protect against this thing? I'm freaking out here, how can this be fixed? Thanks.

A: There are hardware / firewalls that can do this.  Your option at the apache level is a feature called "throttling".  There used to be a module for this, but it seems it's been removed.
https://stackoverflow.com/questions/7467183/throttling-requests-by-ip-address-on-apache

A: It depends on the severity, but you can always attempt to use mod_evasive or mod_security. Those are software firewalls that each do different things to react in case of an attack. If you are being attacked right now, I would recommend using mod_evasive right away since it's easier to understand than mod_security and very configurable from the get go. mod_security is a much better long term solution, but you might need to spend a lot of time configuring it properly so it doesn't get in the way of expected behavior on your server.

A: Check out fail2ban and maybe review your iptables rules.
fail2ban is a traditional, widely used and supported tool to address your situation and similar.  It will blacklist IPs that are attacking you by (depending upon how you've set it up) adding a special chain to iptables and auto populating drop rules for attacking IP addresses.


text:
Q: Internet not available exception in Laravel 5.2 I was trying to open Sandbox paypal page from my Laravel application and faced below issue

This issue came when internet connection was not available. Like we face 404 issue...for that we have 404 blade in View folder.
Is there any way to handle this exception so that we can show a user friendly page to user that Please check your internet connection
It doesn't not works when I write below code:
if ($e instanceof \PayPal\Exception\PayPalConnectionException) {
    return response()->view('errors.InternetConnection');
}

but it works when I write
if ($e instanceof \PayPal\Exception\PayPalConnectionException) {
    \App::abort(404);
}

I created a new blade called InternetConnection in error folder

A: You can listen for this exception in App\Exceptions\Handler@render. Just add this:
    if ($e instanceof PayPalConnectionException) {
        return response()->view('errors.404', [], 404);
    }

A: Yes, you can! (https://laravel.com/docs/5.1/errors#the-exception-handler)
in your App\Exceptions\Handler:
...
public function render($request, Exception $e)
{
    if ($e instanceof PayPalConnectionException) {
        //my paypal exception
        return response()->view('errors.payPalConnectionError', [], 404);
    }

    return parent::render($request, $e);
}

A: This will work:-
you need to create a folder named errors if not already exist in views and place blade file named 404.blade.php in it. and put your error template for 404 error in this blade. laravel will automatically use it when ever a 404 error will occur.

A: In your app/Exceptions/Handler.php edit render method as:
public function render($request, Exception $e)
{
    if($e instanceof ValidationException) return response()->view('errors.abc');
    return parent::render($request, $e);
}

Remember Don't forget to USE the Exception in your Handler.php
Like I am showing abc view for ValidationException So I am adding this line in my Handler.php class
use Illuminate\Validation\ValidationException;
Otherwise this won't work.


text: Q: Looking for a short-story set in a post-apocalyptic environment I'm looking for a short-story set in a post-apocalyptic environment – volcanic eruption I think. The main character is a young woman who has a rather nasty character for a boyfriend. He's abusive and uses violence to get what he wants and for the hell of it. I seem to remember oldsters living in the same space that's maybe an underground parking garage. In a confrontation, the woman stands up to the boyfriend and he backs down when he realizes she is strong and angry enough to hurt him. She escapes to the 'wild' at the end of the story. Read in the 00s, part of an anthology.


text:
Q: output piped to awk is not immediately handled Consider the following dummy backup script:
#!/bin/bash
echo "rsync started"
sleep 1 # rsync time
echo "rsync completed"
echo "starting upload"
sleep 5 # upload time
echo "upload completed"

and the following minimal start script
#!/bin/bash
/path/to/backup.sh|awk '/^rsync completed/ {print "Restarting services"}'
echo "backup completed"

I would have expected the "Restarting services" output to appear after one second, but instead it appears at the end after 6 seconds, when running under Debian Wheezy.
Where is my mistake? Why isn't the awk action directly handled when the "rsync compeleted" string is written to stdout?

A: Use sed instead of awk.
/path/to/backup.sh|sed 's/^rsync completed/Restarting services/g'
echo "backup completed"


text:
Q: How to prevent Mac Outlook from inserting line breaks in sent plain text emails? When I send plain text emails with Mac Outlook, line breaks are automatically inserted. This is annoying for several reasons. (1) long URLs are split over multiple lines which confuses readers; (2) personalised line formatting breaks. Others share the problem (e.g., here and here)
How can I prevent Mac Outlook from inserting line breaks in plain text emails?


text:
Q: Add string to another string I currently encountered a problem:
I want to handle adding strings to other strings very efficiently, so I looked up many methods and techniques, and I figured the "fastest" method.
But I quite can not understand how it actually works:
def method6():
    return ''.join([`num` for num in xrange(loop_count)])

From source (Method 6)
Especially the ([`num` for num in xrange(loop_count)]) confused me totally.

A: it's a list comprehension, that uses backticks for repr conversion. Don't do this. Backticks are deprecated and removed in py3k and more efficient and pythonic way is not to build intermediate list at all, but to use generator expression:
''.join(str(num) for num in xrange(loop_count))        # use range in py3k

A: That bit in the brackets is a list comprehension, arguably one of the most powerful elements of Python. It produces a list from iteration. You may want to look up its documentation. The use of backticks to convert num to a string is not suggestible - try str(num) or some such instead.
join() is a method of the string class. It takes a list of strings and return a single string consisting of each component string separated by "self" (aka the calling string). The trick here is that join() is being called directly from the string literal '', which is allowed in Python. What this code will to is produce a string consisting of the string form of each element of xrange(loop_count) with no separation.

A: xrange() is a faster (written in C) version of range().
Backtick notation -- num, coerces a variable to a string, and is the same as str(num).
[x for x in y] is called a list comprehension, and is basically an one-liner for loop that returns a list as its result.  So all together, your code's semantically equivalent to the following, but faster, because list comprehensions and xrange are faster than for loops and range:
z = []
for i in range(loop_count):
   z.append(str(i))
return "".join(z)

A: First of all: while this code is still correct in the 2.x series of Python, it a bit confusing and can be written differently:
def method6a():
    return ''.join(str(num) for num in xrange(loop_count))

In Python 2.x, the backticks can be used instead of the repr function. The expression within the square brackets [] is a list comprehension. In case you are new to list comprehensions: they work like a combination of a loop and a list append-statement, only that you don't have to invent a name for a variable:
Those two are equivalent:
a = [repr(num) for num in xrange(loop_count)]
# <=>
a = []
for num in xrange(loop_count):
    a.append(repr(num))

As a result, the list comprehension will contain a list of all numbers from 0 to loop_count (exclusively).
Finally, string.join(iterable) will use the contents of string concatenate all of the strings in iterable, using string as the seperator between each element. If you use the empty string as the seperator, then all elements are concatenated without anything between them - this is exactly what you wanted: a concatenation of all of the numbers from 0 to loop_count.
As for my modifications:

*

*I used str instead of repr because the result is the same for all ints and it is easier to read.

*I am using a generator expression instead of a list comprehension because the list built by the list comprehension is unnecessary and gets garbage collected anyway. Generator expressions are iterable, but they don't need to store all elements of the list. Of course, if you already have a list of strings, then simply pass the list to the join.

Generally, the ''.join(iterable) idiom is well understood by most Python programmers to mean "string concatenation of any list of strings", so understandability shouldn't be an issue.


text:
Q: Link Outlook contact card to SharePoint 2010 MySite In Outlook 2010, when a user hovers over a person's name, a "contact card" pops up with various info such as picture, position, presence, etc. Example:

As you can see, the contact name is also hyperlinked. This should be pointing to our SharePoint MySite, but when clicking on the name, it points to an incorrect link (our development environment, actually).
I can easily fix this on my local machine by updating the registry key in
HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Common\Server Links\Published
in here there is a registry subfolder called "Profile Site" (others may instead have a folder called "MySite") and a key called "Url", where I can set it to the correct MySite
(e.g. "http://servername/person.aspx?user=")
Referenced from: http://blogs.technet.com/b/paulpaa/archive/2010/01/19/if-you-want-to-modify-the-mysite-url-to-point-to-a-new-url-or-mysite-url-is-showing-wrong-in-office-application-eg-outlook.aspx
and
http://social.technet.microsoft.com/Forums/sharepoint/en-US/dcc37911-524a-4810-a67a-d51289e2af59/outlook-contact-card-name-link-goes-to-wrong-sharepoint-mysite-url?forum=sharepointadminprevious
This will allow any name to link to their correct MySite, but only on my machine.
The problem is, we have many users that this modification needs to be pushed out to. How do we apply this change to all users on the network? More importantly, instead of applying a registry band-aid to each user, how is this link set up initially for all users so that I may reproduce that configuration? Is there somewhere in SP Central Admin/Outlook that it can be set, or is it setup during installation (either of SharePoint or Outlook/Exchange)?
EDIT: Group Policy update is duly noted, but our only real way out of this at this point is to find out how this is originally set via installation or configuration of SharePoint or Outlook. This should be OOTB functionality (pending admin configuration of course) since it obviously seems like a feature supported by Microsoft.

A: You can use Group Policy to push this registry setting to all users in your environment.

A: Here's what you need to do.
Go to your SharePoint site.
Click on the desired contact list.
Click on the List tab.
Click Open in Outlook.
Click OK.
Hope This Works,
Peter


text:
Q: Function.prototype.apply.bind usages? I perfectly know the usages for  :
Function.prototype.bind.apply(f,arguments)

Explanation - Use the original (if exists) bind method over f  with arguments (which its first item will be used as context to this)

This code can be used ( for example) for creating new functions via constructor function with arguments
Example :
function newCall(Cls) {
    return new (Function.prototype.bind.apply(Cls, arguments));
 }

Execution:
var s = newCall(Something, a, b, c);

But I came across this one : Function.prototype.apply.bind(f,arguments) //word swap
Question :
As it is hard to understand its meaning - in what usages/scenario would I use this code ?

A: This is used to fix the first parameter of .apply.
For example, when you get the max value from an array, you do:
var max_value = Math.max.apply(null, [1,2,3]);

But you want to get the first parameter fixed to null, so you could create an new function by:
var max = Function.prototype.apply.bind(Math.max, null);

then you could just do:
var max_value = max([1,2,3]);


text:
Q: Using Exceptions to validate inputs I am trying to check whether the value passed by an user is valid constant or not. Here is the code I have written.
enum Media_Delivery {
    Streaming, Progressive
}

public class TestMain {
    public static void main(String[] args) {
        String medi_delivery = "streaming";
        try {
            Media_Delivery.valueOf("streaming");
        } catch (IllegalArgumentException e) {
            System.out.print(e);
        }

    }

}

Now, in above code if the String passed is not withing the listed enum then it throws IllegalArgumentException which is obvious.
But my question is: Is this the proper way to validate? As we are using Java's exception mechanism to validate.
Can someone suggest a better idea or what I have coded above itself is the best option ?
-----EDIT--------
Another case which I wanted to discuss:

    public class TestMain {
            public static void main(String[] args) {
                String inputPassed = "2a";
                try {
                    Integer.parseInt(inputPassed);
                } catch (NumberFormatException nfe) {
                    throw new SomeUserDefinedException("Please enter only numeric values");
                }

            }

So is this a good idea ? Or there should be our own parsing mechanism?

A: Exceptions should be used for exceptional conditions; things you don't expect to happen. Validating input isn't very exceptional.
Josh Bloch actually outlines this specifically in his book 'Effective Java' which IMHO is something every Java programmer should have.
EDIT: And this is actually a very good answer to how to approach the problem:
Check valid enum values before using enum

A: It is usually best practice not to catch or throw unchecked expressions (IllegalArgumentException is a RuntimeException which counts as "unchecked"). See the Java Tutorials - Exceptions for more details. If you can avoid it, try rewriting your code such that a runtime exception is not needed to be caught. This is a controversial issue, but runtime exceptions exist for a reason: they help the programmer identify bugs. If you catch them, then the bug is not being fixed, it is just being avoided. Try using an if-else statement?
According to the API, "the name must match exactly an identifier used to declare an enum constant." I believe this means the parameter is case-sensitive. In addition, the return type of the valueOf method is some type, not void, so you can't have that statement in the try block. try blocks should contain commands or void methods, such as int x = 3; or System.out.println(3); or something.
--------EDIT-------
OP, in response to your comment:
Like others here have said, it depends on what you're trying to accomplish. I assume that since you have the line Media_Delivery.valueOf("streaming"); in the try block, that you're attempting to see whether "streaming" is equal to one of the enum constants? In that case, you wouldn't need an if-else statement, you could simply write
boolean result = medi_delivery.equals(Media_Delivery.Streaming.name()) ||
  medi_delivery.equals(Media_Delivery.Progressive.name());
System.out.println(result);

Or even better, if you don't want to have multiple || conditions, try a switch statement that cycles through each enum constant, testing the equality of the given string.
-Chris
PS: on naming convention, since enum constants are implicitly static final, it is common practice to declare them in all caps, such as STREAMING and PROGRESSIVE (the Java Tutorials - Enums).

A: I'd say it depends.
If input comes from GUI element like combobox or anything, where enum values are the only ones to choose - then your approach is ok. Here different value would really be an exception.
But if you're making console app, or textfiled with possibility to type anything then result different then enum values shouldn't be considered as exception. You should use normal if-else or cases with this approach.
generally: use exceptions only for exceptional cases, and not for something that is really likeable to happen.

A: There is no single "proper" way to validate, what you have would certainly be the way I would validate, but there are other ways(for instance you could put all the valid string values of the enumeration in a HashSet and then check against that set to see if its valid, that is probably what the valueOf method does anyway)
Now if the above approach is any "better" or not, that too is to be pretty subjective.  If you are doing the validations in a loop and want to reject anything that contains invalid data, then the exception approach is probably best.  If you want to flag all the inappropriate elements then either approach works.... the HashSet will probably be faster if there is a lot of problematic data as you wont have to generate a lot of new exception objects, but even then the difference in performance will be pretty negligible.


text:
Q: Module of dimension zero over a local ring.
Let $(A,m)$ be a Noetherian local ring and let $M$ be an $A$-module of dimension $0$ ($\dim M=\dim A/\operatorname{Ann}M$). Then every element of $M$ is annihilated by a power of $m$.

I would appreciate some help proving this. Thanks.

A: Since $\dim M=0$ we have $\dim A/\operatorname{Ann}M=0$, so $A/\operatorname{Ann}M$ is a local artinian ring and you are done.


text:
Q: Implementing and visualizing a binary tree in java i had to implement a binary tree pictured on this file
together with the class Diagramm and binary tree for orientation.

So following the text and the Pictures i have to implement a constructor, a get- and insert method for this binary tree.
public class BinaryTree {

 private Node root = null;

private static class Node {
    private Integer key;
    private String value;
    private Node left = null;
    private Node right = null;

    public Node(Integer key, String value) {
        this.key = key;
        this.value = value;
    }
}

public boolean insert(Integer key, String value) {
    if (root == null) {
        root = new Node(key, value);
        return true;
    } else {
        return insert(root, key, value);
    }
}

private boolean insert(Node node, Integer key, String value) {
    if (key.equals(node.key)) {
        // duplicate
        return false;
    } else if (key < node.key) {
        if (node.left == null) {
            node.left = new Node(key, value);
            return true;
        } else {
            return insert(node.left, key, value);
        }
    } else if (key > node.key) {
        if (node.right == null) {
            node.right = new Node(key, value);
            return true;
        } else {
            return insert(node.right, key, value);
        }
    }
    return false;
}

// not tested, crass assumptions, public domain
public String get(Integer key) {
    return get(root, key); // start search from the root.
}

public String get(Node node, Integer key) {
    String result = null; // Assume key is not found

    if (node.key.equals(key)) { // Key matches? This is the result.
        return node.value;
    } else {
        if (key < node.key && node.left != null) { // key is lower than
                                                    // current node,
                                                    // and there is a left
                                                    // branch, keep
                                                    // search from there.
            result = get(node.left, key);
        } else if (key > node.key && node.right != null) { // key is greater
                                                            // than current
                                                            // node,
                                                            // and there is
                                                            // a left
                                                            // branch,
                                                            // keep search
                                                            // from there.
                                                            // The key >
                                                            // node.key is
                                                            // arguably
                                                            // redundant.
            result = get(node.right, key);
        }
    }

    return result;
}

How can i implement a correct main function for testing? And on top i have to visualize the binary tree with help of graphviz and adding a method in the node class which creates a string for the dot-code. How does it work with Eclipses?

A: The get method will start at a specific node within the tree, and check whether that node itself meets the criteria. If it does, it returns the value. If not, it will defer to the appropriate branch and continue searching.
// not tested, crass assumptions, public domain
public String get(Integer key) {
    return get(root, key); // start search from the root.
}

public String get(Node node, Integer key) {
    String result = null; // Assume key is not found

    if (node.key.equals(key)) { // Key matches? This is the result.
        return node.value;
    } else {
        if (key < node.key && node.left != null) {  // key is lower than current node,
                                                    // and there is a left branch, keep
                                                    // search from there.
            result = get(node.left, key);
        } else if (key > node.key && node.right != null) {  // key is greater than current node,
                                                            // and there is a left branch,
                                                            // keep search from there.
                                                            // The key > node.key is arguably
                                                            // redundant.
            result = get(node.right, key);
        }
    }

    return result;
}

A: If you choose procedural approach, right way to do things will be that:
public class BinaryTree {
    private Node root = null;

    private static class Node {
        private Integer key;
        private String value;
        private Node left = null;
        private Node right = null;

        public Node(Integer key, String value) {
            this.key = key;
            this.value = value;
        }
    }

    public boolean insert(Integer key, String value) {
        if (root == null) {
            root = new Node(key, value);
            return true;
        } else {
            return insert(root, key, value);
        }
    }

    private boolean insert(Node node, Integer key, String value) {
        if (key.equals(node.key)) {
            // duplicate
            return false;
        } else if (key < node.key) {
            if (node.left == null) {
                node.left = new Node(key, value);
                return true;
            } else {
                return insert(node.left, key, value);
            }
        } else if (key > node.key) {
            if (node.right == null) {
                node.right = new Node(key, value);
                return true;
            } else {
                return insert(node.right, key, value);
            }
        }
        return false;
    }
}

Now compare it to OOP approach and choose, which one you like more:
public class BinaryTree {
    private Node root = null;

    private static class Node {
        private Integer key;
        private String value;
        private Node left = null;
        private Node right = null;

        public Node(Integer key, String value) {
            this.key = key;
            this.value = value;
        }

        private boolean insert(Integer key, String value) {
            if (key.equals(this.key)) {
                // duplicate
                return false;
            } else if (key < this.key) {
                if (left == null) {
                    left = new Node(key, value);
                    return true;
                } else {
                    return left.insert(key, value);
                }
            } else if (key > this.key) {
                if (right == null) {
                    right = new Node(key, value);
                    return true;
                } else {
                    return right.insert(key, value);
                }
            }
            return false;
        }
    }

    public boolean insert(Integer key, String value) {
        if (root == null) {
            root = new Node(key, value);
            return true;
        } else {
            return root.insert(key, value);
        }
    }
}

Solution is simple. For insert operation:

*

*If there is no root in the tree yet, create one.

*Otherwise add a new value to the root node.

Inserting a value to some node (starting from root one):

*

*If node's key equals to the inserted key => we have a duplicate and won't proceed any further.

*If inserted key is lesser than node's key, do:

*

*If there is no left subtree, create a new node and assign it as a left child.

*If there is already a left subtree, recursively add new (key, value) to it.

*If inserted key is greater than node's key, do: (by analogy with #2)


text:
Q: Pattern Matching with XSLT I'm trying to match a pattern into a string in XSLT/XPath using the matches function, as follows:
<xsl:when test="matches('awesome','awe')">
   ...
</xsl:when>

However, in both Firefox 3.5.9 and IE8, it doesn't show up. IE8 tells me that "'matches' is not a valid XSLT or XPath function." Is this due to XSLT 2.0 not being supported, and is there a way around this?

A: Regular Expressions are supported only in XSLT 2.x/XPath 2.x.
As at this date, no publicly available browser supports XSLT 2.x/XPath 2.x.
In your concrete case you can use:
starts-with('awesome','awe')

other useful XPath 1.0 functions are:

*

*contains()

*substring()

*substring-before()

*substring-after()

*normalize-space()

*translate()

*string-length()

A: In addition to the correct hint that browsers don't support XSLT/XPath 2.0: note that Firefox (since version 3.0 I think) supports some EXSLT functions, in particular for regular expressions: https://developer.mozilla.org/en/EXSLT#Regular_expressions so with Firefox you could consider EXSLT functions. For IE using MSXML you could incorporate http://exslt.org/regexp/functions/match/regexp.match.msxsl.xsl which implements the EXSLT match function using the msxsl:script element.


text:
Q: Getting Error while inserting data in two tables in python I want to insert data into two different tables using same database one is for loop and another is outside for loop but after inserting data into one table I am getting error.
my code
with connection ...
     for loop ....

            sql = "INSERT INTO user_repo (user_id, github_id, repo_id, user_connection, repo_name, contributors, total_commits, commit_by_user, created_date, last_commit) VALUES (  % s, % s, % s, % s, % s, % s, % s, % s, % s, % s)"
            cursor.execute(sql, (
                        initial_details['id'],
                        username,
                        all_repo_data[(repo['name'])]['id'] ,
                        all_repo_data[(repo['name'])]['owner'] ,
                        all_repo_data[(repo['name'])]['name'],
                        all_repo_data[(repo['name'])]['contributors'],
                        all_repo_data[(repo['name'])]['total_commits'],
                        all_repo_data[(repo['name'])]['commit_by_user'],
                        all_repo_data[(repo['name'])]['created_at'] ,
                        all_repo_data[(repo['name'])]['updated_at'],
            ))
       sql = "INSERT INTO initialdetails (github_id, name, email, user_id, location, followers, following,total_commits,total_stars,total_repos) VALUES ( % s, % s, % s, % s, % s, % s, % s, % s, % s, % s)"
       cursor.execute(sql, (initial_details['username'],
                     initial_details['name'],
                     initial_details['email'],
                     initial_details['id'],
                     initial_details['location'],
                     initial_details['followers'],
                     initial_details['following'],
                     Total_commits_of_user,
                     total_stars,
                     total_repos,))
      connection.commit()

the error I am getting is
Traceback (most recent call last):
  File "d:\I8Labs\githubData.py", line 210, in <module>
    cursor.execute(sql, (initial_details['username'],
  File "C:\Python39\lib\site-packages\pymysql\cursors.py", line 143, in execute
    while self.nextset():
  File "C:\Python39\lib\site-packages\pymysql\cursors.py", line 96, in nextset
    return self._nextset(False)
  File "C:\Python39\lib\site-packages\pymysql\cursors.py", line 83, in _nextset
    conn = self._get_db()
  File "C:\Python39\lib\site-packages\pymysql\cursors.py", line 65, in _get_db
    raise err.ProgrammingError("Cursor closed")
pymysql.err.ProgrammingError: Cursor closed


text:
Q: Limit of Momentum Update Equation I am self-studying on optimization algorithm on https://d2l.ai/chapter_optimization/momentum.html and couldn't get my head around some derivation:

Instead of the standard gradient descent update equation:
$$\mathbf{x_t} \leftarrow \mathbf{x}_{t-1} - \eta_t \mathbf{g}_{t,t-1}$$
Momentum descent uses a "momentum gradient", $\mathbf{v_t}$, instead of the gradient, $\mathbf{g}_t$ :
$$\begin{align}\mathbf{v_t}&\leftarrow\beta \mathbf{v_{t-1}+\mathbf{g}_{t,t-1}} \\
\mathbf{x}_t &\leftarrow \mathbf{x}_{t-1} - \eta \mathbf{v}_t
\end{align}$$
where $0<\beta <1$ and $\mathbf{g}_{t,t-1}$ is the gradient at step size $t$ and $\mathbf{v_t}$ is updated recursively as follow:
$$\begin{align}\mathbf{v_t}&=\beta \mathbf{v}_{t-1}+\mathbf{g}_{t,t-1} \\
&=\beta^2 \mathbf{v}_{t-2}+\beta \mathbf{g}_{t-1,t-2}+\mathbf{g}_{t,t-1} \\
&\qquad\vdots \\
&=\sum_{\tau=0}^{t-1} \beta^\tau \mathbf{g}_{t-\tau,t-\tau-1}\end{align}$$

The text then continues by stating (11.6.1.4)

In the limit the terms add up to $\sum_{\tau=0}^\infty \beta^\tau = \frac{1}{1-\beta}$. In other words, rather than taking a step of size $\eta$ in gradient descent or SGD we take a step of size $\frac{\eta}{1-\beta}$ while at the same time, dealing with a potentially much better behaved descent direction.

I am at loss at how $\sum_{\tau=0}^{t-1} \beta^\tau \mathbf{g}_{t-\tau,t-\tau-1} \rightarrow \frac{1}{1-\beta}$ as $t\rightarrow \infty$. I try to reason it as follow:
Since
$$\begin{align}
    \mathbf{x}_t &= \mathbf{x}_{t-2} -\eta\mathbf{v}_{t-1} -\eta\mathbf{v}_t\nonumber\\
    &= \mathbf{x}_{t-3} - \eta\mathbf{v}_{t-2} -\eta\mathbf{v}_{t-1} - \eta\mathbf{v}_t\nonumber\\
    &\hspace{25pt}\vdots\nonumber\\
    &= \mathbf{x}_0 - \sum_{\tau=0}^{t}\eta\mathbf{v}_{t-\tau}\\
    \mathbf{v}_t &= \beta^{t-1}\mathbf{g}_{1,0} + \beta^{t-2}\mathbf{g}_{2,1} + \cdots + \mathbf{g}_{t,t-1}\\
    \mathbf{v}_{t-1} &= \beta^{t-2}\mathbf{g}_{1,0} + \beta^{t-3}\mathbf{g}_{2,1} + \cdots + \mathbf{g}_{t-1,t-2}\\
    &\qquad \vdots\\
    \mathbf{v}_1 &= \mathbf{g}_{1,0}\\ \newline
    \mathbf{v}_0 &= 0
\end{align}
$$
Then,
$$\begin{align}
    \mathbf{x}_t &= \mathbf{x}_0 - \eta\left\{\left(\beta^{t-1}+\beta^{t-2}+\cdots + 1\right)\mathbf{g}_{1,0} + \left(\beta^{t-2}+\beta^{t-3}+\cdots + 1\right)\mathbf{g}_{2,1}+\cdots+\beta\mathbf{g}_{t-1,t-2} + \mathbf{g}_{t,t-1}\right\}\nonumber\\
    &= \mathbf{x}_0 - \eta\left\{\left(\sum_{\tau=0}^{t-1}\beta^{\tau}\right)\mathbf{g}_{1,0}+\left(\sum_{\tau=0}^{t-2}\beta^\tau\right)\mathbf{g}_{2,1}+\cdots+\beta\mathbf{g}_{t-1,t-2}+\mathbf{g}_{t,t-1}\right\}
\end{align}$$
As $t\rightarrow\infty$
$$
    \mathbf{x}_t = \mathbf{x}_0 - \eta\left\{\frac{1}{1-\beta}\mathbf{g}_{1,0} + \frac{1}{1-\beta}\mathbf{g}_{2,1} + \cdots + \underbrace{\beta\mathbf{g}_{t-1,t-2} + \mathbf{g}_{t,t-1}}_{\rightarrow 0\text{ as }t \rightarrow 0}\right\}
$$
And this effectively becomes
$$
    \mathbf{x}_t = \mathbf{x}_0 - \eta\left(\frac{1}{1-\beta}\right)\mathbf{g}
$$
I'm not sure if this is what the text means? To be honest, I feel like I'm kinda forcing my reasoning on the equation. Can someone shed more light on my question? Thanks.

A: It means that each gradient step affects the final position with weight $\eta\over{1-\beta}$ due to the velocity term. This can be seen in your final equations, where $\mathbf g_{1,0}, \mathbf g_{2,1}$ etc. are multiplied with $\eta\over{1-\beta}$. So, their effective step size is $\eta\over{1-\beta}$. In SGD, each term would have contributed to the final position with weight $\eta$, but the momentum expression modifies it.


text:
Q: How to select rows when there is no value in a related table? I have the following schema:
class ModelA(models.Model)
    sold = models.DateFiled(blank=True, null=True)
    enabled = models.BooleanField()

class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA)
    start = models.DateField()
    end = models.DateField(blank=True, null=True, db_index=True)

I want to get all instances of ModelA which do not have related any ModelB with end date set to Null, are enabled and not "sold".
Currently I have the following queryset:
ModelA.objects.exclude(
    pk__in=ModelB.objects.filter(end__isnull=True).values('model_a_id')
).filter(
    enabled=True, sold__isnull=True
)

But it's performance is very poor, is there any better way to model this query/Queryset?

A: You can actually filter on the ModelB relation from ModelA, and get Django to perform a left outer join. The following query should do a join instead of using a subquery:
from django.db.models import Q
q = ModelA.objects.exclude(Q(model_b__isnull=False) & Q(model_b__end__isnull=True))

Try the above in a django shell, and do print q.query to see how it translates to SQL. The Q() syntax lets you do an "OR" filter. We're basically saying: get me all ModelA that dont: have a modelB relation with end__isnull=True.
I think that logic covers the cases you're looking for. Otherwise, you can do something similar.


text:
Q: A sequence of bounded $C^1$ functions whose derivatives are unbounded. What is an example of a sequence of functions, $(f_n)_{n=1}^\infty\subset C^1([a,b])$, which are bounded in $C^1([a,b])$ under $\|\cdot\|_{\infty}$ but are such that their first derivatives $\|f'_n\|_{\infty}\to\infty$ as $n\to\infty$?
There are many examples on this site for a single function, but I am looking for an intance when we have a sequence of functions. Are there any particularly simple instances which can be provided to demonstrate the above point?

A: Take $f_n(x)=\sin(nx)$ as per the comment of Mindlack.
The sequence $(\sin(nx))_{n=1}^\infty\subset C^1([a,b])$ is bounded since for all $n\in\mathbb N$ one has that $\|\sin(nx)\|_{\infty}=1$.
Additionally, for each $n\in\mathbb N$ we have that $f_n'(x)=n\cos(nx)$. Then,
$$\|f_n'\|_\infty=\|n\cos(nx)\|_\infty=|n|\|\cos(nx)\|_\infty= n,$$
which implies that $\lim_{n\to\infty}\|f_n'\|_\infty=\infty$. Thus, the derivatives of $(\sin(nx))_{n=1}^\infty\subset C^1([a,b])$ are unbounded.


text:
Q: My android app not able to open directories to read files I have a app written in python/kivy that i have signed and installed on my android phone. The filemanager , an instance of the MDFileManager opens the root dir (/) and displays the file system. But i am not able to open any directory in internal or external storage, so that i can select a file. Most of the directories have a small lock icon on them and those dirs wont open. The directories without lock icon do not have any files or the type of files i want. I browsed the directory using a terminal app and found that the ls command on a locked directory returns a permission denied error. This happens only with this app. I am able to open directories and chose files with other 3rd party apps as well as my own app, written in react native. So not sure if this is an issue with MDFIleManager or something else. Any advise/workaround is highly appreciated

A: Viewing folders without accessing them is most likely due to not setting permissions. Add the following permissions in your manifest according to level of access:

*

*READ_EXTERNAL_STORAGE

*WRITE_EXTERNAL_STORAGE

*MANAGE_EXTERNAL_STORAGE.


text:
Q: How do I configure a dataset WHERE clause for a bit column in Visual Basic? I am using VB 2010 and SQL Server 2008 R2
I have a database table with a column type "Bit".  The column name is "Inactive".  I have the dataset configured to show all of the data using a fill method.  What I want to be able to do is use a Fillby method to populate a DataGridView with rows of data where the checkboxes are not checked but do not know how to configure the "WHERE" clause.
If I write a WHERE clause like this, "WHERE Inactive = 1", I get the converse of what I want to achieve.  It shows the rows where the checkboxes have been checked.  I want to display all the rows that have not been checked.  "WHERE Inactive = 0" and "WHERE Inactive <> 1" do not work.
Is there a way of doing this in the dataset or must it be done in VB code?  If the latter, can someone provide an example as everything that I have tried gives me error messages such as "Integer cannot be converted to Boolean".
There must be a simple answer but after days of searching Google, I cannot find anything that works.

A: You can construct a query that includes Boolean data types, but the only valid Boolean operand types are the =, != and <> types. The value TRUE is equivalent to the number 1, and the value FALSE is equivalent to the number 0.
The following examples are of queries that compare a Boolean value against the values TRUE or FALSE.
SELECT * FROM MyClass WHERE BoolProp = 1
SELECT * FROM MyClass WHERE BoolProp = TRUE
SELECT * FROM MyClass WHERE BoolProp <> FALSE
SELECT * FROM MyClass WHERE BoolProp = 0
SELECT * FROM MyClass WHERE BoolProp = FALSE
SELECT * FROM MyClass WHERE BoolProp != 1
SELECT * FROM MyClass WHERE BoolProp != FALSE
SELECT * FROM MyClass WHERE BoolProp <> FALSE

Source: MSDN Microsoft

A: Thanks for the quick response.  Before I read your answer, I found a solution.  If I configured the dataset Fill method WHERE clause to "WHERE (Inactive IS NULL)", it worked.


text:
Q: tornado.iostream.StreamClosedError: Stream is closed gremlin-python I have an api that queries cosmos graph db using gremlin-python. But if calls are not made for a few hours this error pops up
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/tornado/websocket.py", line 1104, in wrapper
    await fut
tornado.iostream.StreamClosedError: Stream is closed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/app/disc_api.py", line 20, in visu
    r=final()
  File "/app/dis_parse.py", line 58, in final
    par.add('nodes',parser_node())
  File "/app/dis_parse.py", line 18, in parser_node
    n=node()
  File "/app/cosmo.py", line 16, in node
    for result in callback.result():
  File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 432, in result
    return self.__get_result()
  File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.6/site-packages/gremlin_python/driver/connection.py", line 63, in cb
    f.result()
  File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 425, in result
    return self.__get_result()
  File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.6/site-packages/gremlin_python/driver/protocol.py", line 66, in write
    self._transport.write(message)
  File "/usr/local/lib/python3.6/site-packages/gremlin_python/driver/tornado/transport.py", line 37, in write
    lambda: self._ws.write_message(message, binary=True))
  File "/usr/local/lib/python3.6/site-packages/tornado/ioloop.py", line 532, in run_sync
    return future_cell[0].result()
  File "/usr/local/lib/python3.6/site-packages/tornado/websocket.py", line 1106, in wrapper
    raise WebSocketClosedError()
tornado.websocket.WebSocketClosedError

my api looks like this
app = Flask(__name__)

CORS(app)

@app.route('/visu', methods=['GET'])
def visu():
    r=final()
    return r

the final() function is a parser which calls these functions
from gremlin_python.driver import client, serializer
import sys
import traceback
import json, ast
client = client.Client('wss://database.gremlin.cosmos.azure.com:443/', 'g',
                           username="/dbs/graphdb/colls/graph_name",
                           password="password"
                           )

def node():
    query='g.V()'
    callback=client.submitAsync(query)
    for result in callback.result():
        a=ast.literal_eval(json.dumps(result))
        return a

def edges():
    query='g.V().outE()'
    callback=client.submitAsync(query)
    for result in callback.result():
        #print (json.dumps(result))
        r=ast.literal_eval(json.dumps(result))

        return r

def count(name):
    query='g.V().has("name",'+'"'+name+'").count()'
    callback=client.submitAsync(query)

    for result in callback.result():
        resu=result
        return resu

I don't know what's causing this error and what should i change in my code in order to solve it. This is the first time i am using gremlin...is there something that i am missing because i didn't find anything in the docs related to this.


text:
Q: How to grab a string from an array programming in C.
I'm working on a function that uses getline to get input from the user.
if the first word in a string of text is S, it will call a funtion that will save a 2Darray to a document.
the name of the file will be whatever the user types after the S.
So if the user were to type S myfile.txt, the function will save the file as myfile.txt.  I can't figure out how to grab a string from the aray that will be the name of the file.  I don't think my user of the pointers is correct eaither.
void copy_to_file(char** board, int num_rows, int num_cols, char* filename){

    FILE *fp;
    fp = fopen(filename.txt, "w");
    int i =0;
    int j = 0;
    for (i = (num_rows - 1); i >= 0; --i) {
    fprintf("%d ", i);
    for (j = 0; j < num_cols; ++j) {
    fprintf("%c ", board[i][j]);
    }
    fprintf("\n");
    }
    fprintf(" ");
    for (i = 0; i < num_cols; ++i) {
    fprintf("%d ", i);
    }
    fprintf("\n");

    fclose(f);

    }//end coppy to board

    int main(int argc, char** argv)

    {
    char** board
    do
    {
       printf("Enter your command: ");
       fgets(command, 100, stdin);

    if( command[1] == 's"){

    copy_to_file(char** board, int num_rows, int num_cols, char* filename)

    }

   }while(!(get_valid_input(command)));

A: sample code.
#include <stdio.h>

int main(void){
    char commands[512] = "S myfile.txt\n";
    char command, filename[FILENAME_MAX+1];

    sscanf(commands, " %c %[^\n]", &command, filename);
    printf("command:%c, filename:%s\n", command, filename);
    return 0;
}


text:
Q: Respective form should display only when i check box iam trying to achieve this exact functionalty: http://jsfiddle.net/exttq/  BUT inside using my PHP, right now its displaying 2 checkboxes and 2 forms, BUT what I need is: those  2 forms shouldnt be visible unless I check any box..
so, please check whats wrong in below code...
function eshop_extras_checkout($echo){

    $echo .= '

    ';

    $echo .= '<fieldset class="eshop eshop_extra">' . "\n";

    $echo .= ' <form id="chooseForm">
        <input type="checkbox" name="form1" value="form1"> Form1

        <input type="checkbox" name="form1" value="form2"> Form2

    </form>

    <form id="form1" class="formGroup">

FORM 1

        Name<input type="text">

        Address<input type="text">
    </form>

    <form id="form2" class="formGroup">

FORM 2

        Username<input type="text">

    </form>';

    $echo .= '<legend>Articles Order Form</legend>' . "\n";

    return $echo;
}

waiitng for your replies...

A: The problem is that your script executes before the elements are present in the DOM. See:
//when this line executes:
$(".formGroup").hide(); //the .formGroup is not present in the DOM yet
//in other words, the jQuery object is empty and calling .hide() does nothing

//the same happens to this handler binding:
$("#chooseForm input:checkbox").on("change", ...

Your fiddle's JS is set to use the onDomReady wrapper, that's why it works properly there.
You can put the script below the form's HTML, and/or simply wrap the script contents inside a DOM ready handler:
$(function() {
    $(".formGroup").hide();
    $('#chooseForm input:checkbox').on('change', function() {
        if($(this).is(':checked')) {
            $("#" + $(this).val()).show();
        }
        else {
            $("#" + $(this).val()).hide();
        }
    });
});

One of jQuery's best practices to always wrap your code in a DOM ready handler, that is:
$(document).ready(function() {
    //code here
});

or the much shorter shorthand:
$(function() {
    //code here
});

Both have the same effect, they prevent the code from executing until the DOM is ready.
Another JavaScript best practice is to put the JS code in the footer of the page (right before the ), this way scripts loading won't block the page rendering and when the DOM parser reaches the scripts, your DOM will be already ready for them.
Both best practices above are combinable. Nevertheless, simply using the DOM ready handler will solve the issue, as well as moving the scripts to below the form HTML will also suffice.

Your framework is already loading another copy of jQuery in noConflict mode, that means you can't use the $ alias in the global scope. To remedy that, you can use this special DOM ready syntax, which will alias jQuery back to $ inside its scope:
jQuery(function($) {
    $(".formGroup").hide();
    $("#chooseForm input:checkbox").on("change", function() {
        if($(this).is(":checked")) {
            $("#" + $(this).val()).show();
        }
        else {
            $("#" + $(this).val()).hide();
        }
    });
});

More info on that from the DOM ready handler docs - Aliasing the jQuery Namespace:

When using another JavaScript library, we may wish to call
  $.noConflict() to avoid namespace difficulties. When this function is
  called, the $ shortcut is no longer available, forcing us to write
  jQuery each time we would normally write $. However, the handler
  passed to the .ready() method can take an argument, which is passed
  the global jQuery object. This means we can rename the object within
  the context of our .ready() handler without affecting other code.


text:
Q: differences between org.jboss.redhat-fuse/fabric8-maven-plugin and io.fabric8/fabric8-maven-plugin I'm using org.jboss.redhat-fuse/fabric8-maven-plugin in one my project but somehow the latest version is always behind.
Is there any reason why we are encouraged to use org.jboss.redhat-fuse/fabric8-maven-plugin for RH Fuse project? instead of io.fabric8/fabric8-maven-plugin

A: I'm the maintainer of io.fabric8/fabric8-maven-plugin.
org.jboss.redhat-fuse/fabric8-maven-plugin is Jboss's fork of upstream fabric8 maven plugin i.e io.fabric8/fabric8-maven-plugin. Jboss's fork may contain some jboss related patches as per it's requirements. I think it is used under FUSE internals like for Fuse Online. Usually it's synced with upstream plugin from time to time.
If you want to use plugin as a general purpose Kubernetes/Openshift plugin. I recommend to use upstream Fabric8 Maven Plugin. If you are working around FUSE related stuff, then maybe go with Jboss's fork since it's tried and tested. But I think upstream would also work fine.


text:
Q: Add space between two lines I need to add space between two lines by using OpenCV or PIL.

A: If the lines vary "sufficiently" in their length, then the following approach might be useful:

*

*Inverse binarize the image using cv2.threshold.

*Dilate the image with a horizontal line kernel using cv2.dilate to emphasize the lines.

*Sum all pixels row-wise using np.sum, and calculate the absolute differences between the rows using np.diff.

*There will be "steps" in the differences between the rows, which resemble the step between the lines. Set up a threshold and find the proper indices using np.where.

*Insert white lines in the original image before the found indices using np.insert. In the below example, the index was chosen manually. Work has to be done to properly automatize this: Exclude "steps" to "background", find "steps" between multiple lines.

Here comes a code snippet:
import cv2
from matplotlib import pyplot as plt
import numpy as np
from skimage import io              # Only needed for web grabbing images, use cv2.imread for local images

# Read and binarize image
image = cv2.cvtColor(io.imread('https://i.stack.imgur.com/56g7s.jpg'), cv2.COLOR_RGB2GRAY)
_, image_bin = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY_INV)

# Dilate rows by using horizontal line as kernel
kernel = np.ones((1, 51), np.uint8)
image_dil = cv2.dilate(image_bin, kernel)

# Sum pixels row-wise, and calculate absolute differences between the rows
row_sum = np.sum(image_dil / 255, 1, dtype=np.int32)
row_sum_diff = np.abs(np.diff(row_sum))

# Just for visualization: Summed row-wise pixels
plt.plot(row_sum)
plt.show()

# Find "steps" in the differences between the rows
step_thr = 100
step_idx = np.where(row_sum_diff > step_thr)[0]

# Insert n lines before desired index; simple hard-coding here, more work needs to be done for multiple lines
n_lines = 5
image_mod = np.insert(image, step_idx[1] + 1, 255 * np.ones((n_lines, image.shape[1]), np.uint8), axis=0)

# Result visualization
cv2.imshow('image', image)
cv2.imshow('image_dil', image_dil)
cv2.imshow('image_mod', image_mod)
cv2.waitKey(0)
cv2.destroyAllWindows()

The dilated, inverse binarized image:

The visualization of the "steps":

The final output with n = 5 inserted white lines:

As you can see, the result isn't perfect, but that's due to the original image. In the corresponding row, you have parts of the first and second line. So, a proper distinction between these two isn't possible. One might add a very small morphological closing to the output to get rid of these artifacts.
Hope that helps!


text:
Q: how to check/test specific field in json using rspec This is my rspec code:-
  it "which has max value" do
    get :index, Devise.token_authentication_key => @user.authentication_token, business_id: @business.id, max: '1'
    expect(request.flash[:alert]).to eq(nil)
    expect(response.body).to eq([@location].to_json(LocationFinder::API_PARAMS.merge(:root => false)))
  end

and testing result is-
expected: "[{\"address\":\"1120 Milky Way\",\"business_id\":1,\"city\":\"Cupertino]"
  got: "[{\"address\":\"1120 Milky Way\",\"business_id\":1,\"city\":\"Cupertino,\"distance\":260.33452958767384,]"

Here Distance is an extra field , how can i check particular fields or if it is not possible , how to eliminate "distance" field which is not check by rspec.

A: You could check individual fields using something like:
# get the first entry in the JSON array
json_response = JSON.parse(response.body).first

# compare each field
expect(json_response['address']).to eq(@location.address)
expect(json_response['business_id']).to eq(@location.business_id)
expect(json_response['city']).to eq(@location.city)

Of course you may need to adjust the exact methods you call on @location depending on your implementation, but that's the gist of it.


text:
Q: Document write cause design flaw I write a slider function. And base on value of slider function i print some messages in my document . When i use DW inside a slider after changing the value of the slider that messages are printed without style. How can i fix it?
     $(function() {
        $( "#slider-5" ).slider({
           range:true,
           min: parseInt(ctime[0]),
           max: parseInt(ctime[ctime.length-1]),
           values: [ parseInt(ctime[4]),parseInt(ctime[len])],

           change: function( event, ui ) {
              $( "#slidevalue" )
                 .val( "$" + formatDateTime(ui.values[ 0 ]) + " - $" + formatDateTime(ui.values[ 1 ]) );
                 new_var=ui.values[0];
    document.write('
')
    var ctime  = <?php echo json_encode($tweettimes); ?>;

    for(var x=0; x<10; x++){
    var datum = new Date(parseInt(ctime[x]));
    document.write('
')
    document.write('
')
    document.write('')
    document.write('
')
    document.write('
')
    document.write('
'+(x+1)+'
')
    document.write('
'+<?php echo json_encode($content); ?>[x]+'
')

    document.write(''+formatDateTime(datum)+'')
    document.write('
')
    document.write('
')}
    document.write('
')
           }
       });
     });

A: Please don't use document.write. Use document.createElement() instead.
var body = document.getElementsByTagName('body')[0];

var section = document.createElement('section');
section.id = 'cd-timeline';
section.className = 'cd-container';
body.appendChild(section);

for (var x = 0; x < 10; x++) {
    var datum = new Date(parseInt(ctime[x]));

    var outerDiv = document.createElement('div');
    outerDiv.className = 'cd-timeline-block';
    section.appendChild(outerDiv);

    var div = document.createElement('div');
    div.className = 'cd-timeline-img cd-location';
    outerDiv.appendChild(div);

    var img = document.createElement('img');
    img.src = 'img/cd-icon-location.svg';
    img.setAttribute('alt', 'Location');
    div.appendChild(img);

    var div = document.createElement('div');
    div.className = 'cd-timeline-content';
    outerDiv.appendChild(div);

    var h2 = document.createElement('h2');
    div.appendChild(h2);
    h2_text = document.createTextNode('foo');
    h2.appendChild(h2_text);

    var p = document.createElement('p');
    div.appendChild(p);
    p_text = document.createTextNode('bar');
    p.appendChild(p_text);

    var span = document.createElement('span');
    span.className = 'cd-date';
    div.appendChild(span);
    span_text = document.createTextNode('foobar');
    span.appendChild(span_text);
}

DEMO


text:
Q: Can't create cluster in Dataproc So for my Lab I need to create a cluster in Dataproc.
I've followed all the steps listed so often I can do them blind now.
It just keeps coming up with an error saying I don't have permission.
I can't imagine I'm doing anything wrong.
Or could i...?
I'm on the third course from coursera Data Engineering


text:
Q: Advantage of using nexenta vs. OpenSolaris I am currently building a NAS for about 24 TB of storage. Video files, slow access, long term storage. No performance issues.
I am currently undecided between buying a JBOD case and installing OpenSolaris (because of ZFS), or purchasing a Nexenta license. The difference is about $ 12.500 for licenses over three years.
What would you see as the main advantage in purchasing a nexenta license, beside the support? Did nexenta really enhance the basic OpenSolaris, or is it just a lot of marketing speak? No one really wanted to answer that question.
P.S. With the nexenta license pricing I am even thinking of going with Windows Storage Server.

A: (Disclosure: I am a Nexenta developer)
For NexentaStor 24 TB License cost would be ~3000 (Silver) or ~5500 (Gold). (+20% per year Upgrades/support from second year). Take a look at http://www.nexenta.com/corp/store
Nexenta (core and stor) are currently based on b134. It has access to multiple Open-source plugins (nexentastor.org), and the WebUI provides access to more underlying ZFS features. It also includes replication/snaphotting services.
Featurewise, Nexenta first added COMSTAR/zfs integration, that later became available in OpenSolaris. It was the first to add safe upgrades (via apt-clone). It also developed the VTape library to virtualize zvols over tape (http://www.nexentastor.org/projects/vtape). It was the first appliance to provide dedup. It follows upstream features quickly, and backports fixes to the stable build.
There's a free version you can install to test it.. but it can only be used till you reach 12TB of used storage (nexentastor.org). You can also install the free NCP iso, and community developed NAS interface (napp-it).

A: (Disclosure: I build NexentaStor based solutions)
Take a look at http://www.informationweek.com/news/software/open_source/showArticle.jhtml?articleID=227600191&subSection=Hosted+Software - ultimately 1PB on NexentaStor in mission critical - stability is not a problem.
If you're looking for Enterprise quality and support NexentaStor is the way forward - period.  With the likes of Bill Moore, Richard Elling, Garrett D'Amore involved directly with Nexenta the future is very secure indeed.
De-dupe rock on NexentaStor - just make sure you give it enough memory! It's cheaper that WSS, EMC, 3PAR et al.
If you're in the UK take a look at http://www.va-technologies.com/sbb for a good place to start.

A: As for Windows Storage Server, its SIS/dedup is at the file level versus block level for ZFS and also not real-time.
NexentaStor is based on OpenSolaris, so it also carries basically the same baggage (memory hog, stability, etc.).
The one to watch is FreeNAS and its ZFS support when they roll in SIS/dedup!